branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter import pandas as pd import numpy as np from math import ceil, floor from modules.ComsolModel import ComsolModel from modules.MiscCalculations import TempDistSolver, ThermalConductivity from typing import Dict, List, Type, Union import os from copy import deepcopy # TEST 333 # message # another message # yooooooo # yooooo # new line from precision PC # another line coming form Precision #plt.style.use('dark_background') colors = { 'red': '#FF7A7A', 'orange': '#FFBF70', 'yellow': '#FBFF84', 'green': '#9CFF89', 'blue': '#6BF3FF', 'light_purple': '#70A7FF', 'dark_purple': '#927FFF', 'pink': 'FF92FF'} my_pallete = [ colors['red'], colors['yellow'], colors['green'], colors['blue'], colors['orange'], colors['light_purple'], colors['dark_purple'], colors['pink'], ] # http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/ color_palette = ['#FDEF54', '#3598FE', '#EF3C77', '#08CF96'] #mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=color_pallete) #E69F00 orange #56B4E9 light blue #009E73 green #F0E442 yellow #0072B2 dark blue #D55E00 red #CC79A7 pink # http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/ #print(plt.rcParams['axes.prop_cycle'].by_key()['color']) # Seaborn color-blind color cycle: #0072B2 #009E73 #D55E00 #CC79A7 #F0E442 #56B4E9 # seaborn-colorblind # seaborn-deep # dark_background class PlotMeasurementFigures: """ An instance of this class is initiated only when the user presses any of the plot buttons. That means that an instance is created with a particular sample. There might be a flaw when printing multiple samples. Shouldn't the plotter object be initiated together with the program? SImply initiated with sample_data instead of particular sample? This object does not load data ot r do any sorts of that kind of manipulation... """ def __init__(self, ): # Sample data placeholders: self.sample = None self.test_data = None self.timestamps = [] self.comsol_path = None self.fignames = None self.temp_directions = list() self.moist_directions = list() def load_sample_into_plotter(self, test_data, active_sample, phase_datetimes): """ The function picks the corresponding sample that is selected by user. :param test_data - this is whole test data instance (large_test_data, small_test_data) :param active_sample: the current sample being prepared for plotting :param phase_datetimes: dictionary of phase datetimes. """ self.test_data = test_data self.sample = active_sample self.fignames = self.test_data.fignames self.timestamps = [] phase_count = len(phase_datetimes) phase_number = '1' for phase in range(phase_count): phase_name = active_sample['phase_names'][phase] self.timestamps.append([phase_datetimes[phase_number][1], phase_name]) phase_number = str(int(phase_number) + 1) # These directions are loaded for each sample because the amount of sensors and location is changing: self.temp_directions.clear() self.moist_directions.clear() for direction in self.test_data.temp_directions: self.temp_directions.append(self.sample['sensors'][direction]) for direction in self.test_data.moist_directions: self.moist_directions.append(self.sample['sensors'][direction]) # Sample thermal conductivity (dry thermal conductivity and moist thermal conductivity) porosity = self.sample['sample_props']['porosity'] ks = self.sample['sample_props']['ks'] rhos = self.sample['sample_props']['rhos'] w_grav = self.sample['sample_props']['w_grav'] thermal = ThermalConductivity(porosity, ks, rhos, w_grav) self.kdry, self.kmoist = thermal.calculate_thermal_conductivity() # Initialize two zone solver self.zone_solver = TempDistSolver() # Combined plot calls: def plot_SN_combined_master( self, df: pd.DataFrame, phase_directory: str, folder: str, sizer, styler, xscale, title: bool = False, comsol_model: bool = False, power_line: bool = True, save_fig: bool = True, show_fig: bool = False, xaxis_type: str = 'hours', last_day: bool = False): # initializer: fig, ax = plt.subplots(nrows=4, ncols=3, figsize=sizer['figsize'], sharey='row') fig.patch.set_facecolor(styler['facecolor']) fig.subplots_adjust(wspace=sizer['wspace'], hspace=sizer['hspace']) max_col_ind = ax.shape[1]-1 max_row_ind = ax.shape[0]-1 power_sensor = ['power'] # TEMPERATURE SERIES: column = 0 for temp_direction in self.temp_directions: curr_col_ind = column curr_row_ind = max_row_ind self.executor_time_series( df, ax[0, column], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, temp_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='temperature') column += 1 # TEMPERATURE GRADIENTS: column = 0 for temp_direction in self.temp_directions: curr_col_ind = column curr_row_ind = max_row_ind self.executor_gradients( df, ax[1, column], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, temp_direction, sizer, styler, xscale, comsol_model, data_type='temperature') column += 1 # MOISTURE SERIES: column = 0 for moist_direction in self.moist_directions: curr_col_ind = column curr_row_ind = max_row_ind self.executor_time_series(df, ax[2, column], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='moisture') column += 1 # MOISTURE GRADIENTS: column = 0 for moist_direction in self.moist_directions: curr_col_ind = column curr_row_ind = max_row_ind self.executor_gradients( df, ax[3, column], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, sizer, styler, xscale, comsol_model, data_type='moisture') column += 1 # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, 'all_plots'), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SN_combined_temperature_series( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): save_name = self.fignames['time series temp'] # subversion configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' # initializer: fig, ax = plt.subplots( nrows=3, ncols=1, figsize=sizer['figsize'], #sharex='col', ) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 max_row_ind = len(ax) - 1 power_sensor = ['power'] row = 0 for temp_direction in self.temp_directions: curr_col_ind = 0 curr_row_ind = row self.executor_time_series( df, ax[row], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, temp_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='temperature') row += 1 plt.tight_layout(pad=sizer['tight_layout_pad'], h_pad=sizer['tight_layout_h_pad']) # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name + savename_ext), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SN_combined_temperature_gradient( self, df, phase_directory, folder, sizer, styler, xscale, comsol_model=False, save_fig=True, show_fig=False): """ Plots combined (3x1) temperature gradient figure. This function is called from MainApp by con_SN_combined_temperature_gradient. """ save_name = self.fignames['gradient temp'] # initializer: fig, ax = plt.subplots(nrows=3, ncols=1, figsize=sizer['figsize'], sharex='col') fig.patch.set_facecolor(styler['facecolor']) plt.tight_layout() fig.subplots_adjust(hspace=sizer['hspace']) max_col_ind = 0 max_row_ind = len(ax) - 1 row = 0 for direction in self.temp_directions: curr_col_ind = 0 curr_row_ind = row self.executor_gradients(df, ax[row], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type='temperature') row += 1 # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SN_combined_moisture_series( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): """ Plots combined (3x1) moisture series gradient figure. This function is called from MainApp by con_SN_combined_moisture_series. """ save_name = self.fignames['time series moist'] # subversion configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' # initializer: fig, ax = plt.subplots(nrows=3, ncols=1, figsize=sizer['figsize'], sharex='col') fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 max_row_ind = len(ax) - 1 power_sensor = ['power'] row = 0 for moist_direction in self.moist_directions: curr_col_ind = 0 curr_row_ind = row self.executor_time_series(df, ax[row], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='moisture') row += 1 plt.tight_layout(pad=sizer['tight_layout_pad'], h_pad=sizer['tight_layout_h_pad']) # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name + savename_ext), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SN_combined_moisture_gradients( self, df, phase_directory, folder, sizer, styler, xscale, comsol_model=False, save_fig=True, show_fig=False): save_name = self.fignames['gradient moist'] # initializer: fig, ax = plt.subplots(nrows=3, ncols=1, figsize=sizer['figsize'], sharex='col') fig.patch.set_facecolor(styler['facecolor']) fig.subplots_adjust(hspace=sizer['hspace']) max_col_ind = 0 max_row_ind = len(ax) - 1 row = 0 for direction in self.moist_directions: curr_col_ind = 0 curr_row_ind = row self.executor_gradients(df, ax[row], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type='moisture') row += 1 # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SN_combined_series_moist_vs_temp( self, df, phase_directory, folder, sizer, styler, normalized=False, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): """ Plots combined (3x1) moisture vs temperature series. This function is called from MainApp by app_SN_combined_series_moist_vs_temp. :type show_fig: :param save_fig: :param power_line: :param title: :param styler: :param sizer: :param df - current dataframe to plotted. This can be master dataframe or any of the phase dataframes. :param phase_directory - phase directory (master or phaseXX) directory where the plot will be saved. :param folder - folder to save in located in the phase_directory. :param normalized - if True, the function will plot normalized values of moisture sensors. Those are generated that end with _norm. """ save_name = self.fignames['moist vs temp'] # primary save extension: if not normalized: primary_savename_ext = '' else: primary_savename_ext = '_normalized' # secondary save extension: if xaxis_type == 'datetime' and not last_day: secondary_savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: secondary_savename_ext = '_last_24h' else: secondary_savename_ext = '' # initializer: fig, ax = plt.subplots(nrows=3, ncols=1, figsize=sizer['figsize'], sharex='col') fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 max_row_ind = len(ax) - 1 row = 0 for moist_direction in self.moist_directions: # switch to '_norm' columns: if normalized: moist_direction = deepcopy(moist_direction) for idx in range(len(moist_direction['sensors'])): moist_direction['sensors'][idx] += '_norm' curr_col_ind = 0 curr_row_ind = row self.executor_time_series( df, ax[row], max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, moist_direction['temp_sensors'], sizer=sizer, styler=styler, title=title, power_line=power_line, xaxis_type=xaxis_type, last_day=last_day, data_type='moisture') row += 1 plt.tight_layout(pad=sizer['tight_layout_pad'], h_pad=sizer['tight_layout_h_pad']) # save show options: if save_fig: fig.savefig( os.path.join(phase_directory, folder, save_name + primary_savename_ext + secondary_savename_ext), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() # Separate plot function calls: def plot_SN_separate_temperature_series( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): """ Plots separate figures for every direction for temperature series. This function is called from MainApp by con_SN_separate_temperature_series. """ save_names = [self.fignames['time series temp - up'], self.fignames['time series temp - right'], self.fignames['time series temp - down']] # subversion configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' counter = 0 for temp_direction in self.temp_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 power_sensor = ['power'] self.executor_time_series(df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, temp_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='temperature') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_names[counter] + savename_ext), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def plot_SN_separate_temperature_gradient( self, df, phase_directory, folder, sizer, styler, xscale, comsol_model=False, save_fig=True, show_fig=False): """ Plots separate figures for every direction for temperature gradient. This function is called from MainApp by con_SN_separate_temperature_gradient. """ save_names = [self.fignames['gradient temp - up'], self.fignames['gradient temp - right'], self.fignames['gradient temp - down']] counter = 0 for direction in self.temp_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 self.executor_gradients( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type='temperature') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_names[counter]), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def plot_SN_separate_moisture_series( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): """ Plots separate figures for every direction for moisture series. This function is called from MainApp by con_SN_separate_moisture_series. """ save_names = [self.fignames['time series moist - up'], self.fignames['time series moist - right'], self.fignames['time series moist - down']] # subversion configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' counter = 0 for moist_direction in self.moist_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 power_sensor = ['power'] self.executor_time_series( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='moisture') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_names[counter] + savename_ext), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def plot_SN_separate_moisture_gradient( self, df, phase_directory, folder, sizer, styler, xscale, comsol_model=False, save_fig=True, show_fig=False): """ Plots separate figures for every direction for moisture gradient. This function is called from MainApp by con_SN_separate_moisture_gradient. """ save_names = [self.fignames['gradient moist - up'], self.fignames['gradient moist - right'], self.fignames['gradient moist - down']] counter = 0 for direction in self.moist_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 self.executor_gradients( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type='moisture') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_names[counter]), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def plot_SN_separate_series_moist_vs_temp( self, df, phase_directory, folder, sizer, styler, normalized=False, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): """ Plots combined (3x1) moisture vs temperature series. This function is called from MainApp by app_SN_combined_series_moist_vs_temp. :type show_fig: :param save_fig: :param power_line: :param title: :param styler: :param sizer: :param df - current dataframe to plotted. This can be master dataframe or any of the phase dataframes. :param phase_directory - phase directory (master or phaseXX) directory where the plot will be saved. :param folder - folder to save in located in the phase_directory. :param normalized - if True, the function will plot normalized values of moisture sensors. Those are generated that end with _norm. """ save_names = [self.fignames['time series moist - up'], self.fignames['time series moist - right'], self.fignames['time series moist - down']] # primary save extension: if not normalized: primary_savename_ext = '' else: primary_savename_ext = '_normalized' # secondary save extension: if xaxis_type == 'datetime' and not last_day: secondary_savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: secondary_savename_ext = '_last_24h' else: secondary_savename_ext = '' counter = 0 for moist_direction in self.moist_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 power_sensor = ['power'] # switch to '_norm' columns: if normalized: moist_direction = deepcopy(moist_direction) for idx in range(len(moist_direction['sensors'])): moist_direction['sensors'][idx] += '_norm' self.executor_time_series( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, moist_direction, moist_direction['temp_sensors'], sizer=sizer, styler=styler, title=title, power_line=power_line, xaxis_type=xaxis_type, last_day=last_day, data_type='moisture') plt.tight_layout(pad=sizer['tight_layout_pad'], h_pad=sizer['tight_layout_h_pad']) # save show options: if save_fig: fig.savefig( os.path.join(phase_directory, folder, save_names[counter] + primary_savename_ext + secondary_savename_ext), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def plot_SN_hot_end_temperature( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): save_name = self.fignames['hot end temp'] # subversion configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 power_sensor = ['power'] sensor_dict = {'sensors': ['hot_end']} self.executor_time_series(df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, sensor_dict, power_sensor, sizer, styler, title, power_line, xaxis_type, last_day, data_type='single') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name + savename_ext), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SS_combined_master(self): pass def plot_SS_time_series( self, df, phase_directory, folder, sizer, styler, title=False, power_line=True, save_fig=True, show_fig=False, xaxis_type='hours', last_day=False): save_name = self.fignames['time series'] # subversion save name configuration: if xaxis_type == 'datetime' and not last_day: savename_ext = '_with_datetime' elif xaxis_type == 'datetime' and last_day: savename_ext = '_last_24h' else: savename_ext = '' # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 power_sensor = ['power'] temp_direction = self.temp_directions[0] self.executor_time_series( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, temp_direction, power_sensor, sizer=sizer, styler=styler, title=title, power_line=power_line, xaxis_type=xaxis_type, last_day=last_day, data_type='temperature') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name + savename_ext), dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor()) if show_fig: plt.show() plt.close() def plot_SS_temperature_gradient( self, df, phase_directory, folder, sizer, styler, xscale, comsol_model=False, save_fig=True, show_fig=False): save_name = self.fignames['gradient temp'] counter = 0 for direction in self.temp_directions: # initializer: fig, ax = plt.subplots(figsize=sizer['figsize']) fig.patch.set_facecolor(styler['facecolor']) max_col_ind = 0 curr_col_ind = 0 max_row_ind = 0 curr_row_ind = 0 self.executor_gradients( df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type='temperature') # save show options: if save_fig: fig.savefig(os.path.join(phase_directory, folder, save_name), dpi=300, facecolor=fig.get_facecolor()) if show_fig: plt.show() counter += 1 plt.close() def executor_time_series( self, df: pd.DataFrame, ax: plt.Axes, max_col_ind: int, curr_col_ind: int, max_row_ind: int, curr_row_ind: int, primary_axis_sensors: Dict, secondary_axis_sensors: List, sizer, styler, title: bool, power_line: bool, xaxis_type, last_day, data_type): """ :param df: current dataset to be plotted :param ax: current axis in the plot :param max_col_ind: maximum column index in subplot :param curr_col_ind: current column index in subplot :param max_row_ind: maximum row index in subplot :param curr_row_ind: current row index in the subplot :param primary_axis_sensors: dictionary containing particular direction information (sensors, locations) :param secondary_axis_sensors: list containing only sensor names (multiple ('R1', 'R2',..) or one ('power')) :param sizer: sizer object to adjust the size of plot :param styler: styler object to adjust the style of plot elements :param title: bool value, if True add title to the plot :param power_line: bool value, if True add power measurement on secondary axis :param xaxis_type: type of xaxis selected in gui - 'linear' or 'log' :param last_day: bool value, if True plot only last 24h :param data_type: string value to select datatype: 'temperature', 'moisture' """ # configuration based on data type input: if data_type == 'temperature': yticks, ylim = self.generate_yaxis_ticks_temp_series(df, ['hot_end', 'cold_end']) ylabel = 'Temperature, °C' elif data_type == 'moisture': yticks, ylim = self.generate_yaxis_ticks_temp_series(df, primary_axis_sensors['sensors']) if '_norm' in primary_axis_sensors['sensors'][0]: ylabel = 'Normalized moisture' else: ylabel = 'Moisture, mV' elif data_type == 'single': yticks, ylim = self.generate_yaxis_ticks_temp_series(df, ['hot_end']) ylabel = 'Temperature, °C' else: ylim = [] yticks = [] ylabel = [] # styler: ax.set_facecolor(styler['axis_facecolor']) # primary axis plot input setup: if xaxis_type == 'hours': x_vals = df['hours'] x_label = 'Time, hours' xticks, xlim = self.generate_xaxis_ticks_hours(df) elif xaxis_type == 'datetime': x_vals = df.index x_label = 'Time, daytime' xticks, xlim = self.generate_xaxis_ticks_datetime(df, last_day) else: x_vals = None x_label = None xticks, xlim = None, None plot_list = [] # plot on primary axis: for sensor in primary_axis_sensors['sensors']: plot = ax.plot( x_vals, df[sensor], label=sensor.split('_')[0], lw=sizer['line_width'], marker=None, linestyle='solid') plot_list.append(plot[0]) # plot core and wall temperature if plotting temperature series if data_type == 'temperature': plot = ax.plot( x_vals, df['cold_end'], label='cold end', lw=1.5, color='black', linestyle='dashed') plot_list.append(plot[0]) plot = ax.plot( x_vals, df['hot_end'], label='hot end', lw=1.5, color='black', linestyle='dotted') plot_list.append(plot[0]) ''' # configuration: if curr_row_ind == max_row_ind: ax.set_xlabel( x_label, size=sizer['label_size'], color=styler['label_color'], labelpad=sizer['labelpad']) if title: ax.set_title(primary_axis_sensors['direction_name']) ''' twinx_config = False if secondary_axis_sensors[0] == 'power' and power_line is True: # This filters out of power is plotted on secondary axis # Only this option is linked to the power selection in gui ax_twinx = ax.twinx() twinx_config = True twinx_ylabel = 'Power, W' yticks_sec, ylim_sec = self.generate_yaxis_ticks_temp_series(df, secondary_axis_sensors) # plot data: plot = ax_twinx.plot( x_vals, df['power'], label='power', lw=sizer['line_width'], color='dimgrey', marker=None, linestyle='solid') plot_list.append(plot[0]) elif power_line is False: # This is true for plots when power_line is False: ax_twinx = None # dummy twinx_ylabel = None # dummy yticks_sec = None # dummy ylim_sec = None # dummy else: # Other data is plotted here (for now only temperature for moist vs temp plots) ax_twinx = ax.twinx() twinx_config = True twinx_ylabel = 'Temperature, °C' yticks_sec, ylim_sec = self.generate_yaxis_ticks_temp_series(df, secondary_axis_sensors) for sensor in secondary_axis_sensors: if xaxis_type == 'hours': plot = ax_twinx.plot( df['hours'], df[sensor], label=sensor, lw=sizer['line_width'], marker=None, linestyle='--') plot_list.append(plot[0]) elif xaxis_type == 'datetime': plot = ax_twinx.plot_date( df.index, df[sensor], label=sensor, lw=sizer['line_width'], marker=None, linestyle='--') plot_list.append(plot[0]) # legend configuration labels = [plot.get_label() for plot in plot_list] if len(labels) <= 8: ncols = 1 else: ncols = 2 if twinx_config: # legend: legend = ax_twinx.legend( plot_list, labels, ncol=ncols, loc=sizer['legend_loc'], bbox_to_anchor=sizer['legend_bbox_to_anchor'], borderaxespad=sizer['legend_borderaxespad'], fontsize=sizer['legend_size'], handlelength=sizer['legend_handlelength'], labelcolor=styler['legend_text_color'], edgecolor=styler['legend_edge_color'], frameon=False, labelspacing=sizer['legend_labelspacing']) legend.get_frame().set_linewidth(sizer['legend_frame_width']) legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor(styler['legend_face_color_rgba']) if curr_col_ind == max_col_ind: ax_twinx.set_ylabel( twinx_ylabel, size=sizer['label_size'], color=styler['label_color']) ax_twinx.set_yticks(yticks_sec) else: ax_twinx.set_yticks([]) ax_twinx.set_ylim(ylim_sec) ax_twinx.tick_params( direction='in', width=sizer['tick_width'], labelsize=sizer['tick_size'], length=sizer['tick_length'], color=styler['tick_color'], labelcolor=styler['tick_label_color']) ax_twinx.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax.tick_params( axis='both', direction='in', width=sizer['tick_width'], top=True, labelsize=sizer['tick_size'], length=sizer['tick_length'], color=styler['tick_color'], labelcolor=styler['tick_label_color']) ax.tick_params(axis='x', which='major', pad=2) # spines: for spine in ['top', 'bottom', 'left', 'right']: ax_twinx.spines[spine].set_visible(False) else: # These options are executed if nothing is plotted on the secondary axis legend = ax.legend( plot_list, labels, ncol=ncols, loc=sizer['legend_loc'], bbox_to_anchor=sizer['legend_bbox_to_anchor'], borderaxespad=sizer['legend_borderaxespad'], fontsize=sizer['legend_size'], handlelength=sizer['legend_handlelength'], labelcolor=styler['legend_text_color'], edgecolor=styler['legend_edge_color'], frameon=False, labelspacing=sizer['legend_labelspacing']) legend.get_frame().set_linewidth(sizer['legend_frame_width']) legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor(styler['legend_face_color_rgba']) ax.tick_params( axis='both', direction='in', width=sizer['tick_width'], right=True, top=True, labelsize=sizer['tick_size'], length=sizer['tick_length'], color=styler['tick_color'], labelcolor=styler['tick_label_color']) # configuration: ax.set_xlim(xlim) ax.set_xticks(xticks) if xaxis_type == 'hours': ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) elif xaxis_type == 'datetime' and last_day: ax.xaxis.set_major_formatter(DateFormatter('%d-%m %H:%M')) else: ax.xaxis.set_major_formatter(DateFormatter('%d-%m')) if curr_col_ind == 0: ax.set_ylabel(ylabel, size=sizer['label_size'], color=styler['label_color']) ax.set_ylim(ylim) ax.set_yticks(yticks) for spine in ['top', 'bottom', 'left', 'right']: ax.spines[spine].set_linewidth(sizer['spine_width']) ax.spines[spine].set_color(styler['spine_color']) plt.setp(ax.get_xticklabels(), rotation=sizer['tick_rotation'], ha='right') if yticks[-1] == 1: ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) else: ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) def executor_gradients( self, df, ax, max_col_ind, curr_col_ind, max_row_ind, curr_row_ind, direction, sizer, styler, xscale, comsol_model, data_type): hot_end_temp = None cold_end_temp = None max_date = df.index.max() min_date = df.index.min() for timestamp in self.timestamps: if min_date <= timestamp[0] <= max_date: if data_type == 'temperature': # Get hot end temperature value (single value) as ndarray: hot_end_temp = [ self.calculate_mean(df, timestamp[0], self.sample['hot_end_sensors']['sensors']).mean()] # Get sensor temperature values (multiple values) as ndarray: sensors_temps = self.calculate_mean(df, timestamp[0], direction['sensors']).values.tolist() # Get cold end temperature value as pandas Series: cold_end_temp = [ self.calculate_mean(df, timestamp[0], self.sample['cold_end_sensors']['sensors']).mean()] power = self.calculate_mean(df, timestamp[0], 'power') # Concatenated temperatures into single ndarray. grad_values = hot_end_temp + sensors_temps + cold_end_temp # Get sensor locations and add wall and core locs: sensor_loc = direction['locations'].copy() sensor_loc.insert(0, self.sample['hot_end_sensors']['locations'][0]) sensor_loc.append(self.sample['cold_end_sensors']['locations'][0]) label = timestamp[1] elif data_type == 'moisture': if len(direction['sensors']) != 0: grad_values = self.calculate_mean(df, timestamp[0], direction['sensors']) sensor_loc = direction['locations'].copy() label = timestamp[1] else: grad_values = [] sensor_loc = [] label = '' else: grad_values = 0 sensor_loc = 0 label = 0 # plot data: ax.plot( sensor_loc, grad_values, label=label, linestyle='solid', lw=sizer['line_width'], marker='o', ms=sizer['marker_size'], mew=sizer['marker_edge_width'], mfc=sizer['marker_face_color']) # data type configuration: if data_type == 'temperature': yticks, ylim = self.generate_yaxis_ticks_temp_gradient(hot_end_temp, cold_end_temp) ylabel = 'Temperature, °C' elif data_type == 'moisture': yticks = [450, 500, 550] ylim = [450, 550] ylabel = 'Moisture, mV' else: yticks = 0 ylim = 0 ylabel = 0 # styler: ax.set_facecolor(styler['axis_facecolor']) # configuration: legend = ax.legend( loc='upper right', fontsize=sizer['legend_size'], handlelength=sizer['legend_handlelength'], labelcolor=styler['legend_text_color'], edgecolor=styler['legend_edge_color']) legend.get_frame().set_linewidth(sizer['legend_frame_width']) legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor(styler['legend_face_color_rgba']) if curr_row_ind == max_row_ind: ax.set_xlabel( 'Distance from core, cm', size=sizer['label_size'], color=styler['label_color'], labelpad=sizer['labelpad']) if curr_col_ind == 0: ax.set_ylabel(ylabel, size=sizer['label_size'], color=styler['label_color']) if xscale == 'log': ax.set_xscale(xscale) ax.set_xlim([0.1, 27]) else: # this means xscale=='linear' ax.set_xlim([-1, 27]) ax.set_ylim(ylim) ax.set_yticks(yticks) ax.tick_params( axis='both', direction='in', width=sizer['tick_width'], right=True, top=True, labelsize=sizer['tick_size'], length=sizer['tick_length'], color=styler['tick_color'], labelcolor=styler['tick_label_color']) for spine in ['top', 'bottom', 'left', 'right']: ax.spines[spine].set_linewidth(sizer['spine_width']) ax.spines[spine].set_color(styler['spine_color']) ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) # comsol model data: if comsol_model: model = ComsolModel(self.comsol_path) for model in model.comsol_models_dfs: ax.plot( model['loc'], model['temp'], lw=sizer['line_width'], linestyle='--', color='dimgrey') ''' # theoretical model fit: if data_type == 'temperature': temp_dist = self.zone_solver.two_zone_solver(self.kdry, self.kmoist, float(wall_temp), float(core_temp), power) ''' @staticmethod def calculate_mean(df, timestamp, sensors): """ The function returns mean values of given columns. Returned value is Pandas Series with one or multiple values. """ end_time = timestamp time_delta = pd.Timedelta(30, unit='m') start_time = end_time - time_delta mask = (df.index >= start_time) & (df.index <= end_time) mean_values = df[mask][sensors].mean() return mean_values @staticmethod def step_size_ticks(range_diff): if 0 < range_diff <= 1: step = 0.2 elif 1 < range_diff <= 10: step = 1 elif 10 < range_diff <= 20: step = 2 elif 20 < range_diff <= 50: step = 5 elif 50 < range_diff <= 100: step = 10 elif 100 < range_diff <= 200: step = 20 elif 200 < range_diff <= 500: step = 50 else: step = None return step @staticmethod def generate_xaxis_ticks_datetime(df, last_day): """ This function return xlim and xticks for datetime plots: If last_day==True, then the function return date_range of every second hour. If last_day==False, function returns date_range based on the total length of the dataframe. """ def round_down_day(t): return t.replace(microsecond=0, second=0, minute=0, hour=0) def round_up_day(t): one_day = pd.Timedelta(days=1) t.replace(microsecond=0, second=0, minute=0, hour=0) t += one_day return t def round_hour_down(t): return t.replace(microsecond=0, second=0, minute=0) def round_hour_up(t): if t.hour == 23: return t.replace(microsecond=0, second=0, minute=0, hour=0, day=t.day + 1) else: return t.replace(microsecond=0, second=0, minute=0, hour=t.hour + 1) def roundup_periods(hours, period): return int(ceil(hours / period)) if last_day: start_time = round_hour_down(df.index[0]) end_time = round_hour_up(df.index[-1]) periods = 13 freq = '2H' else: start_time = round_down_day(df.index[0]) end_time = round_up_day(df.index[-1]) diff = end_time - start_time total_hours = diff.days * 24 + diff.seconds / 3600 if total_hours <= 144: # up to 6 days period = 6 freq = '6H' elif 144 < total_hours <= 432: # from 6 to 18 days period = 12 freq = '12H' elif 432 < total_hours <= 864: # from 18 to 36 days period = 24 freq = '24H' else: # more than 36 days period = 48 freq = '48H' periods = roundup_periods(total_hours, period) periods += 1 xticks = pd.date_range(start=start_time, periods=periods, freq=freq) xlim = [start_time, end_time] return xticks, xlim @staticmethod def generate_xaxis_ticks_hours(df): """ This function returns: - x axis values to plot - labels for x axis """ max_hour = df['hours'][-1] min_hour = df['hours'][0] total_hours = (max_hour - min_hour) def roundup_hours(max_hour, period): return int(ceil(max_hour / period) * period) def rounddown_hours(min_hour, period): return int(floor(min_hour / period) * period) if total_hours <= 72: period = 6 max_hour = roundup_hours(max_hour, period) min_hour = rounddown_hours(min_hour, period) elif 72 < total_hours <= 144: period = 12 max_hour = roundup_hours(max_hour, period) min_hour = rounddown_hours(min_hour, period) elif 144 < total_hours <= 288: period = 24 max_hour = roundup_hours(max_hour, period) min_hour = rounddown_hours(min_hour, period) else: period = 48 max_hour = roundup_hours(max_hour, period) min_hour = rounddown_hours(min_hour, period) xticks = np.arange(min_hour, max_hour + period, period) offset = (max_hour - min_hour) * 0.02 xlim = [xticks[0] - offset, xticks[-1] + offset] return xticks, xlim def generate_yaxis_ticks_temp_series(self, df, sensors: List): """ The function generate yticks and ylim values based on temperature, moisture or power column(s) Step size is determined based on the range (max - min): range 0 - 1: 0.2 range 1 - 10: 1 range 10 - 20: 2 range 20 - 50: 5 range 50 - 100: 10 range 100 - 200: 20 range 200 - 500: 50 :param df: active dataframe (master or phase) :param sensors: list with one or multiple entry :return: yticks and ylim """ max_val = np.nanmax(df[sensors]) min_val = np.nanmin(df[sensors]) step = self.step_size_ticks(max_val - min_val) def roundup_max(val): return int(ceil(val / step) * step) def rounddown_min(val): return int(floor(val / step) * step) max_val = roundup_max(max_val) min_val = rounddown_min(min_val) offset = (max_val - min_val) * 0.03 ylim = [min_val - offset, max_val + offset] yticks = np.arange(min_val, max_val + step, step) return yticks, ylim @staticmethod def generate_yaxis_ticks_temp_gradient(hot_end_temp: List, cold_end_temp: List): """ The function generates yticks and ylim for temperature gradient plot. The maximum and minimum values are derived from the cold and hot end temperatures. """ max_val = np.nanmax(hot_end_temp) min_val = np.nanmin(cold_end_temp) def roundup_max(val): return int(ceil(val / 10) * 10) def rounddown_min(val): return int(floor(val / 10) * 10) max_val = roundup_max(max_val) min_val = rounddown_min(min_val) offset = max_val * 0.03 ylim = [min_val - offset, max_val + offset] yticks = np.arange(min_val, max_val + 10, 10) return yticks, ylim <file_sep>class HydraulicTestControl: def __init__(self, test_data): self.test_data = test_data class RetentionTestControl: def __init__(self, test_data): self.test_data = test_data class ThermalTestControl: def __init__(self, test_data): self.test_data = test_data class DrainageTestControl: def __init__(self, test_data): self.test_data = test_data class GradationTestControl: def __init__(self, test_data): self.test_data = test_data <file_sep>class SampleDataWaterRetention: def __init__(self): self.WR1 = {'sample_name': 'WR1'} self.WR2 = {'sample_name': 'WR2'} self.WR3 = {'sample_name': 'WR3'} self.WR4 = {'sample_name': 'WR4'} self.WR5 = {'sample_name': 'WR5'} self.WR6 = {'sample_name': 'WR6'} self.WR7 = {'sample_name': 'WR7'} self.WR8 = {'sample_name': 'WR8'} self.WR9 = {'sample_name': 'WR9'} self.WR10 = {'sample_name': 'WR10'} self.samples = [self.WR1, self.WR2, self.WR3, self.WR4, self.WR5, self.WR6, self.WR7, self.WR8, self.WR9, self.WR10] <file_sep>import pandas as pd class SampleDataLarge: def __init__(self): self.test_info = {'test_name': 'LargeMoistureCell', 'sample_dir': 'C:\\Users\\karlisr\\OneDrive - NTNU\\3_PostDoc_Sintef\\' '01_laboratory_work\\01_large_test\\01_measured_samples'} self.fignames = {'time series temp - up': 'time_series_temp_up', 'time series temp - right': 'time_series_temp_right', 'time series temp - down': 'time_series_temp_down', 'time series moist - up': 'time_series_moist_up', 'time series moist - right': 'time_series_moist_right', 'time series moist - down': 'time_series_moist_down', 'gradient temp - up': 'gradient_temp_up', 'gradient temp - right': 'gradient_temp_right', 'gradient temp - down': 'gradient_temp_down', 'gradient moist - up': 'gradient_moist_up', 'gradient moist - right': 'gradient_moist_right', 'gradient moist - down': 'gradient_moist_down', 'time series temp': 'time_series_temp', 'gradient temp': 'gradient_temp', 'time series moist': 'time_series_moisture', 'gradient moist': 'gradient_moisture', 'moist vs temp': 'moist_vs_temp', 'moist vs temp - up': 'moist_vs_temp_up', 'moist vs temp - right': 'moist_vs_temp_right', 'moist vs temp - down': 'moist_vs_temp_down', 'hot end temp': 'hot_end_temp'} self.folders = {'01_combined_plots': '01_combined_plots', '02_time_series_temperature': '02_time_series_temperature', '03_time_series_moisture': '03_time_series_moisture', '04_gradient_temperature': '04_gradient_temperature', '05_gradient_moisture': '05_gradient_moisture', '06_last_24_hours': '06_last_24_hours', '07_animated_plots': '07_animated_plots', '08_time_series_moisture_vs_temperature': '08_time_series_moisture_vs_temperature', '09_tracking_individual_sensors': '09_tracking_individual_sensors'} self.plot_folders = [self.folders['01_combined_plots'], self.folders['02_time_series_temperature'], self.folders['03_time_series_moisture'], self.folders['04_gradient_temperature'], self.folders['05_gradient_moisture'], self.folders['06_last_24_hours'], self.folders['07_animated_plots'], self.folders['08_time_series_moisture_vs_temperature'], self.folders['09_tracking_individual_sensors']] self.temp_directions = ['temp_up', 'temp_right', 'temp_down'] self.moist_directions = ['moist_up', 'moist_right', 'moist_down'] self.SN0 = {'sample_name': 'SN0', 'columns': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X3', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power'], 'temperature_columns_main': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'temperature_columns_moist': ['U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4'], 'temperature_columns_ext': ['X1', 'X2', 'X3', 'K1', 'K2', 'K3'], 'moisture_columns': ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'], 'power_column': ['power'], 'timestamps': [[pd.Timestamp(2021, 4, 4, 17, 00), '50W power'], [pd.Timestamp(2021, 4, 7, 11, 00), '70W power'], [pd.Timestamp(2021, 4, 12, 9, 00), '90W power']], 'phases': [{'start': 'timestamp', 'end': 'timestamp', 'name': '50W_core'}, {'start': 'timestamp', 'end': 'timestamp', 'name': '70W_core'}], 'core_sensors': {'sensors': ['C1', 'C2'], 'locations': [0, 26]}, 'wall_sensors': {'sensors': ['W1', 'W2'], 'locations': [0, 26]}, 'sensors': {'temp_up': {'sensors': ['U3', 'U5', 'U7', 'U8', 'U9', 'U10'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D3', 'D5', 'D7', 'D8', 'D9', 'D10'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': [], 'locations': [], 'direction_name': ''}, 'moist_right': {'sensors': [], 'locations': [], 'direction_name': ''}, 'moist_down': {'sensors': [], 'locations': [], 'direction_name': ''}}, 'other_sensors': [['Core at 5cm', 'U1'], ['Core at 5cm', 'U2'], ['Wall at 5cm', 'U4'], ['Core at 25cm', 'U6'], ['Core at 25cm', 'D1'], ['Core at 65cm', 'D2'], ['Core at 65cm', 'D4'], ['Core at 85cm', 'D6'], ['Cable', 'X1']], 'del_data': [], 'comsol_files': [], 'sample_props': {'porosity': 0.4, # this is dummy data 'ks': 2.66, # this is dummy data 'rhos': 3.02, # this is dummy data 'w_grav': 3.0}} # this is dummy data self.SN1 = {'sample_name': 'SN1', 'timestamps': [[pd.Timestamp(2020, 10, 30, 15, 40), '30 degC core'], [pd.Timestamp(2020, 10, 31, 17, 10), '40 degC core'], [pd.Timestamp(2020, 11, 1, 15, 10), '45 degC core'], [pd.Timestamp(2020, 11, 2, 7, 50), '50 degC core'], [pd.Timestamp(2020, 11, 3, 20, 20), '20 degC core'], [pd.Timestamp(2020, 11, 4, 10, 10), '50 degC core'], [pd.Timestamp(2020, 11, 7, 15, 10), '60 degC core']], 'phases': [{'start': 'timestamp', 'end': 'timestamp', 'name': 'name'}, {'start': 'timestamp', 'end': 'timestamp', 'name': 'name'}, {'start': 'timestamp', 'end': 'timestamp', 'name': 'name'}, {'start': 'timestamp', 'end': 'timestamp', 'name': 'name'}, {'start': 'timestamp', 'end': 'timestamp', 'name': 'name'}], 'sensors': {'temp_up': {'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up'}, 'moist_right': {'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right'}, 'moist_down': {'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down'}}, 'core_sensors': {'sensors': ['X1', 'X2'], 'locations': [0, 26]}, 'wall_sensors': {'sensors': ['K1', 'K2', 'K3'], 'locations': [0, 26]}, 'del_data': [], 'comsol_files': ['comsol_model_288W.csv']} self.SN2 = {'sample_name': 'SN2', 'columns': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'X1', 'X2', 'X3', 'K1', 'K2', 'K3', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power'], 'temperature_columns_main': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'temperature_columns_moist': ['U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4'], 'temperature_columns_ext': ['X1', 'X2', 'X3', 'K1', 'K2', 'K3'], 'moisture_columns': ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'], 'power_column': ['power'], 'timestamps': [[pd.Timestamp(2021, 1, 19, 14, 33), '154W core'], [pd.Timestamp(2021, 1, 26, 14, 5), '174W core'], [pd.Timestamp(2021, 2, 1, 10, 29), '194W core'], [pd.Timestamp(2021, 2, 6, 9, 17), '214W core'], [pd.Timestamp(2021, 2, 23, 13, 7), '288W core']], 'phases': [{'start': pd.Timestamp(2021, 1, 14, 9, 56), 'end': pd.Timestamp(2021, 1, 19, 14, 33), 'name': '154W_core'}, {'start': pd.Timestamp(2021, 1, 19, 14, 34), 'end': pd.Timestamp(2021, 1, 26, 14, 5), 'name': '174W_core'}, {'start': pd.Timestamp(2021, 1, 26, 14, 6), 'end': pd.Timestamp(2021, 2, 1, 10, 29), 'name': '196W_core'}, {'start': pd.Timestamp(2021, 2, 1, 10, 30), 'end': pd.Timestamp(2021, 2, 6, 9, 17), 'name': '217W_core'}, {'start': pd.Timestamp(2021, 2, 6, 9, 18), 'end': pd.Timestamp(2021, 2, 23, 13, 7), 'name': '290W_core'}], 'hot_end_sensors': {'sensors': ['X1', 'X2'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['K2', 'X3'], 'locations': [26]}, 'sensors': {'temp_up': {'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U1', 'U2', 'U3', 'U4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up'}, 'moist_right': {'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right'}, 'moist_down': {'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D1', 'D2', 'D3', 'D4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down'}}, 'other_sensors': [], 'failed_sensors': [], 'del_data': [{'sensor': 'R1', 'start': pd.Timestamp(2021, 2, 6, 12, 40), 'end': pd.Timestamp(2021, 2, 8, 17, 40)}], 'comsol_files': ['comsol_model_288W.csv'], 'sample_props': {'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0}} self.SN3 = {'sample_name': 'SN3', 'columns': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power'], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2'], 'temperature_columns_main': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'temperature_columns_moist': ['U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4'], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'], 'power_column': ['power'], 'phase_names': ['170W'], 'hot_end_sensors': {'sensors': ['C1', 'C2'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['W1', 'W2'], 'locations': [26]}, 'sensors': {'temp_up': {'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up'}, 'moist_right': {'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right'}, 'moist_down': {'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down'}}, 'other_sensors': [], 'failed_sensors': ['M5'], 'del_data': [], 'comsol_files': [], 'sample_props': {'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0}} self.SN4 = {'sample_name': 'SN4', 'columns': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power'], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2'], 'temperature_columns_main': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'temperature_columns_moist': ['U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4'], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'], 'power_column': ['power'], 'phase_names': ['230W_core', '320W_core'], 'hot_end_sensors': {'sensors': ['C1', 'C2'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['W1', 'W2'], 'locations': [26]}, 'sensors': {'temp_up': {'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up'}, 'moist_right': {'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right'}, 'moist_down': {'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down'}}, 'other_sensors': [], 'failed_sensors': [], 'del_data': [], 'comsol_files': [], 'sample_props': {'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0}} self.SN5 = {'sample_name': 'SN5', 'columns': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power'], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2'], 'temperature_columns_main': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6'], 'temperature_columns_moist': ['U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4'], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'], 'power_column': ['power'], 'phase_names': ['230W_core'], 'hot_end_sensors': {'sensors': ['C1', 'C2'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['W1', 'W2'], 'locations': [26]}, 'sensors': {'temp_up': {'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up'}, 'temp_right': {'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right'}, 'temp_down': {'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down'}, 'moist_up': {'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up'}, 'moist_right': {'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right'}, 'moist_down': {'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down'}}, 'other_sensors': [], 'failed_sensors': [], 'del_data': [], 'comsol_files': [], 'sample_props': {'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0}} self.SN6 = { 'sample_name': 'SN6', 'columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power' ], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2', ], 'temperature_columns_main': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', ], 'temperature_columns_moist': [ 'U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4', ], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': [ 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', ], 'power_column': ['power'], 'phase_names': ['170W_core'], 'hot_end_sensors': { 'sensors': ['C1', 'C2'], 'locations': [0.1], }, 'cold_end_sensors': { 'sensors': ['W1', 'W2'], 'locations': [26], }, 'sensors': { 'temp_up': { 'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up', }, 'temp_right': { 'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right', }, 'temp_down': { 'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down', }, 'moist_up': { 'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up', }, 'moist_right': { 'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right', }, 'moist_down': { 'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down', }, }, 'other_sensors': [], 'failed_sensors': [], 'del_data': [], 'comsol_files': [], 'sample_props': { 'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0 } } self.SN7 = { 'sample_name': 'SN7', 'columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power' ], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2', ], 'temperature_columns_main': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', ], 'temperature_columns_moist': [ 'U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4', ], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': [ 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', ], 'power_column': ['power'], 'phase_names': ['170W_core'], 'hot_end_sensors': { 'sensors': ['C1', 'C2'], 'locations': [0.1], }, 'cold_end_sensors': { 'sensors': ['W1', 'W2'], 'locations': [26], }, 'sensors': { 'temp_up': { 'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up', }, 'temp_right': { 'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right', }, 'temp_down': { 'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down', }, 'moist_up': { 'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up', }, 'moist_right': { 'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right', }, 'moist_down': { 'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down', }, }, 'other_sensors': [], 'failed_sensors': [], 'del_data': [], 'comsol_files': [], 'sample_props': { 'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0 } } self.SN8 = { 'sample_name': 'SN8', 'columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'U7', 'U8', 'U9', 'U10', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'C1', 'C2', 'W1', 'D7', 'D8', 'D9', 'D10', 'X1', 'W2', 'X2', 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', 'power' ], 'temperature_columns': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'C1', 'C2', 'W1', 'W2', 'X1', 'X2', ], 'temperature_columns_main': [ 'U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', ], 'temperature_columns_moist': [ 'U1', 'U2', 'U3', 'U4', 'R1', 'R2', 'R3', 'R4', 'D1', 'D2', 'D3', 'D4', ], 'temperature_columns_ext': ['C1', 'C2', 'X1', 'X2', 'W1', 'W2'], 'moisture_columns': [ 'MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12', ], 'power_column': ['power'], 'phase_names': ['100W_core'], 'hot_end_sensors': { 'sensors': ['C1', 'C2'], 'locations': [0.1], }, 'cold_end_sensors': { 'sensors': ['W1', 'W2'], 'locations': [26], }, 'sensors': { 'temp_up': { 'sensors': ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - up', }, 'temp_right': { 'sensors': ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'], 'locations': [4, 8, 12, 16, 20, 24], 'direction_name': 'Direction - right', }, 'temp_down': { 'sensors': ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], 'locations': [1.3, 2.7, 4, 6, 8, 10, 12, 16, 20, 24], 'direction_name': 'Direction - down', }, 'moist_up': { 'sensors': ['MS1', 'MS2', 'MS3', 'MS4'], 'temp_sensors': ['U3', 'U5', 'U7', 'U8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - up', }, 'moist_right': { 'sensors': ['MS5', 'MS6', 'MS7', 'MS8'], 'temp_sensors': ['R1', 'R2', 'R3', 'R4'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - right', }, 'moist_down': { 'sensors': ['MS9', 'MS10', 'MS11', 'MS12'], 'temp_sensors': ['D3', 'D5', 'D7', 'D8'], 'locations': [4, 8, 12, 16], 'direction_name': 'Direction - down', }, }, 'other_sensors': [], 'failed_sensors': [], 'del_data': [], 'comsol_files': [], 'sample_props': { 'porosity': 0.4, 'ks': 2.66, 'rhos': 3.02, 'w_grav': 3.0 } } self.SN9 = {'sample_name': 'SN9'} self.SN10 = {'sample_name': 'SN10'} self.samples = [ self.SN3, self.SN4, self.SN5, self.SN6, self.SN7, self.SN8, #self.SN9, #self.SN10, ] <file_sep>class SampleDataWaterDrainage: def __init__(self): self.WD1 = {'sample_name': 'WD1'} self.WD2 = {'sample_name': 'WD2'} self.WD3 = {'sample_name': 'WD3'} self.WD4 = {'sample_name': 'WD4'} self.WD5 = {'sample_name': 'WD5'} self.WD6 = {'sample_name': 'WD6'} self.WD7 = {'sample_name': 'WD7'} self.WD8 = {'sample_name': 'WD8'} self.WD9 = {'sample_name': 'WD9'} self.WD10 = {'sample_name': 'WD10'} self.samples = [self.WD1, self.WD2, self.WD3, self.WD4, self.WD5, self.WD6, self.WD7, self.WD8, self.WD9, self.WD10]<file_sep>import pandas as pd class SensorCorrection: """ ms - moisture sensor calibration factors ts - temperature sensor calibration factors """ def __init__(self, path): self.ms = pd.read_excel(path + 'moisture_sensor_calibration_factors.xlsx', sheet_name='Sheet1', index_col=0) self.ts = pd.read_excel(path + 'temperature_sensor_calibration_factors.xlsx', sheet_name='Sheet1', index_col=0) def moisture_sensor_correction(self, TS, MS, read_temp, read_vol): """ V1L - low moisture, low temperature V1H - low moisture, high temperature V2L - high moisture, low temperature V2H - high moisture, high temperature """ sensor = self.ms.loc[MS] pos = (read_temp - sensor['T1']) / (sensor['T2'] - sensor['T1']) VxL = sensor['V1L'] + (sensor['V1H'] - sensor['V1L']) * pos VxH = sensor['V2L'] + (sensor['V2H'] - sensor['V2L']) * pos slope = (sensor['wH%'] - sensor['wL%']) / (VxH - VxL) w_grav = slope * (read_vol - VxH) + sensor['wH%'] return w_grav def tempertaure_sensor_correction(self, TS, mes_val): sensor = self.ts.loc[TS] temp = sensor['a'] * mes_val + sensor['b'] return temp <file_sep>import numpy as np import math from scipy.optimize import fsolve class TempDistSolver(): def __init__(self): self.ri = 0.036 self.ro = 0.30 def radial_one_zone(self, kmoist, tcold, thot): ri = 0.036 ro = 0.3 tdiff = thot - tcold step = 0.001 T_x = [] power = 2*math.pi*kmoist / math.log(ro/ri) * tdiff T_x = [] for x in np.arange(ri, ro+step, step): temp = thot - power / (2*math.pi*kmoist) * math.log(x / ri) T_x.append(temp) return T_x def radial_two_zones(self, dry_zone, kdry, kmoist, tcold, thot): ri = 0.036 ro = 0.3 rdry = ri + dry_zone tdiff = thot - tcold T_moist = [] T_dry = [] power = 2*math.pi*tdiff / (1/kdry*math.log(rdry/ri) + 1/kmoist*math.log(ro/rdry)) step = 0.001 # Dry zone temperature distribution for x in np.arange(ri, rdry+step, step): temp = thot - power / (2*math.pi*kdry) * math.log(x/ri) T_dry.append(temp) # Moist zone temperature distribution tdry_hot = T_dry[-1] for x in np.arange(rdry, ro+step, step): temp = tdry_hot - power / (2*math.pi*kmoist) * math.log(x/rdry) T_moist.append(temp) def two_zone_solver(self, kdry, kmoist, tcold, thot, power): tdiff = thot - tcold print(type(power)) def min_max_temp_checker(k, power, tcold, ro, ri): res = math.log(ro/ri) / 2*math.pi*k thot = power * res + tcold return thot # Step 0: check if max and min are within the limits thot_max_temp = min_max_temp_checker(kdry, power, tcold, self.ro, self.ri) thot_min_temp = min_max_temp_checker(kmoist, power, tcold, self.ro, self.ri) print(f'thot max is {thot_max_temp}') print(f'thot is {thot}') print(f'thot min is {thot_min_temp}') if thot < thot_min_temp or thot > thot_max_temp: print('Hot side temperature is not in range!') # Step 1: find radius of the dry zone def func(rdry): f = 2*math.pi*tdiff / (math.log(rdry/self.ri)/kdry + math.log(self.ro/rdry)/kmoist) - power return f rdry = float(fsolve(func, np.array(self.ri))[0]) # Step 2: Generate temperature dry zone step = 0.001 T_dry = [] for x in np.arange(self.ri, rdry+step, step): temp = thot - power / (2*math.pi*kdry) * math.log(x/self.ri) T_dry.append(temp) # Step 3: Generate temperature moist zone T_moist = [] tdry_hot = T_dry[-1] for x in np.arange(rdry, self.ro+step, step): # Insted of step size put step count somehow temp = tdry_hot - power / (2*math.pi*kmoist) * math.log(x/rdry) T_moist.append(temp) return T_dry + T_moist def onedim_one_zone(self): pass def onedim_two_zones(self): pass class ThermalConductivity: def __init__(self, porosity, ks, rhos, w_grav): self.porosity = porosity self.ks = ks self.rhos = rhos self.w_grav = w_grav def calculate_thermal_conductivity(self): kdry = 0 kmoist = 0 rhod = (1 - self.porosity) * self.rhos Sr = (self.w_grav/100*rhod)/self.porosity ksat = self.ks**(1-self.porosity)*0.6**(self.porosity) kdry = self.ks**((1-self.porosity)**0.59)*0.024**(self.porosity**0.73) kr = (4.7*Sr)/(1+3.7*Sr) kmoist = (ksat - kdry) * kr + kdry #print(kmoist) #print(kdry) return kdry, kmoist porosity = 0.424 ks = 2.66 rhos = 3.02 w_grav = 3 thermal = ThermalConductivity(porosity, ks, rhos, w_grav) thermal.calculate_thermal_conductivity()<file_sep>import matplotlib.pyplot as plt import pandas as pd class PlotCalibrationFigures: def __init__(self, data_path, sample): self.sample = sample self.calib_data = pd.read_excel(data_path + 'moisture_sensor_calibration_data.xlsx', sheet_name='Sheet2') self.calib_data_from_testing = pd.read_excel(data_path + 'moitsure_sensor_calibration_data_during_testing.xlsx', sheet_name='Sheet1') self.sensor_names = ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'] self.temp_names = ['30degC', '40degC', '50degC', '60degC', '70degC'] def plot_calibration_figure(self): nrows = 4 ncols = 3 fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(20, 20)) fig.subplots_adjust(hspace=0.3) sensor_counter = 0 for row in range(nrows): for column in range(ncols): subset = self.calib_data[self.calib_data['sensor'] == self.sensor_names[sensor_counter]] for temp in self.temp_names: subsubset = subset[subset['temp'] == temp] ax[row, column].plot(subsubset['vol'], subsubset['w%'], label=temp, marker='o') ax[row, column].plot(self.calib_data_from_testing[self.sensor_names[sensor_counter]], self.calib_data_from_testing['w%'], linestyle='none', marker='o', mec='black') ax[row, column].set_xlabel('Voltage, mV') ax[row, column].set_ylabel('Moisture, %') ax[row, column].set_title(self.sensor_names[sensor_counter]) ax[row, column].legend() #ax[row, column].set_xlim([450, 570]) sensor_counter += 1 plt.savefig('moisture_figure.png', dpi=300) plt.show()<file_sep>class SampleDataParticleGradation: def __init__(self): self.PG1 = {'sample_name': 'PG1'} self.PG2 = {'sample_name': 'PG2'} self.PG3 = {'sample_name': 'PG3'} self.PG4 = {'sample_name': 'PG4'} self.PG5 = {'sample_name': 'PG5'} self.PG6 = {'sample_name': 'PG6'} self.PG7 = {'sample_name': 'PG7'} self.PG8 = {'sample_name': 'PG8'} self.PG9 = {'sample_name': 'PG9'} self.PG10 = {'sample_name': 'PG10'} self.samples = [self.PG1, self.PG2, self.PG3, self.PG4, self.PG5, self.PG6, self.PG7, self.PG8, self.PG9, self.PG10]<file_sep> if 1 is True: print('yooo') else: print('nooo')<file_sep>import tkinter as tk from tkinter import ttk from app.StyleConfiguration import StyleConfiguration from typing import List from modules.FigureFormatting import FigureFormatting from modules.DataProcessor import DataProcessor from modules.DirectoryGenerator import DirectoryGenerator from modules.PlotMeasurementFigures import PlotMeasurementFigures from sample_data.SampleDataSmall import SampleDataSmall from sample_data.SampleDataLarge import SampleDataLarge from sample_data.SampleDataHydraulicConductivity import SampleDataHydraulicConductivity from sample_data.SampleDataWaterRetention import SampleDataWaterRetention from sample_data.SampleDataThermalConductivity import SampleDataThermalConductivity from sample_data.SampleDataWaterDrainage import SampleDataWaterDrainage from sample_data.SampleDataParticleGradation import SampleDataParticleGradation try: from ctypes import windll windll.shcore.SetProcessDpiAwareness(1) except: pass # new message class MainApp(tk.Tk): def __init__(self): """ # notation: # SN - refers to the large test # SS - refers to the small test # FRAME LAYOUT: # self.main_frame (top) # self.test_setup_plot_options_frame (top) # self.test_setup_sample_frame (left) # self.test_setup_frame (top) # self.sample_frame (top) # self.plot_options_frame (left) # self.plot_control_container_frame # self.LargeTestPlotControl (class frame, grid) # SN_master_controller_frame (top) # SN_combined_separate_plots_frame (top) # SN_combined_plots_frame (left) # SN_combined_plots_frame (left) # SN_last_24h_plots_frame (top) # self.SmallTestPlotControl (class frame, grid) """ super().__init__() self.title('Plot figures') # Sample data: self.large_test_data = SampleDataLarge() self.large_sample_names = [sample['sample_name'] for sample in self.large_test_data.samples] self.small_test_data = SampleDataSmall() self.small_sample_names = [sample['sample_name'] for sample in self.small_test_data.samples] self.hydraulic_sample_data = SampleDataHydraulicConductivity() self.hydraulic_samples = [sample['sample_name'] for sample in self.hydraulic_sample_data.samples] self.retention_sample_data = SampleDataWaterRetention() self.retention_samples = [sample['sample_name'] for sample in self.retention_sample_data.samples] self.thermal_sample_data = SampleDataThermalConductivity() self.thermal_samples = [sample['sample_name'] for sample in self.thermal_sample_data.samples] self.drainage_sample_data = SampleDataWaterDrainage() self.drainage_samples = [sample['sample_name'] for sample in self.drainage_sample_data.samples] self.gradation_sample_data = SampleDataParticleGradation() self.gradation_samples = [sample['sample_name'] for sample in self.gradation_sample_data.samples] # Initiating module objects: self.formatter = FigureFormatting() self.data_processor = DataProcessor( self.large_test_data, self.small_test_data) self.plotter = PlotMeasurementFigures() self.directory_generator = DirectoryGenerator() self.active_test = self.large_test_data # Place holders: self.df = None self.dfs = None # Adding main frame: self.main_frame = ttk.Frame(self, style='Standard.TFrame', padding=10) self.main_frame.grid(row=0, column=0) # Adding section frames: self.test_setup_plot_options_frame = ttk.Frame(self.main_frame, style='Standard.TFrame') self.test_setup_plot_options_frame.pack(side='top', fill='x') self.test_setup_sample_frame = ttk.Frame(self.test_setup_plot_options_frame, style='Standard.TFrame') self.test_setup_sample_frame.pack(side='left', fill='both') self.plot_options_frame = ttk.Frame(self.test_setup_plot_options_frame, style='Standard.TFrame') self.plot_options_frame.pack(side='left', fill='both', expand=True, padx=(10, 0)) self.plot_control_container_frame = ttk.Frame(self.main_frame, style='Standard.TFrame') self.plot_control_container_frame.pack(side='top', fill='both', expand=True) # check if fill='both' necessary self.plot_control_container_frame.rowconfigure(0, weight=1) self.plot_control_container_frame.columnconfigure(0, weight=1) self.frame_pages = dict() for page_class in [LargeTestPlotControl, SmallTestPlotControl, HydraulicConductivityPlotControl, WaterRetentionPlotControl, ThermalConductivityPlotControl, WaterDrainagePlotControl, ParticleGradationPlotControl]: page = page_class(self.plot_control_container_frame, self) self.frame_pages[page_class] = page page.grid(row=0, column=0, sticky='nsew') frame = self.frame_pages[LargeTestPlotControl] frame.tkraise() # Test setup section widgets: self.test_setup_frame = ttk.Frame(self.test_setup_sample_frame, style='Standard.TFrame') self.test_setup_frame.pack(side='top', fill='x') self.test_setup_label_frame = ttk.Frame(self.test_setup_frame, style='DarkFrame.TFrame') self.test_setup_label_frame.pack(side='top', fill='x') self.test_setup_label = ttk.Label( self.test_setup_label_frame, text='Test setup:', style='ExtraLargeLabel.TLabel', ) self.test_setup_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.test_type_var = tk.StringVar(value='large') self.large_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.large_test_radiobutton_frame.pack(side='top', fill='x') self.large_test_radiobutton = ttk.Radiobutton( self.large_test_radiobutton_frame, style='Standard.TRadiobutton', value='large', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.large_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.large_test_radiobutton_text = ttk.Label( self.large_test_radiobutton_frame, style='LeftAligned.TLabel', text='Large moisture transfer test', ) self.large_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.small_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.small_test_radiobutton_frame.pack(side='top', fill='x') self.small_test_radiobutton = ttk.Radiobutton( self.small_test_radiobutton_frame, style='Standard.TRadiobutton', value='small', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.small_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.small_test_radiobutton_text = ttk.Label( self.small_test_radiobutton_frame, style='LeftAligned.TLabel', text='Small moisture transfer test', ) self.small_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.hydraulic_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.hydraulic_test_radiobutton_frame.pack(side='top', fill='x') self.hydraulic_test_radiobutton = ttk.Radiobutton( self.hydraulic_test_radiobutton_frame, style='Standard.TRadiobutton', value='hydraulic', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.hydraulic_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.hydraulic_test_radiobutton_text = ttk.Label( self.hydraulic_test_radiobutton_frame, style='LeftAligned.TLabel', text='Hydraulic conductivity test', ) self.hydraulic_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.retention_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.retention_test_radiobutton_frame.pack(side='top', fill='x') self.retention_test_radiobutton = ttk.Radiobutton( self.retention_test_radiobutton_frame, style='Standard.TRadiobutton', value='retention', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.retention_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.retention_test_radiobutton_text = ttk.Label( self.retention_test_radiobutton_frame, style='LeftAligned.TLabel', text='Water retention test', ) self.retention_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.thermal_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.thermal_test_radiobutton_frame.pack(side='top', fill='x') self.thermal_test_radiobutton = ttk.Radiobutton( self.thermal_test_radiobutton_frame, style='Standard.TRadiobutton', value='thermal', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.thermal_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.thermal_test_radiobutton_text = ttk.Label( self.thermal_test_radiobutton_frame, style='LeftAligned.TLabel', text='Thermal conductivity test', ) self.thermal_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.drainage_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.drainage_test_radiobutton_frame.pack(side='top', fill='x') self.drainage_test_radiobutton = ttk.Radiobutton( self.drainage_test_radiobutton_frame, style='Standard.TRadiobutton', value='drainage', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.drainage_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.drainage_test_radiobutton_text = ttk.Label( self.drainage_test_radiobutton_frame, style='LeftAligned.TLabel', text='Water drainage test', ) self.drainage_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.gradation_test_radiobutton_frame = ttk.Frame(self.test_setup_frame, style='Standard.TFrame') self.gradation_test_radiobutton_frame.pack(side='top', fill='x') self.gradation_test_radiobutton = ttk.Radiobutton( self.gradation_test_radiobutton_frame, style='Standard.TRadiobutton', value='gradation', variable=self.test_type_var, takefocus=False, command=self.switch_frames, ) self.gradation_test_radiobutton.pack(side='left', pady=(10, 0), padx=(20, 0)) self.gradation_test_radiobutton_text = ttk.Label( self.gradation_test_radiobutton_frame, style='LeftAligned.TLabel', text='Particle gradation test', ) self.gradation_test_radiobutton_text.pack(side='left', padx=(5, 5), pady=(10, 0)) self.sample_frame = ttk.Frame(self.test_setup_sample_frame, style='Standard.TFrame') self.sample_frame.pack(side='top', fill='x', pady=(20, 0)) self.sample_label_frame = ttk.Frame(self.sample_frame, style='DarkFrame.TFrame') self.sample_label_frame.pack(side='top', fill='x') self.samples_label = ttk.Label( self.sample_label_frame, text='Samples:', style='ExtraLargeLabel.TLabel', ) self.samples_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.samples_combobox = ttk.Combobox( self.sample_frame, style='Standard.TCombobox', values=self.large_sample_names, state='readonly', ) self.samples_combobox.current(len(self.active_test.samples)-1) self.samples_combobox.pack(side='top', fill='x', padx=(10, 10), pady=(10, 0)) # Plot options section widgets: self.plot_options_label_frame = ttk.Frame(self.plot_options_frame, style='DarkFrame.TFrame') self.plot_options_label_frame.pack(side='top', fill='x') self.plot_options_label = ttk.Label( self.plot_options_label_frame, style='ExtraLargeLabel.TLabel', text='Options:', ) self.plot_options_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.file_update_option_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.file_update_option_frame.pack(side='top', fill='x', padx=(20, 10)) self.file_update_label = ttk.Label( self.file_update_option_frame, style='LeftAligned.TLabel', text='Update files:', ) self.file_update_label.pack(side='left', padx=(5, 0), pady=(10, 0)) self.file_update_button = ttk.Button( self.file_update_option_frame, style='Standard.TButton', text='update', width=6, takefocus=False, command=self.update_files, ) self.file_update_button.pack(side='left', padx=(10, 0), pady=(10, 0)) self.update_dfs_var = tk.IntVar() self.file_update_checkbox = ttk.Checkbutton( self.file_update_option_frame, style='Standard.TCheckbutton', variable=self.update_dfs_var) self.file_update_checkbox.pack(side='left', padx=(10, 0), pady=(10, 0)) self.comsol_option_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.comsol_option_frame.pack(side='top', fill='x', padx=(20, 10)) self.comsol_option_checkbox = ttk.Checkbutton(self.comsol_option_frame, style='Standard.TCheckbutton') self.comsol_option_checkbox.pack(side='left', padx=(5, 0), pady=(10, 0)) self.comsol_option_text = ttk.Label( self.comsol_option_frame, style='LeftAligned.TLabel', text='Comsol model', ) self.comsol_option_text.pack(side='left', padx=(5, 0), pady=(10, 0)) self.power_line_option_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.power_line_option_frame.pack(side='top', fill='x', padx=(20, 10)) self.power_line_option_checkbox = ttk.Checkbutton(self.power_line_option_frame, style='Standard.TCheckbutton') self.power_line_option_checkbox.pack(side='left', padx=(5, 0), pady=(10, 0)) self.power_line_option_text = ttk.Label( self.power_line_option_frame, style='LeftAligned.TLabel', text='Power line', ) self.power_line_option_text.pack(side='left', padx=(5, 0), pady=(10, 0)) self.xscale_option_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.xscale_option_frame.pack(side='top', fill='x', padx=(20, 10)) self.xscale_text_option = ttk.Label( self.xscale_option_frame, style='LeftAligned.TLabel', text='xscale:', ) self.xscale_text_option.grid(row=0, column=0, padx=(5, 0), pady=(10, 0)) self.xscale_var = tk.StringVar(value='linear') self.log_radiobutton = ttk.Radiobutton( self.xscale_option_frame, style='Standard.TRadiobutton', value='log', variable=self.xscale_var, takefocus=False ) self.log_radiobutton.grid(row=0, column=1, padx=(5, 0), pady=(10, 0)) self.log_text = ttk.Label( self.xscale_option_frame, style='LeftAligned.TLabel', text='log' ) self.log_text.grid(row=0, column=2, sticky='W', padx=(5, 0), pady=(10, 0)) self.linear_radiobutton = ttk.Radiobutton( self.xscale_option_frame, style='Standard.TRadiobutton', value='linear', variable=self.xscale_var, takefocus=False ) self.linear_radiobutton.grid(row=1, column=1, sticky='W', padx=(5, 0), pady=(5, 0)) self.linear_text = ttk.Label( self.xscale_option_frame, style='LeftAligned.TLabel', text='linear' ) self.linear_text.grid(row=1, column=2, padx=(5, 0), pady=(5, 0)) self.output_style_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.output_style_frame.pack(side='top', fill='x', padx=(20, 10)) self.output_style_text = ttk.Label( self.output_style_frame, style='LeftAligned.TLabel', text='output style:' ) self.output_style_text.grid(row=0, column=0, padx=(5, 0), pady=(10, 0)) self.sizer_var = tk.StringVar(value='paper') self.paper_radiobutton = ttk.Radiobutton( self.output_style_frame, style='Standard.TRadiobutton', value='paper', variable=self.sizer_var, takefocus=False ) self.paper_radiobutton.grid(row=0, column=1, padx=(5, 0), pady=(10, 0)) self.paper_text = ttk.Label( self.output_style_frame, style='LeftAligned.TLabel', text='paper' ) self.paper_text.grid(row=0, column=2, sticky='W', padx=(5, 0), pady=(10, 0)) self.presentation_radiobutton = ttk.Radiobutton( self.output_style_frame, style='Standard.TRadiobutton', value='presentation', variable=self.sizer_var, takefocus=False ) self.presentation_radiobutton.grid(row=1, column=1, sticky='W', padx=(5, 0), pady=(5, 0)) self.presentation_text = ttk.Label( self.output_style_frame, style='LeftAligned.TLabel', text='presentation' ) self.presentation_text.grid(row=1, column=2, padx=(5, 0), pady=(5, 0)) self.data_density_frame = ttk.Frame(self.plot_options_frame, style='Standard.TFrame') self.data_density_frame.pack(side='top', fill='x', padx=(20, 10)) self.data_density_text = ttk.Label( self.data_density_frame, style='LeftAligned.TLabel', text='data density:' ) self.data_density_text.grid(row=0, column=0, padx=(5, 0), pady=(10, 0)) self.data_density_var = tk.StringVar(value='1minute') self.one_minute_radiobutton = ttk.Radiobutton( self.data_density_frame, style='Standard.TRadiobutton', value='1minute', variable=self.data_density_var, takefocus=False ) self.one_minute_radiobutton.grid(row=0, column=1, padx=(5, 0), pady=(10, 0)) self.one_minute_text = ttk.Label( self.data_density_frame, style='LeftAligned.TLabel', text='measured (1 min)' ) self.one_minute_text.grid(row=0, column=2, sticky='W', padx=(5, 0), pady=(10, 0)) self.six_minute_radiobutton = ttk.Radiobutton( self.data_density_frame, style='Standard.TRadiobutton', value='6minute', variable=self.data_density_var, takefocus=False ) self.six_minute_radiobutton.grid(row=1, column=1, padx=(5, 0), pady=(10, 0)) self.six_minute_text = ttk.Label( self.data_density_frame, style='LeftAligned.TLabel', text='6-min averaged' ) self.six_minute_text.grid(row=1, column=2, sticky='W', padx=(5, 0), pady=(10, 0)) self.ten_minute_radiobutton = ttk.Radiobutton( self.data_density_frame, style='Standard.TRadiobutton', value='10minute', variable=self.data_density_var, takefocus=False ) self.ten_minute_radiobutton.grid(row=2, column=1, padx=(5, 0), pady=(10, 0)) self.ten_minute_text = ttk.Label( self.data_density_frame, style='LeftAligned.TLabel', text='10-min averaged' ) self.ten_minute_text.grid(row=2, column=2, sticky='W', padx=(5, 0), pady=(10, 0)) def switch_frames(self): if self.test_type_var.get() == 'large': self.active_test = self.large_test_data self.samples_combobox['values'] = self.large_sample_names self.samples_combobox.current(len(self.active_test.samples)-1) frame = self.frame_pages[LargeTestPlotControl] frame.tkraise() elif self.test_type_var.get() == 'small': self.active_test = self.small_test_data self.samples_combobox['values'] = self.small_sample_names self.samples_combobox.current(len(self.active_test.samples)-1) frame = self.frame_pages[SmallTestPlotControl] frame.tkraise() elif self.test_type_var.get() == 'hydraulic': self.active_test = self.hydraulic_sample_data self.samples_combobox['values'] = self.hydraulic_samples self.samples_combobox.current(0) frame = self.frame_pages[HydraulicConductivityPlotControl] frame.tkraise() elif self.test_type_var.get() == 'retention': self.active_test = self.retention_sample_data self.samples_combobox['values'] = self.retention_samples self.samples_combobox.current(0) frame = self.frame_pages[WaterRetentionPlotControl] frame.tkraise() elif self.test_type_var.get() == 'thermal': self.active_test = self.thermal_sample_data self.samples_combobox['values'] = self.thermal_samples self.samples_combobox.current(0) frame = self.frame_pages[ThermalConductivityPlotControl] frame.tkraise() elif self.test_type_var.get() == 'drainage': self.active_test = self.drainage_sample_data self.samples_combobox['values'] = self.drainage_samples self.samples_combobox.current(0) frame = self.frame_pages[WaterDrainagePlotControl] frame.tkraise() elif self.test_type_var.get() == 'gradation': self.active_test = self.gradation_sample_data self.samples_combobox['values'] = self.gradation_samples self.samples_combobox.current(0) frame = self.frame_pages[ParticleGradationPlotControl] frame.tkraise() def update_files(self): # Before updating, make sure that all samples have their folders generated. for test_data in [self.large_test_data, self.small_test_data]: for sample in test_data.samples: self.directory_generator.directory_generator(test_data, sample) # Get value form update override checkbox: if self.update_dfs_var.get() == 1: override_dfs = True else: override_dfs = False # Update data (pull data from OneDrive) self.data_processor.update_data() # Update dfs: executed only for sample with new data (tho teh check for data is done on all samples) self.data_processor.generate_corrected_dfs(override_dfs=override_dfs) def preprocessing_before_plotting(self, active_sample, phases): # Directory generator: phase_directories = self.directory_generator.directory_generator(self.active_test, active_sample) # Loading corrected dataframe: self.df = self.data_processor.load_corrected_df(active_sample, self.active_test) # Get phase datetimes: phase_datetimes = self.data_processor.generate_df(active_sample, self.active_test, return_phases_times=True) if phases == 'master': dfs = [self.df] phase_dirs = phase_directories[0:1] else: self.dfs = self.data_processor.generate_phase_dfs(active_sample, self.active_test, self.df) dfs = self.dfs phase_dirs = phase_directories # Loading sample into plotter for preprocessing self.plotter.load_sample_into_plotter(self.active_test, active_sample, phase_datetimes) # Getting sizer and styler values: sizer_val = self.sizer_var.get() if self.sizer_var.get() == 'paper': styler_val = 'light' else: styler_val = 'dark' return dfs, phase_dirs, sizer_val, styler_val # Master plot function calls: def app_SN_plot_all_active_sample(self, sample_list: List, phases): """ Plots all figures for selected sample. User inputs for this function: - comsol model (for gradient plots) - power line (for series plots) - xscale (for gradient plots) - output style :param sample_list: list of samples to be ploted. This function can execute a single active sample as [sample] or all samples as [sample1, smaple2, sample3, ..] :param phases: """ for sample in sample_list: sample_name = sample['sample_name'] print(f'processing: {sample_name}') dfs, phase_dirs, sizer_val, styler_val = self.preprocessing_before_plotting(sample, phases=phases) self.app_SN_combined_master(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_combined_temperature_series(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_combined_temperature_gradient(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_combined_moisture_series(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_combined_moisture_gradient(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_combined_series_moist_vs_temp(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_separate_temperature_series(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_separate_temperature_gradient(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_separate_moisture_series(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_separate_moisture_gradient(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_separate_series_moist_vs_temp(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_last_24h_plots(dfs, phase_dirs, sizer_val, styler_val) self.app_SN_hot_end_temperature(dfs, phase_dirs, sizer_val, styler_val) def app_SN_plot_all_active_test(self): active_test_samples = self.active_test.samples self.app_SN_plot_all_active_sample(active_test_samples, phases='phases') def app_SN_SS_plot_all_both_tests(self): if self.active_test is self.large_test_data: self.app_SN_plot_all_active_test() self.active_test = self.small_test_data self.app_SS_plot_all_active_test() self.active_test = self.large_test_data else: self.active_test = self.large_test_data self.app_SN_plot_all_active_test() self.active_test = self.small_test_data self.app_SS_plot_all_active_test() # Combined plot calls: def app_SN_combined_master(self, dfs, phase_dirs, sizer_val, styler_val): # need to implement other options """ Plots the 4x3 figure: User inputs for this function: - comsol model (for gradient plots) NOT IMPLEMENTED! - power line (for series plots) NOT IMPLEMENTED! - xscale (for gradient plots) - sizer """ print('Currently plotting con_SN_combined_master') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SN_combined_master( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['4x3_full_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def app_SN_combined_temperature_series(self, dfs, phase_dirs, sizer_val, styler_val): # need to implement other options """ Plots combined (3x1) temperature series figure (with hours and datetime). User inputs for this function: - power line NOT IMPLEMENTED! """ print('Currently plotting plot_SN_combined_temperature_series') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_combined_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val] ) self.plotter.plot_SN_combined_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime' ) print('Done\n') def app_SN_combined_temperature_gradient(self, dfs, phase_dirs, sizer_val, styler_val): # need to implement other options """ Plots combined (3x1) temperature gradient figure. User inputs for this function: - comsol model NOT IMPLEMENTED! - xscale """ print('Currently plotting plot_SN_combined_temperature_gradient') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_combined_temperature_gradient( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_partial_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def app_SN_combined_moisture_series(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots combined (3x1) moisture series gradient figure. User inputs for this function: - power line NOT IMPLEMENTED! - output style NOT IMPLEMENTED! """ print('Currently plotting plot_SN_combined_moisture_series') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_combined_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val] ) self.plotter.plot_SN_combined_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime' ) print('Done\n') def app_SN_combined_moisture_gradient(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots combined (3x1) moisture gradient figure. User inputs for this function: - comsol model NOT IMPLEMENTED! - xscale - output style NOT IMPLEMENTED! """ print('Currently plotting plot_SN_combined_moisture_gradients') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SN_combined_moisture_gradients( df=df, phase_directory=direc, folder=self.large_test_data.folders['01_combined_plots'], sizer=self.formatter.sizer[sizer_val]['3x1_partial_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def app_SN_combined_series_moist_vs_temp(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots combined (3x1) moisture vs temperature series. User inputs for this function: - output style NOT IMPLEMENTED! """ print('Currently plotting plot_SN_combined_series_moist_vs_temp') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_combined_series_moist_vs_temp( df=df, phase_directory=direc, folder=self.large_test_data.folders['08_time_series_moisture_vs_temperature'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], ) self.plotter.plot_SN_combined_series_moist_vs_temp( df=df, phase_directory=direc, folder=self.large_test_data.folders['08_time_series_moisture_vs_temperature'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime', ) self.plotter.plot_SN_combined_series_moist_vs_temp( df=df, phase_directory=direc, folder=self.large_test_data.folders['08_time_series_moisture_vs_temperature'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], normalized=True, ) print('Done\n') # Separate plot function calls: def app_SN_separate_temperature_series(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots separate figures for every direction for temperature series. User input for this function: - power line NOT IMPLEMENTED! - output style NOT IMPLEMENTED! """ print('Currently plotting plot_SN_separate_temperature_series') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SN_separate_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['02_time_series_temperature'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val] ) self.plotter.plot_SN_separate_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['02_time_series_temperature'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime' ) print('Done\n') def app_SN_separate_temperature_gradient(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots separate figures for every direction for temperature gradient. User input for this function: - comsol model NOT IMPLEMENTED! - xscale - output style NOT IMPLEMENTED! """ print('Currently plotting con_SN_separate_temperature_gradient') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SN_separate_temperature_gradient( df=df, phase_directory=direc, folder=self.large_test_data.folders['04_gradient_temperature'], sizer=self.formatter.sizer[sizer_val]['1x1_partial_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def app_SN_separate_moisture_series(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots separate figures for every direction for moisture series. User input for this function: - power line NOT IMPLEMENTED! """ print('Currently printing plot_SN_separate_moisture_series') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SN_separate_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['03_time_series_moisture'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val] ) self.plotter.plot_SN_separate_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['03_time_series_moisture'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime' ) print('Done\n') def app_SN_separate_moisture_gradient(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots separate figures for every direction for moisture gradient. User input for this function: - comsol model NOT IMPLEMENTED! - xscale - output style NOT IMPLEMENTED! """ print('Currently plotting plot_SN_separate_moisture_gradient') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_separate_moisture_gradient( df=df, phase_directory=direc, folder=self.large_test_data.folders['05_gradient_moisture'], sizer=self.formatter.sizer[sizer_val]['1x1_partial_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def app_SN_separate_series_moist_vs_temp(self, dfs, phase_dirs, sizer_val, styler_val): """ :param dfs: :param phase_dirs: :param sizer_val: :param styler_val: :return: """ print('Currently plotting app_SN_separate_series_moist_vs_temp') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times self.plotter.plot_SN_separate_series_moist_vs_temp( df=df, phase_directory=direc, folder=self.large_test_data.folders['08_time_series_moisture_vs_temperature'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], normalized=True, ) print('Done\n') # Animated plot calls: def app_SN_animated_gradient_plot(self): """ Plots animated temperature and moisture gradient. """ print('this option is yet to be implemented') def app_SN_animated_series_plot(self): """ Plots animated temperature and moisture series. """ print('this option is yet to be implemented') # Short period plot calls: def app_SN_last_24h_plots(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots figures for the last 24h our period. This produces separate and combined plots for temperature and moisture series. User input for this function: - power line NOT IMPLEMENTED! """ print('Currently plotting con_last_24h_plots') for df, direc in zip(dfs, phase_dirs): df = self.data_processor.create_24h_subset(df) self.plotter.plot_SN_separate_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['06_last_24_hours'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime', last_day=True ) self.plotter.plot_SN_separate_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['06_last_24_hours'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime', last_day=True ) self.plotter.plot_SN_combined_temperature_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['06_last_24_hours'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime', last_day=True, ) self.plotter.plot_SN_combined_moisture_series( df=df, phase_directory=direc, folder=self.large_test_data.folders['06_last_24_hours'], sizer=self.formatter.sizer[sizer_val]['3x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime', last_day=True, ) print('Done\n') def app_SN_hot_end_temperature(self, dfs, phase_dirs, sizer_val, styler_val): """ Plots figures for the last 24h our period. This produces separate and combined plots for temperature and moisture series. User input for this function: - power line NOT IMPLEMENTED! """ print('Currently plotting con_SN_hot_end_temperature') for df, direc in zip(dfs, phase_dirs): df = self.data_processor.create_10perc_subset(df) self.plotter.plot_SN_hot_end_temperature( df=df, phase_directory=direc, folder=self.large_test_data.folders['09_tracking_individual_sensors'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val] ) print('Done\n') # Small moisture cell plot functions: def app_SS_plot_all_active_sample(self, sample_list: List, phases): for sample in sample_list: sample_name = sample['sample_name'] print(f'processing: {sample_name}') dfs, phase_dirs, sizer_val, styler_val = self.preprocessing_before_plotting(sample, phases=phases) self.app_SS_temperature_series(dfs, phase_dirs, sizer_val, styler_val) self.app_SS_temperature_gradient(dfs, phase_dirs, sizer_val, styler_val) def app_SS_plot_all_active_test(self): active_test_samples = self.active_test.samples self.app_SS_plot_all_active_sample(active_test_samples, phases='phases') def app_SS_temperature_series(self, dfs, phase_dirs, sizer_val, styler_val): print('Currently printing plot_SS_time_series') for df, direc in zip(dfs, phase_dirs): # this iterates one or multiple times (master or phases) self.plotter.plot_SS_time_series( df=df, phase_directory=direc, folder=self.small_test_data.folders['01_time_series_plots'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val] ) self.plotter.plot_SS_time_series( df=df, phase_directory=direc, folder=self.small_test_data.folders['01_time_series_plots'], sizer=self.formatter.sizer[sizer_val]['1x1_full_width'], styler=self.formatter.styler[styler_val], xaxis_type='datetime' ) print('Done\n') def app_SS_temperature_gradient(self, dfs, phase_dirs, sizer_val, styler_val): print('Currently printing plot_SS_temperature_gradient') for df, direc in zip(dfs, phase_dirs): self.plotter.plot_SS_temperature_gradient( df=df, phase_directory=direc, folder=self.small_test_data.folders['02_temperature_gradient_plots'], sizer=self.formatter.sizer[sizer_val]['1x1_partial_width'], styler=self.formatter.styler[styler_val], xscale=self.xscale_var.get() ) print('Done\n') def SS_animated_temperature_series(self): print('button 17') def SS_animated_temperature_gradient(self): print('button 18') def retrieve_active_sample(self): selected_sample = self.samples_combobox.get() for sample in self.active_test.samples: if selected_sample == sample['sample_name']: return [sample] class LargeTestPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent, style='Standard.TFrame') self.parent = parent self.controller = controller # Large test section subframes: self.SN_master_controller_frame = ttk.Frame(self, style='Standard.TFrame') self.SN_master_controller_frame.pack(side='top', fill='x', pady=(20, 0)) self.SN_master_controller_frame.grid_columnconfigure(0, weight=1) self.SN_master_controller_frame.grid_columnconfigure(1, weight=1) self.SN_master_controller_frame.grid_columnconfigure(2, weight=1) self.SN_master_controller_frame.grid_columnconfigure(3, weight=1) self.SN_combined_separate_plots_frame = ttk.Frame(self, style='Standard.TFrame') self.SN_combined_separate_plots_frame.pack(side='top', fill='x', pady=(20, 0)) self.SN_combined_plots_frame = ttk.Frame(self.SN_combined_separate_plots_frame, style='Standard.TFrame') self.SN_combined_plots_frame.pack(side='left', fill='y') self.SN_combined_plots_frame.grid_columnconfigure(1, weight=1) self.SN_separate_plots_frame = ttk.Frame(self.SN_combined_separate_plots_frame, style='Standard.TFrame') self.SN_separate_plots_frame.pack(side='left', fill='both', expand=True, padx=(10, 0)) self.SN_separate_plots_frame.grid_columnconfigure(1, weight=1) self.SN_animated_last_24h_plots_frame = ttk.Frame(self, style='Standard.TFrame') self.SN_animated_last_24h_plots_frame.pack(side='top', fill='x', pady=(20, 0)) self.SN_animated_plots_frame = ttk.Frame(self.SN_animated_last_24h_plots_frame, style='Standard.TFrame') self.SN_animated_plots_frame.pack(side='left', fill='y') self.SN_animated_plots_frame.grid_columnconfigure(1, weight=1) self.SN_last_24h_plots_frame = ttk.Frame(self.SN_animated_last_24h_plots_frame, style='Standard.TFrame') self.SN_last_24h_plots_frame.pack(side='left', fill='both', expand=True, padx=(10, 0)) self.SN_last_24h_plots_frame.grid_columnconfigure(1, weight=1) # Master control section widgets: self.master_controller_label_frame = ttk.Frame(self.SN_master_controller_frame, style='DarkFrame.TFrame') self.master_controller_label_frame.grid(row=0, column=0, columnspan=4, sticky='nsew') self.master_control_label = ttk.Label( self.master_controller_label_frame, text='Master control:', style='ExtraLargeLabel.TLabel' ) self.master_control_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.plot_all_active_sample_label = ttk.Label( self.SN_master_controller_frame, style='LeftAligned.TLabel', text='plot master phase:' ) self.plot_all_active_sample_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_active_sample_button = ttk.Button( self.SN_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_plot_all_active_sample( self.controller.retrieve_active_sample(), phases='master' ) ) self.plot_all_active_sample_button.grid(row=1, column=1, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_phase_plots_label = ttk.Label( self.SN_master_controller_frame, style='LeftAligned.TLabel', text='plot all phases:' ) self.plot_all_phase_plots_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_phase_plots_button = ttk.Button( self.SN_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_plot_all_active_sample( self.controller.retrieve_active_sample(), phases='phases' ) ) self.plot_all_phase_plots_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.plot_all_active_test_label = ttk.Label( self.SN_master_controller_frame, style='LeftAligned.TLabel', text='plot all (active test):' ) self.plot_all_active_test_label.grid(row=1, column=2, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_active_test_button = ttk.Button( self.SN_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SN_plot_all_active_test ) self.plot_all_active_test_button.grid(row=1, column=3, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_both_tests_label = ttk.Label( self.SN_master_controller_frame, style='LeftAligned.TLabel', text='plot all (both tests):' ) self.plot_all_both_tests_label.grid(row=2, column=2, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_both_test_button = ttk.Button( self.SN_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SN_SS_plot_all_both_tests ) self.plot_all_both_test_button.grid(row=2, column=3, sticky='w', padx=(20, 5), pady=(10, 0)) # Combined plots section widgets: self.combined_plots_label_frame = ttk.Frame( self.SN_combined_plots_frame, style='DarkFrame.TFrame' ) self.combined_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.combined_plots_label = ttk.Label( self.combined_plots_label_frame, text='Combined plots:', style='ExtraLargeLabel.TLabel' ) self.combined_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.plot_all_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='combined plot:' ) self.plot_all_combined_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_master( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.plot_all_combined_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.temperature_series_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='temperature series:' ) self.temperature_series_combined_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.temperature_series_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_temperature_series( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.temperature_series_combined_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.temperature_gradient_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='temperature gradient:' ) self.temperature_gradient_combined_label.grid(row=3, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.temperature_gradient_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_temperature_gradient( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.temperature_gradient_combined_button.grid(row=3, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moisture_series_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='moisture series:') self.moisture_series_combined_label.grid(row=4, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moisture_series_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_moisture_series( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moisture_series_combined_button.grid(row=4, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moisture_gradient_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='moisture gradient:' ) self.moisture_gradient_combined_label.grid(row=5, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moisture_gradient_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_moisture_gradient( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moisture_gradient_combined_button.grid(row=5, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moist_vs_temp_series_combined_label = ttk.Label( self.SN_combined_plots_frame, style='LeftAligned.TLabel', text='moisture vs temperature:' ) self.moist_vs_temp_series_combined_label.grid(row=6, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moist_vs_temp_series_combined_button = ttk.Button( self.SN_combined_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_combined_series_moist_vs_temp( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moist_vs_temp_series_combined_button.grid(row=6, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) # Separate plots: self.separate_plots_label_frame = ttk.Frame( self.SN_separate_plots_frame, style='DarkFrame.TFrame' ) self.separate_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.separate_plots_label = ttk.Label( self.separate_plots_label_frame, text='Separate plots:', style='ExtraLargeLabel.TLabel' ) self.separate_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.temperature_series_separate_label = ttk.Label( self.SN_separate_plots_frame, style='LeftAligned.TLabel', text='temperature series:' ) self.temperature_series_separate_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.temperature_series_separate_button = ttk.Button( self.SN_separate_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_separate_temperature_series( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.temperature_series_separate_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.temperature_gradient_separate_label = ttk.Label( self.SN_separate_plots_frame, style='LeftAligned.TLabel', text='temperature gradient:' ) self.temperature_gradient_separate_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.temperature_gradient_separate_button = ttk.Button( self.SN_separate_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_separate_temperature_gradient( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.temperature_gradient_separate_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moisture_series_separate_label = ttk.Label( self.SN_separate_plots_frame, style='LeftAligned.TLabel', text='moisture series:' ) self.moisture_series_separate_label.grid(row=3, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moisture_series_separate_button = ttk.Button( self.SN_separate_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_separate_moisture_series( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moisture_series_separate_button.grid(row=3, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moisture_gradient_separate_label = ttk.Label( self.SN_separate_plots_frame, style='LeftAligned.TLabel', text='moisture gradient:' ) self.moisture_gradient_separate_label.grid(row=4, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moisture_gradient_separate_button = ttk.Button( self.SN_separate_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_separate_moisture_gradient( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moisture_gradient_separate_button.grid(row=4, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.moist_vs_temp_series_separate_label = ttk.Label( self.SN_separate_plots_frame, style='LeftAligned.TLabel', text='moisture vs temperature:' ) self.moist_vs_temp_series_separate_label.grid(row=5, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.moist_vs_temp_series_separate_button = ttk.Button( self.SN_separate_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_separate_series_moist_vs_temp( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.moist_vs_temp_series_separate_button.grid(row=5, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) # Animated plots control: self.animated_plots_label_frame = ttk.Frame( self.SN_animated_plots_frame, style='DarkFrame.TFrame' ) self.animated_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.animated_plots_label = ttk.Label( self.animated_plots_label_frame, text='Animated plots:', style='ExtraLargeLabel.TLabel' ) self.animated_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.animated_gradient_label = ttk.Label( self.SN_animated_plots_frame, style='LeftAligned.TLabel', text='animated gradient:' ) self.animated_gradient_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.animated_gradient_button = ttk.Button( self.SN_animated_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SN_animated_gradient_plot ) self.animated_gradient_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.animated_gradient_series_label = ttk.Label( self.SN_animated_plots_frame, style='LeftAligned.TLabel', text='animated series:') self.animated_gradient_series_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.animated_gradient_series_button = ttk.Button( self.SN_animated_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SN_animated_series_plot ) self.animated_gradient_series_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) # Short period plots: self.short_term_plots_label_frame = ttk.Frame( self.SN_last_24h_plots_frame, style='DarkFrame.TFrame' ) self.short_term_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.short_term_plots_label = ttk.Label( self.short_term_plots_label_frame, text='Short term plots:', style='ExtraLargeLabel.TLabel' ) self.short_term_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.last_24h_label = ttk.Label( self.SN_last_24h_plots_frame, style='LeftAligned.TLabel', text='last 24h plots:' ) self.last_24h_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.last_24h_button = ttk.Button( self.SN_last_24h_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_last_24h_plots( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.last_24h_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.hot_end_temperature_label = ttk.Label( self.SN_last_24h_plots_frame, style='LeftAligned.TLabel', text='core temperature:') self.hot_end_temperature_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.hot_end_temperature_button = ttk.Button( self.SN_last_24h_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SN_hot_end_temperature( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.hot_end_temperature_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) class SmallTestPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent, style='Standard.TFrame') self.parent = parent self.controller = controller # Small test section subframes: self.SS_master_controller_frame = ttk.Frame(self, style='Standard.TFrame') self.SS_master_controller_frame.pack(side='top', fill='x', pady=(20, 0)) self.SS_master_controller_frame.grid_columnconfigure(1, weight=1) self.SS_regular_animated_plots_frame = ttk.Frame(self, style='Standard.TFrame') self.SS_regular_animated_plots_frame.pack(side='top', fill='x', pady=(20, 0)) self.SS_regular_plots_frame = ttk.Frame(self.SS_regular_animated_plots_frame, style='Standard.TFrame') self.SS_regular_plots_frame.pack(side='left', fill='y') self.SS_regular_plots_frame.grid_columnconfigure(1, weight=1) self.SS_animated_plots_frame = ttk.Frame(self.SS_regular_animated_plots_frame, style='Standard.TFrame') self.SS_animated_plots_frame.pack(side='left', fill='both', expand=True, padx=(10, 0)) self.SS_animated_plots_frame.grid_columnconfigure(1, weight=1) # Master control section widgets: self.master_controller_label_frame = ttk.Frame(self.SS_master_controller_frame, style='DarkFrame.TFrame') self.master_controller_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.master_control_label = ttk.Label( self.master_controller_label_frame, text='Master control:', style='ExtraLargeLabel.TLabel' ) self.master_control_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.plot_all_active_sample_label = ttk.Label( self.SS_master_controller_frame, style='LeftAligned.TLabel', text='plot all (active sample):' ) self.plot_all_active_sample_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_active_sample_button = ttk.Button( self.SS_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SS_plot_all_active_sample( self.controller.retrieve_active_sample(), phases='phases', ) ) self.plot_all_active_sample_button.grid(row=1, column=1, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_active_test_label = ttk.Label( self.SS_master_controller_frame, style='LeftAligned.TLabel', text='plot all (active test):' ) self.plot_all_active_test_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_active_test_button = ttk.Button( self.SS_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SS_plot_all_active_test ) self.plot_all_active_test_button.grid(row=2, column=1, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_both_tests_label = ttk.Label( self.SS_master_controller_frame, style='LeftAligned.TLabel', text='plot all (both tests):' ) self.plot_all_both_tests_label.grid(row=3, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_all_both_test_button = ttk.Button( self.SS_master_controller_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.app_SN_SS_plot_all_both_tests ) self.plot_all_both_test_button.grid(row=3, column=1, sticky='w', padx=(20, 0), pady=(10, 0)) # Regular plots control section widgets: self.regular_plots_label_frame = ttk.Frame(self.SS_regular_plots_frame, style='DarkFrame.TFrame') self.regular_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.regular_plots_label = ttk.Label( self.regular_plots_label_frame, text='Regular plots control:', style='ExtraLargeLabel.TLabel' ) self.regular_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.plot_temperature_series_label = ttk.Label( self.SS_regular_plots_frame, style='LeftAligned.TLabel', text='temperature series:') self.plot_temperature_series_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_temperature_series_button = ttk.Button( self.SS_regular_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SS_temperature_series( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master' ) ) ) self.plot_temperature_series_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.plot_temperature_gradient_label = ttk.Label( self.SS_regular_plots_frame, style='LeftAligned.TLabel', text='temperature gradient:' ) self.plot_temperature_gradient_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_temperature_gradient_button = ttk.Button( self.SS_regular_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=lambda: controller.app_SS_temperature_gradient( *self.controller.preprocessing_before_plotting( self.controller.retrieve_active_sample()[0], phases='master', ) ) ) self.plot_temperature_gradient_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) # Animated plots control section widgets: self.animated_plots_label_frame = ttk.Frame(self.SS_animated_plots_frame, style='DarkFrame.TFrame') self.animated_plots_label_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') self.animated_plots_label = ttk.Label( self.animated_plots_label_frame, text='Animated plots control:', style='ExtraLargeLabel.TLabel' ) self.animated_plots_label.pack(side='left', padx=(10, 0), pady=(5, 5)) self.plot_animated_temperature_series_label = ttk.Label( self.SS_animated_plots_frame, style='LeftAligned.TLabel', text='temperature series:' ) self.plot_animated_temperature_series_label.grid(row=1, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_animated_temperature_series_button = ttk.Button( self.SS_animated_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.SS_animated_temperature_series ) self.plot_animated_temperature_series_button.grid(row=1, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) self.plot_animated_temperature_gradient_label = ttk.Label( self.SS_animated_plots_frame, style='LeftAligned.TLabel', text='temperature gradient:' ) self.plot_animated_temperature_gradient_label.grid(row=2, column=0, sticky='w', padx=(20, 0), pady=(10, 0)) self.plot_animated_temperature_gradient_button = ttk.Button( self.SS_animated_plots_frame, style='Standard.TButton', text='plot', width=6, takefocus=False, command=controller.SS_animated_temperature_gradient ) self.plot_animated_temperature_gradient_button.grid(row=2, column=1, sticky='w', padx=(20, 5), pady=(10, 0)) class HydraulicConductivityPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent) # add style='Standard.TFrame' self.parent = parent self.controller = controller class WaterRetentionPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent) # add style='Standard.TFrame' self.parent = parent self.controller = controller class ThermalConductivityPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent) # add style='Standard.TFrame' self.parent = parent self.controller = controller class WaterDrainagePlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent) # add style='Standard.TFrame' self.parent = parent self.controller = controller class ParticleGradationPlotControl(ttk.Frame): def __init__(self, parent, controller): super().__init__(parent) # add style='Standard.TFrame' self.parent = parent self.controller = controller def main(): root = MainApp() style = ttk.Style() StyleConfiguration(style) root.mainloop() main() <file_sep>import pandas as pd class SampleDataSmall: def __init__(self): self.test_info = {'test_name': 'SmallMoistureCell', 'sample_dir': 'C:\\Users\\karlisr\\OneDrive - NTNU\\3_PostDoc_Sintef\\' '01_laboratory_work\\02_small_test\\01_measured_samples'} self.fignames = {'time series': 'time_series', 'gradient temp': 'gradient_temp', 'animated series': 'animated_series', 'animated gradient': 'animated_gradient'} self.folders = {'01_time_series_plots': '01_time_series_plots', '02_temperature_gradient_plots': '02_temperature_gradient_plots', '03_animated_plots': '03_animated_plots'} self.plot_folders = [self.folders['01_time_series_plots'], self.folders['02_temperature_gradient_plots'], self.folders['03_animated_plots']] self.temp_directions = ['temp'] self.moist_directions = [] self.SS1 = { 'sample_name': 'SS1', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power'], 'temperature_columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext'], 'phase_names': ['5.3W_hot_end'], 'hot_end_sensors': { 'sensors': ['top'], 'locations': [0.1], }, 'cold_end_sensors': { 'sensors': ['bot'], 'locations': [25], }, 'sensors': {'temp': { 'sensors': ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], 'locations': [3.4, 6.4, 9.4, 12.4, 15.4, 18.4, 21.4]}, }, 'del_data': [{ 'sensor': '', 'start': '', 'end': '', }], 'comsol_files': [], 'sample_props': { 'porosity': 0.4, # this is dummy data 'ks': 2.66, # this is dummy data 'rhos': 3.02, # this is dummy data 'w_grav': 3.0, # this is dummy data } } self.SS2 = {'sample_name': 'SS2', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power'], 'temperature_columns': [ 'top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext'], 'phase_names': ['4.0W_hot_end'], 'hot_end_sensors': {'sensors': ['top'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['bot'], 'locations': [25]}, 'sensors': {'temp': {'sensors': ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], 'locations': [3.4, 6.4, 9.4, 12.4, 15.4, 18.4, 21.4]}}, 'del_data': [{'sensor': '', 'start': '', 'end': ''}], 'comsol_files': [], 'sample_props': {'porosity': 0.4, # this is dummy data 'ks': 2.66, # this is dummy data 'rhos': 3.02, # this is dummy data 'w_grav': 3.0}} # this is dummy data self.SS3 = {'sample_name': 'SS3', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power'], 'temperature_columns': [ 'top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext'], 'phase_names': ['4.0W_hot_end'], 'hot_end_sensors': {'sensors': ['top'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['bot'], 'locations': [25]}, 'sensors': {'temp': {'sensors': ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], 'locations': [3.4, 6.4, 9.4, 12.4, 15.4, 18.4, 21.4]}}, 'del_data': [{'sensor': '', 'start': '', 'end': ''}], 'comsol_files': [], 'sample_props': {'porosity': 0.4, # this is dummy data 'ks': 2.66, # this is dummy data 'rhos': 3.02, # this is dummy data 'w_grav': 3.0}} # this is dummy data} self.SS4 = {'sample_name': 'SS4', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power'], 'temperature_columns': [ 'top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext'], 'phase_names': ['4.0W_hot_end'], 'hot_end_sensors': {'sensors': ['top'], 'locations': [0.1]}, 'cold_end_sensors': {'sensors': ['bot'], 'locations': [25]}, 'sensors': {'temp': {'sensors': ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], 'locations': [3.4, 6.4, 9.4, 12.4, 15.4, 18.4, 21.4]}}, 'del_data': [{'sensor': '', 'start': '', 'end': ''}], 'comsol_files': [], 'sample_props': {'porosity': 0.4, # this is dummy data 'ks': 2.66, # this is dummy data 'rhos': 3.02, # this is dummy data 'w_grav': 3.0}} # this is dummy data} self.SS5 = {'sample_name': 'SS5', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.SS6 = {'sample_name': 'SS6', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.SS7 = {'sample_name': 'SS7', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.SS8 = {'sample_name': 'SS8', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.SS9 = {'sample_name': 'SS9', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.SS10 = {'sample_name': 'SS10', 'columns': ['top', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'bot', 'ext', 'power']} self.samples = [ self.SS1, self.SS2, self.SS3, self.SS4, #self.SS5, #self.SS6, #self.SS7, #self.SS8, #self.SS9, #self.SS10, ]<file_sep>import pandas as pd import matplotlib.pyplot as plt class MoistureSensorCalibrationFit: def __init__(self): self.ms = pd.read_excel('moisture_sensor_calibratoin_full_data.xlsx', sheet_name='Sheet1') #self.sensor_names = ['MS1', 'MS2', 'MS3', 'MS4', 'MS5', 'MS6', 'MS7', 'MS8', 'MS9', 'MS10', 'MS11', 'MS12'] self.sensor_names = ['MS1'] self.temperatures = ['30degC', '40degC', '50degC', '60degC', '70degC'] def plot_figures(self): for sensor in self.sensor_names: sensor_df = self.ms[self.ms['sensor'] == sensor] # initializer: fig, ax = plt.subplots(figsize=(12, 6)) for temp in self.temperatures: temp_df = sensor_df[sensor_df['temp'] == temp] x_vals = temp_df['vol'].values y_vals = temp_df['w%'].values ax.plot(x_vals, y_vals, label=temp, marker='o') # configuration: ax.set_ylabel('Moisture content, %', size=10) ax.set_xlabel('Measured voltage, mV', size=10) ax.tick_params(axis='both', direction='in', width=1.5, right=True, top=True) for j in ['top', 'bottom', 'left', 'right']: ax.spines[j].set_linewidth(1.5) plt.show() moist = MoistureSensorCalibrationFit() moist.plot_figures() <file_sep>import numpy as np import pandas as pd import os import shutil class DataProcessor: def __init__(self, large_test_data, small_test_data): self.large_test_data = large_test_data self.small_test_data = small_test_data self.test_setups = [ self.large_test_data, #self.small_test_data, ] self.measurement_folder = '02_measurement_data' self.comsol_folder = '03_comsol_model' self.calib_folder = '04_calib_data' self.corrected_df_folder = '01_calibrated_datasets' self.source_folder_list = [ 'C:\\Users\\karlisr\\OneDrive\\LargeMoistureCell', #'C:\\Users\\karlisr\\OneDrive\\SmallMoistureCell', ] self.target_folder_list = [ 'C:\\Users\\karlisr\\OneDrive - NTNU\\3_PostDoc_Sintef\\01_laboratory_work\\' '01_large_test\\01_measured_samples', #'C:\\Users\\karlisr\\OneDrive - NTNU\\3_PostDoc_Sintef\\01_laboratory_work\\' #'02_small_test\\01_measured_samples', ] @staticmethod def load_single_file(sample_data_dir, file): def combine_datetime(x): """Combines date and time cells into one""" return x[0] + ' ' + x[1] df_loc = pd.read_csv( os.path.join(sample_data_dir, file), skiprows=5, header=None, delim_whitespace=True) df_loc[0] = df_loc.iloc[:, 0:2].apply(combine_datetime, axis=1) df_loc.drop(df_loc.columns[1], axis=1, inplace=True) df_loc.index = df_loc[0] df_loc.index = pd.to_datetime(df_loc.index) df_loc.drop(df_loc.columns[0], axis=1, inplace=True) return df_loc @staticmethod def add_hours_column_to_df(df_loc): start_time = df_loc.index[0] def calc_hour_diff(time_point): diff = time_point - start_time return diff.days * 24 + diff.seconds / 3600 df_loc['hours'] = df_loc.index.to_series().apply(calc_hour_diff) return df_loc @staticmethod def add_cold_end_temp_column(active_sample, df_loc): df_loc['cold_end'] = df_loc[active_sample['cold_end_sensors']['sensors']].mean(axis=1) return df_loc @staticmethod def add_hot_end_temp_column(active_sample, df_loc): df_loc['hot_end'] = df_loc[active_sample['hot_end_sensors']['sensors']].mean(axis=1) return df_loc @staticmethod def nan_out_low_moisture_vals(active_sample, df_loc): def f(x): if x < 300: x = np.nan return x for column in active_sample['moisture_columns']: df_loc[column] = df_loc[column].apply(f) return df_loc @staticmethod def normalize_moisture_values(active_sample, df_loc): def normalized_vals(moist_val, min_val, max_val): if moist_val != np.nan: moist_val = (moist_val - min_val) / (max_val - min_val) return moist_val for sensor in active_sample['moisture_columns']: # find min and max values: min_val = np.nanmin(df_loc[sensor]) max_val = np.nanmax(df_loc[sensor]) df_loc[sensor + '_norm'] = df_loc[sensor].apply(lambda x: normalized_vals(x, min_val, max_val)) return df_loc @staticmethod def delete_flawed_data(active_sample, df_loc): for data_chunk in active_sample['del_data']: start_time = data_chunk['start'] end_time = data_chunk['end'] sensor = data_chunk['sensor'] df_loc[sensor][start_time:end_time] = df_loc[sensor][start_time:end_time].apply(lambda val: np.nan) return df_loc def generate_phase_dfs(self, active_sample, active_test, df_loc): """ The function generates a list with of phased dfs. The first element in the list is the master phase while the following are each particular phase based on start and end datetimes. :return: list with all phase dfs as follows: [MASTER_PHASE, PHASE1, PHASE2..] """ # Get pahse dates: phase_datetimes = self.generate_df(active_sample, active_test, return_phases_times=True) # Find how many phases: phase_count = len(phase_datetimes) dfs = [df_loc] phase_number = '1' for phase in range(phase_count): df_subset = df_loc.loc[phase_datetimes[phase_number][0]:phase_datetimes[phase_number][1]] dfs.append(df_subset) phase_number = str(int(phase_number) + 1) return dfs @staticmethod def create_24h_subset(df): diff = pd.Timedelta(hours=24) end_time = df.index[-1] start_time = end_time - diff df = df[start_time:end_time] return df def generate_df(self, active_sample, active_test, return_phases_times=False): """ The functions loads all phase datasets and concatenate them together. :param - active_sample: active sample :param - active_test: current test setup :param - return_phases_times: if set tu True, this function will only return phase times :return - df, phases: df - full uncalibrated dataframe; phases - start and end datetime of each phase. """ # Get sample data directory: sample_name = active_sample['sample_name'] active_test_dir = active_test.test_info['sample_dir'] sample_data_dir = os.path.join(active_test_dir, sample_name, self.measurement_folder) # Loading dataframes: df = pd.DataFrame() files = os.listdir(sample_data_dir) phase_datetimes = {} for index, file in enumerate(files): if file.endswith('csv'): filename, extension = os.path.splitext(file) # Separating filename to extract phase number keyword = 'phase' sample_name, keyword, phase_number = filename.partition(keyword) if len(phase_number) == 1: # Normal case: phase consist of single file # Both, start and end of phase index can be extracted df_loc = self.load_single_file(sample_data_dir, file) df = pd.concat([df, df_loc]) phase_datetimes[phase_number] = [df_loc.index[0], df_loc.index[-1]] elif index == len(files) - 1: # Phase consists of multiple files, but this is the very last file # End datetime of phase can be extracted df_loc = self.load_single_file(sample_data_dir, file) df = pd.concat([df, df_loc]) phase_datetimes[phase_number.split('-')[0]].append(df_loc.index[-1]) else: # When multiple files, one of the phase files. # Retrieving phase number for the next file: filename_next, extension_next = os.path.splitext(files[index + 1]) sample_name_next, keyword_next, phase_number_next = filename_next.partition(keyword) if len(phase_number_next) == 1: # This is the last file of the phase df_loc = self.load_single_file(sample_data_dir, file) df = pd.concat([df, df_loc]) phase_datetimes[phase_number.split('-')[0]].append(df_loc.index[-1]) else: # This is not teh last file of the phase df_loc = self.load_single_file(sample_data_dir, file) last_index = pd.to_datetime(df_loc.index[-1]) df_loc = df_loc.append(pd.Series(name=last_index + pd.Timedelta(seconds=1))) df = pd.concat([df, df_loc]) if phase_number not in active_sample: # Adds a list with phase start time phase_datetimes[phase_number.split('-')[0]] = [df_loc.index[0]] df.index.name = None df.columns = active_sample['columns'] if not return_phases_times: return df else: return phase_datetimes def generate_corrected_dfs(self, override_dfs): """" This function is executed together with teh update function. The function will iterate through both test setups and update corrected dfs if there is any new date for any of the samples. """ # This function should be executed together with update files function. # This way it would ensure that any time I update the files, I also add new data # to corrected dataset corrected_df_folder = '01_calibrated_datasets' # Iterate through all samples: for active_test in self.test_setups: active_test_dir = active_test.test_info['sample_dir'] for active_sample in active_test.samples: sample_name = active_sample['sample_name'] corrected_df_name = sample_name + '_calibrated_df.csv' corrected_df_dir = os.path.join( active_test_dir, sample_name, self.measurement_folder, corrected_df_folder) temperature_sensor_columns = active_sample['temperature_columns'] corr_coef_dir = os.path.join(active_test_dir, sample_name, self.calib_folder) corr_coef_filename = 'temperature_sensor_calibration_factors.csv' corr_coef_data = pd.read_csv( os.path.join(corr_coef_dir, corr_coef_filename), header=0, index_col=0) def correcting_data(x, column): a = corr_coef_data['a'][column] b = corr_coef_data['b'][column] return x * a + b if override_dfs: # load all phase files into df corrected_df = self.generate_df(active_sample, active_test) for column in temperature_sensor_columns: corrected_df.loc[:, column].apply(lambda x: correcting_data(x, column)) # Do preprocessing: corrected_df = self.add_hours_column_to_df(corrected_df) corrected_df = self.add_cold_end_temp_column(active_sample, corrected_df) corrected_df = self.add_hot_end_temp_column(active_sample, corrected_df) if active_test is self.large_test_data: corrected_df = self.nan_out_low_moisture_vals(active_sample, corrected_df) corrected_df = self.normalize_moisture_values(active_sample, corrected_df) corrected_df = self.delete_flawed_data(active_sample, corrected_df) corrected_df.to_csv(os.path.join(corrected_df_dir, corrected_df_name)) else: if corrected_df_name not in os.listdir(corrected_df_dir): # load all phase files into df corrected_df = self.generate_df(active_sample, active_test) for column in temperature_sensor_columns: corrected_df.loc[:, column].apply(lambda x: correcting_data(x, column)) # Do preprocessing: corrected_df = self.add_hours_column_to_df(corrected_df) corrected_df = self.add_cold_end_temp_column(active_sample, corrected_df) corrected_df = self.add_hot_end_temp_column(active_sample, corrected_df) if active_test is self.large_test_data: corrected_df = self.nan_out_low_moisture_vals(active_sample, corrected_df) corrected_df = self.normalize_moisture_values(active_sample, corrected_df) corrected_df = self.delete_flawed_data(active_sample, corrected_df) corrected_df.to_csv(os.path.join(corrected_df_dir, corrected_df_name)) else: corrected_df = pd.read_csv( os.path.join(corrected_df_dir, corrected_df_name), index_col=0, header=0) corrected_df = corrected_df[active_sample['columns']] corrected_df.index = pd.to_datetime(corrected_df.index) corr_df_last_index = corrected_df.index[-1] sample_data_dir = os.path.join( active_test_dir, sample_name, self.measurement_folder) phase_files = [] for file in os.listdir(sample_data_dir): if os.path.isfile(os.path.join(sample_data_dir, file)): phase_files.append(file) phase_files.sort() df_loc = self.load_single_file(sample_data_dir, phase_files[-1]) origin_df_last_index = df_loc.index[-1] if origin_df_last_index > corr_df_last_index: # Load whole df and make a slice: df = self.generate_df(active_sample, active_test) df_subset = df[df.index > corr_df_last_index] for column in temperature_sensor_columns: df_subset.loc[:, column] = df_subset.loc[:, column].apply(lambda x: correcting_data(x, column)) # Concatenate new data to old: corrected_df = pd.concat([corrected_df, df_subset]) # Do preprocessing: corrected_df = self.add_hours_column_to_df(corrected_df) corrected_df = self.add_cold_end_temp_column(active_sample, corrected_df) corrected_df = self.add_hot_end_temp_column(active_sample, corrected_df) if active_test is self.large_test_data: corrected_df = self.nan_out_low_moisture_vals(active_sample, corrected_df) corrected_df = self.normalize_moisture_values(active_sample, corrected_df) corrected_df = self.delete_flawed_data(active_sample, corrected_df) # Save corrected df: corrected_df.to_csv(os.path.join(corrected_df_dir, corrected_df_name)) def load_corrected_df(self, active_sample, active_test): """ Load dataframe with correceted values. Any necessary preprocessing has already been done for this dataframe. :param active_sample - current sample to be plotted. :param active_test - current test setup to be processed. :return: df - master dataframe used for any plot. """ sample_name = active_sample['sample_name'] active_test_dir = active_test.test_info['sample_dir'] corrected_df_dir = os.path.join( active_test_dir, sample_name, self.measurement_folder, self.corrected_df_folder) corrected_df_name = sample_name + '_calibrated_df.csv' df = pd.read_csv( os.path.join(corrected_df_dir, corrected_df_name), index_col=0, header=0) df.index = pd.to_datetime(df.index) return df def generate_averaged_dfs(self): pass @staticmethod def create_10perc_subset(df): """ The function creates a subset from the current dataframe. The subset is the last 10% temperature increase. The last value of teh dataset is teh last value of teh input df. The first value is defined as the last*0.9. Then the df subset is limited to this range. :param df: Current data set :return: a subset of the current df """ last_temp = df['hot_end'].values[-1] min_temp = last_temp*0.9 start_time = None for index_val, temp_val in zip(df.index, df['hot_end']): if temp_val >= min_temp: start_time = index_val break df = df.loc[start_time:] return df def update_data(self): for source_folder, target_folder in zip(self.source_folder_list, self.target_folder_list): for root, dirs, files in os.walk(source_folder): for file in files: if len(file) != 0: # Getting sample name: sample_name = file.split('_')[0] # Check if the file exists, copy or replace: sample_folder_raw = os.path.join( target_folder, sample_name, '01_raw_data') sample_folder_csv = os.path.join( target_folder, sample_name, '02_measurement_data') if file not in os.listdir(sample_folder_raw): # Executed when new file is added shutil.copy(os.path.join(root, file), sample_folder_raw) # Should convert from .lvm to .csv here shutil.copy(os.path.join(sample_folder_raw, file), sample_folder_csv) name, ext = os.path.splitext(os.path.join(sample_folder_csv, file)) os.rename(os.path.join(sample_folder_csv, file), name + '.csv') else: # Executed when file already exists src_mod_time = os.stat(os.path.join(root, file)).st_mtime trg_mod_time = os.stat(os.path.join(sample_folder_raw, file)).st_mtime if src_mod_time - trg_mod_time > 1: shutil.copy(os.path.join(root, file), sample_folder_raw) shutil.copy(os.path.join(sample_folder_raw, file), sample_folder_csv) # Updating csv version of the file: name, ext = os.path.splitext(os.path.join(sample_folder_csv, file)) csv_name = file.split('.')[0] + '.csv' if csv_name not in os.listdir(sample_folder_csv): os.rename(os.path.join(sample_folder_csv, file), name + '.csv') else: os.remove(os.path.join(sample_folder_csv, csv_name)) os.rename(os.path.join(sample_folder_csv, file), name + '.csv') <file_sep>import pandas as pd import matplotlib.pyplot as plt SN1_summary = pd.read_excel('sample_summaries\\SN1_summary.xlsx', sheet_name='Sheet1') SN2_summary = pd.read_excel('sample_summaries\\SN2_summary.xlsx', sheet_name='Sheet1') fig, ax = plt.subplots() ax.plot(SN1_summary['power'], SN1_summary['core'], label='SN1', marker='o') ax.plot(SN2_summary['power'], SN2_summary['core'], label='SN2', marker='o') ax.set_xlabel('Power, W') ax.set_ylabel('Core temperature, °C') ax.legend() plt.show()<file_sep>class SampleDataThermalConductivity: def __init__(self): self.TH1 = {'sample_name': 'TH1'} self.TH2 = {'sample_name': 'TH2'} self.TH3 = {'sample_name': 'TH3'} self.TH4 = {'sample_name': 'TH4'} self.TH5 = {'sample_name': 'TH5'} self.TH6 = {'sample_name': 'TH6'} self.TH7 = {'sample_name': 'TH7'} self.TH8 = {'sample_name': 'TH8'} self.TH9 = {'sample_name': 'TH9'} self.TH10 = {'sample_name': 'TH10'} self.samples = [self.TH1, self.TH2, self.TH3, self.TH4, self.TH5, self.TH6, self.TH7, self.TH8, self.TH9, self.TH10]<file_sep>class SampleDataHydraulicConductivity: def __init__(self): self.HC1 = {'sample_name': 'HC1'} self.HC2 = {'sample_name': 'HC2'} self.HC3 = {'sample_name': 'HC3'} self.HC4 = {'sample_name': 'HC4'} self.HC5 = {'sample_name': 'HC5'} self.HC6 = {'sample_name': 'HC6'} self.HC7 = {'sample_name': 'HC7'} self.HC8 = {'sample_name': 'HC8'} self.HC9 = {'sample_name': 'HC9'} self.HC10 = {'sample_name': 'HC10'} self.samples = [self.HC1, self.HC2, self.HC3, self.HC4, self.HC5, self.HC6, self.HC7, self.HC8, self.HC9, self.HC10]<file_sep>import os class DirectoryGenerator: def __init__(self): pass @staticmethod def directory_generator(active_test, active_sample): """ Generates sample directory structure as follows: - Generate sample parent directory: (SN1(SS1), SN2(SS2), SN3(SS3), ..., etc) - Generate sample child directories: (01_raw_data, 02_measurement_data, ..., etc) - Generate child subdirectories (MASTER, PHASE1, PHASE2, ..., etc) - Generate child subdirectory subdirectories (01_combined.., 02_time_series, ..., etc): :return: phase_directories """ plot_folders = active_test.plot_folders sample_name = active_sample['sample_name'] sample_dir = active_test.test_info['sample_dir'] # child folder names: raw_data_folder = '01_raw_data' measurement_data_folder = '02_measurement_data' comsol_model_folder = '03_comsol_model' calib_data_folder = '04_calib_data' moisture_weight_measurements_folder = '05_moisture_weight_measurements' other_folder = '06_other' pics_folder = '07_pics' measurement_figures_folder = '08_measurement_figures' child_folders = [ raw_data_folder, measurement_data_folder, comsol_model_folder, calib_data_folder, moisture_weight_measurements_folder, other_folder, pics_folder, measurement_figures_folder ] # Generate sample parent directory: (SN1(SS1), SN2(SS2), ..., etc) parent_directory = os.path.join(sample_dir, sample_name) if not os.path.exists(parent_directory): os.mkdir(parent_directory) # Generate sample child directories: (01_raw_data, 02_measurement_data, ..., etc) for folder in child_folders: child_subdirectory = os.path.join(parent_directory, folder) if not os.path.exists(child_subdirectory): os.mkdir(child_subdirectory) # inner 01_calibrated_datasets folder generation: if folder == '02_measurement_data': inner_child_subdirectory = os.path.join(parent_directory, folder, '01_calibrated_datasets') if not os.path.exists(inner_child_subdirectory): os.mkdir(inner_child_subdirectory) # Generate child subdirectories (MASTER, PHASE1, PHASE2, ..., etc) if 'phase_names' in active_sample: phase_folders = ['PHASE_MASTER'] phase_directories = [] phase_num = 1 for phase in active_sample['phase_names']: subdirectory_folders = 'PHASE' + str(phase_num) + '_' + phase phase_num += 1 phase_folders.append(subdirectory_folders) measurement_figures_directory = os.path.join( sample_dir, sample_name, measurement_figures_folder ) for new_phase_name in phase_folders: phase_directories.append(os.path.join(measurement_figures_directory, new_phase_name)) # check if particular phase (except MASTER) exists: if 'MASTER' not in new_phase_name: # Break down the phase_name into phase_number and phase_tag: new_phase_number, new_phase_tag = new_phase_name.split('_', 1) # Check if such phase number exists: current_phase_folders = os.listdir(measurement_figures_directory) exists = False for phase_folder in current_phase_folders: if new_phase_number in phase_folder: exists = True if not exists: os.mkdir(os.path.join(measurement_figures_directory, new_phase_name)) else: for phase_folder in current_phase_folders: if new_phase_number in phase_folder: current_phase_tag = phase_folder.split('_', 1)[1] if new_phase_tag != current_phase_tag: os.rename( os.path.join(measurement_figures_directory, phase_folder), os.path.join(measurement_figures_directory, new_phase_name), ) elif 'MASTER' in new_phase_name: if not os.path.exists(os.path.join(measurement_figures_directory, new_phase_name)): os.mkdir(os.path.join(measurement_figures_directory, new_phase_name)) for plot in plot_folders: if not os.path.exists(os.path.join(measurement_figures_directory, new_phase_name, plot)): os.mkdir(os.path.join(measurement_figures_directory, new_phase_name, plot)) return phase_directories <file_sep>import os import pandas as pd class ComsolModel: def __init__(self, comsol_path): self.comsol_path = comsol_path self.comsol_models_dfs = [] for file in os.listdir(comsol_path): if file.endswith('csv'): df_loc = pd.read_csv(self.comsol_path + file, names=['loc', 'temp']) df_loc['loc'] = df_loc['loc'].apply(lambda dist: dist*100) self.comsol_models_dfs.append(df_loc) else: pass if __name__ == "__main__": model = ComsolModel('C:\\Users\\karlisr\\OneDrive - NTNU\\3_PostDoc_Sintef\\01_laboratory_work\\01_large_test\\' '07_testing_data\\01_Sample_1_Vassfjell_4%_fines_Pallet_1\\03_comsol_model\\') print(model.comsol_models_dfs) class ComsolProcessor: def __init__(self, sample, comsol_path): self.comsol_path = comsol_path self.sample = sample def generate_comsol_df(self): comsol_dfs = [] wall_loc = 0.26 core_loc = 0.00 for comsol_sol in self.sample['comsol_files']: df = pd.read_csv(self.comsol_path + comsol_sol, names=['loc', 'mes']) index_vals_core = df.index[df['loc'] == core_loc].tolist() index_vals_wall = df.index[df['loc'] == wall_loc].tolist() for core_ind, wall_ind in zip(index_vals_core, index_vals_wall): subset = df.iloc[core_ind:wall_ind+1] subset['loc'] = subset['loc'].apply(lambda val: val*100) comsol_dfs.append(subset) return comsol_dfs <file_sep>import matplotlib.pyplot as plt def plotter(ax): plot_list = [] plot = ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5], label='label') plot_list.append(plot[0]) plot = ax.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6], label='label') plot_list.append(plot[0]) ax_twin = plt.twinx(ax) plot = ax_twin.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], label='label') plot_list.append(plot[0]) ax_twin.set_ylabel('Axis label') labels = [plot.get_label() for plot in plot_list] legend = ax_twin.legend( plot_list, labels, ncol=3, loc='center left', bbox_to_anchor=(1.05, 0.5)) fig, axes = plt.subplots(ncols=1, nrows=3, figsize=(28/2.54, 12/2.54), sharex='col') for ax in axes: plotter(ax) plt.tight_layout(pad=0.2, h_pad=0.2) plt.show() fig.savefig('testing', dpi=300) <file_sep>class FigureFormatting: def __init__(self): ''' Sizer parameter explanations: tick_size - size of the tick text tick_length - length of tick lines tick_width = width of tick lines tight_layout_rect (tight_layout_rect) - restricted plot area (left, bottom, right, top) line_width - width of plot lines legend_borderaxespad (borderaxespad) - pad outside the legend frame legend_handlelenght (handlelength) - length of the handle in legend legend_loc (loc) - location of the legend anchor ''' inch = 2.54 pres_scaler = 1.2 self.styler = { 'light': { 'name': 'light', 'facecolor': 'white', 'axis_facecolor': 'white', 'label_color': 'black', 'tick_color': 'black', 'tick_label_color': 'black', 'spine_color': 'black', 'axis_label_color': 'black', 'text_color': 'black', 'aidline_color': 'black', 'legend_text_color': 'black', 'legend_edge_color': 'black', 'legend_face_color': 'white', 'legend_framealpha': 0.8, 'legend_edge_color_rgba': (0, 0, 0, 0), 'legend_face_color_rgba': (1, 1, 1, 0.5)}, 'dark': { 'name': 'dark', 'facecolor': 'black', 'axis_facecolor': 'black', 'label_color': 'white', 'tick_color': '#999999', # 999999 is grey 'tick_label_color': 'white', 'spine_color': '#999999', # 999999 is grey 'axis_label_color': 'white', 'text_color': 'white', 'aidline_color': 'white', 'legend_text_color': 'white', 'legend_edge_color': 'white', 'legend_face_color': 'black', 'legend_framealpha': 0.5, 'legend_edge_color_rgba': (1, 1, 1, 0), 'legend_face_color_rgba': (0, 0, 0, 0.5)}} self.paper_1x1_full_width = { 'fig_type': 'paper', 'tight_layout_pad': 0.2, 'tight_layout_h_pad': 0.4, 'figsize': (16/inch, 6/inch), 'legend_size': 8, 'label_size': 8, 'tick_size': 8, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), 'legend_loc': 'center left', 'legend_labelspacing': 0.4, 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.pres_1x1_full_width = { 'fig_type': 'paper', 'tight_layout_pad': 0.2, 'tight_layout_h_pad': 0.4, 'figsize': (pres_scaler*16/inch, pres_scaler*6/inch), 'legend_size': 8, 'label_size': 8, 'tick_size': 8, 'tick_length': 3, 'tick_width': 0.5, # decreased 'tick_rotation': 45, 'spine_width': 0.5, # decreased 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), 'legend_loc': 'center left', 'legend_labelspacing': 0.4, 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} # this has to be moved to styler self.paper_3x1_full_width = { 'figsize': (16/inch, 12/inch), 'tight_layout_pad': 0.2, 'tight_layout_h_pad': 0.4, 'legend_size': 8, 'label_size': 8, 'tick_size': 8, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'hspace': 0.1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), 'legend_loc': 'center left', 'legend_labelspacing': 0.3, 'labelpad': 2, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.pres_3x1_full_width = { 'figsize': (pres_scaler*16/inch, pres_scaler*12/inch), 'tight_layout_pad': 0.2, 'tight_layout_h_pad': 0.6, 'legend_size': 6, # decreased 'label_size': 6, # decreased 'tick_size': 6, 'tick_length': 3, 'tick_width': 0.5, # decreased 'tick_rotation': 45, 'spine_width': 0.5, # decreased 'hspace': 0.6, # increased 'line_width': 0.6, # decreased 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.06, 0.5), 'legend_loc': 'center left', 'legend_labelspacing': 0.6, # increased 'labelpad': 2, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.paper_3x1_partial_width = { 'figsize': (10/inch, 12/inch), 'tight_layout_pad': 0.2, 'tight_layout_rect': (0.02, 0.05, 0.81, 1.0), # (left, bottom, right, top) 'legend_size': 8, 'label_size': 8, 'tick_size': 8, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'hspace': 0.1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'marker_size': 5, 'marker_edge_width': 1, 'marker_face_color': 'none', 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.pres_3x1_partial_width = { 'figsize': (10 / inch, 12 / inch), # THIS SIZE IS NOT MODIFIED!!!! 'tight_layout_pad': 0.2, 'tight_layout_rect': (0.02, 0.05, 0.81, 1.0), # (left, bottom, right, top) 'legend_size': 8, 'label_size': 8, 'tick_size': 8, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'hspace': 0.1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'marker_size': 5, 'marker_edge_width': 1, 'marker_face_color': 'none', 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.paper_1x1_partial_width = { 'figsize': (8/inch, 6/inch), 'tight_layout_pad': 0.2, 'tight_layout_rect': (0.02, 0.05, 0.81, 1.0), # (left, bottom, right, top) 'legend_size': 7, 'label_size': 7, 'tick_size': 7, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'hspace': 0.1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'marker_size': 5, 'marker_edge_width': 1, 'marker_face_color': 'none', 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.pres_1x1_partial_width = { 'figsize': (8 / inch, 6 / inch), # THIS SIZE IS NOT MODIFIED!!!! 'tight_layout_pad': 0.2, 'tight_layout_rect': (0.02, 0.05, 0.81, 1.0), # (left, bottom, right, top) 'legend_size': 7, 'label_size': 7, 'tick_size': 7, 'tick_length': 3, 'tick_width': 1, 'tick_rotation': 45, 'spine_width': 1, 'hspace': 0.1, 'line_width': 1, 'legend_handlelength': 3, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'marker_size': 5, 'marker_edge_width': 1, 'marker_face_color': 'none', 'labelpad': 3, 'legend_frame_width': 0.5, 'legend_edge_color': 'dimgray'} self.paper_4x3_full_width = { 'figsize': (16/inch, 14/inch), 'legend_size': 6, 'label_size': 6, 'tick_size': 6, 'tick_length': 1, 'tick_width': 0.5, 'tick_rotation': 45, 'spine_width': 0.5, 'hspace': 0.4, 'wspace': 0.05, 'line_width': 0.5, 'legend_handlelength': 2, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'legend_labelspacing': 0.6, 'marker_size': 2, 'marker_edge_width': 0.5, 'marker_face_color': 'none', 'labelpad': 1, 'legend_frame_width': 0.25, 'legend_edge_color': 'dimgray'} self.pres_4x3_full_width = { 'figsize': (pres_scaler*16 / inch, pres_scaler*14 / inch), 'legend_size': 6, 'label_size': 6, 'tick_size': 6, 'tick_length': 1, 'tick_width': 0.5, 'tick_rotation': 45, 'spine_width': 0.5, 'hspace': 0.4, 'wspace': 0.05, 'line_width': 0.5, 'legend_handlelength': 2, 'legend_borderaxespad': 0, 'legend_bbox_to_anchor': (1.1, 0.5), # not modified 'legend_loc': 'center left', 'legend_labelspacing': 0.6, 'marker_size': 2, 'marker_edge_width': 0.5, 'marker_face_color': 'none', 'labelpad': 1, 'legend_frame_width': 0.15, 'legend_edge_color': 'dimgray'} self.sizer = {'paper': {'1x1_full_width': self.paper_1x1_full_width, '1x1_partial_width': self.paper_1x1_partial_width, '3x1_full_width': self.paper_3x1_full_width, '3x1_partial_width': self.paper_3x1_partial_width, '4x3_full_width': self.paper_4x3_full_width}, 'presentation': {'1x1_full_width': self.pres_1x1_full_width, '1x1_partial_width': self.pres_1x1_partial_width, '3x1_full_width': self.pres_3x1_full_width, '3x1_partial_width': self.pres_3x1_partial_width, '4x3_full_width': self.pres_4x3_full_width}}
896a4f562141ff2725a1d09489aa445d73960464
[ "Python" ]
21
Python
reeksts/DynKap_data_processing
8813236d553de51babdc3b37a77a7cf53f190729
f8e50b492b84c74b6739a79ac0f9e7df5f24c527
refs/heads/master
<repo_name>marcushellberg/shopping-list<file_sep>/src/main/java/com/vaadin/tutorial/data/endpoint/ShoppingListEndpoint.java package com.vaadin.tutorial.data.endpoint; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; import com.vaadin.flow.server.connect.Endpoint; import com.vaadin.flow.server.connect.auth.AnonymousAllowed; import com.vaadin.tutorial.data.entity.Category; import com.vaadin.tutorial.data.entity.ListItem; import com.vaadin.tutorial.data.service.CategoryRepository; import com.vaadin.tutorial.data.service.ListItemRepository; import lombok.RequiredArgsConstructor; @Endpoint @AnonymousAllowed @RequiredArgsConstructor public class ShoppingListEndpoint { private final ListItemRepository listRepo; private final CategoryRepository categoryRepo; public List<ListItem> getShoppingList() { return listRepo.findAll(); } public ListItem saveListItem(ListItem listItem) { return listRepo.save(listItem); } public List<Category> getCategories() { return categoryRepo.findAll(); } @PostConstruct public void init() { if (categoryRepo.count() == 0) { categoryRepo.saveAll(Stream .of("Produce", "Deli", "Bakery", "Meat & Seafood", "Dairy, Cheese & Eggs", "Breakfast", "Coffee & Tea", "Nut Butters, Honey & Jam", "Baking & Spices", "Rice, Grains & Beans", "Canned & Jarred Goods", "Pasta & Sauces", "Oils, Sauces & Condiments", "International", "Frozen", "Snacks", "Nuts, Seeds & Dried Fruit", "Candy", "Beverages", "Wine, Beer & Spirits", "Personal Care", "Health", "Baby", "Household", "Kitchen", "Cleaning Products", "Pet Care", "Party", "Floral", "Other") .map(Category::new).collect(Collectors.toList())); } } } <file_sep>/src/main/java/com/vaadin/tutorial/data/entity/Category.java package com.vaadin.tutorial.data.entity; import javax.persistence.Entity; import com.vaadin.tutorial.data.AbstractEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Category extends AbstractEntity { private String name; } <file_sep>/frontend/views/list/item-form.ts import { css, customElement, html, internalProperty, LitElement, property, } from "lit-element"; import "@vaadin/vaadin-text-field"; import "@vaadin/vaadin-text-field/vaadin-integer-field"; import "@vaadin/vaadin-combo-box"; import "@vaadin/vaadin-button"; import { MobxLitElement } from "@adobe/lit-mobx"; import { store } from "../../store"; import ListItemModel from "../../generated/com/vaadin/tutorial/data/entity/ListItemModel"; import { Binder, field } from "@vaadin/form"; import ListItem from "../../generated/com/vaadin/tutorial/data/entity/ListItem"; @customElement("item-form") export class ItemForm extends MobxLitElement { private binder = new Binder(this, ListItemModel); @property({ type: Object }) set item(item: ListItem) { this.binder.read(item); } static styles = css` :host { display: block; } vaadin-integer-field { width: 4em; } vaadin-combo-box { width: 20em; } `; render() { const { model } = this.binder; return html` <vaadin-integer-field label="Quantity" ...=${field(model.quantity)} ></vaadin-integer-field> <vaadin-text-field label="Item" ...=${field(model.name)} ></vaadin-text-field> <vaadin-combo-box label="Category" ...=${field(model.category)} .items=${store.categories} item-label-path="name" ></vaadin-combo-box> <vaadin-button theme="primary" @click=${this.submit}> ${this.binder.value.id ? "Save" : "Add"} </vaadin-button> `; } submit() { this.binder.submitTo(async (item) => { store.saveItem(item); this.binder.clear(); }); } } <file_sep>/index-preview.ts const addCssBlock = (block: string) => { const tpl = document.createElement('template'); tpl.innerHTML = block; document.head['insertBefore'](tpl.content, document.head.firstChild); }; addCssBlock('<custom-style><style include="lumo-color lumo-typography"></style></custom-style>'); import '@polymer/iron-icon/iron-icon.js'; import '@polymer/iron-list/iron-list.js'; import '@vaadin/vaadin-accordion/theme/lumo/vaadin-accordion.js'; import '@vaadin/vaadin-app-layout/theme/lumo/vaadin-app-layout.js'; import '@vaadin/vaadin-app-layout/theme/lumo/vaadin-drawer-toggle.js'; import '@vaadin/vaadin-board/vaadin-board-row.js'; import '@vaadin/vaadin-board/vaadin-board.js'; import '@vaadin/vaadin-button/theme/lumo/vaadin-button.js'; import '@vaadin/vaadin-charts/src/vaadin-chart.js'; import '@vaadin/vaadin-checkbox/theme/lumo/vaadin-checkbox-group.js'; import '@vaadin/vaadin-checkbox/theme/lumo/vaadin-checkbox.js'; import '@vaadin/vaadin-combo-box/theme/lumo/vaadin-combo-box.js'; import '@vaadin/vaadin-confirm-dialog/theme/lumo/vaadin-confirm-dialog.js'; import '@vaadin/vaadin-context-menu/theme/lumo/vaadin-context-menu.js'; import '@vaadin/vaadin-cookie-consent/theme/lumo/vaadin-cookie-consent.js'; import '@vaadin/vaadin-crud/src/vaadin-crud-edit-column.js'; import '@vaadin/vaadin-crud/theme/lumo/vaadin-crud.js'; import '@vaadin/vaadin-custom-field/theme/lumo/vaadin-custom-field.js'; import '@vaadin/vaadin-date-picker/theme/lumo/vaadin-date-picker.js'; import '@vaadin/vaadin-date-time-picker/theme/lumo/vaadin-date-time-picker.js'; import '@vaadin/vaadin-details/theme/lumo/vaadin-details.js'; import '@vaadin/vaadin-dialog/theme/lumo/vaadin-dialog.js'; import '@vaadin/vaadin-form-layout/theme/lumo/vaadin-form-item.js'; import '@vaadin/vaadin-form-layout/theme/lumo/vaadin-form-layout.js'; import '@vaadin/vaadin-grid-pro/theme/lumo/vaadin-grid-pro-edit-column.js'; import '@vaadin/vaadin-grid-pro/theme/lumo/vaadin-grid-pro.js'; import '@vaadin/vaadin-grid/theme/lumo/vaadin-grid-column-group.js'; import '@vaadin/vaadin-grid/theme/lumo/vaadin-grid-column.js'; import '@vaadin/vaadin-grid/theme/lumo/vaadin-grid-sorter.js'; import '@vaadin/vaadin-grid/theme/lumo/vaadin-grid-tree-toggle.js'; import '@vaadin/vaadin-grid/theme/lumo/vaadin-grid.js'; import '@vaadin/vaadin-icons/vaadin-icons.js'; import '@vaadin/vaadin-item/theme/lumo/vaadin-item.js'; import '@vaadin/vaadin-list-box/theme/lumo/vaadin-list-box.js'; import '@vaadin/vaadin-login/theme/lumo/vaadin-login-form.js'; import '@vaadin/vaadin-login/theme/lumo/vaadin-login-overlay.js'; import '@vaadin/vaadin-lumo-styles/color.js'; import '@vaadin/vaadin-lumo-styles/icons.js'; import '@vaadin/vaadin-lumo-styles/sizing.js'; import '@vaadin/vaadin-lumo-styles/spacing.js'; import '@vaadin/vaadin-lumo-styles/style.js'; import '@vaadin/vaadin-lumo-styles/typography.js'; import '@vaadin/vaadin-menu-bar/theme/lumo/vaadin-menu-bar.js'; import '@vaadin/vaadin-notification/theme/lumo/vaadin-notification.js'; import '@vaadin/vaadin-ordered-layout/theme/lumo/vaadin-horizontal-layout.js'; import '@vaadin/vaadin-ordered-layout/theme/lumo/vaadin-vertical-layout.js'; import '@vaadin/vaadin-ordered-layout/vaadin-scroller.js'; import '@vaadin/vaadin-progress-bar/theme/lumo/vaadin-progress-bar.js'; import '@vaadin/vaadin-radio-button/theme/lumo/vaadin-radio-button.js'; import '@vaadin/vaadin-radio-button/theme/lumo/vaadin-radio-group.js'; import '@vaadin/vaadin-rich-text-editor/theme/lumo/vaadin-rich-text-editor.js'; import '@vaadin/vaadin-select/theme/lumo/vaadin-select.js'; import '@vaadin/vaadin-split-layout/theme/lumo/vaadin-split-layout.js'; import '@vaadin/vaadin-tabs/theme/lumo/vaadin-tab.js'; import '@vaadin/vaadin-tabs/theme/lumo/vaadin-tabs.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-email-field.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-integer-field.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-number-field.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-password-field.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-text-area.js'; import '@vaadin/vaadin-text-field/theme/lumo/vaadin-text-field.js'; import '@vaadin/vaadin-time-picker/theme/lumo/vaadin-time-picker.js'; import '@vaadin/vaadin-upload/src/vaadin-upload-file.js'; import '@vaadin/vaadin-upload/theme/lumo/vaadin-upload.js'; import { LitElement, html, css, customElement, property } from 'lit-element'; import { render } from 'lit-html'; import { applyPolyfill } from 'custom-elements-hmr-polyfill'; //@ts-ignore import { DiffDOM, nodeToObj } from 'diff-dom'; // Use custom elements polyfill to speed up things // Might also help avoid leaking memory since old classes can maybe be reclaimed (window as any).HMR_SKIP_DEEP_PATCH = true; applyPolyfill(); const dd = new DiffDOM(); // Previously rendered DiffDOM tree, used for diffing let oldTree: any; // Empty shell that will host the preview DOM @customElement('my-element') //@ts-ignore class MyElement extends LitElement {} const registeredClass = customElements.get('my-element'); const element = new registeredClass(); let currentlySelectedElementId: number; // This section should be in a separate module that is updated with HMR when imports are updated (window as any).importScope = { LitElement: LitElement, html: html, css: css, customElement: customElement, property: property, }; const importHeader = ` const LitElement = window.importScope.LitElement; const html = window.importScope.html; const css = window.importScope.css; const customElement = window.importScope.customElement; const property = window.importScope.property; `; const update = async (code: string) => { console.log('Start update'); const fullCode = importHeader + code; const url = URL.createObjectURL(new Blob([fullCode], { type: 'application/javascript' })); let c: CustomElementConstructor[] = []; const hmrPolyfillDefineFn = CustomElementRegistry.prototype.define; CustomElementRegistry.prototype.define = function ( name: string, constructor: CustomElementConstructor, options?: ElementDefinitionOptions ) { hmrPolyfillDefineFn.apply(this, [name, constructor, options]); c.push(constructor); }; await eval('import(url)'); CustomElementRegistry.prototype.define = hmrPolyfillDefineFn; URL.revokeObjectURL(url); if (c.length === 0) { document.getElementById('outlet')!.innerText = 'The file must define a custom element.'; return; } else if (c.length > 1) { document.getElementById( 'outlet' )!.innerText = `The file defines ${c.length} custom elements. Do not know which one to preview. Please define only one custom element in the file.`; return; } // Override static LitElement helper that delegates to lit-html render (c[0] as any).render = (result: unknown, container: Element | DocumentFragment, options: any) => { let tempContainer = document.createDocumentFragment(); let originalImport = document.importNode; try { document.importNode = (node, deep) => node.cloneNode(deep) as any; render(result, tempContainer, options); } finally { document.importNode = originalImport; } let newTree = nodeToObj(tempContainer); if (oldTree) { const diff = dd.diff(oldTree, newTree); dd.apply(element.shadowRoot!, diff); } else { element.shadowRoot!.append(tempContainer.cloneNode(true)); } //@ts-ignore element.shadowRoot!.adoptedStyleSheets = container.adoptedStyleSheets; oldTree = newTree; refreshSelection(); console.log('Complete update'); window.parent.postMessage({ command: 'updateFinished' }, '*'); }; // Register as custom element to allow creating instance customElements.define('my-element', c[0]); // Emulate attaching so that it will render itself new registeredClass().connectedCallback(); }; const refresh = (code: string) => { const postTranspile = new XMLHttpRequest(); postTranspile.open('POST', '/VAADIN/transpile'); postTranspile.setRequestHeader('Content-Type', 'text/plain'); postTranspile.onreadystatechange = () => { if (postTranspile.readyState === 4 && postTranspile.status === 200) { update(postTranspile.responseText); } }; postTranspile.send(code); }; document.getElementById('outlet')?.appendChild(element); window.addEventListener( 'message', (event) => { const message = event.data; switch (message.command) { case 'transpile': { refresh(message.code); break; } case 'selectFromEditor': { showSelectIndicatorOn(message.id); return; } } }, false ); window.parent.postMessage({ command: 'previewReady' }, '*'); let indicatorAnimation: Animation | undefined; const indicator = document.createElement('div'); { indicator.style.position = 'absolute'; indicator.style.backgroundColor = 'rgb(255, 203, 106)'; indicator.style.opacity = '0'; indicator.style.zIndex = '10000'; indicator.style.pointerEvents = 'none'; const inner = document.createElement('div'); inner.style.height = '100%'; inner.style.backgroundColor = 'rgb(138, 255, 173)'; inner.style.boxSizing = 'border-box'; inner.style.border = '0px solid yellow'; indicator.appendChild(inner); const innermost = document.createElement('div'); innermost.style.height = '100%'; innermost.style.backgroundColor = 'rgb(149, 195, 255)'; inner.appendChild(innermost); } document.body.appendChild(indicator); document.body.onmousedown = (event) => { const targetComponent = document.querySelector('my-element'); const el = targetComponent?.shadowRoot?.elementFromPoint(event.clientX, event.clientY); const id = Number(el!.getAttribute('data-design-id')!) || -1; log(`id found: ${id}Element found: ${el!.outerHTML}`); window.parent.postMessage({ command: 'selectFromPreview', id: id }, '*'); showSelectIndicatorOn(id, Number.MAX_VALUE); event.preventDefault(); event.stopPropagation(); }; const refreshSelection = () => { showSelectIndicatorOn(currentlySelectedElementId); }; const showSelectIndicatorOn = (id: number, delay?: number) => { delay = delay ?? 800; const targetComponent = document.querySelector('my-element'); const el = targetComponent?.shadowRoot?.querySelector('[data-design-id="' + id + '"]'); if (el) { currentlySelectedElementId = id; // POSITION const rect = el.getBoundingClientRect(); indicator.style.top = rect.top + window.scrollY + 'px'; indicator.style.left = rect.left + window.scrollX + 'px'; indicator.style.width = rect.width + 'px'; indicator.style.height = rect.height + 'px'; // MARGIN const cs = window.getComputedStyle(el); indicator.style.padding = cs.margin; indicator.style.marginTop = '-' + cs.marginTop; indicator.style.marginRight = '-' + cs.marginRight; indicator.style.marginBottom = '-' + cs.marginBottom; indicator.style.marginLeft = '-' + cs.marginLeft; // PADDING const padding = indicator.firstElementChild as HTMLElement; padding.style.padding = cs.padding; // BORDER padding.style.borderWidth = cs.borderWidth; // ANIMATE indicatorAnimation?.cancel(); indicatorAnimation = indicator.animate([{ opacity: 0.5 }, { opacity: 0.5 }, { opacity: 0.0 }], { duration: delay, iterations: 1, }); } else { log('Did not find element with id ' + id); indicatorAnimation?.cancel(); indicator.style.opacity = '0'; } }; const log = (msg: string) => { window.parent.postMessage({ logMessage: msg }, '*'); }; <file_sep>/frontend/views/overview/overview-view.ts import "@vaadin/vaadin-charts/src/vaadin-chart-series"; import { css, customElement, html, LitElement } from "lit-element"; import "@vaadin/vaadin-charts"; import { store } from "../../store"; @customElement("overview-view") export class OverviewView extends LitElement { static styles = css` :host { display: block; padding: var(--lumo-space-m); } `; render() { return html` <h1>Shopping stats</h1> <vaadin-chart type="pie"> <vaadin-chart-series .values=${store.countByCategory} ></vaadin-chart-series> </vaadin-chart> `; } } <file_sep>/frontend/routes.ts import { Route } from "@vaadin/router"; import "./views/main/main-view"; import "./views/list/list-view"; export const routes: Route[] = [ { path: "", component: "main-view", children: [ { path: "", component: "list-view", }, { path: "list", component: "list-view", }, { path: "overview", component: "overview-view", action: async () => { await import("./views/overview/overview-view"); }, }, ], }, ]; <file_sep>/README.md # Vaadin Fusion, LitElement and MobX demo app Requires Java 11, run with `mvn` <file_sep>/frontend/views/list/list-view.ts import "./item-form"; import { css, customElement, html, LitElement } from "lit-element"; import { MobxLitElement } from "@adobe/lit-mobx"; import { store } from "../../store"; @customElement("list-view") export class ListView extends MobxLitElement { static styles = css` :host { display: block; padding: var(--lumo-space-m); } `; render() { return html` <h1>Shopping list</h1> <item-form></item-form> ${store.itemsByCategory.map( ([category, items]) => html` <h2>${category}</h2> ${items.map((item) => html` <item-form .item=${item}></item-form> `)} ` )} `; } } <file_sep>/frontend/index.ts import { Router } from "@vaadin/router"; import { routes } from "./routes"; export const router = new Router(document.querySelector("#outlet")); router.setRoutes(routes); <file_sep>/frontend/store.ts import { makeAutoObservable } from "mobx"; import Category from "./generated/com/vaadin/tutorial/data/entity/Category"; import ListItem from "./generated/com/vaadin/tutorial/data/entity/ListItem"; import { getCategories, getShoppingList, saveListItem, } from "./generated/ShoppingListEndpoint"; class Store { items: ListItem[] = []; categories: Category[] = []; constructor() { makeAutoObservable(this); this.initFromServer(); } async initFromServer() { this.setItems(await getShoppingList()); this.setCategories(await getCategories()); } setCategories(categories: Category[]) { this.categories = categories; } setItems(items: ListItem[]) { this.items = items; } async saveItem(item: ListItem) { const saved = await saveListItem(item); if (item.id) { this.setItems(this.items.map((i) => (i.id === saved.id ? saved : i))); } else { this.setItems([...this.items, saved]); } } get itemsByCategory() { const grouped = this.items.reduce( (map, item) => map.set(item.category.name, [ ...(map.get(item.category.name) || []), item, ]), new Map<string, ListItem[]>() ); return Array.from(grouped.entries()); } get countByCategory() { return this.itemsByCategory.map(([category, items]) => ({ name: category, y: items.reduce((sum, i) => (sum += i.quantity), 0), })); } } export const store = new Store(); <file_sep>/frontend/views/main/main-view.ts import { CSSModule } from '@vaadin/flow-frontend/css-utils'; import { AppLayoutElement } from '@vaadin/vaadin-app-layout/src/vaadin-app-layout'; import '@vaadin/vaadin-app-layout/theme/lumo/vaadin-app-layout'; import '@vaadin/vaadin-app-layout/vaadin-drawer-toggle'; import '@vaadin/vaadin-tabs/theme/lumo/vaadin-tab'; import '@vaadin/vaadin-tabs/theme/lumo/vaadin-tabs'; import { css, customElement, html, LitElement, property } from 'lit-element'; import { router } from '../../index'; interface MenuTab { route: string; name: string; } @customElement('main-view') export class MainView extends LitElement { @property({ type: Object }) location = router.location; @property({ type: Array }) menuTabs: MenuTab[] = [ { route: 'list', name: 'List' }, { route: 'overview', name: 'Overview' }, ]; @property({ type: String }) projectName = ''; static get styles() { return [ CSSModule('lumo-typography'), CSSModule('lumo-color'), CSSModule('app-layout'), css` :host { display: block; height: 100%; } header { align-items: center; box-shadow: var(--lumo-box-shadow-s); display: flex; height: var(--lumo-size-xl); width: 100%; } header h1 { font-size: var(--lumo-font-size-l); margin: 0; } header img { border-radius: 50%; height: var(--lumo-size-s); margin-left: auto; margin-right: var(--lumo-space-m); overflow: hidden; background-color: var(--lumo-contrast); } vaadin-app-layout[dir='rtl'] header img { margin-left: var(--lumo-space-m); margin-right: auto; } #logo { align-items: center; box-sizing: border-box; display: flex; padding: var(--lumo-space-s) var(--lumo-space-m); } #logo img { height: calc(var(--lumo-size-l) * 1.5); } #logo span { font-size: var(--lumo-font-size-xl); font-weight: 600; margin: 0 var(--lumo-space-s); } vaadin-tab { font-size: var(--lumo-font-size-s); height: var(--lumo-size-l); font-weight: 600; color: var(--lumo-body-text-color); } vaadin-tab:hover { background-color: var(--lumo-contrast-5pct); text-decoration: none; } vaadin-tab[selected] { background-color: var(--lumo-primary-color-10pct); color: var(--lumo-primary-text-color); } hr { margin: 0; } `, ]; } render() { return html` <vaadin-app-layout primary-section="drawer"> <header slot="navbar" theme="dark"> <vaadin-drawer-toggle></vaadin-drawer-toggle> <h1>${this.getSelectedTabName(this.menuTabs)}</h1> <img src="images/user.svg" alt="Avatar" /> </header> <div slot="drawer"> <div id="logo"> <img src="images/logo.png" alt="${this.projectName} logo" /> <span>${this.projectName}</span> </div> <hr /> <vaadin-tabs orientation="vertical" theme="minimal" id="tabs" .selected="${this.getIndexOfSelectedTab()}"> ${this.menuTabs.map( (menuTab) => html` <vaadin-tab> <a href="${router.urlForPath(menuTab.route)}" tabindex="-1">${menuTab.name}</a> </vaadin-tab> ` )} </vaadin-tabs> </div> <slot></slot> </vaadin-app-layout> `; } private _routerLocationChanged() { AppLayoutElement.dispatchCloseOverlayDrawerEvent(); } connectedCallback() { super.connectedCallback(); window.addEventListener('vaadin-router-location-changed', this._routerLocationChanged); this.projectName = 'Shopping List'; } disconnectedCallback() { super.disconnectedCallback(); window.removeEventListener('vaadin-router-location-changed', this._routerLocationChanged); } private isCurrentLocation(route: string): boolean { return router.urlForPath(route) === this.location.getUrl(); } private getIndexOfSelectedTab(): number { const index = this.menuTabs.findIndex((menuTab) => this.isCurrentLocation(menuTab.route)); // Select first tab if there is no tab for home in the menu if (index === -1 && this.isCurrentLocation('')) { return 0; } return index; } private getSelectedTabName(menuTabs: MenuTab[]): string { const currentTab = menuTabs.find((menuTab) => this.isCurrentLocation(menuTab.route)); let tabName = ''; if (currentTab) { tabName = currentTab.name; } else { tabName = 'List'; } return tabName; } }
eda71c854ca9d7a5ba649c912dd2067aea82ecf4
[ "Markdown", "Java", "TypeScript" ]
11
Java
marcushellberg/shopping-list
0c9d863a2d2df31cef8ba1694ba4ed32935f57f1
0f79ba61bccadd9d4b2b89894e9cc973f9da6422
refs/heads/master
<repo_name>LiboHuang1992/JavaSE<file_sep>/JavaSE_apps/src/com/bnu/DataStructures/CycleLinkedList.java package com.bnu.DataStructures; public class CycleLinkedList { private int length; private class Node { private Node prev; private Node next; private int data; } } <file_sep>/JavaSE_apps/src/com/bnu/basic/rhombus.java package com.bnu.basic; import java.util.Scanner; /******** * Print rhombus: * *** ***** ******* ***** *** * **********/ public class rhombus { public static void main(String[] args) { System.out.print("请输入菱形的层数(请注意菱形的层数一定是奇数):"); Scanner sc = new Scanner(System.in); int layer = sc.nextInt();//layer代表菱形的层数 for (int i = 1; i <= layer; i++) { //打印菱形的上半部分 if (i <= layer / 2 + 1) { //打印空格 for (int p = layer / 2 + 1 - i; p > 0; p--) { System.out.print(" "); } //打印星号 for (int j = 1; j <= 2 * i - 1; j++) { System.out.print("*"); } System.out.println(); } //打印菱形的下半部分 else { //打印空格 for (int q = i - (layer / 2 + 1); q > 0; q--) { System.out.print(" "); } //打印星号 for (int k = 2 * (2 * (layer / 2 + 1) - i) - 1; k >= 1; k--) { System.out.print("*"); } System.out.println(); } } sc.close(); } }
9621c2e70ae26145cf0971de5970f822f9f6c13e
[ "Java" ]
2
Java
LiboHuang1992/JavaSE
05bd29a7ef1f7d58a4db58f016017ff0063e10d7
119d2da499c36a0283a01d43a7d4286bbcf306e6
refs/heads/master
<repo_name>hanyoupcho/react-native-chat<file_sep>/index.ios.js import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './components/App'; export default class ChatNow extends Component { render() { return ( <App /> ); } } AppRegistry.registerComponent('ChatNow', () => ChatNow); <file_sep>/components/App.js import React, {Component} from 'react'; import { Navigator, StyleSheet, Platform, } from 'react-native'; import routes from '../routes'; import MainScreen from './MainScreen'; import SignInScreen from './SignInScreen'; import NavBarRouteMapper from './NavBarRouteMapper'; export default class App extends Component { _renderScene(route, navigator) { switch (route.name) { case 'SignInScreen': return <SignInScreen /> case 'MainScreen': return <MainScreen getHelpPressHandler={() => { navigator.push(routes.signIn) }} /> } } render() { return ( <Navigator initialRoute={routes.main} renderScene={this._renderScene} style={styles.container} sceneStyle={styles.sceneContainer} navigationBar={<Navigator.NavigationBar routeMapper={NavBarRouteMapper} style={styles.navBar} />} /> ) } }; const styles = StyleSheet.create({ container: { flex: 1, }, sceneContainer: { flex: 1, justifyContent: 'center', alignItems: 'stretch', marginTop: Platform.OS === 'ios' ? 64 : 56, }, navBar: { backgroundColor: '#efefef', borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#494949', }, });
c944f687b1226a4c86b855e5e396fb5e66e91a3c
[ "JavaScript" ]
2
JavaScript
hanyoupcho/react-native-chat
2bd8645c1a36f674b1cbeb2179ec399b6a2a505f
d3438848456fa1f0754a44d0092aea4e002ade26
refs/heads/master
<file_sep>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package alertinitializer import ( informers "github.com/maleck13/kubeop-bot/pkg/client/informers_generated/internalversion" "k8s.io/apiserver/pkg/admission" ) // WantsInternalAlertInformerFactory defines a function which sets InformerFactory for admission plugins that need it type WantsInternalAlertInformerFactory interface { SetInternalAlertInformerFactory(informers.SharedInformerFactory) admission.Validator } <file_sep>package alert import ( "fmt" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/storage" "k8s.io/apiserver/pkg/storage/names" "github.com/maleck13/kubeop-bot/pkg/apis/kubeopbot" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" ) func NewStrategy(typer runtime.ObjectTyper) alertStrategy { return alertStrategy{typer, names.SimpleNameGenerator} } func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, bool, error) { apiserver, ok := obj.(*kubeopbot.Alert) if !ok { return nil, nil, false, fmt.Errorf("given object is not an Alert.") } return labels.Set(apiserver.ObjectMeta.Labels), alertToSelectableFields(apiserver), apiserver.Initializers != nil, nil } // MatchAlert is the filter used by the generic etcd backend to watch events // from etcd to clients of the apiserver only interested in specific labels/fields. func MatchAlert(label labels.Selector, field fields.Selector) storage.SelectionPredicate { return storage.SelectionPredicate{ Label: label, Field: field, GetAttrs: GetAttrs, } } // alertToSelectableFields returns a field set that represents the object. func alertToSelectableFields(obj *kubeopbot.Alert) fields.Set { return generic.ObjectMetaFieldsSet(&obj.ObjectMeta, true) } type alertStrategy struct { runtime.ObjectTyper names.NameGenerator } func (alertStrategy) NamespaceScoped() bool { return false } func (alertStrategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) { } func (alertStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) { } func (alertStrategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList { return field.ErrorList{} } func (alertStrategy) AllowCreateOnUpdate() bool { return false } func (alertStrategy) AllowUnconditionalUpdate() bool { return false } func (alertStrategy) Canonicalize(obj runtime.Object) { } func (alertStrategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList { return field.ErrorList{} } <file_sep># kubeopbot POC bot for kubernetes Idea is to create a chat bot that gives information back to chat clients about various events and resources in kube <file_sep>download minikube set the following values in the rc ``` - --requestheader-client-ca-file=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt - --requestheader-username-headers=X-Remote-User - --requestheader-group-headers=X-Remote-Group - --requestheader-extra-headers-prefix=X-Remote-Extra ```<file_sep>package v1alpha1 import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Alert struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` Spec AlertSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` Status AlertStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type AlertList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of Alert Items []Alert `json:"items" protobuf:"bytes,2,rep,name=items"` } type AlertSpec struct { } type AlertStatus struct { } <file_sep>package kubeopbot import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // AlertList is a list of Alert objects. type AlertList struct { metav1.TypeMeta metav1.ListMeta Items []Alert } type AlertSpec struct { } type AlertStatus struct { } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Alert struct { metav1.TypeMeta metav1.ObjectMeta Spec AlertSpec Status AlertStatus } <file_sep>#!/bin/bash # Copyright 2017 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Register function to be called on EXIT to remove generated binary. function cleanup { rm "./artifacts/simple-image/kubeop-bot" } trap cleanup EXIT export GOOS=linux; go build . cp -v ./kubeop-bot ./artifacts/simple-image/kubeop-bot docker build -t maleck13/kubeop-bot:latest ./artifacts/simple-image <file_sep>#!/bin/bash NAMESPACE=kubeop-bot kubectl create ns ${NAMESPACE} kubectl create -f ./artifacts/example/sa.yaml -n ${NAMESPACE} kubectl create -f ./artifacts/example/auth-delegator.yaml -n kube-system kubectl create -f ./artifacts/example/auth-reader.yaml -n kube-system kubectl create -f ./artifacts/example/rc.yaml -n ${NAMESPACE} kubectl create -f ./artifacts/example/service.yaml -n ${NAMESPACE}<file_sep>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package banalert import ( "fmt" "io" "github.com/maleck13/kubeop-bot/pkg/admission/alertinitializer" "github.com/maleck13/kubeop-bot/pkg/apis/kubeopbot" informers "github.com/maleck13/kubeop-bot/pkg/client/informers_generated/internalversion" listers "github.com/maleck13/kubeop-bot/pkg/client/listers_generated/kubeopbot/internalversion" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apiserver/pkg/admission" ) // Register registers a plugin func Register(plugins *admission.Plugins) { plugins.Register("BanAlert", func(config io.Reader) (admission.Interface, error) { return New() }) } type disallowAlert struct { *admission.Handler lister listers.AlertLister } var _ = alertinitializer.WantsInternalAlertInformerFactory(&disallowAlert{}) // Admit ensures that the object in-flight is of kind Alert. // In addition checks that the Name is not on the banned list. // The list is stored in Alert API objects. func (d *disallowAlert) Admit(a admission.Attributes) error { // we are only interested in alerts if a.GetKind().GroupKind() != kubeopbot.Kind("Alert") { return nil } metaAccessor, err := meta.Accessor(a.GetObject()) if err != nil { return err } alertName := metaAccessor.GetName() if alertName == "" { return errors.NewForbidden( a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this name may not be used, please change the resource name"), ) } return nil } // SetInternalAlertInformerFactory gets Lister from SharedInformerFactory. // The lister knows how to lists Alerts. func (d *disallowAlert) SetInternalAlertInformerFactory(f informers.SharedInformerFactory) { d.lister = f.Kubeopbot().InternalVersion().Alerts().Lister() } // Validate checks whether the plugin was correctly initialized. func (d *disallowAlert) Validate() error { if d.lister == nil { return fmt.Errorf("missing alert lister") } return nil } // New creates a new ban alerts admission plugin func New() (admission.Interface, error) { return &disallowAlert{ Handler: admission.NewHandler(admission.Create), }, nil }
7a023898d56c1bcc5921f76e66d654df97fe9ddc
[ "Markdown", "Go", "Shell" ]
9
Go
maleck13/kubeopbot
b0068e9227f011361b880952b0e804a19e5c8494
317017fe904956bb3ab7fa1942ceb7dc4e63c038
refs/heads/master
<repo_name>kirisanth-g/watrhub<file_sep>/water.py import json def solve(elm): limit = elm['truck'] n = len(elm['pipes']) pipes = sorted(elm['pipes'], key=lambda p: p['litres']) table = knapsack(limit, n, pipes) i, cost = find_last_value(table[n]) route = trace(table, i, n, pipes) res = {'Pipes': route, 'Cost': cost} return res def knapsack(limit, n, pipes): table = [[0 for i in range(limit+1)] for j in range(n+1)] for i in range(1, limit + 1): table[0][i] = float('inf') for i in range(1, n+1): cost = pipes[i-1]['cost'] litres = pipes[i-1]['litres'] for j in range (1, limit+1): if (litres > j): table[i][j] = table[i-1][j] else: table[i][j] = min(table[i-1][j], table[i-1][j-litres] + cost) return table def find_last_value(table): index = 0 cost = 0 for i in range(len(table)-1, -1, -1): if (table[i] != float('inf')): index = i cost = table[i] break return index, cost def trace(table, index, n, pipes): route = [] j = index for i in range (n, 0, -1): if (table[i][j] != table[i-1][j]): route.append(pipes[i-1]['name']) j -= pipes[i-1]['litres'] if (j <= 0): break return route if __name__ == "__main__": txt = { 'truck': 10, 'pipes': [{ 'name': 'pipe 1', 'cost': 1, 'litres': 4 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 6}] } print(solve(txt)) <file_sep>/README.md # watrhub WatrHub Take Home Problem: You are the operator of a water company whose job is to maximize the water drainage of a polluted lake while minimizing the cost to do so. The way the company does this is by draining the lake into a truck for one hour at a time. This specialized truck can have any number of pipes attached to it and also has a capacity given in litres. The company must select the optimal set of pipes to attach to the truck to maximize the drainage each hour, while minimizing cost. Input is given in the following JSON format: ``` input = { truck: capacity_in_litres pipes: [ { name: n1, cost: c1, litres: l1 // how much can get drained in one hour }, { name: n2, cost: c2, litres: l2 }, ... ] } ``` Output: ``` Pipes: optimal_pipe_n1, optimal_pipe_n2, ... optimal_pipe_nN Cost: cost to optimally fill ``` Note: *** It is not necessary that the truck is filled to the top. *** Example input: ``` input = { truck: 60 pipes: [ { name: 'pipe 1', cost: 10, litres: 20 }, { name: 'pipe 2', cost: 15, litres: 50 }, { name: 'pipe 3', cost: 4, litres: 25 }, { name: 'pipe 4', cost: 11, litres: 30 } ] } ``` Example output: ``` Pipes: pipe 3, pipe 4 Cost: 15 ``` <file_sep>/testWater.py import unittest import water class TestSolver(unittest.TestCase): def testGivenExample(self): input = { 'truck': 60, 'pipes': [ { 'name': 'pipe 1', 'cost': 10, 'litres': 20 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 50 }, { 'name': 'pipe 3', 'cost': 4, 'litres': 25 }, { 'name': 'pipe 4', 'cost': 11, 'litres': 30 } ] } expected_pipes = set(['pipe 3', 'pipe 4']) expected_cost = 15 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testSmallerLimit(self): input = { 'truck': 10, 'pipes': [ { 'name': 'pipe 3', 'cost': 4, 'litres': 2 }, { 'name': 'pipe 4', 'cost': 11, 'litres': 3 }, { 'name': 'pipe 1', 'cost': 1, 'litres': 4 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 6} ] } expected_pipes = set(['pipe 1', 'pipe 2']) expected_cost = 16 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testOnePipe(self): input = { 'truck': 10, 'pipes': [ { 'name': 'pipe 3', 'cost': 4, 'litres': 2 }] } expected_pipes = set(['pipe 3']) expected_cost = 4 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testTwoPipe(self): input = { 'truck': 10, 'pipes': [{ 'name': 'pipe 1', 'cost': 1, 'litres': 4 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 6}] } expected_pipes = set(['pipe 1', 'pipe 2']) expected_cost = 16 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testMulitplePossible(self): input = { 'truck': 10, 'pipes': [{ 'name': 'pipe 1', 'cost': 1, 'litres': 10 }, { 'name': 'pipe 2', 'cost': 1, 'litres': 10}] } expected_pipes = set(['pipe 1', 'pipe 2']) expected_cost = 1 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertTrue(set(actual['Pipes']).issubset(expected_pipes)) def testOnePipeNotPossible(self): input = { 'truck': 10, 'pipes': [ { 'name': 'pipe 1', 'cost': 14, 'litres': 20 }] } expected_pipes = set([]) expected_cost = 0 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testMultiPipeNotPossible(self): input = { 'truck': 10, 'pipes': [ { 'name': 'pipe 3', 'cost': 4, 'litres': 20 }, { 'name': 'pipe 4', 'cost': 11, 'litres': 30 }, { 'name': 'pipe 1', 'cost': 1, 'litres': 11 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 26} ] } expected_pipes = set([]) expected_cost = 0 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testNoPipes(self): input = { 'truck': 10, 'pipes': [] } expected_pipes = set([]) expected_cost = 0 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testZeroLimit(self): input = { 'truck': 0, 'pipes': [{ 'name': 'pipe 1', 'cost': 1, 'litres': 4 }, { 'name': 'pipe 2', 'cost': 15, 'litres': 6}] } expected_pipes = set([]) expected_cost = 0 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes'])) def testNoPipesZeroLimit(self): input = { 'truck': 0, 'pipes': [] } expected_pipes = set([]) expected_cost = 0 actual = water.solve(input) self.assertEqual(expected_cost, actual['Cost']) self.assertEqual(expected_pipes, set(actual['Pipes']))
06ab44fde265f2da0419c06de753239bfa03d147
[ "Markdown", "Python" ]
3
Python
kirisanth-g/watrhub
a770c08c96a48e924d45965a4e4d27af72e25db3
71c307bf6ced490aded3652b7617682511a7fa44
refs/heads/master
<file_sep>from rest_framework import serializers from django.contrib.auth.models import User from datetime import date from .models import Flight, Booking, Profile class FlightSerializer(serializers.ModelSerializer): class Meta: model = Flight fields = ['destination', 'time', 'price', 'id'] class BookingSerializer(serializers.ModelSerializer): flight = serializers.SlugRelatedField( read_only=True, slug_field='destination' ) class Meta: model = Booking fields = ['flight', 'date', 'id'] class BookingDetailsSerializer(serializers.ModelSerializer): flight = FlightSerializer() total = serializers.SerializerMethodField() class Meta: model = Booking fields = ['flight', 'date', 'total', 'passengers', 'id'] def get_total(self, obj): return obj.passengers * obj.flight.price class AdminUpdateBookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = ['date', 'passengers'] class UpdateBookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = ['passengers'] class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] def create(self, validated_data): username = validated_data['username'] password = validated_data['<PASSWORD>'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] new_user = User(username=username, first_name=first_name, last_name=last_name) new_user.set_password(password) new_user.save() return validated_data class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['first_name', 'last_name'] class ProfileSerializer(serializers.ModelSerializer): past_bookings = serializers.SerializerMethodField() tier = serializers.SerializerMethodField() user = UserProfileSerializer() class Meta: model = Profile fields = ['user', 'miles', 'past_bookings', 'tier'] def get_past_bookings(self, obj): #obj is the profile and if it were booking it would be the booking object bookings = Booking.objects.filter(user=obj.user, date__lt= date.today()) serializer = BookingSerializer(bookings, many=True) return serializer.data def get_tier(self, obj): if obj.miles <= 9999: return "Blue" elif obj.miles <= 59999: return "Silver" elif obj.miles <= 99999: return "Gold" else: return "Platinum"
011ebc7f3f0964dd6f41553245f3e08c22d6838e
[ "Python" ]
1
Python
bnmre81/REST_task_08
1b46a1ae411047cab00581c754e050f90f0194c7
c5a4515d92e97b84b93d7014c279eb0d4896e6ff
refs/heads/master
<repo_name>patrick-etcheverry/openclassdut-partie2<file_sep>/src/Migrations/Version20181105095333.php <?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20181105095333 extends AbstractMigration { public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE ressource (id INT AUTO_INCREMENT NOT NULL, type_ressource_id INT NOT NULL, titre VARCHAR(255) NOT NULL, descriptif LONGTEXT NOT NULL, date_ajout DATETIME NOT NULL, url_ressource VARCHAR(255) NOT NULL, url_vignette VARCHAR(255) NOT NULL, INDEX IDX_939F45447B2F6F2F (type_ressource_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE ressource_module (ressource_id INT NOT NULL, module_id INT NOT NULL, INDEX IDX_E665F595FC6CD52A (ressource_id), INDEX IDX_E665F595AFC2B591 (module_id), PRIMARY KEY(ressource_id, module_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE ressource ADD CONSTRAINT FK_939F45447B2F6F2F FOREIGN KEY (type_ressource_id) REFERENCES type_ressource (id)'); $this->addSql('ALTER TABLE ressource_module ADD CONSTRAINT FK_E665F595FC6CD52A FOREIGN KEY (ressource_id) REFERENCES ressource (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE ressource_module ADD CONSTRAINT FK_E665F595AFC2B591 FOREIGN KEY (module_id) REFERENCES module (id) ON DELETE CASCADE'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE ressource_module DROP FOREIGN KEY FK_E665F595FC6CD52A'); $this->addSql('DROP TABLE ressource'); $this->addSql('DROP TABLE ressource_module'); } } <file_sep>/README.md <h1>Contexte</h1> <p> Ce dépôt contient le code source développé et versionné durant le deuxième module de cours dédié au framework Symfony. Les notions abordées concernent les requêtes sur mesure (QueryBuilder et DQL), la gestion des formulaires (création, génération, affichage, contrôle des données, soumission et imbrication), la gestion de la sécurité et des utilisateurs et la mise en place d'une interface d'administration </p> <p>L'application Openclass DUT est une application développée avec le framework Symfony (version 4) et le framework Bootstrap (version 4). Cette application sert d'exemple pour illustrer un cours réalisé à l'IUT de Bayonne sur le framework Symfony.</p> <p style="text-align:center;"> <img src="https://www.iutbayonne.univ-pau.fr/~etchever/Elearn/M4105C/openclassdut2.jpg" alt="openclass dut" style="width:400px;"> </p> <h1>Objectif de l'application</h1> <p> L'application Openclass DUT est une application de partage de ressources pédagogiques. Elle permet à des étudiants issus d'un département d'IUT de référencer des ressources pédagogiques utiles pour leur formation. Différents types de ressources peuvent être référencés : des fichiers PDF, des images, des tutoriels vidéos, des applications, des sites web... </p> <p> Les ressources partagées sont caractérisées par un nom, un descriptif, une image d'aperçu, le ou les modules dans lesquels cette ressource est utile, le semestre de chacun de ces modules, une date d'ajout de la ressource et un lien de téléchargement. Toutes ces informations sont fournies par l'étudiant qui partage la ressource.</p> <p>Openclass DUT n'héberge pas de ressources pédagogiques : L'application référence uniquement des liens vers des ressources qui sont hébergées ailleurs par l'étudiant (serveur personnel, dropbox, google drive). </p> <file_sep>/src/DataFixtures/AppFixtures.php <?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity\Module; use App\Entity\Ressource; use App\Entity\TypeRessource; use App\Entity\User; class AppFixtures extends Fixture { public function load(ObjectManager $manager) { // Création de 2 utilisateurs de test $patrick = new User(); $patrick->setPrenom("Patrick"); $patrick->setNom("Etcheverry"); $patrick->setEmail("<EMAIL>"); $patrick->setRoles(['ROLE_USER', 'ROLE_ADMIN']); $patrick->setPassword('<PASSWORD>'); $manager->persist($patrick); $pantxika = new User(); $pantxika->setPrenom("Pantxika"); $pantxika->setNom("Dagorret"); $pantxika->setEmail("<EMAIL>"); $pantxika->setRoles(['ROLE_USER']); $pantxika->setPassword('<PASSWORD>'); $manager->persist($pantxika); /* Création d'un générateur de données à partir de la classe Faker*/ $faker = \Faker\Factory::create('fr_FR'); /*************************************** *** CREATION DES TYPES DE RESSOURCES *** ****************************************/ $pdf = new TypeRessource(); $pdf -> setNomType("Fichier PDF"); $pdf -> setIcone("icon-doc-2"); $image = new TypeRessource(); $image -> setNomType("Image"); $image -> setIcone("icon-picture"); $son = new TypeRessource(); $son -> setNomType("Ressource audio"); $son -> setIcone("icon-sound"); $video = new TypeRessource(); $video -> setNomType("Vidéo"); $video -> setIcone("icon-video"); $code = new TypeRessource(); $code -> setNomType("Code source"); $code -> setIcone("icon-code-1"); $archive = new TypeRessource(); $archive -> setNomType("Archive"); $archive -> setIcone("icon-archive-1"); $siteWeb = new TypeRessource(); $siteWeb -> setNomType("Site web"); $siteWeb -> setIcone("icon-globe"); $application = new TypeRessource(); $application -> setNomType("Application"); $application -> setIcone("icon-window"); /* On regroupe les objets "types de ressources" dans un tableau pour pouvoir s'y référer au moment de la création d'une ressource particulière */ $tableauTypesRessources = array($pdf,$image,$son,$video,$code,$archive,$siteWeb,$application); // Mise en persistance des objets typeRessource foreach ($tableauTypesRessources as $typeRessource) { $manager->persist($typeRessource); } /*************************************** *** LISTE DES MODULES DE DUT INFO *** ****************************************/ $modulesDutInfo = array( "M1101" => "Introduction aux systèmes informatiques", "M1102" => "Introduction à l'algorithmique et à la programmation", "M1103" => "Structures de données et algorithmes fondamentaux", "M1104" => "Introduction aux bases de données", "M1105" => "Conception de documents et d'interfaces numériques", "M1106" => "Projet tutoré – Découverte", "M1201" => "Mathématiques discrètes", "M1202" => "Algèbre linéaire", "M1203" => "Environnement économique", "M1204" => "Fonctionnement des organisations", "M1205" => "Fondamentaux de la communication", "M1206" => "Anglais et informatique", "M1207" => "PPP - Connaître le monde professionnel", "M2101" => "Architecture et programmation des mécanismes de base d'un système informatique", "M2102" => "Architecture des réseaux", "M2103" => "Bases de la programmation orientée objet", "M2104" => "Bases de la conception orientée objet", "M2105" => "Introduction aux interfaces homme-machine (IHM)", "M2106" => "Programmation et administration des bases de données", "M2107" => "Projet tutoré – Description et planification de projet", "M2201" => "Graphes et langages", "M2202" => "Analyse et méthodes numériques", "M2203" => "Environnement comptable, financier, juridique et social", "M2204" => "Gestion de projet informatique", "M2205" => "Communication, information et argumentation", "M2206" => "Communiquer en anglais", "M2207" => "PPP – Identifier ses compétences" ); /******************************************************** *** CREATION DES MODULES ET DES RESSOURCES ASSOCIEES *** *********************************************************/ foreach ($modulesDutInfo as $codeModule => $titreModule) { // ************* Création d'un nouveau module ************* $module = new Module(); // Définition du code du semestre $module->setCode($codeModule); // Définition du titre du semestre $module->setTitre($titreModule); // Définition du numéro du semestre $module->setSemestre($codeModule[1]); // Enregistrement du module créé $manager->persist($module); // **** Création de plusieurs ressources associées au module $nbRessourcesAGenerer = $faker->numberBetween($min = 0, $max = 7); for ($numRessource=0; $numRessource < $nbRessourcesAGenerer; $numRessource++) { $ressource = new Ressource(); $ressource -> setTitre($faker->sentence($nbWords = 6, $variableNbWords = true)); $ressource -> setDescriptif($faker->realText($maxNbChars = 200, $indexSize = 2)); $ressource -> setDateAjout($faker->dateTimeBetween($startDate = '-6 months', $endDate = 'now', $timezone = 'Europe/Paris')); $ressource -> setUrlRessource($faker->url); $ressource -> setUrlVignette($faker->imageUrl(400, 400, 'technics')); // Création relation Ressource --> Module $ressource -> addModule($module); /****** Définir et mettre à jour le type de ressource ******/ // Sélectionner un type de ressource au hasard parmi les 8 types enregistrés dans $tableauTypesRessources $numTypeRessource = $faker->numberBetween($min = 0, $max = 7); // Création relation Ressource --> TypeRessource $ressource -> setTypeRessource($tableauTypesRessources[$numTypeRessource]); // Création relation TypeRessource --> Ressource $tableauTypesRessources[$numTypeRessource] -> addRessource($ressource); // Persister les objets modifiés $manager->persist($ressource); $manager->persist($tableauTypesRessources[$numTypeRessource]); } } // Envoi des objets créés en base de données $manager->flush(); } } <file_sep>/src/Entity/TypeRessource.php <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\TypeRessourceRepository") */ class TypeRessource { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nomType; /** * @ORM\Column(type="string", length=40) */ private $icone; /** * @ORM\OneToMany(targetEntity="App\Entity\Ressource", mappedBy="typeRessource") */ private $ressources; public function __construct() { $this->ressources = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getNomType(): ?string { return $this->nomType; } public function setNomType(string $nomType): self { $this->nomType = $nomType; return $this; } public function getIcone(): ?string { return $this->icone; } public function setIcone(string $icone): self { $this->icone = $icone; return $this; } /** * @return Collection|Ressource[] */ public function getRessources(): Collection { return $this->ressources; } public function addRessource(Ressource $ressource): self { if (!$this->ressources->contains($ressource)) { $this->ressources[] = $ressource; $ressource->setTypeRessource($this); } return $this; } public function removeRessource(Ressource $ressource): self { if ($this->ressources->contains($ressource)) { $this->ressources->removeElement($ressource); // set the owning side to null (unless already changed) if ($ressource->getTypeRessource() === $this) { $ressource->setTypeRessource(null); } } return $this; } public function __toString() { return $this->getNomType(); } } <file_sep>/src/Controller/OpenclassdutController.php <?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; use App\Entity\Ressource; use App\Repository\RessourceRepository; use Symfony\Component\HttpFoundation\Request; use Doctrine\Common\Persistence\ObjectManager; use App\Form\RessourceType; class OpenclassdutController extends AbstractController { /** * @Route("/", name="openclassdut_accueil") */ public function index(RessourceRepository $repositoryRessource) { // Récupérer les ressources enregistrées en BD $ressources = $repositoryRessource->findByDateAjoutDql(); // Envoyer les ressources récupérées à la vue chargée de les afficher return $this->render('openclassdut/index.html.twig', ['ressources'=>$ressources]); } /** * @Route("/ressources/ajouter", name="openclassdut_ajoutRessource") */ public function ajouterRessource(Request $request, ObjectManager $manager) { //Création d'une ressource vierge qui sera remplie par le formulaire $ressource = new Ressource(); // Création du formulaire permettant de saisir une ressource $formulaireRessource = $this->createForm(RessourceType::class, $ressource); /* On demande au formulaire d'analyser la dernière requête Http. Si le tableau POST contenu dans cette requête contient des variables titre, descriptif, etc. alors la méthode handleRequest() récupère les valeurs de ces variables et les affecte à l'objet $ressource*/ $formulaireRessource->handleRequest($request); if ($formulaireRessource->isSubmitted() && $formulaireRessource->isValid()) { // Mémoriser la date d'ajout de la ressources $ressource->setDateAjout(new \dateTime()); // Enregistrer la ressource en base de donnéelse $manager->persist($ressource); $manager->flush(); // Rediriger l'utilisateur vers la page d'accueil return $this->redirectToRoute('openclassdut_accueil'); } // Afficher la page présentant le formulaire d'ajout d'une ressource return $this->render('openclassdut/ajoutModifRessource.html.twig',['vueFormulaire' => $formulaireRessource->createView(), 'action'=>"ajouter"]); } /** * @Route("/ressources/modifier/{id}", name="openclassdut_modifRessource") */ public function modifierRessource(Request $request, ObjectManager $manager, Ressource $ressource) { // Création du formulaire permettant de modifier une ressource $formulaireRessource = $this->createForm(RessourceType::class, $ressource); /* On demande au formulaire d'analyser la dernière requête Http. Si le tableau POST contenu dans cette requête contient des variables titre, descriptif, etc. alors la méthode handleRequest() récupère les valeurs de ces variables et les affecte à l'objet $ressource*/ $formulaireRessource->handleRequest($request); if ($formulaireRessource->isSubmitted() ) { // Enregistrer la ressource en base de donnéelse $manager->persist($ressource); $manager->flush(); // Rediriger l'utilisateur vers la page d'accueil return $this->redirectToRoute('openclassdut_accueil'); } // Afficher la page présentant le formulaire d'ajout d'une ressource return $this->render('openclassdut/ajoutModifRessource.html.twig',['vueFormulaire' => $formulaireRessource->createView(), 'action'=>"modifier"]); } /** * @Route("/ressources/semestre{semestre}", name="openclassdut_ressources_semestre") */ public function ressourcesParSemestre(RessourceRepository $repositoryRessource, $semestre) { // Récupérer les ressources enregistrées en BD $ressources = $repositoryRessource->findBySemestre($semestre); // Envoyer les ressources récupérées à la vue chargée de les afficher return $this->render('openclassdut/index.html.twig', ['ressources'=>$ressources]); } /** * @Route("/ressources/{id}", name="openclassdut_ressource") */ public function afficherRessourcePeda(Ressource $ressource) { // Envoyer la ressource récupérée à la vue chargée de l'afficher return $this->render('openclassdut/affichageRessource.html.twig', ['ressource' => $ressource]); } } <file_sep>/src/Form/RessourceType.php <?php namespace App\Form; use App\Entity\Ressource; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use App\Entity\TypeRessource; use App\Entity\Module; class RessourceType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('titre') ->add('descriptif') ->add('urlRessource') ->add('urlVignette') /* ->add('typeRessource', EntityType::class, array( 'class' => TypeRessource::class, 'choice_label' => 'nomType', // used to render a select box, check boxes or radios 'multiple' => false, 'expanded' => true, )) ->add('modules', EntityType::class, array( 'class' => Module::class, 'choice_label' => function(Module $module) {return $module->getCode().' '.$module->getTitre();}, // used to render a select box, check boxes or radios 'multiple' => true, 'expanded' => true, )) */ ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Ressource::class, ]); } } <file_sep>/src/Entity/Ressource.php <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass="App\Repository\RessourceRepository") */ class Ressource { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank * @Assert\Length( * min = 5, * max = 255, * minMessage = "Le titre doit faire au minimum {{ limit }} caractères", * maxMessage = "Le titre doit faire au maximum {{ limit }} caractères" * ) */ private $titre; /** * @ORM\Column(type="text") * @Assert\NotBlank * @Assert\Length( * min = 20, * minMessage = "Le descriptif doit faire au minimum {{ limit }} caractères", * ) */ private $descriptif; /** * @ORM\Column(type="datetime") */ private $dateAjout; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank * @Assert\Url */ private $urlRessource; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank * @Assert\Url */ private $urlVignette; /** * @ORM\ManyToOne(targetEntity="App\Entity\TypeRessource", inversedBy="ressources") * @ORM\JoinColumn(nullable=true) */ private $typeRessource; /** * @ORM\ManyToMany(targetEntity="App\Entity\Module", inversedBy="ressources") */ private $modules; public function __construct() { $this->modules = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitre(): ?string { return $this->titre; } public function setTitre(string $titre): self { $this->titre = $titre; return $this; } public function getDescriptif(): ?string { return $this->descriptif; } public function setDescriptif(string $descriptif): self { $this->descriptif = $descriptif; return $this; } public function getDateAjout(): ?\DateTimeInterface { return $this->dateAjout; } public function setDateAjout(\DateTimeInterface $dateAjout): self { $this->dateAjout = $dateAjout; return $this; } public function getUrlRessource(): ?string { return $this->urlRessource; } public function setUrlRessource(string $urlRessource): self { $this->urlRessource = $urlRessource; return $this; } public function getUrlVignette(): ?string { return $this->urlVignette; } public function setUrlVignette(string $urlVignette): self { $this->urlVignette = $urlVignette; return $this; } public function getTypeRessource(): ?TypeRessource { return $this->typeRessource; } public function setTypeRessource(?TypeRessource $typeRessource): self { $this->typeRessource = $typeRessource; return $this; } /** * @return Collection|Module[] */ public function getModules(): Collection { return $this->modules; } public function addModule(Module $module): self { if (!$this->modules->contains($module)) { $this->modules[] = $module; } return $this; } public function removeModule(Module $module): self { if ($this->modules->contains($module)) { $this->modules->removeElement($module); } return $this; } public function __toString() { return $this->getTitre(); } } <file_sep>/src/Entity/Module.php <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\ModuleRepository") */ class Module { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=10) */ private $code; /** * @ORM\Column(type="string", length=255) */ private $titre; /** * @ORM\Column(type="smallint") */ private $semestre; /** * @ORM\ManyToMany(targetEntity="App\Entity\Ressource", mappedBy="modules") */ private $ressources; public function __construct() { $this->ressources = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getCode(): ?string { return $this->code; } public function setCode(string $code): self { $this->code = $code; return $this; } public function getTitre(): ?string { return $this->titre; } public function setTitre(string $titre): self { $this->titre = $titre; return $this; } public function getSemestre(): ?int { return $this->semestre; } public function setSemestre(int $semestre): self { $this->semestre = $semestre; return $this; } /** * @return Collection|Ressource[] */ public function getRessources(): Collection { return $this->ressources; } public function addRessource(Ressource $ressource): self { if (!$this->ressources->contains($ressource)) { $this->ressources[] = $ressource; $ressource->addModule($this); } return $this; } public function removeRessource(Ressource $ressource): self { if ($this->ressources->contains($ressource)) { $this->ressources->removeElement($ressource); $ressource->removeModule($this); } return $this; } public function __toString() { return $this->getCode()." - ".$this->getTitre(); } } <file_sep>/src/Repository/RessourceRepository.php <?php namespace App\Repository; use App\Entity\Ressource; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method Ressource|null find($id, $lockMode = null, $lockVersion = null) * @method Ressource|null findOneBy(array $criteria, array $orderBy = null) * @method Ressource[] findAll() * @method Ressource[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class RessourceRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, Ressource::class); } /** * @return Ressource[] Returns an array of Ressource objects */ public function findBySemestre($semestre) { return $this->createQueryBuilder('r') ->join('r.modules', 'm') ->andWhere('m.semestre = :numSemestre') ->setParameter('numSemestre', $semestre) ->orderBy('r.dateAjout', 'DESC') ->getQuery() ->getResult() ; } /** * @return Ressource[] Returns an array of Ressource objects */ public function findByDateAjout() { return $this->createQueryBuilder('r') ->orderBy('r.dateAjout', 'DESC') ->getQuery() ->getResult() ; } /** * @return Ressource[] Returns an array of Ressource objects */ public function findByDateAjoutDql() { // Récupérer le gestionnaire d'entité $entityManager = $this->getEntityManager(); // Construction de la requêtemp $requete = $entityManager->createQuery( 'SELECT r FROM App\Entity\Ressource r ORDER BY r.dateAjout DESC' ); // Exécuter la requête et retourner les résultats return $requete->execute(); } /* public function findOneBySomeField($value): ?Ressource { return $this->createQueryBuilder('r') ->andWhere('r.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ }
9039f2a565ddfeac0735e2facf0d12bd0438a3e7
[ "Markdown", "PHP" ]
9
PHP
patrick-etcheverry/openclassdut-partie2
7853b131fecb64bb273fb2793bf98b2578224dc0
db919b1cc90f21cb3474933bab6bde6abc85bf67
refs/heads/master
<repo_name>hexiaoah/hexiao<file_sep>/union-entrance/src/views/nav/navBar/createNavItems.js import util from '../util' import navList from './navData' //menuIdList是权限的id集合 const { menuIdList = [] } = util.getCookie('entrance') //判断有无权限显示 function hasPermission(id) { return menuIdList.indexOf(id) !== -1 } function getNavItems(items, active) { let navItems = '' items.forEach(({ url, target, name, id, children }) => { //当存在二级菜单 if (children && children.length) { //只要有其中一个二级菜单有权限就显示父节点 if (children.some(item => hasPermission(item.id))) { navItems += `<div class="nav-item-parent"> <span class="nav-item-parent-title">${name}</span> <div class="nav-item-child">${getNavItems( children, active )}</div> </div>` } } else if (hasPermission(id)) { const flag = name === active navItems += `<a class="nav-item${flag ? ' nav-active' : ''}" go="${ flag ? '-' : url || '' }" target="${target || '__self'}">${name}</a>` } }) return navItems } export default function createNavBar(config) { const { navBar } = config if (!navBar) { return '' } const isChangePage = location.pathname.indexOf('page/change.html') !== -1 const active = util.getCookie('active', false) return `<div class="nav-bar"style="${ isChangePage ? 'display:none;' : '' }" id="common-nav-bar">${getNavItems( navList.filter(function (item) { return !item.hidden }), active )}</div>` } <file_sep>/inside-chain/src/tools/feed-back-auto/readme.md # feed-back-auto 提供各种姿势召唤弹框`api`接口方案。 [设计稿参考](http://git.2dfire-inc.com/static/npm-feed-back/raw/7c8c1aa34ccd6298c06a51d37f6c459bf95f894a/doc/%E8%AE%BE%E8%AE%A1%E7%A8%BF/preview/%E5%BC%B9%E7%AA%97%E6%A0%B7%E5%BC%8F-%E5%BC%B9%E7%AA%97%E8%A7%84%E8%8C%83.png) ## Description 各类弹框的集合`api`,主要意义如下两点 1. 提供各弹框参数约定以及实现要求 2. 提供各弹框`api`调用方法,然后分发给具体实现方案 ## Usage ### 1. 引入提醒弹框实现部分 #### 1) 微信小程序 现在完整的实现有官方接口和模板实现, 引入方法分别如下 官方接口实现 ```js // 官方接口实现,有局限性,但是使用官方api,性能较好 // 依赖官方接口: wx.showModal wx.showToast wx.hideToast import mountFeedBackImpl, { unmount } from '@2dfire/feed-back-auto-impl-wxapp'; mountFeedBackImpl(); // 只需要全局挂载一次 // unmount(); // 可以在需要的时候卸载 ``` 模板实现 ```js // 推荐,实现完整,ui定制性高 // 参考static-light-template,需要拷贝components/dui/feed-back到项目目录 import './components/dui/feed-back/auto'; // 只需要全局引入一次,推荐在app.js ``` ```html <!-- 需要在每个page.wxml都挂载 --> <include src="/components/dui/feed-back/auto.wxml"/> ``` #### 2) web 现在完整的实现只有`jQuery`, 引入方法如下,引入前需要全局绑定`$` ```js import mountFeedBackImpl, { unmount } from '@2dfire/feed-back-auto-impl-jquery'; mountFeedBackImpl(); // 只需要全局挂载一次 // unmount(); // 可以在需要的时候卸载 ``` ### 2. api使用 ```js import toast from '@2dfire/feed-back-auto/toast'; import alert from '@2dfire/feed-back-auto/alert'; import modal from '@2dfire/feed-back-auto/modal'; import message from '@2dfire/feed-back-auto/message'; // 最简单的调用 toast.loading('加载中'); // 提醒弹窗类型.级别(内容|参数, 回调) // 回调使用 modal.info('确认', function(res) { // res: 用户交互的结果 if (res.ok) { toast.success('保存成功'); } else if (res.cancel) { toast.success('已经取消'); } }); // 等同于 modal.info({ content: '确认', callback: function(res) { // res: 用户交互的结果 if (res.ok) { toast.success('保存成功'); } else if (res.cancel) { toast.success('已经取消'); // 不允许,弹窗继续 return false; } } }); // 隐藏弹框 message toast alert modal 都支持 message.hide(); toast.hide(); ``` 支持的级别说明 - `info`: 提示 - `warning`: 警告 - `error`: 错误 - `success`: 成功 - `loading`: loading ## 各弹框参数说明 ### alert ![alert](http://git.2dfire-inc.com/static/npm-feed-back/raw/master/packages/feed-back-auto/images/alert.png) | 名字 | 说明 | 类型 | 默认值 | 必须实现 | 实现备注 | |:----------|:-----------------------|:---------|:-------|:---------|:-------------------------| | title | 标题 | String | '' | 否 | 没有表示不显示 | | closeText | 关闭按钮文案 | String | '确认' | 是 | 没有表示不显示 | | duration | 延迟时间,单位毫秒 | Number | -1 | 是 | 设定时间后自动隐藏 | | showIcon | 是否需要显示icon | Boolean | true | 否 | | | iconImage | icon图片地址 | String | '' | 否 | | | content | 内容 | String | '' | 是 | | | callback | 回调 | Function | null | 是 | 如果有则回调,详细见下文 | | level | 级别,success、error.. | String | 'info' | 否 | 根据此产生不同样式弹框 | | mask | 背景蒙层 | Boolean | true | 是 | | | visible | 是否显示 | Boolean | false | 是 | | ### toast ![toast](http://git.2dfire-inc.com/static/npm-feed-back/raw/master/packages/feed-back-auto/images/toast.png) | 名字 | 说明 | 类型 | 默认值 | 必须实现 | 实现备注 | |:----------|:-----------------------|:---------|:-------|:---------|:-------------------------| | duration | 延迟时间,单位毫秒 | Number | -1 | 是 | 设定时间后自动隐藏 | | iconImage | icon图片地址 | String | '' | 否 | | | content | 内容 | String | '' | 是 | | | callback | 回调 | Function | null | 是 | 如果有则回调,详细见下文 | | level | 级别,success、error.. | String | 'info' | 否 | 根据此产生不同样式弹框 | | mask | 背景蒙层 | Boolean | true | 是 | | | visible | 是否显示 | Boolean | false | 是 | | ### message ![message](http://git.2dfire-inc.com/static/npm-feed-back/raw/master/packages/feed-back-auto/images/message.png) | 名字 | 说明 | 类型 | 默认值 | 必须实现 | 实现备注 | |:----------|:-----------------------|:---------|:-------|:---------|:-------------------------| | duration | 延迟时间,单位毫秒 | Number | 3000 | 是 | 设定时间后自动隐藏 | | showIcon | 是否需要显示icon | Boolean | true | 否 | | | iconImage | icon图片地址 | String | '' | 否 | | | content | 内容 | String | '' | 是 | | | callback | 回调 | Function | null | 是 | 如果有则回调,详细见下文 | | level | 级别,success、error.. | String | 'info' | 否 | 根据此产生不同样式弹框 | | mask | 背景蒙层 | Boolean | false | 是 | | | visible | 是否显示 | Boolean | false | 是 | | ### Modal ![modal-confirm](http://git.2dfire-inc.com/static/npm-feed-back/raw/master/packages/feed-back-auto/images/modal.png) | 名字 | 说明 | 类型 | 默认值 | 必须实现 | 实现备注 | |:-----------|:-----------------------|:---------|:-------|:---------|:-------------------------| | title | 标题 | String | -1 | 否 | 没有表示不显示 | | okText | 确定按钮文案 | String | '确认' | 是 | 没有表示不显示 | | cancelText | 取消按钮文案 | String | '取消' | 是 | 没有表示不显示 | | showIcon | 是否需要显示icon | Boolean | true | 否 | | | iconImage | icon图片地址 | String | '' | 否 | | | content | 内容 | String | '' | 是 | | | callback | 回调 | Function | null | 是 | 如果有则回调,详细见下文 | | level | 级别,success、error.. | String | 'info' | 否 | 根据此产生不同样式弹框 | | mask | 背景蒙层 | Boolean | true | 是 | | | visible | 是否显示 | Boolean | false | 是 | | ## 各端实现要求 ### 1. 实现`callback` 考虑业务希望写的代码如下: ```js model({ content: '空调开了吗?', okText: '开了', cancelText: '没开', callback: (result) => { if (result.ok) { log('用户说开了'); } else if (result.cancel) { log('用户说没开'); // 不允许,弹窗继续 return false; } } }) ``` 上述代码中对`callback`有如下要求 1. 单一`callback`,传入参数result表示事件情况,回调参数如下结构 - `Object` result - `Boolean` ok 是否是点击ok按钮 - `Boolean` cancel 是否是点击cancel按钮 2. 如果`callback`返回`false`,表示不关闭弹窗 ### 2. 蒙层 1. 蒙层仅仅作为防止用户其它操作的遮挡物 2. 点击蒙层不触发事件 3. 点击蒙层不隐藏弹窗 ### 3. 弹窗实现 1. 同一类型的弹窗,全局应该只有一个(消息`message`按情况除外),因此同类型弹窗应 该覆盖原先弹窗,而不是弹出两个同类型弹窗。 2. 弹出同类型弹窗时,应该在原有dom上修改。特别在倒计时类弹窗情况时,需要避免弹窗抖动。 <file_sep>/inside-boss/src/container/rootContainer/pathMap.js export default item => { const {query = {}} = item return { visual_config_design: '/visual_config_design', visual_config_pages: '/visual_config_pages', visual_config_templates: '/visual_config_templates', visual_config_backups: '/visual_config_backups', visual_config_union: '/visual_config_union', visual_config_adPage: '/visual_config_adPage', visual_config_recommendedGood: '/visual_config_recommendedGood', price_tag: '/price_tag', CHART: `/CHART/${query.reportId || ''}`, ITEM_EXPORT: '/ITEM_EXPORT/item', ITEM_EDIT: '/ITEM_EDIT/item', COMBINED_GOODS_EDIT: '/COMBINED_GOODS_EDIT/item', DOWNLOAD_COMM_TMPL: '/DOWNLOAD_COMM_TMPL/template', IMPORT_LOG: '/IMPORT_LOG/comm', HIGH_ROUTE_IMPORT: '/HIGH_ROUTE_IMPORT/item', HIGH_TRAIN_IMPORT: '/HIGH_TRAIN_IMPORT/item', MEMBER_EXPORT: '/MEMBER_EXPORT/member', RECHARGE_BATCH: '/RECHARGE_BATCH/recharge', BOSS_VIDEO_IMPORT: '/BOSS_VIDEO_IMPORT/video', ORDER_HISTORY_SNAPSHOT: '/ORDER_HISTORY_SNAPSHOT/order', BOSS_MENU_IMG_IMPORT: '/BOSS_MENU_IMG_IMPORT/picture', UPLOAD_COMM_FILE: '/UPLOAD_COMM_FILE/item', PC_BRAND_ISSUE_COUPON: '/PC_BRAND_ISSUE_COUPON/coupon',//优惠券批量发放 PC_ISSUE_COUPON: '/PC_BRAND_ISSUE_COUPON/coupon',//优惠券批量发放一样的 NO_OWNER_COUPON: '/NO_OWNER_COUPON/coupon',//不记名优惠券 HIGH_DAILY_MONITOR: '/HIGH_DAILY_MONITOR/list', MALL_BANNER_MANAGER: '/MALL_BANNER_MANAGER/list', MALL_PROMOTION_MANAGER: '/MALL_PROMOTION_MANAGER/list', IMPORT_HISTORY: '/IMPORT_HISTORY/import_history', CUSTOM_BILL: '/CUSTOM_BILL/main', //自定义单据 ITEM_IMPORT: '/ITEM_IMPORT/item', design: '/design', visual_template: '/visual_template', visual_backup: '/visual_backup', CUSTOM_BILL: '/CUSTOM_BILL/main',//自定义单据, FHY_EXTERNAL_LINK: '/EXTERNAL_LINK/shopManage', FHY_CATEGORY_LINK: '/EXTERNAL_LINK/category', FHY_DYNAMIC_LINK: '/EXTERNAL_LINK/dynamic', FHY_CHAINMANAGE_LINK: '/EXTERNAL_LINK/chainManage', FHY_ACCOUNTGUARANTEE_LINK:'/EXTERNAL_LINK/bankCardCheckForGuarantee', FHY_VEDIO_LINK: '/EXTERNAL_LINK/vedio', FHY_REPORT_LINK:'/EXTERNAL_LINK/report', FHY_GROUPORDER_LINK: '/EXTERNAL_LINK/groupbuyOrder', FHY_SHAREMAKEMONEY_LINK: '/EXTERNAL_LINK/shareMakeMoney', FHY_GROUPDINNER_LINK: '/EXTERNAL_LINK/groupDinner', PRICE_TAG_EDIT: '/PRICE_TAG_EDIT/main', } } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/mypage/index.js import Editor from './myEditor.js' import Preview from './myPreview.js' export default { type: Editor.designType, editor: Editor, preview: Preview }; <file_sep>/inside-chain/src/store/modules/group/state.js export default{ groupTableList:{ list:[], total:'' }, classTableList:[], classList:[], editGroupItem:{ itemId:'', itemClassId:'', itemName:'', itemps:'', shopList:[] }, }<file_sep>/static-hercules/src/static-html/main.js var Vue = require('vue') var VueRouter = require('vue-router') var App = require('./App.vue') import toast from './components/toast/index.js' Vue.use(toast) Vue.use(VueRouter) var router = new VueRouter({ routes: [ { path: '*', redirect: '/index' }, { path: '/index', name: 'index', title: '微信商户实名认证流程', component: require('./views/index/index.vue') }, { path: '/expiration-reminder', name: 'index', component: require('./views/expiration-reminder/index.vue') } ] }) router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: '<App/>', components: { App } }) <file_sep>/inside-boss/src/container/noOwnerCoupon/reducers.js /** * Created by air on 2018/3/14. */ import { SET_NO_OWNER_COUPON, INIT_NO_OWNER_COUPON, SET_NO_OWNER_COUPON_LIST, SET_NO_OWNER_PAGE_NUM, SET_SEARCH_PARAM, IS_SHOW_SET_PAGE, SET_NO_OWNER_SET_LIST, SET_NO_SET_PAGE_NUM } from '../../constants' export default (state = {}, action) => { switch (action.type) { case INIT_NO_OWNER_COUPON: return action.data case SET_NO_OWNER_COUPON: return Object.assign({}, state, {select: action.data}) case SET_NO_OWNER_COUPON_LIST: return Object.assign({}, state, { list: action.data.list, listLeg: action.data.goodsListTotal }) case SET_NO_OWNER_PAGE_NUM: return Object.assign({}, state, {pageNumber: action.data}) case SET_SEARCH_PARAM: return Object.assign({}, state, {search: action.data}) case IS_SHOW_SET_PAGE: return Object.assign({}, state, {setPageIsShow: action.data}) case SET_NO_OWNER_SET_LIST: return Object.assign({}, state, { setList: action.data.list, setListLeg: action.data.goodsListTotal, }) case SET_NO_SET_PAGE_NUM: return Object.assign({}, state, {setPageNumber: action.data}) default: return state } } <file_sep>/static-hercules/src/static/js/jsSdkUtil.0.1.4.js /** * Created by hupo on 16/8/30. */ /* 微信 & QQ & 支付宝 & 百度统计 jsSdk 的封装 * * 不依赖任何其他js文件 * * 请使用全局的 "JsSdkUtil" 或 "window.JsSdkUtil" * * 在此js文件加载后(可以是加载后的任何地方), 根据所需要使用的功能, 配置 JsSdkUtil, 配置完成后, 显式调用 JsSdkUtil.initialize() 执行初始化 * * 使用示例: * <script src="../js/jsSdkUtil.js"></script> 加载此文件 * <script> * JsSdkUtil.scanCodeId = "scanCode"; (或 JsSdkUtil.scanCodeId = "wrapper"; JsSdkUtil.scanCodeConfirmId = "scanCode";) 根据需要配置所使用的功能 (可选) * JsSdkUtil.scanCallback = function (result) { 配置功能回调 (可选) * console.log("scanCallback run"); * window.location.href = result * }; * JsSdkUtil.initialize() 初始化 (必须) * </script> * * 更新日志: * 20170912: * 增加第三方APP bridge * */ (function () { var FILE_BASE_URL = '__FILE_BASE_URL'; // 本工程路径,由gulp替换 var SHARE_API_BASE_URL = '__SHARE_API_BASE_URL'; // 分享api路径,由gulp替换 var API_BASE_URL = '__SHARE_API_BASE_URL'; var WX_JS_SDK_URL = "//res.wx.qq.com/open/js/jweixin-1.3.2.js"; var ALIPAY_JS_SDK_URL = "https://as.alipayobjects.com/g/component/antbridge/1.1.4/antbridge.min.js"; var ALIPAY_TRACK_URL = "https://os.alipayobjects.com/rmsportal/oknmeDPmBzRhliY.js"; var QQ_JS_SDK_URL = "https://mp.gtimg.cn/open/js/openApi.js"; var QQ_PAY_JS_SDK_URL = "//pub.idqqimg.com/qqmobile/qqapi.js?_bid=152"; var APP_JS_SDK_URL = FILE_BASE_URL + "/js/FRWCardApp.0.0.6.js"; var APP_BRIDGE_SDK_URL = FILE_BASE_URL + "/js/DFireBridge.js?v=0.0.2"; var JX_JS_SDK_URL = "https://cdn.52shangou.com/lib/bridge/2.0.3/build/bridge.js"; //联华鲸选app内嵌bridge var BAIDU_ANALYSIS_URL = "//hm.baidu.com/hm.js?24910471637fcf3fc7f8a730579094d1"; var WX_CONFIG_URL = SHARE_API_BASE_URL + "/share/v1/get_jsapi_ticket"; var QQ_CONFIG_URL = SHARE_API_BASE_URL + "/share/v1/get_qq_jsapi_ticket"; var V_CONSOLE_URL = FILE_BASE_URL + "/js/vconsole.2.5.2.js"; // 预售域名下,或预售新人红包页面(便于项目、预发环境测试)用饭好约的公众号sdk鉴权接口 var url = window.location.href || ""; if (url.search("fanhaoyue.com") >= 0 || url.search("presellRedEnvelopes") >= 0 ) { WX_CONFIG_URL = SHARE_API_BASE_URL + "/share/v1/get_fan_jsapi_ticket"; // 饭好约公众号用 } // SHARE_API_BASE_URL = 'http://mock.2dfire-daily.com/mockjs/27/mockjsdata/7/' var SHARE_INFO = SHARE_API_BASE_URL + "/share/v1/info"; //获取分享所需的数据 var jsSdk, JsSdkUtil; var isInit = false; // 是否已经开始初始化 var isGetShareDataRetry = false; // 获取分享信息失败重试一次 var isGetSdkConfigRetry = false; // 获取分享信息失败重试一次 JsSdkUtil = { client: 0, // 客户端类型 1 微信; 2 支付宝; 3 qq; 4 app内嵌; 7 小程序 debug: false, // 是否开启微信或qqSDk的调试 默认关闭 在init执行前配置 useShare: true, // 是否使用分享功能(包括朋友圈和分享给好友) 默认开启 在init执行前配置 useHideMenu: true, // 是否使用隐藏菜单功能 默认开启 在init执行前配置 useLocation: false, // 是否使用定位功能 默认关闭 在init执行前配置 userProtectMenu: false, // 是否开启传播类菜单 在init执行前配置 scanCodeId: undefined, // 是否使用扫码功能(直接指定 dom ID 自动开启, 应保证事件绑定时此ID对应的DOM已存在) 默认关闭 scanCodeConfirmId: undefined, // 此时 scanCodeId 作为wrapper用来绑定事件, scanCodeConfirmId 作为实际触发的 target(主要用于处理事件绑定时,扫码DOM元素还未生成的情况) shareInfo: undefined, // 分享的内容, 默认使用获取分享内容的接口 shareUrlParam: undefined, // 获取分享内容的url, 默认使用获取分享内容的接口 hideMenuList: undefined, // 隐藏的menuList, 有默认list,可以不传 scanCallback: undefined, // 扫码后的回调, 默认自动跳转到扫码地址 locationCallback: undefined, // 定位后的回调, 默认设置到 sessionStorage 名称: gps shareCallback: undefined, // 分享成功后的回调, 默认无 shareFailCallback: undefined, // 分享失败后的回调, 默认无 shareCancelCallback: undefined, // 分享中断后的回调, 默认无 showProtectMenus: showProtectMenus, // init执行后 通过执行function 开启传播类菜单 bindShareData: bindShareData, // init执行后 通过执行function 绑定分享数据, 用于需要临时指定分享内容的情况, 会自动开启传播发送给好友和分享到朋友圈的菜单 initialize: initialize, // sdk配置初始化, 请再此文件加载后调用 (必须!) useGetNetworkType: false, isMpWebViewEnv: isMpWebViewEnv, getNetworkTypeCallback: undefined, trigger: triggerFunction }; window.JsSdkUtil = JsSdkUtil; /** * 是否是小程序内嵌 * @return {Boolean} */ function isMpWebViewEnv() { return window.__wxjs_environment === 'miniprogram'; } /* * 工具类方法 start */ // 简单封装 ajax 只用 get 方法 function ajax(url, arg1, arg2, arg3) { var params, success, error; if (typeof (arg1) == "object") { params = arg1; success = arg2; error = arg3 } else { params = undefined; success = arg1; error = arg2 } var xmlHttp = new XMLHttpRequest(); if (params && Object.keys(params).length > 0) { url += "?"; for (var k in params) { if (params.hasOwnProperty(k)) { url = url + k + "=" + encodeURIComponent(params[k]) + "&" } } if (url[url.length - 1] === "&") { url = url.slice(0, -1) } } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { var resp = JSON.parse(xmlHttp.responseText); if (resp.code == 1 && success) { success(resp.data) } else if (error) { error(resp) } } else if (error) { error("error status: " + xmlHttp.status) } } }; xmlHttp.open("get", url, true); xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.timeout = 15000; xmlHttp.ontimeout = function () { error("timeout") }; xmlHttp.send(); } // 获取 token function getToken() { var _DFMAP_COMMON_ = '_DFMAP_common_'; var f_val; try { var key = 'token' var val = sessionStorage.getItem(_DFMAP_COMMON_ + key) || sessionStorage.getItem(_DFMAP_COMMON_ + "ytoken"); // 新人红包注册后的yToken if (val) { f_val = JSON.parse(val); } else { var error_msg = 'undefined_common_key:' + key; console.log(error_msg); window.DFAnalytics && window.DFAnalytics.fire('Er', error_msg, {}); f_val = null; } } catch (e) { return null; } return f_val; } // 获取 entity_id function getEntityId() { var str = sessionStorage.getItem('_DFMAP_sid_current') || ''; if (str.indexOf('_')) { return str.split('_')[1]; } else { return ''; } } // 简单封装获取 cookie 的方法 // function getCookie(name) { // var cookieValue = null; // if (document.cookie && document.cookie != '') { // var cookies = document.cookie.split(';'); // for (var i = 0; i < cookies.length; i++) { // var cookie = cookies[i].replace(/.*\s/, ""); // // Does this cookie string begin with the name we want? // if (cookie.substring(0, name.length + 1) == (name + '=')) { // cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); // break; // } // } // } // return cookieValue; // } // 动态加载sdk和指定回调 function loadScript(src, callback) { var script = document.createElement('script'); var head = document.getElementsByTagName('head')[0]; script.type = 'text/javascript'; script.charset = 'UTF-8'; script.src = src; // script.onload = function () { // if (callback) { // callback(); // } // script.onLoad = null // }; script.addEventListener('load', function () { if (callback) { callback(); } script.removeEventListener('load', function () { }); }, false); head.appendChild(script); } // 地址栏参数替换 url 原始地址:如/hello/:id/ arg 如果只有一个参数,则为string,多个需传递数组 function api_get_request_url(url, arg) { if (typeof arg === "string") { return url.replace(':id', arg); } else if (typeof arg === "object" && arg.length > 0) { return api_get_request_url(url.replace(':id', arg[0]), arg.slice(1, arg.length)); } else { return url; } } /* 工具类方法 end */ // 设置 js api config 到 sessionStorage function setJsApi(page, data) { var obj = {}; obj.time = new Date().getTime(); obj.data = data; sessionStorage.setItem(page, JSON.stringify(obj)); } function getJsApi(page) { var result = JSON.parse(sessionStorage.getItem(page)); try { if (new Date().getTime() - result.time > 1.5 * 60 * 60 * 100) { result = null; } else { result = result.data; } } catch (ex) { result = null; } return result; } // 设置 shareInfo 到 sessionStorage function setShareInfo(shareInfo) { if (typeof shareInfo === "object" && shareInfo != null) { shareInfo = JSON.stringify(shareInfo); } else { shareInfo = ""; } var SID = sessionStorage.getItem('_DFMAP_sid_current'); sessionStorage.setItem("shareInfo" + (SID ? '_' + SID : ''), shareInfo); } function getShareInfo() { var shareInfo = null; try { var SID = sessionStorage.getItem('_DFMAP_sid_current'); shareInfo = JSON.parse(sessionStorage.getItem("shareInfo" + (SID ? '_' + SID : ''))); } catch (ex) { console.log("share need init"); } return shareInfo; } // 初始化sdk function initialize() { isInit = true; // client有值说明scriptInit先完成, 那么在此处初始化, client无值说明scriptInit后完成, 则在scriptInit回调中自动初始化. 以此保证初始化绝对执行 if (JsSdkUtil.client === 1 || JsSdkUtil.client === 7) { getSdkConfig(WX_CONFIG_URL) } else if (JsSdkUtil.client === 2) { aliPayInit() } else if (JsSdkUtil.client === 3) { getSdkConfig(QQ_CONFIG_URL) } else if (JsSdkUtil.client === 4) { appInit() } else if (JsSdkUtil.client === 6) { TAppInit() } } // 获取sdk验证信息 function getSdkConfig(url) { var page = "jsapi-" + window.location.href; // 直接使用完整的url做缓存 防止hash变化造成的问题 if (page.indexOf('#') > 0) { page = page.split("#")[0]; } var jsApi = getJsApi(page); if (jsApi) { wxQqInit(jsApi) } else { var path = window.location.href; if (path.indexOf('#') > 0) { path = path.split("#")[0]; } ajax(url, { xtoken: getToken(), url: path }, function (resp) { wxQqInit(resp); setJsApi(page, resp) }, function (resp) { if (!isGetSdkConfigRetry) { isGetSdkConfigRetry = true; getSdkConfig(url) } } ) } } // 获取分享数据 function getShareData() { var entityId = getEntityId(); var token = getToken(); var params = { xtoken: token, entityId: entityId, type: 0 }; if (JsSdkUtil.shareUrlParam && typeof JsSdkUtil.shareUrlParam === 'object') { for (var k in JsSdkUtil.shareUrlParam) { if (JsSdkUtil.shareUrlParam.hasOwnProperty(k)) { params[k] = JsSdkUtil.shareUrlParam[k] } } } if (entityId) { ajax(SHARE_INFO, params, function (resp) { bindShareData(resp); setShareInfo(resp) }, function (resp) { if (!isGetShareDataRetry) { isGetShareDataRetry = true; getShareData() } } ) } } function isEmpty(obj) { // null and undefined are "empty" if (obj === null) return true; if (obj === undefined) return true; // Assume if it has a length property with a non-zero value // that that property is correct. if (typeof obj === "number") { if (obj === 0) { return true; } else { return false; } } if (typeof obj === "string") { if (obj.length === 0) { return true; } else { return false; } } // Otherwise, does it have any properties of its own? // Note that this doesn't handle // toString and valueOf enumeration bugs in IE < 9 // bug:如果是Date类型,则总是会返回为空 if (typeof obj === "object") { if (obj.length === undefined) {//对象 for (var key in obj) { if (hasOwnProperty.call(obj, key)) return false; } } else {//数组 if (obj.length > 0) { return false; } else { return true; } } } return true; } // 调用分享接口 function bindShareData(shareInfo) { // todo 第三方app需要增加分享到朋友圈的能力 by hup @2017.8.8 if (isEmpty(shareInfo)) { console.log("shareInfo 不能为空"); return } var friend = shareInfo.friend || {};//朋友 var moment = shareInfo.moment || {};//朋友圈 if (shareInfo.friend.shareUrl.match(/\#/) && shareInfo.friend.shareUrl.match(/\?/)) { var router1 = shareInfo.friend.shareUrl.match(/\#\/[a-zA-Z]+/ig) ? shareInfo.friend.shareUrl.match(/\#\/[a-zA-Z]+/ig) :''; shareInfo.friend.shareUrl = shareInfo.friend.shareUrl.replace(/\#\/[a-zA-Z]+/ig, '') + router1; }; if (shareInfo.moment.shareUrl.match(/\#/) && shareInfo.moment.shareUrl.match(/\?/)) { var router2 = shareInfo.moment.shareUrl.match(/\#\/[a-zA-Z]+/ig) ? shareInfo.moment.shareUrl.match(/\#\/[a-zA-Z]+/ig) :''; shareInfo.moment.shareUrl = shareInfo.moment.shareUrl.replace(/\#\/[a-zA-Z]+/ig, '') + router2; }; if (JsSdkUtil.client == 4) { // 调用app分享接口 jsSdk.share({ shareType: friend.shareType || 2, // 展示分享的类型,用于app分享 value: 1 保存到朋友圈图片, 2 分享链接(默认使用链接) 3、图片+链接 icon: friend.imgUrl || "../images/shop/wechatshare.png", title: friend.title, desc: friend.memo, link: friend.shareUrl, logo: friend.iconUrl, third: friend.third, background: friend.background, qrCodeWidth: friend.qrCodeWidth, xCoordinate: friend.xCoordinate, yCoordinate: friend.yCoordinate, wechatMiniExtension: friend.wechatMiniExtension, success: function (res) { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback(res) } }, cancel: function (res) { if (JsSdkUtil.shareCancelCallback) { JsSdkUtil.shareCancelCallback(res) } }, failer: function (res) { // 用户分享失败后执行的回调函数 if (JsSdkUtil.shareFailCallback) { JsSdkUtil.shareFailCallback(res) } } }); } else if (JsSdkUtil.client === 5) { jsSdk.callNative('weixin', true, { 'type': "shareFriend", //sharelink shareFriend 'title': friend.title, 'description': friend.memo, 'url': friend.shareUrl, 'imgUrl': friend.imgUrl }, function (data) { if (data.status && data.result) { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback("shareInApp") } } }) } else if (JsSdkUtil.client == 1 || JsSdkUtil.client == 3) { jsSdk.showMenuItems({ menuList: [ "menuItem:share:appMessage", "menuItem:share:timeline" ] // 要显示的菜单项,所有menu项见附录3 }); //分享给朋友 jsSdk.onMenuShareAppMessage({ title: friend.title, // 分享标题 desc: friend.memo, // 分享描述 link: friend.shareUrl, // 分享链接 imgUrl: friend.imgUrl || "../images/shop/wechatshare.png", // 分享图标 success: function () { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback("shareToFriend") } }, cancel: function () { // 用户取消分享后执行的回调函数 } }); //分享到朋友圈 jsSdk.onMenuShareTimeline({ title: moment.title, // 分享标题 link: moment.shareUrl, // 分享链接 imgUrl: moment.imgUrl || "../images/shop/wechatshare.png", // 分享图标 success: function () { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback("shareToTimeLine") } }, cancel: function () { // 用户取消分享后执行的回调函数 } }); } else if (JsSdkUtil.client == 7) { if (!friend) { return; } wx.miniProgram.postMessage({ data: { type: 'updateShareData', data: { source: friend.source, title: friend.title, // 分享标题 url: friend.shareUrl, // 分享链接 imageUrl: friend.bigImgUrl || friend.imgUrl || 'https://assets.2dfire.com/frontend/3880475a93fc4de7886a6dd7e1c9ceab.png', // 分享图标 }, }, }); } } function triggerFunction(key, params) { var func = JsSdkUtil[key]; if (func) { func(params) } else { // nofunc console.log('no func name:', key) } } function bindFunction(key, func) { if (JsSdkUtil[key]) return; console.log('bind', key, func); JsSdkUtil[key] = func; } // 开启保护类菜单 function showProtectMenus() { jsSdk.showMenuItems({ menuList: [ "menuItem:copyUrl", "menuItem:openWithQQBrowser", "menuItem:openWithSafari" ] // 要显示的菜单项,所有menu项见附录3 }); } /* * wx 和 qq 初始化 */ function wxQqInit(config) { jsSdk.config({ debug: JsSdkUtil.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: config.appId, // 必填,公众号的唯一标识 timestamp: config.timestamp, // 必填,生成签名的时间戳 nonceStr: config.noncestr, // 必填,生成签名的随机串 signature: config.sign,// 必填,签名,见附录1 jsApiList: [ "getLocation", "onMenuShareTimeline", "onMenuShareAppMessage", "scanQRCode", "hideMenuItems", "showMenuItems", "getNetworkType", "chooseImage", ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); //这里把checkApi改为ready,因为版本较低的微信不支持check jsSdk.ready(function () { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.getNetworkType({ success: function (res) { var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } if (JsSdkUtil.useHideMenu) { var menuList = [ "menuItem:favorite", "menuItem:share:qq", "menuItem:copyUrl", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:weiboApp", "menuItem:share:QZone", "menuItem:share:facebook", "menuItem:share:appMessage", "menuItem:share:timeline" ]; // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3 jsSdk.hideMenuItems({ menuList: (JsSdkUtil.hideMenuList && JsSdkUtil.hideMenuList.length > 0) ? JsSdkUtil.hideMenuList : menuList }); } function scanQRCode() { jsSdk.scanQRCode({ needResult: 1, desc: "scanQRCode desc", success: function (res) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(res.resultStr) } else { if (JsSdkUtil.client == 7) { var token = getToken(); /** * 如果是小程序需要调定制的接口进行解析(不授权) * 有问题联系@炒饭 和 @排骨 */ window.location.href = API_BASE_URL + '/mini-app/jump/v1/scan?xtoken=' + token + '&url=' + encodeURIComponent(res.resultStr); } else { window.location.href = res.resultStr } } return false; } }); } bindFunction('scanQRCode', scanQRCode); // 微信扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId) || {}; function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } }; scanCodeDom.onclick = null; scanCodeDom.onclick = scanCodeClickListener; } // 分享接口调用 if (JsSdkUtil.useShare) { var shareData = JsSdkUtil.shareInfo || getShareInfo(); if (shareData) { bindShareData(shareData); } else { getShareData(); } } // 开启保护类接口 if (JsSdkUtil.userProtectMenu) { showProtectMenus() } // 微信定位 if (JsSdkUtil.useLocation) { jsSdk.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90 var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。 var speed = res.speed; // 速度,以米/每秒计 var accuracy = res.accuracy; // 位置精度 var obj = { longitude: longitude, latitude: latitude, speed: speed, accuracy: accuracy }; window.localStorage.removeItem("position"); window.localStorage.setItem("position", JSON.stringify(obj)); window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); window.localStorage.removeItem("location"); window.localStorage.setItem("location", JSON.stringify(obj)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(latitude, longitude) } }, fail: function (res) { console.log('获取位置失败', res); } }); } }); } function aliPayInitFunc() { if ((jsSdk.alipayVersion).slice(0, 3) >= 8.1) { // 支付宝获取网络类型 if (JsSdkUtil.useGetNetworkType) { jsSdk.network.getType({ timeout: 5000 }, function (result) { if (result.errorCode) { //没有获取网络状态的情况 //errorCode=5,调用超时 if (result.errorCode == 5) { jsSdk.alert({ title: '亲', message: '调用超时', button: '确定' }); } } else { //成功获取网络状态的情况 //result.isWifi bool 是否在Wifi下使用 //result.isOnline bool 是否联网 //result.type string 网络类型'fail': 无网络,或网络断开'wifi': wifi网络'wwan': 移动网络 8.2 //result.networkAvailable bool 网络是否连网可用 8.2 var networkType = result.type; window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } function scanQRCode() { jsSdk.scan({ type: 'qr' //qr(二维码) / bar(条形码) / card(银行卡号) }, function (result) { if (result.errorCode) { //没有扫码的情况 //errorCode=10,用户取消 //errorCode=11,操作失败 if (result.errorCode == 11) { //alert('操作失败'); } } else { //成功扫码的情况 if (result.qrCode !== undefined) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(result.qrCode) } else { window.location.href = result.qrCode } } } }); } bindFunction('scanQRCode', scanQRCode); // 支付宝扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } } scanCodeDom.onclick = null; scanCodeDom.onclick = scanCodeClickListener; } // 支付宝定位 if (JsSdkUtil.useLocation) { jsSdk.geolocation.getCurrentPosition({ timeout: 5000 //超时时间 }, function (res) { if (res.errorCode) { //没有定位的情况 //errorCode=5,调用超时 } else { //成功定位的情况 var latitude = res.coords.latitude; //double 纬度 var longitude = res.coords.longitude; //double 经度 var city = res.city; //string 城市 var province = res.province; //string 省份 var cityCode = res.cityCode; //string 城市编码 var address = res.address;// array 地址 var obj = { latitude: latitude, longitude: longitude, city: city, province: province, cityCode: cityCode, address: address }; window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); window.localStorage.removeItem("position"); window.localStorage.setItem("position", JSON.stringify(obj)); window.localStorage.removeItem("location"); window.localStorage.setItem("location", JSON.stringify(obj)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(latitude, longitude) } } }); } } else { var userAgent = navigator.userAgent; // 配合口碑客户端所做的判断, 检测的口碑客户端时, 大于6.0.0的版本不提醒更新 by hupo if (userAgent.indexOf("KoubeiClient") !== -1) { var koubeiVersion = userAgent.match(/KoubeiClient\/[0-9]/) || ""; if (koubeiVersion) { var version = parseInt(koubeiVersion[0].split("/")[1]); if (version < 6) { jsSdk.alert({ title: '亲', message: '请升级您的口碑到最新版', button: '确定' }); } } } else { jsSdk.alert({ title: '亲', message: '请升级您的钱包到最新版', button: '确定' }); } } } /* * 支付宝初始化 */ function aliPayInit() { if (window.AlipayJSBridge && window.AlipayJSBridge.call) { aliPayInitFunc() } else { jsSdk.on("AlipayJSBridgeReady", aliPayInitFunc); window.DFAnalytics && window.DFAnalytics.fire && window.DFAnalytics.fire("Cu", "AlipayJSBridge not defind when jssdk is ready"); } } /* * 口碑统计相关 */ function koubeiTrackInit() { var status = ""; var url = window.location.href; if (url.search("welcome.html") >= 0) { status = "welcome" } else if (url.search("paySuccess") >= 0) { status = "paySuccess" } if (!status) { return } var kouBeiInfoString = sessionStorage.getItem("kouBeiInfo") || "{}"; var kouBeiInfo = JSON.parse(kouBeiInfoString); var source = kouBeiInfo.source || ""; var shopId = kouBeiInfo.source || ""; if (source && shopId) { var operateName = status === "welcome" ? "支付宝点菜-开始点菜" : "支付宝点菜-订单完成"; var operateId = status === "welcome" ? "dc_start" : "dc_end"; var commodityId = source === "koubeishop" ? "201601260038260226" : "201601260038260226"; loadScript(ALIPAY_TRACK_URL, function () { setTimeout(function () { document.addEventListener("AlipayJSBridgeReady", function () { var req = { appId: "2015122201024689", operateName: operateName, operateId: operateId, shopId: shopId, commodityId: commodityId }; MCloudJSBridge.processStartLog(req) }) }, 0); }); } } /* * App内嵌初始化 */ function appInit() { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.getNetworkType({ success: function (res) { var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } // App定位 if (JsSdkUtil.useLocation) { if (jsSdk.getLocation) { jsSdk.getLocation({ type: 'wgs84', // 坐标系类型,默认为wgs84的gps坐标 success: function (res) { //成功定位的情况 var latitude = res.latitude; var longitude = res.longitude; var obj = { latitude: latitude, longitude: longitude, }; window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); window.localStorage.removeItem("position"); window.localStorage.setItem("position", JSON.stringify(obj)); window.localStorage.removeItem("location"); window.localStorage.setItem("location", JSON.stringify(obj)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(latitude, longitude) } }, cancel: function (res) { console.log("cancel") }, fail: function (res) { console.log("fail") } }); } } function scanQRCode() { jsSdk.getQrCode({ needResult: 0, success: function (res) { if (res && res.resultStr) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(res.resultStr) } else { window.location.href = res.resultStr } } return false; } }); } bindFunction('scanQRCode', scanQRCode); // app唤起扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } } scanCodeDom.onclick = null; scanCodeDom.onclick = scanCodeClickListener; } } /* * App内嵌初始化 */ function jxInit() { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.callNative('getNetwork_sync', function (data) { if (data.status && data.result) { var networkType = data.result; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } // App定位 if (JsSdkUtil.useLocation) { // console.log('use location') jsSdk.callNative('getLocation', true, {}, function (data) { // console.log('getLocation', data) if (data.status && data.result) { var latitude = data.result.latitude; var longitude = data.result.longitude; var obj = { latitude: latitude, longitude: longitude }; window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); window.localStorage.removeItem("position"); window.localStorage.setItem("position", JSON.stringify(obj)); window.localStorage.removeItem("location"); window.localStorage.setItem("location", JSON.stringify(obj)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(latitude, longitude) } } }); } function scanQRCode() { jsSdk.callNative('openScan', true, { "scanType": "qr" }, function (data) { if (data.status && data.result) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(data.result) } else { window.location.href = data.result } return false; } else { console.log("扫码失败") } }) } bindFunction('scanQRCode', scanQRCode); // 联华app唤起扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } } // changed by qinghe scanCodeDom.onclick = ""; scanCodeDom.onclick = scanCodeClickListener; } } // 第三方 APP 内嵌脚本 function TAppInit() { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.getNetworkType({ success: function (res) { var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } // App定位 if (JsSdkUtil.useLocation) { jsSdk.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90 var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。 if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(latitude, longitude); } } }); } function scanQRCode() { jsSdk.scanQRCode({ success: function (res) { var resultStr = res.resultStr; // 返回 扫码结果 字符串 if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(resultStr); } else { window.location.href = resultStr; } } }); } bindFunction('scanQRCode', scanQRCode); // 联华app唤起扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode(); } } else { scanQRCode(); } } // changed by qinghe scanCodeDom.onclick = ""; scanCodeDom.onclick = scanCodeClickListener; } } // 根据客户端加载对应的sdk文件 function scriptInit() { var userAgent = navigator.userAgent; if (userAgent.indexOf("MicroMessenger") !== -1) { loadScript(WX_JS_SDK_URL, function () { // 用 setTimeOut 保证 加载后的jsSdk执行完成 if (window.wx && window.wx.miniProgram) { setTimeout(function () { wx.miniProgram.getEnv(function (res) { jsSdk = window.wx; if (res.miniprogram) { JsSdkUtil.client = 7; // 小程序 } else { JsSdkUtil.client = 1; // 微信h5 } if (isInit) { getSdkConfig(WX_CONFIG_URL) } }); }, 0); } }); } else if (userAgent.indexOf("AlipayClient") !== -1) { loadScript(ALIPAY_JS_SDK_URL, function () { setTimeout(function () { jsSdk = window.Ali; JsSdkUtil.client = 2; if (isInit) { aliPayInit() } }, 0); }); koubeiTrackInit() } else if (userAgent.indexOf("cardapp.client") !== -1 || userAgent.indexOf("hestia.client") !== -1) { if (!window.FRWCardApp) { loadScript(APP_JS_SDK_URL, function () { setTimeout(function () { jsSdk = window.FRWCardApp; JsSdkUtil.client = 4; if (isInit) { appInit() } }, 0); }); } else { jsSdk = window.FRWCardApp; JsSdkUtil.client = 4; if (isInit) { appInit() } } } else if (userAgent.indexOf("appType(lianhua)") !== -1) { // 联华鲸选 js bridge loadScript(JX_JS_SDK_URL, function () { setTimeout(function () { jsSdk = window.lib.bridge; JsSdkUtil.client = 5; if (isInit) { jxInit() } }, 0); }); } else if (userAgent.indexOf("QQ") !== -1) { loadScript(QQ_JS_SDK_URL, function () { // 加载qq钱包 loadScript(QQ_PAY_JS_SDK_URL, function () { }); setTimeout(function () { jsSdk = window.mqq; JsSdkUtil.client = 3; if (isInit) { getSdkConfig(QQ_CONFIG_URL) } }, 0); }); } else { // mock: // window.DFireBridge = { // messageSend: function( func , id , param){ // console.log(func , id , param) // } // } loadScript(APP_BRIDGE_SDK_URL, function () { setTimeout(function () { JsSdkUtil.client = 6; jsSdk = window.DFireBridge; if (isInit) { TAppInit() } }, 0); }); } // 加载百度统计脚本 loadScript(BAIDU_ANALYSIS_URL); if (localStorage.debug) { loadScript(V_CONSOLE_URL); } // // 加载vconsole // if (window.location.href.indexOf('vconsole_open')) { // window.localStorage.setItem('vconsole_expire', new Date().getTime() + 3e6); // loadScript(V_CONSOLE_URL); // } else if (window.location.href.indexOf('vconsole_close')) { // window.localStorage.setItem('vconsole_expire', ''); // } else { // var vconsoleExpire = window.localStorage.getItem('vconsole_expire'); // if (vconsoleExpire && vconsoleExpire > (new Date).getTime()) { // loadScript(V_CONSOLE_URL); // } // } } scriptInit() })(); <file_sep>/inside-boss/src/container/mallBannerManager/index.js import React, { Component }from 'react' import { connect } from 'react-redux' import Main from '../../components/mall' import { initBannerList, editBannerIndex, editBannerItem } from '../../action' import Cookie from '@2dfire/utils/cookie' class container extends Component { render () { const baseInfo = this.props.baseInfo return ( <div> <Main module='banner' contentList={ this.props.bannerList } initList={ this.props.initBannerList(baseInfo) } editItem={ this.props.editBannerItem(baseInfo) } editBannerIndex={ this.props.editBannerIndex(baseInfo) } /> </div> ) } } const mapStateToProps = (state) => { const { bannerList = [] } = state.mallBannerManager || {} const entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) const baseInfo = { entityId: entrance.shopInfo.entityId, userId: entrance.userInfo.memberId, } return { baseInfo, bannerList } } const mapDispatchToProps = { initBannerList, editBannerItem, editBannerIndex, } export default connect(mapStateToProps, mapDispatchToProps)(container) <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionPictureAds/TmpEditor.js import React from 'react'; import { Radio } from 'antd'; import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor'; import style from './TmpEditor.css' export default class AdEditor extends DesignEditor { state = { defaultImg: 'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png' }; ChangeGroup = (str, e) => { const { value, onChange } = this.props; const {config} = value onChange(value, {config: { ...config, [str]: e.target.value }}) } render(){ const { value, prefix, validation } = this.props; const { config } = value; return ( <div className={`${prefix}-design-component-config-editor`}> <div className={style.componentConfigEditor}> <ControlGroup label="选择模板:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <Radio.Group value={config.mode} buttonStyle="solid" className={style.controlGroupControl} onChange={(e) => this.ChangeGroup('mode', e)}> <Radio.Button value="单图" name='mode' className={style.imgType}> <img src={value.config.mode == '单图' ? 'https://assets.2dfire.com/frontend/d777e5330a31b209352eff0db2fe568e.png':'https://assets.2dfire.com/frontend/3bc532d72c77bcabc0bc8602d9a26249.png'} /> </Radio.Button> <Radio.Button value="轮播图" name='mode' className={style.imgType}> <img src={config.mode == '轮播图' ? 'https://assets.2dfire.com/frontend/e25c6ce74c7a13e93c801e6b5e5cdde7.png':'https://assets.2dfire.com/frontend/e036d229a2c1f0d260b7dd6229d000b7.png'} /> </Radio.Button> {/* <Radio.Button value="c" name='hasPadding' className={style.imgType}> <img src={value.hasPadding == 'c' ? 'https://assets.2dfire.com/frontend/36cbfa04856035395fe5a388b9ff0bf9.png':'https://assets.2dfire.com/frontend/e926936b709902682c4c6265babb0735.png'} /> </Radio.Button> */} </Radio.Group> </div> </div> ) } } <file_sep>/static-hercules/src/oasis/constants/index.js const wxJlText = '需要在二维火绑定收款银行卡。' const wxZlText = '需要再二维火开通微信特约商户。' const alipayJlText = '会在活动页重新绑定收款银行卡。' const alipayTlJlText = '需要在二维火绑定收款银行卡。' const alipayZlText = '你的支付宝账号需要入驻二维火,并已经开通当面付。' const wxJl = [ { url: 'https://assets.2dfire.com/frontend/56fbfedf1a74097ccdf527afb03ad23c.jpg', name: '法人身份证' }, { url: 'https://assets.2dfire.com/frontend/b0636d2b0538323a44aae2c1ae71ae6e.jpg', name: '营业执照' }, { url: 'https://assets.2dfire.com/frontend/7f73c9bc97448b1fc71dfed43c2354c9.png', name: '收银台照片' }, { url: 'https://assets.2dfire.com/frontend/ba0a5ec23a724be7c4124ea8fe298409.jpg', name: '门头照片' }, { url: 'https://assets.2dfire.com/frontend/5a42f13fd3d623f4b8d2c82ba928bfa1.jpg', name: '店内环境照片' }, { url: 'https://assets.2dfire.com/frontend/e5c3d8778a5d57b40d3210762b7afce5.jpg', name: '门头照合照' }, { url: 'https://assets.2dfire.com/frontend/e0500eb6df9ded2c8d6856fcc026e667.jpg', name: '微信扫码点餐' }, { url: 'https://assets.2dfire.com/frontend/556194d4757031c8696d41bfbb5c89fa.jpg', name: '其他平台截图' } ] const wxZl = [ { url: 'https://assets.2dfire.com/frontend/b0636d2b0538323a44aae2c1ae71ae6e.jpg', name: '营业执照' }, { url: 'https://assets.2dfire.com/frontend/7f73c9bc97448b1fc71dfed43c2354c9.png', name: '收银台照片' }, { url: 'https://assets.2dfire.com/frontend/ba0a5ec23a724be7c4124ea8fe298409.jpg', name: '门头照片' }, { url: 'https://assets.2dfire.com/frontend/5a42f13fd3d623f4b8d2c82ba928bfa1.jpg', name: '店内环境照片' }, { url: 'https://assets.2dfire.com/frontend/e5c3d8778a5d57b40d3210762b7afce5.jpg', name: '门头照合照' }, { url: 'https://assets.2dfire.com/frontend/e0500eb6df9ded2c8d6856fcc026e667.jpg', name: '微信扫码点餐' }, { url: 'https://assets.2dfire.com/frontend/556194d4757031c8696d41bfbb5c89fa.jpg', name: '其他平台截图' } ] const alipayJl = [ { url: 'https://assets.2dfire.com/frontend/56fbfedf1a74097ccdf527afb03ad23c.jpg', name: '法人身份证' }, { url: 'https://assets.2dfire.com/frontend/b0636d2b0538323a44aae2c1ae71ae6e.jpg', name: '营业执照' }, { url: 'https://assets.2dfire.com/frontend/ba0a5ec23a724be7c4124ea8fe298409.jpg', name: '门头照片' }, { url: 'https://assets.2dfire.com/frontend/5a42f13fd3d623f4b8d2c82ba928bfa1.jpg', name: '店内环境照片' }, { url: 'https://assets.2dfire.com/frontend/71d026e37c2f5fbef6f39d012f6397f7.jpg', name: '收银台照片' }, { url: 'https://assets.2dfire.com/frontend/556194d4757031c8696d41bfbb5c89fa.jpg', name: '其他平台截图' } ] const alipayZl = [ { url: 'https://assets.2dfire.com/frontend/b0636d2b0538323a44aae2c1ae71ae6e.jpg', name: '营业执照' }, { url: 'https://assets.2dfire.com/frontend/ba0a5ec23a724be7c4124ea8fe298409.jpg', name: '门头照片' }, { url: 'https://assets.2dfire.com/frontend/5a42f13fd3d623f4b8d2c82ba928bfa1.jpg', name: '店内环境照片' }, { url: 'https://assets.2dfire.com/frontend/71d026e37c2f5fbef6f39d012f6397f7.jpg', name: '收银台照片' }, { url: 'https://assets.2dfire.com/frontend/556194d4757031c8696d41bfbb5c89fa.jpg', name: '其他平台截图' } ] const alipayTlJl = [ { url: 'https://assets.2dfire.com/frontend/b0636d2b0538323a44aae2c1ae71ae6e.jpg', name: '营业执照' }, { url: 'https://assets.2dfire.com/frontend/ba0a5ec23a724be7c4124ea8fe298409.jpg', name: '门头照片' }, { url: 'https://assets.2dfire.com/frontend/5a42f13fd3d623f4b8d2c82ba928bfa1.jpg', name: '店内环境照片' }, { url: 'https://assets.2dfire.com/frontend/71d026e37c2f5fbef6f39d012f6397f7.jpg', name: '收银台照片' }, { url: 'https://assets.2dfire.com/frontend/556194d4757031c8696d41bfbb5c89fa.jpg', name: '其他平台截图' } ] module.exports = { wxJl, wxJlText, wxZlText, alipayJlText, alipayTlJlText, alipayTlJl, wxZl, alipayJl, alipayZl, alipayZlText } <file_sep>/union-entrance/src/base/config/daily.js module.exports = { NEW_API_BASE_URL:'../../api', API_BASE_URL: 'http://gateway.2dfire-daily.com/?app_key=200800&method=', SHARE_BASE_URL: 'http://api.l.whereask.com', IMAGE_BASE_URL: 'http://ifiletest.2dfire.com/', API_WEB_SOCKET: 'http://10.1.5.114:9003/web_socket', MOCK_BASE_URL: 'http://mock.2dfire-daily.com/mockjsdata/7', WEB_SOCKET_URL: 'http://10.1.5.114:9003', // 根据不同环境设置不同链接地址 // PROJECT_ENV_INDEX: 'http://d.2dfire-daily.com/entrance/page/index.html', //登录页 // PROJECT_ENV_CHANGE: 'http://d.2dfire-daily.com/entrance/page/change.html', //选店页 // CHAIN_MANAGEMENT_URL: 'http://d.2dfire-daily.com/chain/page/index.html', //连锁管理页 }; <file_sep>/inside-boss/src/container/importLog/reducers.js import { INIT_LOG_DATA, INIT_IMPORT_LOG_DATA, INIT_LOG_DETAIL_DATA } from '../../constants' const goodsReducer = (state = {}, action) => { switch (action.type) { case INIT_IMPORT_LOG_DATA: // Object.assign({}, state, {totalCount: action.data.totalCount}) // console.log('count!!!',action.data.totalCount) return Object.assign({}, state, action.data) case INIT_LOG_DETAIL_DATA: return Object.assign({}, state, {detail: action.data}) case INIT_LOG_DATA: return action.data default: return state } } export default goodsReducer <file_sep>/inside-boss/src/components/goodTagEdit/tagInput.js import React, { Component } from 'react' import { Input, Form } from 'antd' const FormItem = Form.Item import * as action from '../../action' import styles from './moduleTag.css' class tagInput extends Component { constructor(props) { super(props) this.state = { showInput: true, showCloseImg: false } } radioCheckMap = { name: 'goodsNameType', barCode: 'goodsBarCodeType', retailPrice: 'goodsRetailPriceType', memberPrice: 'goodsMemberPriceType', unit: 'goodsUnitType', shelfLife: 'goodsPeriodType', productDate: 'goodsManufactureType', customText: 'definitionType', specifications: 'goodsSpecificationType' } textMap = { name: 'goodsNameExt', retailPrice: 'goodsRetailPriceExt', memberPrice: 'goodsMemberPriceExt', unit: 'goodsUnitExt', shelfLife: 'goodsPeriodExt', productDate: 'goodsManufactureExt', productDateContent: 'goodsManufacture', customText: 'definitionExt', specifications: 'goodsSpecificationExt' } closeInput(type) { const { dispatch, moduleDetail } = this.props const changeText = this.textMap[type] const changeType = this.radioCheckMap[type] if (type !== 'productDate') { moduleDetail[changeText] = 'del' delete moduleDetail[changeType] } else{ moduleDetail.goodsManufactureExt = 'del' moduleDetail.goodsManufacture = 'del' delete moduleDetail.goodsManufactureType } this.props.isShowEdit(type, false) dispatch(action.setModuleDetail(moduleDetail)) } hiddenInput() { this.setState({ showCloseImg: false }) } showInputArea() { this.setState({ showCloseImg: true }) } getInputValue(type, content, productDate, exampleContent) { if (type === 'productDate') { if (content !== 'del') { if (productDate) { return content !== 'del' ? content + ' ' + productDate : productDate } else { return content !== 'del' ? content + ' 2019-01-01' : '2019-01-01' } } else { if (productDate) { return productDate !== 'del' ? productDate : '' } else if (content === null || content === 'del') { return '2019-01-01' } else { return '生产日期 2019-01-01' } } } else { return !(content.split(' ')[0] === 'del') ? content : exampleContent } } drawBoardValue = () => { const { getFieldDecorator, content, type, productDate = '', moduleDetail = {}, isShowEdit, backgroundImage = '', exampleContent = '' } = this.props const { showCloseImg } = this.state const radioType = this.radioCheckMap[type] const isCanEdit = moduleDetail[radioType] ? true : false const showBarCode = type === 'barCode' return ( isCanEdit && ( <div> {!showBarCode && ( <FormItem> {getFieldDecorator(type, { initialValue: this.getInputValue( type, content, productDate, exampleContent ) })( <Input onClick={() => { this.showInputArea() isShowEdit(type, true) }} onBlur={this.hiddenInput.bind(this)} className={styles.inputText} readOnly="readOnly" /> )} {showCloseImg && ( <div className={styles.closeIcon}> <img src="https://assets.2dfire.com/frontend/e72eee699579e0922be27ad1ebe20587.png" className={styles.closeIcon} onMouseDown={this.closeInput.bind( this, type )} /> </div> )} </FormItem> )} {showBarCode && ( <div> <Input onClick={() => { this.showInputArea() isShowEdit(type, true) }} onBlur={this.hiddenInput.bind(this)} className={styles.inputText} readOnly="readOnly" style={{ backgroundImage: backgroundImage, backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }} /> {showCloseImg && ( <div className={styles.closeIcon}> <img src="https://assets.2dfire.com/frontend/e72eee699579e0922be27ad1ebe20587.png" className={styles.closeIcon} onMouseDown={this.closeInput.bind( this, type )} /> </div> )} </div> )} </div> ) ) } render() { const { className } = this.props const { showInput } = this.state return ( showInput && ( <div className={styles[className]} tabIndex="0"> <div>{this.drawBoardValue()}</div> </div> ) ) } } export default tagInput <file_sep>/static-hercules/src/secured-account/libs/rules.js // 字符串长度2~10 const twoToTen = /^\w{2,10}$/ // 字符串长度1~15 const oneToFifteen = /^\w{1,15}$/ // 字符串1~40 const oneToForty = /^\w{1,40}$/ // 验证手机 const checkTel = /^[1][0-9]{10}$/ /*** * 修改银行卡部分表单提交 */ export const ruleUpdateBankList = { accountName: { isRequired: true, types: 'twoToThirty', name: '开户人名称' }, idCard: { isRequired: true, types: 'id', name: '身份证号码' }, accountBank: { isRequired: true, types: 'twoToThirty', name: '开户银行' }, accountNumber: { isRequired: true, types: 'bankCardId', name: '银行卡号' }, accountAddressProvince: { isRequired: true, types: 'twoToThirty', name: '开户省份' }, accountAddressCity: { isRequired: true, types: 'twoToThirty', name: '开户城市' }, accountSubBank: { isRequired: true, types: 'twoToThirty', name: '开户支行' }, businessLicensePic: { isRequired: true, types: 'img', name: '绑卡公函' }, userTelNumber: { isRequired: true, types: 'mobile', name: '手机号码' }, authCode: { isRequired: true, types: 'number', name: '验证码' } }; /** * 表单验证修改银行卡部分 * */ export const inputUpdateBankIsOk = function (val, dataVal) { let data = ruleUpdateBankList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (!val) { return { data: false, message: data.name + '不能为空' } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 根据类型判断 */ const getSwitchMatchResult = (val, data) => { let returnData; switch (data.types) { case "number": //验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break; case 'mobile': //验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break; case "tel": //验证电话(3-20位数字|连字符) returnData = getMatchResult(/^([0-9-]){3,20}$/, val, data.name) break; case 'email': returnData = getMatchResult(/(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name) break; case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break; case 'id': // 证件号码 returnData = getMatchResult(/(^[0-9]{15}$)|(^[0-9]{17}([0-9]|X|x)$)/, val, data.name) break; case 'twoToThirty': // 2-30 returnData = getMatchResult(/^([A-Za-z0-9]{2,30})|([\u4e00-\u9fa5]{1,15})|([\u4e00-\u9fa5][\w\W]{2})$/, val, data.name) break; case 'bankCardId': // 银行卡 returnData = getMatchResult(/^[623501|621468|620522|625191|622384|623078|940034|622150|622151|622181|622188|955100|621095|620062|621285|621798|621799|621797|22199|621096|62215049|62215050|62215051|62218849|62218850|62218851|621622|623219|621674|623218|621599|623698|623699|623686|621098|620529|622180|622182|622187|622189|621582|623676|623677|622812|622810|622811|628310|625919|625368|625367|518905|622835|625603|625605|518905]/, val, data.name) break; default: returnData = { data: true } } return returnData } /** * 返回正则效验结果 * @param reg 正则效验规则 * @param val 值 * @param name 效验字段名字 * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ const getMatchResult = (reg, val, name) => { let r; r = val.match(reg); if (r == null) { return {data: false, message: '请输入正确的' + name} } else { return {data: true} } } <file_sep>/inside-chain/src/utils/wxApp/url.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.createUrl = undefined; var _qs = require('./qs'); var _qs2 = _interopRequireDefault(_qs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 创建一个地址附带查询参数 * @param {String} baseUrl 基础地址 * @param {Object} params key-value 对象,选填 * @return {void} */ function createUrl(baseUrl, params) { var paramsStr = _qs2.default.stringify(params || {}); if (!paramsStr) { return baseUrl; } var subStr = ''; // 没有问号 if (baseUrl.lastIndexOf('?') === -1) { subStr = '?'; } else { // 最后一个字符 var lastChar = baseUrl.slice(-1); // 如果最后接在最后一个字符不是是?并且是&加上一个& if (lastChar !== '&' && lastChar !== '?') { subStr = '&'; } } return baseUrl + subStr + paramsStr; } exports.createUrl = createUrl; exports.default = { createUrl: createUrl };<file_sep>/inside-chain/src/tools/eslint-config-2dfire/rules/react-only-env.js module.exports = { plugins: [ 'react', ], parserOptions: { ecmaFeatures: { jsx: true, }, }, settings: { 'import/resolver': { node: { extensions: ['.js', '.jsx', '.json'] } }, react: { pragma: 'React', version: '15.0' }, }, rules: { 'react/jsx-uses-vars': 2, } }; <file_sep>/inside-chain/src/config/api_pass.js import { API_BASE_URL } from 'apiConfig' import Requester from '@/base/requester' import catchError from '@/base/catchError' import { GW } from '@2dfire/gw-params' import router from '@2dfire/utils/router' import cookie from '@2dfire/utils/cookie' const entity_id = JSON.parse(cookie.getItem('entrance')).shopInfo.entityId function withEntityId() { return '&' + GW + '&' + 'entity_id=' + getEntityId() } export function getEntityId() { return router.route.query.entityId || entity_id } async function http(url, config) { try { const res = await Requester.get(API_BASE_URL + url, config) const { code } = res if (code === 1) { return { ...res, success: true } } else { return { ...res, success: false } } } catch (e) { catchError(e) } } /** * 连锁和门店传菜相关api */ export default { //连锁、门店传菜列表 getPassSchemeList: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.listPantries' + withEntityId(), { params } ), //连锁、门店传菜列表点击商品进入详情列表 getPassSchemeDetail: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.listMenuDetail' + withEntityId(), { params } ), //连锁、门店传菜列表点击商品进入详情列表,再点击关联商品的时候调用 addSchemeDetailGoods: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.updatePantryMenu' + withEntityId(), { params } ), //连锁、门店传菜列表点击商品进入详情列表,删除关联商品 delSchemeDetailGoods: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.removePantryMenu' + withEntityId(), { params } ), //添加传菜信息 addPassSchemeInfo: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.savePantryInfo' + withEntityId(), { params } ), //编辑更新传菜信息 updatePassSchemeInfo: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.updatePantryInfo' + withEntityId(), { params } ), //删除传菜信息 delPassSchemeInfo: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.removePantry' + withEntityId(), { params } ), //获取不出单商品列表 getNotIssueList: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.listNoPrint' + withEntityId(), { params } ), //删除不出单商品(总部的) delNotIssue: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.deleteNoPrint4Chain' + withEntityId(), { params } ), //删除或更新不出单商品(门店的) updateNotIssue: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.updateNoPrint' + withEntityId(), { params } ), //查询所有商品 getAllGoodsList: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.listItem' + withEntityId(), { params } ), //查询所有商品类别 getAllGoodsType: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.listEndKind' + withEntityId(), { params } ), //未出单商品中添加商品 addNotIssueGoods: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryMenuClientService.saveNoPrint4Chain' + withEntityId(), { params } ), //套餐中商品分类打印设置 getPrintSettingList: params => http( 'com.dfire.soa.cashplatform.client.service.ICashClientService.getKindMenuPrintSettings' + withEntityId(), { params } ), //商品分类打印设置中增加套餐分类 updatePrintSetting: params => http( 'com.dfire.soa.cashplatform.client.service.ICashClientService.updateKindMenuPrintSettings' + withEntityId(), { params } ), //商品分类打印设置中删除套餐分类 delPrintSetting: params => http( 'com.dfire.soa.cashplatform.client.service.ICashClientService.deleteKindMenuPrintSettings' + withEntityId(), { params } ), //门店传菜列表中获取区域列表 getAllArea: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.listArea' + withEntityId(), { params } ), //门店传菜列表中更新区域列表 updateArea: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.updatePantryArea' + withEntityId(), { params } ), //门店备用打印机列表 getPrinterList: params => http( 'com.dfire.soa.cashplatform.client.service.IBackupPrinterClientService.list' + withEntityId(), { params } ), //门店添加备用打印机 addPrinter: params => http( 'com.dfire.soa.cashplatform.client.service.IBackupPrinterClientService.save' + withEntityId(), { params } ), //门店添加编辑更新打印机 updatePrinter: params => http( 'com.dfire.soa.cashplatform.client.service.IBackupPrinterClientService.update' + withEntityId(), { params } ), //门店添加删除打印机 delPrinter: params => http( 'com.dfire.soa.cashplatform.client.service.IBackupPrinterClientService.remove' + withEntityId(), { params } ), //门店分区域打印列表 getAreaPrintList: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.getPrintList' + withEntityId(), { params } ), //门店分区域打印添加打印信息 addAreaPrint: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.uploadPrint' + withEntityId(), { params } ), //门店分区域打印编辑保存打印信息 updateAreaPrint: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.updatePrintInfoById' + withEntityId(), { params } ), //门店分区域打印删除打印信息 delAreaPrint: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.deletePrintById' + withEntityId(), { params } ), //门店分区域打印更新区域 updateAreaPrintArea: params => http( 'com.dfire.soa.cashplatform.client.service.IPrintClientService.updatePrintAreaById' + withEntityId(), { params } ), //门店传菜检查 getPassCheckList: params => http( 'com.dfire.soa.cashplatform.client.service.ICashInspectionClientService.queryCashInspection' + withEntityId(), { params } ), //门店传菜检查关联设置传菜方案 setPassCheckList: params => http( 'com.dfire.soa.cashplatform.client.service.ICashInspectionClientService.saveCashPrint' + withEntityId(), { params } ), //添加传菜方案时选在标签打印机的时候获取打印纸宽高 getPrinterWH: params => http( 'com.dfire.soa.cashplatform.client.service.IPantryClientService.getPrintType' + withEntityId(), { params } ), //添加传菜方案时获取的打印设备列表 getPrinterSys: params => http( 'com.dfire.soa.cashplatform.client.service.ISysMobileClientService.listDicSysItems' + withEntityId(), { params } ), //添传菜检查设置关联的时候 getCheckSetting: params => http( 'com.dfire.soa.cashplatform.client.service.ICashInspectionClientService.queryCashPrint' + withEntityId(), { params } ) } <file_sep>/inside-boss/src/container/trainInfoImport/reducers.js import { INIT_TRAIN_DATA, SET_TRAIN_LIST, SET_CUR_NUM } from '../../constants' const routeInfoImportReducer = (state = {}, action) => { switch (action.type) { case INIT_TRAIN_DATA: return action.data case SET_TRAIN_LIST: return Object.assign({}, state, { trainList: action.data.records, trainListTotal : action.data.totalRecord }) case SET_CUR_NUM: return Object.assign({}, state, { pageNumber:action.data }) default: return state } } export default routeInfoImportReducer <file_sep>/static-hercules/src/ocean/router.js var Router = require("vue-router"); export var router = new Router({ routes: [ { path: '*', redirect: '/result' }, { path: '/bankSub', name: 'bankSub', component: require("./views/bank/BankSub.vue"), }, { path: '/input/:step', name: 'inputs', component: require("./views/inputshopinfo/Input.vue"), children: [ { path: 'first', component: require("./views/inputshopinfo/InputStep1.vue") }, { path: 'second', component: require("./views/inputshopinfo/InputStep2.vue") }, { path: 'third', component: require("./views/inputshopinfo/InputStep3.vue") }, { path: 'fourth', component: require("./views/inputshopinfo/InputStep4.vue") } ] }, { path: '/result', name: 'result', component: require("./views/result/ApplyResult.vue") }, { path: '/rule', name: 'rule', component: require("./views/rule/Rule.vue") } ] }); router.beforeEach((to, from, next) => { // console.log(to,from,next); // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() })<file_sep>/inside-chain/src/base/catchError.js import Vue from "vue"; import iView from "iview"; Vue.use(iView); let Modal = iView.Modal; function catchError(e) { if (e.result) { let errorCode = e.result.errorCode; let errorMsg = e.result.message; if (errorMsg === '保存的名称重复') { Modal.warning({ title: '请注意', content: "已存在同名付款方式,请修改后再保存", }); }else{ Modal.warning({ title: '请注意', content: errorMsg || '网络波动,请稍后再试', }); } } } export default catchError <file_sep>/inside-boss/src/api/index.js import axios from './networkAxios' // 全局 AppKey const APP_AUTH = '?app_key=200800&s_os=pc_merchant_back' import { merApiPrefix } from '../utils/env' import getUserInfo from '../utils/getUserInfo' export default { // 搜索条件 getSearchFormArgs(params) { return axios({ url: 'report/queryArgs.json' + APP_AUTH, mockUrl: '127/report/queryArgs.json', method: 'POST', data: params }) }, // 报表 chart 结构 getChartDetails(params) { return axios({ url: 'report/details.json' + APP_AUTH, mockUrl: '127/report/details.json', method: 'POST', data: params }) }, // 报表 chart 数据 getChartData(params) { return axios({ url: 'report/data.json' + APP_AUTH, mockUrl: '127/report/data.json', method: 'POST', data: params }) }, // "导出 Excel " getExcel(params) { return axios({ url: 'report/exportXls.do' + APP_AUTH, mockUrl: '127/report/exportXls.do', method: 'POST', data: params }) }, // 联动下拉框时,异步取数据 getUnionSelect(params) { return axios({ url: 'report/lovValues.json' + APP_AUTH, mockUrl: '127/report/lovValues.json', method: 'POST', data: params }) }, //获取充值批次列表 fetchBatchList(params) { return axios({ mock: false, url: 'merchant/batch/v1/get_batch_list' + APP_AUTH, mockUrl: '123/getFilesSuccess', method: 'GET', params }) }, //删除批次 deleteBatch(params) { return axios({ mock: false, url: 'merchant/batch/v1/delete_batch' + APP_AUTH, mockUrl: '123/deleteBatchSuccess', method: 'GET', params }) }, //查询表格数据 fetchRechargeList(params) { return axios({ mock: false, url: 'merchant/batch/v1/get_batch_details_list_by_query' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_batch_details_list', method: 'GET', params }) }, //查询导入日志信息 getCommTypes(params) { return axios({ mock: false, url: 'merchant/batch/v1/getCommTypes' + APP_AUTH, mockUrl: '123/merchant/batch/v1/getCommTypes', method: 'GET', params }) }, //查询导入日志信息 getImportLog(params) { return axios({ mock: false, url: 'merchant/import/v1/query_import_operate_Log' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET', params }) }, //查询日志详情 getImportLogDetail(params) { return axios({ mock: false, url: 'merchant/import/v1/query_import_operate_detail_Log' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET', params }) }, //获取商家可选择的类目列表 getCategory(params) { return axios({ mock: false, url: 'merchant/import/v1/query_category' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET', params }) }, //下载商品模板 downloadTemplate(params) { return axios({ mock: false, url: 'merchant/import/v1/create_import_template' + APP_AUTH, mockUrl: '123/merchant/import/v1/create_import_template', method: 'GET', params }) }, //商品库列表 getGoodsList(params) { return axios({ mock: false, url: 'merchant/menu/v1/menu_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'POST', data: params }) }, //商品库列表(新) getGoodsListNew(params) { return axios({ mock: false, url: 'merchant/menu/v2/menu_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'POST', data: params }) }, getSpecification(params) { return axios({ mock: false, url: 'merchant/menu/v1/query_sku_by_menuId' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'GET', params }) }, //获取数据订正状态 getIsShowBrand(params) { return axios({ mock: false, url: 'merchant/plate/fixstatus' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjs/532/merchant/plate/fixstatus', method: 'GET', params }) }, //获取品牌列表 getBrandList(params) { return axios({ mock: false, url: 'merchant/plate/get_plate_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'GET', params }) }, /********************************************************************************************************************************************* */ // 商品模板列表 getTemplateList(params) { return axios({ mock: false, url: 'merchant/plate/fixstatus' + APP_AUTH, mockUrl: '', method: 'GET', params }) }, // 获取模板详情 getTemplateDetail(params) { return axios({ mock: false, url: 'merchant/plate/fixstatus' + APP_AUTH, mockUrl: '', method: 'GET', params }) }, // 保存模板 saveEditTemplate(params) { return axios({ mock: false, url: 'merchant/plate/fixstatus' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, // 交路信息库列表 getRouteList(params) { return axios({ mock: false, url: 'railway/v1/queryTrains' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, // 车次时刻信息库列表 getTrainList(params) { return axios({ mock: false, url: 'railway/v1/queryTrainStations' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, //充值信息编辑 rechargeModify(params) { return axios({ mock: false, url: 'merchant/batch/v1/modify_batch_details' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, //批量删除充值信息 deleteMultiple(params) { return axios({ mock: false, url: 'merchant/batch/v1/delete_batch_details_list' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, //批量充值 rechargeMultiple(params) { return axios({ mock: false, url: 'merchant/batch/v1/batch_recharge' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, //批量红冲 refund(params) { return axios({ mock: false, url: 'merchant/batch/v1/cancel_charge_card' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, //删除单个 deleteSingle(params) { return axios({ mock: false, url: 'merchant/batch/v1/delete_batch_details' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, modifyInfo(params) { return axios({ mock: false, url: 'merchant/batch/v1/modify_batch_details' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, // 视频列表 videoList(params) { return axios({ mock: false, url: 'shadow_deer/list_video_library' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, // 名字检验是否重复 is_name_repeat(params) { return axios({ mock: false, url: 'shadow_deer/is_name_repeat' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, getDuplicatedItems(params) { return axios({ mock: false, url: 'merchant/menu/v1/list_duplicated_item' + APP_AUTH, mockUrl: '', method: 'POST', data: params }) }, pictureList(params) { return axios({ mock: false, url: 'merchant/menu/v1/get_menu_page' + APP_AUTH, mockUrl: '281/pictureList', method: 'POST', data: params }) }, pictureDetailList(params) { return axios({ mock: false, url: 'merchant/menu/v2/get_menu_image' + APP_AUTH, mockUrl: '281/pictureDetailList', method: 'POST', data: params }) }, //商品排序 changeListSort(params) { return axios({ mock: false, url: 'merchant/menu/v1/sort_image' + APP_AUTH, mockUrl: '496/sort_image', method: 'POST', data: params }) }, //删除图片 deletePicture(params) { return axios({ mock: false, url: 'merchant/menu/v2/remove_menu_image' + APP_AUTH, mockUrl: '281/pageChange', method: 'POST', data: params }) }, //订单存照列表 orderList(params) { return axios({ mock: false, url: 'cashlog/orderHistoryList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/427/orderList', method: 'POST', data: params }) }, //是否展示会员导出按钮 isShowMemberExportBtn(params) { return axios({ mock: false, url: 'merchant/export/v1/init_page' + APP_AUTH, mockUrl: '', method: 'GET', params }) }, //发放优惠券 getCouponType(params) { return axios({ mock: false, url: 'coupon/back/v1/getCouponType' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/getCouponType', method: 'GET', params }) }, importFileList(params) { return axios({ mock: false, url: 'coupon/back/v1/importFileList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/importFileList', method: 'GET', params }) }, rechargeList(params) { return axios({ mock: false, url: 'coupon/back/v1/rechargeList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/rechargeList', method: 'POST', data: params }) }, reupload(params) { return axios({ mock: false, url: 'coupon/back/v1/reupload' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/reupload', method: 'POST', data: params }) }, deleteBatch_(params) { return axios({ mock: false, url: 'coupon/back/v1/deleteBatch' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/deleteBatch', method: 'POST', data: params }) }, pushProgress(params) { return axios({ mock: false, url: 'coupon/back/v1/pushProgress' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, //获取掌柜侧边栏 getBossMenuList(params) { return axios({ url: merApiPrefix + 'merchant/function/v1/get_boss_functions' + APP_AUTH + '&' + getUserInfo(true), method: 'POST', data: params }) }, //获取高铁侧边栏 getRailwayMenuList(params) { return axios({ url: merApiPrefix + 'merchant/function/v1/get_railway_functions' + APP_AUTH + '&' + getUserInfo(true), method: 'POST', data: params }) }, // 获取不记名优惠券下拉框内容 getNoOwnerCoupon(params) { return axios({ mock: false, url: 'coupon/offline/v1/init' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 不记名优惠券批量激活 noOwnerCouponActive(params) { return axios({ mock: false, url: ' coupon/offline/v1/batchActivate' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 不记名优惠券批量停用 noOwnerCouponStop(params) { return axios({ mock: false, url: 'coupon/offline/v1/batchStop' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 不记名优惠券批量激活 noOwnerCouponSearch(params) { return axios({ mock: false, url: 'coupon/offline/v1/report' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 不记名优惠券查询 noOwnerSetList(params) { return axios({ mock: false, url: 'coupon/offline/v1/report' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 不记名优惠券获取优惠券 noOwnerGetCoupon(params) { return axios({ mock: false, url: 'coupon/offline/v1/couponList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST', data: params }) }, // 商品多规格导入 uploadSpec: { mock: false, url: 'merchant/import/item/spec' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // 商品无规格导入 uploadNospec: { mock: false, url: 'merchant/import/item/no_spec' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // 商品信息导出 exportItems(params) { return axios({ mock: false, url: 'merchant/export/v1/retail/sku/menus' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'GET', params }) }, //导入履历查询 getImportHistoryList(params) { console.log('output params', params) return axios({ mock: false, url: ' record/v1/query_all' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'GET', params }) } } <file_sep>/inside-boss/src/components/goods/goodsList.js import React, { Component } from 'react' import { Table, Pagination, Button, Modal, Select, Input, message } from 'antd' import styles from './style.css' import * as bridge from '../../utils/bridge' import * as action from '../../action' import Specification from './specification' import FieldTemplate from './fieldTemplate' import { getColumns, recursionClass } from './data' const Option = Select.Option const Search = Input.Search class GoodsList extends Component{ constructor (props) { super(props) this.showSpecification=this.showSpecification.bind(this); this.state={ visible: false, show:false, columns1 : [ { title: '分类名称', dataIndex: 'kindMenuName', key: 'kindMenuName', width: 100, }, { title: '商品名称', dataIndex: 'name', key: 'name', width: 100, }, { title: '编码', dataIndex: 'code', key: 'code', width: 100, }, { title: '单价(元)', dataIndex: 'price', key: 'price', width: 100, }, { title: '会员价(元)', dataIndex: 'memberPrice', key: 'memberPrice', width: 100, }, { title: '结账单位', dataIndex: 'account', key: 'account', width: 100, }, { title: '点菜单位', dataIndex: 'buyAccount', key: 'buyAccount', width: 100, }, { title: '是否打折', dataIndex: 'isRatio', key: 'isRatio', width: 100, render: (text, record) => { return record.isRatio==1?"是":"否"; }, }, { title: '商品简介', dataIndex: 'memo', key: 'memo', width: 500, }, { title: '商品库存', dataIndex: 'stock', key: 'stock', width: 100, }, { title: '加工耗时', dataIndex: 'consume', key: 'consume', width: 100, render: (text, record) => { return record.consume==0?"":record.consume; }, } ], columns2 :[ { title: '分类名称', dataIndex: 'kindMenuName', key: 'kindMenuName', }, { title: '商品名称', dataIndex: 'name', key: 'name', }, { title: '条形码', dataIndex: 'code', key: 'code', }, { title: '单价(元)', dataIndex: 'price', key: 'price', render: (text, record) => { return record.specification?record.scopePrice:record.price; }, }, { title: '会员价(元)', dataIndex: 'memberPrice', key: 'memberPrice', render: (text, record) => { return record.specification?record.scopeMemberPrice:record.memberPrice; }, }, { title: '结账单位', dataIndex: 'account', key: 'account', }, { title: '是否为称重商品', dataIndex: 'isTwoAccount', key: 'isTwoAccount', render: (text, record) => { return record.isTwoAccount==1?"是":"否"; }, }, { title: '是否打折', dataIndex: 'isRatio', key: 'isRatio', render: (text, record) => { return record.isRatio==1?"是":"否"; }, }, { title: '规格属性', dataIndex: 'specification', key: 'specification', render: (text, record) => { return !record.specification?'-':<Button onClick={this.showSpecification.bind(this,record.id)}>查看规格</Button>; }, }, { title: '商品介绍', width: '200', dataIndex: 'memo', key: 'memo', } ], searchParams:{ keyWord:'', kindId: '' } } } paginationChange(pageNumber){ const t =this const { dispatch ,data} = t.props this.setState({ current: pageNumber, }); dispatch(action.setPageIndex(pageNumber)) // if(data.isShowBrand==="fixed"){ // let brandId=data.brandId?data.brandId:''; // dispatch(action.getGoodsList(pageNumber,brandId)) // }else { // dispatch(action.getGoodsList(pageNumber)) // } this.getGoodsList(pageNumber) } showSpecification(data){ this.setState({ specificationDataId:data, visible: true, }); } handleOk = (e) => { console.log(e); this.setState({ visible: false, }); } handleCancel = (e) => { this.setState({ visible: false, }); } handleReset = ()=>{ const { dispatch } = this.props const tableFieldsOptions = this.props.data.tableFieldsOptions Object.keys(tableFieldsOptions).map(key=>{ tableFieldsOptions[key].selectedList = [].concat(tableFieldsOptions[key].defaultList) }) dispatch(action.setTableFiledOptions(tableFieldsOptions)) } handleHide = ()=>{ this.setState(()=>({show:false})) } selectComplete=()=>{ const plateEntityId = this.props.data.brandId ? this.props.data.brandId :'' const gridType = '2' let data = [] let fieldsList = [] Object.values(this.props.data.tableFieldsOptions).map(i=>{ data = data.concat(i.selectedList) }) this.props.data.tableFieldsList.map(i=>{ let list = i.children ? i.fields.concat(i.children.map(h=>h.fields)): [].concat(i.fields) action.flatDeep(list).filter(j=>{ // if(data.includes(j.gridFieldId)){ if(data.indexOf(j.gridFieldId) >= 0 ){ fieldsList.push(j.customId) } }) }) if(!data.length) return message.info('选择字段不能为空') this.props.dispatch(action.batchCreatUserGridField({data:fieldsList,plateEntityId,gridType})) this.props.dispatch(action.setTableHeader(data)) this.setState(()=>({show:false})) } handleShow=()=>{ const plateEntityId = this.props.data.brandId ? this.props.data.brandId :'' const MenuLanguage = this.props.data.menuLanguage this.props.dispatch(action.getCustomTableHeader(plateEntityId,false,MenuLanguage)) this.setState(()=>({show:true})) } handleMenuChange = (kindId)=>{ this.getGoodsList(1,kindId) } handleInputChange = (e)=>{ const keyWord = e.target.value const params = { kindId: this.props.data.goodsParams.kindId, keyWord } this.props.dispatch(action.setGoodsParams(params)) } componentWillReceiveProps(nextProps){ const query = bridge.getInfoAsQuery() const industry = query.industry if( nextProps.data.tableHeader && nextProps.data.tableHeader.length && this.props.data.tableHeader != nextProps.data.tableHeader && industry !== 3 ){ const columns = getColumns(nextProps.data.tableHeader) const tableWidth = document.getElementsByClassName('customGoodsTable')[0].offsetWidth || 0 const scrollXWidth = columns.map(i=>i.width?i.width:120).reduce((a,b)=>a+b) columns = columns.map(i=>{ if(i.dataIndex === 'kindMenuName' || i.dataIndex === 'name' ){ if(scrollXWidth > tableWidth ){ i.fixed = 'left' }else{ i.fixed || delete i.fixed } } return i }) this.setState({columns1: columns && columns.length ? columns : this.state.columns1 }) } } getGoodsList=(index=1,kindId = undefined)=>{ const { dispatch ,data} = this.props const pageNumber = index const params = { kindId: kindId === undefined ? data.goodsParams.kindId : kindId, keyWord: data.goodsParams.keyWord } dispatch(action.setGoodsParams(params)) dispatch(action.setPageIndex(pageNumber)) if(data.isShowBrand==="fixed"){ const brandId = data.brandId?data.brandId:''; dispatch(action.getGoodsList(pageNumber,brandId,params)) }else { dispatch(action.getGoodsList(pageNumber,null,params)) } } render(){ const t = this const query = bridge.getInfoAsQuery() const industry=query.industry const { data, dispatch } = t.props const total = data.goodsListTotal const picturelist = data.goodsList const pageNumber = data.pageNumber const columns=industry===3?this.state.columns2:this.state.columns1 const menuList = this.props.data.menuList? recursionClass(this.props.data.menuList) : [] return ( <div className={styles.wrap}> { industry !== 3 && <div className={styles.headTip}> <span>商品库</span> <Select value = {data.goodsParams.kindId} onChange={this.handleMenuChange} defaultValue='1' style={{width:180,marginLeft:20}}> <Option className={styles.menuListItem} value=''>全部分类</Option> { menuList && menuList.map(item=>{ return <Option className={styles.menuListItem} key={item.id} value={item.id}>{item.name}</Option> }) } </Select> <Search onChange = {this.handleInputChange} value = {data.goodsParams.keyWord} onSearch={()=>(this.getGoodsList())} placeholder='搜索' style={{width:180,marginLeft:20}}></Search> <Button onClick={this.handleShow} style={{float:"right"}}>自定义表头</Button> </div> } <Table className="customGoodsTable" dataSource={picturelist} columns={columns} scroll={{x:industry !== 3 && columns.map(i=>i.width?i.width:120).reduce((a,b)=>a+b),y:industry !== 3 }} pagination={false} bordered/> <div className={styles.paginationBox}> <Pagination className={styles.paginationHtml} showQuickJumper current={pageNumber} total={total} defaultPageSize={10} pageSize={10} onChange={this.paginationChange.bind(this)} /> <p>共{total}条记录</p> </div> <Modal title="规格详情" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} style={{minWidth:'720px'}} footer={null} > <Specification data={this.state.specificationDataId}/> </Modal> <FieldTemplate visible={this.state.show} dispatch = { dispatch } data = { data } handleCancel = {this.handleHide} // handleOk = {this.selectComplete} > <Button onClick={this.handleReset} style={{float:"left"}}>恢复默认值</Button> <Button onClick={this.handleHide} >取消</Button> <Button onClick={this.selectComplete} type="primary">确定</Button> </FieldTemplate> </div> ) } } export default GoodsList <file_sep>/static-hercules/src/ele-account/main.js import Vue from 'vue'; import App from './App'; import router from './router'; import MaskLayer from './components/mask-layer' import TableView from './components/table-view' import SubTitle from './components/sub-title' import ScrollLoading from './components/scroll-loading' import DatePicker from './components/date-picker/lib/date-picker' import toast from './components/toast/index.js' import confirm from './components/confirm/index.js' import filters from './filters/index' import ClipBoard from './components/clip-board' Object.keys(filters).map((key) => { Vue.filter(key, filters[key]) }) Vue.use(toast) Vue.use(confirm) Vue.component('MaskLayer', MaskLayer) Vue.component('TableView', TableView) Vue.component('SubTitle', SubTitle) Vue.component('ScrollLoading', ScrollLoading) Vue.component('DatePicker', DatePicker) Vue.component('ClipBoard', ClipBoard) Vue.config.productionTip = false; router.beforeEach((to, from, next) => { document.title = to.meta.title // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: '<App/>', components: {App}, }); <file_sep>/inside-chain/src/views/pass/utils/index.js import API from '@/config/api_pass' //获取顶部下拉选择的门店id export function getPlateId(self) { return self.$route.query.plate_entity_id } //获取所有商品类别 export async function getGoodTypes(params) { const { data } = await API.getAllGoodsType(params) const res = (data || []).map(({ name, kindId }) => ({ label: name, value: kindId })) res.unshift({ label: '全部', value: '-' }) return res } <file_sep>/static-hercules/src/oasis/store/getters.js /** * Created by zyj on 2018/4/3. */ // 店铺原始基本信息 export const baseInfo = state => { let { shopName, shopCode, businessLicenseName, creditCode, contactName, contactMobile, contactEmail, otherPlateformName, wechatMerId } = state.shopInfo return { shopName, // 店铺名称 shopCode, // 店铺编码 businessLicenseName, // 营业执照名称 creditCode, // 统一社会信用代码 contactName, // 联系人名称 contactMobile, // 联系人手机 contactEmail, // 联系人邮箱 otherPlateformName, // 其他平台店名 // needMaterial, // 是否需要邮寄物料 wechatMerId // 特约商户id } } // 店铺原始地址 export const area = state => { let { provinceName, provinceId, cityName, cityId, townName, townId, streetName, streetId, detailAddress} = state.shopInfo return { provinceName, provinceId, cityName, cityId, townName, townId, streetName, streetId, detailAddress } } // 店铺原始图片 export const photos = state => { let { businessLicensePic, checkoutCounterPic, idCardBackPic, idCardFrontPic, otherPlateformPic, shopEvnPic, doorPic, otherCertificationPic1, otherCertificationPic2, otherCertificationPic3,saleWithDoorPic,saleWithActivityPic } = state.shopInfo return { businessLicensePic, // 营业执照照片 checkoutCounterPic, // 收银台照片 idCardBackPic, // 身份证反面照 idCardFrontPic, // 身份证正面照 otherPlateformPic, // 其他平台店名 shopEvnPic, // 店铺环境照 doorPic, // 门头照 saleWithDoorPic,//商户门头照的合照 saleWithActivityPic,//商户摇摇乐活动合照 otherCertificationPic1, otherCertificationPic2, otherCertificationPic3 } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/mine/TmpEditor.js // 商品分类 编辑组件 import React from 'react' import { Radio, Checkbox, Row, Col } from 'antd' import ImgUpload from '@src/container/visualConfig/views/design/common/imgUpload' import style from './TmpEditor.css' import cx from 'classnames' const RadioGroup = Radio.Group export default class CateEditor extends React.PureComponent { constructor(props) { super(props) this.state = { orderIcons: [ '待付款', '进行中', '已完成', '退款', ], infoIcons: [ '我的订单', '我的会员卡', '我的优惠券', '收货地址', '个人信息', ], isShowImgUpload: false, typeName:null } } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } changeAvatar = (e) => { this.configChang({userInfoAlign: e.target.value}) } changePageStyle = (e) => { this.configChang({visualStyle: e.target.value}) } _getImg = (data) => { // 获取图片 const { value, onChange } = this.props; const { config } = value const {typeName} = this.state const icons = Object.assign({}, config.icons) icons[typeName] = data this.configChang({icons}) } close = () => { this.setState({ isShowImgUpload: false, }) } onChangeBtn = (item) => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, typeName: item, }) } render() { const { value } = this.props const { orderIcons, infoIcons} = this.state const { config } = value const { userInfoAlign, visualStyle, icons} = config const { isShowImgUpload }= this.state; return ( <div className={style.member_editor_container}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <div className={style.member_position}> <div className={style.member_title}>用户信息位置:</div> <RadioGroup value={userInfoAlign} onChange={this.changeAvatar} className={style.radio_group}> <Radio name="mode" value={'center'}>居中</Radio> <Radio name="mode" value={'left'}>居左</Radio> </RadioGroup> </div> <div className={style.member_position}> <div className={style.member_title}>页面风格:</div> <RadioGroup value={visualStyle} onChange={this.changePageStyle} className={style.radio_group}> <Radio name="mode" value={'卡片式'}>卡片式</Radio> <Radio name="mode" value={'平铺式'}>平铺式</Radio> </RadioGroup> </div> <div className={style.member_icons_box}> { orderIcons.map( (item, i) => { return ( <div className={style.member_flex_icon} key={i}> <div className={style.member_title}>{ item }:</div> <div className={style.member_upload} onClick={() => this.onChangeBtn(item)}> <img className={style.orderImg} src={icons[item]} alt=""/> </div> </div> ) }) } <p className={style.member_upload_tips}>icon尺寸要求:60*60px,支持PNG、JPG格式</p> </div> <div className={style.member_icons_box}> { infoIcons.map( (item, i) => { return ( <div className={style.member_flex_icon} key={i}> <div className={style.member_title}>{ item }:</div> <div className={style.member_upload} onClick={() => this.onChangeBtn(item)}> <img src={icons[item]} alt=""/> </div> </div> ) }) } <p className={style.member_upload_tips}>icon尺寸要求:48*48px,支持PNG、JPG格式</p> </div> <div className={style.member_icons_box}> <div className={style.member_flex_icon}> <div className={style.member_title}>代理中心:</div> <div className={style.member_upload} onClick={() => this.onChangeBtn('代理中心')}> <img src={icons['代理中心']} alt=""/> </div> </div> <p className={style.member_upload_tips}>icon尺寸要求:48*48px,支持PNG、JPG格式</p> <p className={style.member_upload_tips}>只有开通微代理功能后才会展示此项</p> </div> </div> ) } static designType = 'mine' static designDescription = '我的页面' static getInitialValue() { return { config: { type: 'mine', userInfoAlign: 'center', // 用户信息位置 居中:'center', 居左:'left' visualStyle: '卡片式', // 页面风格 卡片式:'card' 平铺式: 'pave' icons: { // 各菜单项的图标 会员中心: 'https://assets.2dfire.com/frontend/41b4df097e2c94b6d9678a1c664624fd.png', 待付款: 'https://assets.2dfire.com/frontend/c39a86a4752d7e4682b61975fe065a14.png', 待发货: 'https://assets.2dfire.com/frontend/7bdad89ffdac56c3bd397e785e3c56ec.png', 待收货: 'https://assets.2dfire.com/frontend/a8fe06f2a9fd2d31778f3c852ac132c7.png', 退款: 'https://assets.2dfire.com/frontend/b11dccab9a76574324ea42ff3cc7effe.png', 我的会员卡: 'https://assets.2dfire.com/frontend/ea21f0970b3fecf24d82d71c117c6420.png', 我的优惠券: 'https://assets.2dfire.com/frontend/2594320ee9012a3c8e669fabfe01faa5.png', 收货地址: 'https://assets.2dfire.com/frontend/d57d4489c19a2df11322332762a6e406.png', 个人信息: 'https://assets.2dfire.com/frontend/1972fef81801be620f28d1dd3c8a2e36.png', 代理中心: 'https://assets.2dfire.com/frontend/7e02fd5ce8e2036ff9289bcc6a6950fc.png', 我的订单: 'https://assets.2dfire.com/frontend/5947312739430077be9bdd641fa6adb2.png', } } } } } <file_sep>/inside-boss/src/container/visualConfig/store/formatters/design.js /** * 装修数据相关 formatter * 2019/05/02 @fengtang */ import store from '@src/store' import { randstr, format, first, omit, isObject } from '../../utils' import { getPageDesignComponentNames, getPageDesignComponentMap } from '../selectors' // 各 position 值的先后顺序 const positionOrder = { top: 1, nature: 2, bottom: 3, fixed: 4, } function getState() { return store.getState() } /** * 返回组件在页面定义里出现的序号 */ function getComponentIndex(comName) { return getPageDesignComponentNames(getState()).indexOf(comName) } export function makeComponentConfigItem(name, config = null) { const def = getPageDesignComponentMap(getState())[name].definition const id = (isObject(config) && config.id) || `${name}-${new Date().getTime()}-${randstr(5)}` config = format(def.config, isObject(config) ? omit(config, 'id') : config) return { id, name, config } } // 把 appConfig 整理成 componentConfigs export function transformConfigData(configData) { const state = getState() const { configName } = state.visualConfig.design const comNames = getPageDesignComponentNames(state) const comMap = getPageDesignComponentMap(state) let configs = [] // 把 bare=true 的组件整理到 configs 数组中 Object.keys(configData).forEach(key => { if (key === 'components') return // 排除不支持的组件(有的组件之前保存 config 时还支持,但现在已不支持) if (getComponentIndex(key) === -1) { console.warn(`不支持的组件:${configName} ${key}`) return } configs.push(makeComponentConfigItem(key, configData[key])) }); // 把 bare=false 的组件整理到 configs 数组中 (configData.components || []).forEach(config => { config = { ...config } const comName = config.type delete config.type // 排除不支持的组件(有的组件之前保存 config 时还支持,但现在已不支持) if (getComponentIndex(comName) === -1) { console.warn(`不支持的组件:${configName} ${comName}`) return } configs.push(makeComponentConfigItem(comName, config)) }) // 把 choosable=false 但没出现在 configs 里的组件强制加入到 configs 中 comNames.forEach(comName => { const comDef = comMap[comName].definition if (comDef.choosable) return if (first(configs, item => item.name === comName)) return configs.push(makeComponentConfigItem(comName)) }) // 对组件进行排序 configs = sortComponentConfigs(configs) return configs } export function sortComponentConfigs(configs) { const comMap = getPageDesignComponentMap(getState()) configs = [...configs] configs.sort((a, b) => { const nameA = a.name const nameB = b.name const posA = comMap[nameA].definition.position const posB = comMap[nameB].definition.position // 若两个组件都未设置 position,保持原排序 if (!posA && !posB) return 0 // position 值相同的两个组件,按照在页面定义里的出现顺序排序 if (posA === posB) { return getComponentIndex(nameA) - getComponentIndex(nameB) } // position 不同的两个组件,根据 position 确定顺序 return positionOrder[posA || 'nature'] - positionOrder[posB || 'nature'] }) return configs } // 把 componentConfigs 格式化成 appConfig export function makeConfigData(componentConfigs) { const comMap = getPageDesignComponentMap(getState()) const appConfig = {} const components = [] componentConfigs.forEach(item => { const def = comMap[item.name].definition if (def.bare) { appConfig[item.name] = item.config } else { components.push({ ...item.config, id: item.id, type: item.name, }) } }) if (components.length) appConfig.components = components return appConfig } export function formatPreviewUrl(url) { // 后端对同一 config 返回的预览 url 始终是一样的 // 在 url 后加时间戳以避免缓存,并使预览二维码产生变化以让用户感觉到预览内容变化了 const search = `t=${new Date().getTime()}` return url.indexOf('?') > -1 ? url + '&' + search : url + '?' + search } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/ad/AdPreview.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Carousel } from 'antd'; import style from './AdPreview.css' export default class AdPreview extends PureComponent { static propTypes = { value: PropTypes.object, // 用来和 Design 交互 design: PropTypes.object, }; sigleItem = () => { const { config } = this.props.value; const { items } = config let picture = false if(items.length > 0) { if(items[0].picture){ picture = true } else { picture = false } } if(items.length == 0){ picture = false } return picture ? <img className={style.sigleImg} src={items[0].picture} /> : <div className={style.defulatImg}><p>点击进行图片广告编辑<br />建议宽度750像素</p></div> } swiperItem = () => { const { config } = this.props.value; const { items } = config const length = items.length let arrImg = []; for(var i=0; i < length; i++){ if(items[i].picture !== '') { arrImg.push(items[i].picture) } } const imgList = ( arrImg.map((item) => <div><img src={item} alt="" /></div> ) ) return ( <Carousel> {arrImg.length ? imgList : <div className={style.defulatImg}><p>点击进行图片广告编辑<br />建议宽度750像素</p></div> } </Carousel> ) } compontItem = () => { const { config } = this.props.value; switch(config.mode) { case '单图': return this.sigleItem(); break; case '轮播图': return this.swiperItem(); break; default: } } render() { return ( <div className={style.adPreview}> {this.compontItem()} </div> ); } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/announce/TmpEditor.js import React, { Component } from 'react' import { Radio, Button, Input } from 'antd' import { SketchPicker } from 'react-color' import style from './TmpEditor.css' import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor' const RadioGroup = Radio.Group export default class AnnounceEditor extends DesignEditor { constructor(props) { super(props) this.state = { isSketchPicker: false, isSketchPickerbg: false, announWordLeng: 0, } } componentDidMount() { this.getTextLength() } configChang = (obj) => { const { value, onChange } = this.props const { config } = value onChange(value, { config: { ...config, ...obj, } }) } changeGroup = (str, val) => { this.configChang({ [str]: val.target.value }) } showSkentPick = (str) => { this.setState({ [str]: !this.state[str], }) } handleChangeComplete = (str, color) => { // 拾色器的回调 this.configChang({ [str]: color.hex }) } getTextLength = () => { const { value } = this.props const { config } = value this.setState({ announWordLeng: config.text.length, }) } onChangeInput = (e) => { const val = e.target.value.trim() if (val.length > 20) { return } // TODO: 这句虽然不合法,但是不能删,删了文本框就不能输入中文 this.props.value.config.text = val this.setState({ announWordLeng: val.length, }) this.configChang({ text: val }) } render() { const { value, prefix, validation } = this.props const { config } = value const { text } = config const { isSketchPicker, isSketchPickerbg, announWordLeng } = this.state return ( <div className={`${prefix}-design-component-Announce-editor`}> <div className={style.componentAnnounceEditor}> <ControlGroup label="标题内容:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.AnnouncInput}> <input className={style.input} placeholder='请输入公告内容' value={text} type="text" onChange={(e) => this.onChangeInput(e)} /> <p className={style.wordNumber}>{announWordLeng}/20</p> </div> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="框体样式:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.mode} className={style.controlGroupControl} onChange={(e) => this.changeGroup('mode', e)}> <Radio name="shape" value='1'>样式一</Radio> {/* <Radio name="shape" value='round'>圆角</Radio> */} </RadioGroup> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="背景颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{ backgroundColor: value.config.backgroundColor }} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPickerbg')} type="primary" /> {isSketchPickerbg && <SketchPicker color={value.config.backgroundColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('backgroundColor', e)} />} </div> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="文本位置:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.textAlign} className={style.controlGroupControl} onChange={(e) => this.changeGroup('textAlign', e)}> <Radio name="textAlign" value='left'>居左</Radio> <Radio name="textAlign" value='center'>居中</Radio> </RadioGroup> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="文本颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{ backgroundColor: value.config.textColor }} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPicker')} type="primary" /> {isSketchPicker && <SketchPicker color={value.config.textColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('textColor', e)} />} </div> </div> </div> ) } static designType = 'announce'; static designDescription = '公告信息'; static designTemplateType = '其他类'; static getInitialValue() { return { announWordLeng: 0, config: { type: 'announce', text: '', // 公告内容。必填。1 ~ 20个字 mode: '1', // 公告样式。可选值:'1'(暂时只支持这一个值) backgroundColor: '#ffedca', // 背景色 textAlign: 'left', // 文字位置。可选值:left、center textColor: '#f86e21', // 文字颜色 }, } } } <file_sep>/inside-chain/DIRECTORY.md ## 项目目录说明 #### src为开发主目录 base | |---config 各个环境对应参数 | |---daily.js 其中ENV需要修改为开发变更对应的ENV |---dev.js config | |---api_xxx.js 模块对应api接口配置 const 映射常量 router | |---index.js 路由配置 store | |---modules | |---xxx 功能模块名 | |---actions.js |---getters.js |---mutations.js |---state.js |---index.js store入口 components 项目公用组件 | |---brand-select 品牌选择 |---shop-select 门店选择 |--- views | |---xxx 功能模块页文件夹 | |---components 该功能用组件 |---xxx-a | |---index.vue <file_sep>/inside-boss/src/container/visualConfig/designComponents/whitespace/TmpEditor.js import React, {Component} from 'react' import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor'; import { Slider } from 'antd'; import style from './TmpEditor.css' export default class SliderEditor extends DesignEditor { constructor(props) { super(props); this.state= {} } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } sliderChange = (val) => { this.configChang({height: val}) } render() { const { prefix, value } = this.props; const {config} = value return ( <div className={`${prefix}-design-component-line-editor`}> <div className={style.componentConfigEditor}> <ControlGroup label="留白高度" className={style.groupLabel} > </ControlGroup> <Slider min={10} max={100} onChange={this.sliderChange} value={config.height} /> </div> </div> ) } static designType = 'whitespace'; static designDescription = '辅助留白'; static designTemplateType = '其他类'; static getInitialValue() { return { config:{ type: 'whitespace', height: 30, } } } } <file_sep>/inside-chain/src/const/emu-payKind.js // 现金、银行卡、自己发现的储值卡、由客房结算、优惠券、免单、代金券、其他 // all 系统所有支付类型,筛选时使用 // user 用户新建/编辑支付方式使用,只能创建部分类型的支付方式 const payKindList = { all: [ { kind: 0, name: "现金" }, { kind: 1, name: "银行卡" }, { kind: 2, name: "支付宝" }, { kind: 3, name: "微信" }, { kind: 5, name: "自己发行的储值卡" }, { kind: 10, name: "代金券" }, { kind: 10, name: "饿了么代金券" }, { kind: 4, name: "免单" }, ], user: [ { kind: 0, name: "现金" }, { kind: 1, name: "银行卡" }, { kind: 5, name: "自己发行的储值卡" }, { kind: 10, name: "代金券" }, { kind: 10, name: "饿了么代金券" }, { kind: 4, name: "免单" }, ] } export default payKindList <file_sep>/inside-boss/src/container/visualConfig/components/pageParts/Header.js import React from 'react' import PropTypes from 'prop-types' import c from 'classnames' import s from './index.css' // 页首组件 export default function Header(props) { const titleElm = props.title ? <div className={c(s.title, 'title')}>{props.title}</div> : null return <div className={c(s.header, props.className)}> {titleElm} {props.children} </div> } Header.propTypes = { className: PropTypes.string, // 向 header 指定额外的 class title: PropTypes.node, // 页面标题 children: PropTypes.node, // 通过此 props 向页首内附加内容 } <file_sep>/inside-boss/src/container/visualConfig/sences/union/home.js import { currentWeixinMealUrl } from '@src/utils/env' import { getEntityId } from '@src/container/visualConfig/utils' const page = { name: '店铺首页', configName: 'page:home', link: () => `${currentWeixinMealUrl}/page_split/v1/retail_home/${getEntityId()}`, components: [ {'unionPictureAds': 'pictureAds'}, {'unionHotGoods': 'hotGoods'}, {'unionRecommendGoods': 'recommendGoods'}, {'unionBanner': 'banner'}, {'unionNav': 'functionNav'}, {'unionMemberCard': 'memberCard'}, {'unionCoupons': 'coupons'}, {'unionRelativeShops': 'relativeShops'}, {'unionAdPlace': 'adPlace'}, {'unionHotspot': 'hotspot'}, {'unionPage': 'page'}, {'unionGroupActivity': 'groupActivity'}, 'whitespace', // 'searchInput', ], defaults: {}, } const defaults = { components: [ { type: 'banner', mode: '2', backgroundImage: null, }, { type: 'whitespace', height: 25, }, { type: 'goodsList', mode: '大图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '新品', image: null, }, }, { type: 'goodsList', mode: '详细列表', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'goodsList', mode: '双列小图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'whitespace', height: 35, }, { type: 'title', text: '更多商品', size: 'medium', textAlign: 'center', textColor: '#000000', backgroundColor: '#fff', linkType: 'page', linkGoodsId: '', linkPage: '商品分类', }, { type: 'whitespace', height: 25, }, ], } export default { ...page, // defaults, } <file_sep>/inside-boss/src/utils/jump.js import { currentEnvString } from './env' export const logout = function() { if (currentEnvString === 'PRE') { location.href = 'https://biz.2dfire-pre.com' } else if (currentEnvString === 'PUBLISH') { location.href = 'https://biz.2dfire.com' } else { location.href = location.origin + '/entrance/page/index.html' } } //跳转到选择店铺页面 export const goToChangePage = function() { if(currentEnvString !== "LOCAL" && currentEnvString !== "DEV"){ if (currentEnvString === 'PRE') { location.href = 'https://biz.2dfire-pre.com/page/change.html' } else if (currentEnvString === 'PUBLISH') { location.href = 'https://biz.2dfire.com/page/change.html' } else { location.href = location.hostname + '/entrance/page/change.html' } } } <file_sep>/inside-boss/src/container/externalLink/init.js export default (key) => { const options = { shopManage: '/third/shopManage', category: '/third/category', bankCardCheckForGuarantee: '/third/bankCardCheckForGuarantee', chainManage: '/third/chainManage', dynamic: '/third/dynamic', vedio: '/third/vedio', report: '/third/report', groupbuyOrder: '/third/groupbuyOrder', shareMakeMoney: '/third/shareMakeMoney', groupDinner: '/third/groupDinner', } return options[key] }<file_sep>/inside-chain/src/config/mock.js /** * * @param res * @author * */ const BASE_URL = 'http://localhost:8089/api/' const MOCK_API = { GET_GOOD_CLASSES:BASE_URL+'getGoodClass',//获取商品分类 GET_GOOD_FEEDS:BASE_URL+'getGoodFeed',//获取新料 GET_GOOD_REMARKS:BASE_URL+'getGoodRemark',//获取新料 } export default MOCK_API; <file_sep>/inside-boss/src/container/visualConfig/views/backups/index.js import React, { Component } from 'react' import { hashHistory } from 'react-router' import { connect } from 'react-redux' import { Modal, message } from 'antd' import * as actions from '@src/container/visualConfig/store/actions' import { getPages } from '@src/container/visualConfig/store/selectors' import { first } from '@src/container/visualConfig/utils' import checkShopStatus from '@src/container/visualConfig/components/checkShopStatus' import { Layout, Header, Content } from '@src/container/visualConfig/components/pageParts' import s from './index.css' @checkShopStatus @connect(state => ({ loadingStatus: state.visualConfig.backups.loadingStatus, backups: state.visualConfig.backups.list, pages: getPages(state), })) class Backups extends Component { componentWillMount() { actions.loadBackups() } recover(item) { Modal.confirm({ title: '确定要恢复此备份内容吗?', onOk: () => ( actions.recoverBackup(item).then(result => { if (result) { hashHistory.push('/visual_config_design') } else { message.error('备份恢复失败') } }) ), }) } remove(item) { Modal.confirm({ title: '确定要删除此备份吗?', onOk: () => ( actions.removeBackup(item).then(result => { if (result) { message.info('备份删除成功') } else { message.error('备份删除失败') } }) ), }) } // ======================================= render() { const { loadingStatus } = this.props let content if (loadingStatus === null) content = this.statusLoading() else if (loadingStatus === false) content = this.statusLoadFailed() else content = this.table() return <Layout> <Header title="备份" /> <Content className={s.content}> <div className={s.body}>{content}</div> </Content> </Layout> } statusLoading() { return <div className={s.loading}>载入中...</div> } statusLoadFailed() { return <div className={s.loadFailed}> 备份列表加载失败,<a onClick={actions.loadBackups}>点此重试</a> </div> } table() { return <table className={s.table}> <thead><tr> <th>备份名称</th> <th>备份类型</th> <th>备份时间</th> <th>操作</th> </tr></thead> <tbody> {this.items()} </tbody> </table> } items() { const { backups } = this.props if (!backups.length) { return <tr><td className={s.noBackup} colSpan="4">无备份内容</td></tr> } return backups.map(item => { const recover = () => this.recover(item) const remove = () => this.remove(item) return (<tr key={item.configId}> <td>应用模板备份</td> <td>{this.getName(item.name)}</td> <td>{this.formatBackupTime(item.createTime)}</td> <td> <div className={`${s.btn} ${s.recover}`} onClick={recover}>恢复</div> <div className={`${s.btn} ${s.remove}`} onClick={remove}>删除</div> </td> </tr>) }) } getName(configName) { const page = first(this.props.pages, p => p.configName === configName) return page ? page.name : configName } formatBackupTime(time) { const pad = v => (v >= 10 ? v.toString() : '0' + v.toString()) const d = new Date(time) const year = pad(d.getFullYear()) const month = pad(d.getMonth() + 1) const date = pad(d.getDate()) const hours = pad(d.getHours()) const minutes = pad(d.getMinutes()) const seconds = pad(d.getSeconds()) return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}` } } export default Backups <file_sep>/inside-boss/src/components/goodEdit/specification.js import React, { Component } from 'react' import { Input, Switch, Checkbox, Table, Form, message, Select, Message } from 'antd' import Card from './card' import styles from './specification.css' import Format from './format' import * as action from "../../action"; const FormItem = Form.Item const Option = Select.Option class Sepcification extends Component { constructor(props) { super(props) this.state = { multiSpe: false, showSpecSelect: false, // 批量设置弹窗 isShowVolumnPop: false, volumnValue: { price: '', memberPrice: '', expectStock: '', expectCost: '', }, selectedRowKeys: [], selectedRows: [], } } // 展示批量设置弹窗 _showVolumnModal() { const { selectedRowKeys } = this.state if (selectedRowKeys.length === 0) { Message.info('请至少选择一项规格进行操作') return } this.setState({ isShowVolumnPop: true }) } // 隐藏批量设置弹窗 _hideVolumnModal() { this.setState({ isShowVolumnPop: false }) } _priceChange(e) { const value = e.target.value const { volumnValue } = this.state volumnValue.price = value this.setState({ volumnValue }) } _memberPriceChange(e) { const value = e.target.value const { volumnValue } = this.state volumnValue.memberPrice = value this.setState({ volumnValue }) } _expectStockChange(e) { const value = e.target.value const { volumnValue } = this.state volumnValue.expectStock = value this.setState({ volumnValue }) } _expectCostChange(e) { const value = e.target.value const { volumnValue } = this.state volumnValue.expectCost = value this.setState({ volumnValue }) } // 批量设置 _saveVolumn() { const { skuTableList = [], dispatch } = this.props const { volumnValue, selectedRowKeys } = this.state const { price, memberPrice, expectStock, expectCost} = volumnValue if (price === '') { Message.error('单价不能为空') return } selectedRowKeys.map(item => { skuTableList[item].price = price skuTableList[item].memberPrice = memberPrice if (expectCost) { skuTableList[item].costPrice = expectCost } if (expectStock) { skuTableList[item].openingInventory = expectStock } }) dispatch(action.setSkuTableData(skuTableList)) this._hideVolumnModal() } // 切换无规格到多规格 // 多规格无法切换成无规格 toggleMultiSpe(checked) { if (checked) { this.setState({ multiSpe: true }) } else { this.setState({ multiSpe: false, showSpecSelect: false, }) } } addSpec() { this.setState({ showSpecSelect: true }) } // 删除新增的规格 deleteSku(item, index) { const { selectedSkuList, dispatch } = this.props const { isSelect } = item if (isSelect === 1) { message.info('已存在商品无法修改商品规格,请于规格库中停用或删除该商品') return } else { const selected = selectedSkuList[index].skuValueList.filter(item => item.isSelect === 1) if (selected.length) { message.info('请先取消勾选已选规格值, 再删除相关规格') } else { selectedSkuList.splice(index, 1) dispatch(action.setSelectedSkuList(selectedSkuList)) } } } // 选择新的规格 // 每个商品最多三个规格 selectMoreSku(value) { const { goodSkuList, selectedSkuList } = this.props // 首先判断商品规则是不是已经存在再做后续操作 const result = selectedSkuList.some(item => { if (item.name === value) { return true } }) if (result) { message.info('此规格已经存在') } else { if (selectedSkuList.length < 3) { goodSkuList.map(item => { if (item.name === value) { selectedSkuList.push(item) } }) } else { message.info('每个商品最多添加三种规格') } } this.setState({ showSpecSelect: false }) } // 已选规格变化时 规格表格里的数据也更新 selectedSkuChange(e, index, tIndex, result, id) { let { selectedSkuList, skuTableList, dispatch } = this.props let newTableData = [] if (e.target.checked) { selectedSkuList[index].skuValueList[tIndex].isSelect = 1 dispatch(action.setSelectedSkuList(selectedSkuList)) newTableData = Format.selectdSkuToTableData(selectedSkuList, index, result, id) } else { if (selectedSkuList[index].isSelect === 1) { const skuList = selectedSkuList[index].skuValueList.filter(item => item.isSelect === 1) if (skuList.length === 1) { Message.info('除非该规格停用,否则原规格项下必选择一个规格值') return } } selectedSkuList[index].skuValueList[tIndex].isSelect = 0 dispatch(action.setSelectedSkuList(selectedSkuList)) newTableData = Format.deleteSkuValue(selectedSkuList, skuTableList, index,id) } if (newTableData.length > 64) { message.info('每个商品最多添加64个商品规格') selectedSkuList[index].skuValueList[tIndex].isSelect = 0 dispatch(action.setSelectedSkuList(selectedSkuList)) newTableData = Format.deleteSkuValue(selectedSkuList, skuTableList, index,id) } dispatch(action.setSkuTableData(newTableData)) } // 多规格商品不能转化成无规格 hasSkuClick(flag) { if (flag) { Message.info('规格商品无法转为无规格商品,请删除该商品重新创建。') } } columnPriceChange(text, record) { const { skuTableList, dispatch } = this.props const { key } = record skuTableList[key].price = text dispatch(action.setSkuTableData(skuTableList)) } columnMemberpriceChange(text, record) { const { skuTableList, dispatch } = this.props const { key } = record skuTableList[key].memberPrice = text dispatch(action.setSkuTableData(skuTableList)) } columnCodeChange(text, record) { const { skuTableList, dispatch } = this.props const { key } = record skuTableList[key].code = text dispatch(action.setSkuTableData(skuTableList)) } columnCostPriceChange(text, record) { const { skuTableList, dispatch } = this.props const { key } = record skuTableList[key].costPrice = text dispatch(action.setSkuTableData(skuTableList)) } columnOpeningInventoryChange(text, record) { const { skuTableList, dispatch } = this.props const { key } = record skuTableList[key].openingInventory = text dispatch(action.setSkuTableData(skuTableList)) } checkPrice(rule, value, callback) { const reg = /^\d*(?:\.\d{0,2})?$/ if (value) { const valueStr = value.toString() if ((!reg.test(valueStr.trim()) || valueStr.split('.')[0].length > 6 )) { callback('只能输入数字并且整数位最多六位,小数位最多保留两位') } } callback() } /** * 检验期初库存输入是否合格 */ checkInventory = (rule, value, callback) => { const { getFieldValue } = this.props const isTwoAccount = getFieldValue('isTwoAccount') if (isTwoAccount) { const reg = /^\d*(?:\.\d{0,2})?$/ if (value) { const valueStr = value.toString() if ((!reg.test(valueStr.trim()) || valueStr.split('.')[0].length > 6 )) { callback('只能输入数字并且整数位最多六位,小数位最多保留两位') } } } else { const reg = /^\d{1,6}$/ if (value) { const valueStr = value.toString() if ((!reg.test(valueStr.trim()) )) { callback('非散称商品的期初库存只能输入六位以内的整数') } } } callback() } render() { const { isShowVolumnPop, volumnValue, multiSpe, selectedRows} = this.state const { skuTableList = [], getFieldDecorator, formItemLayout, specInfo, goodSkuList, selectedSkuList=[], chain } = this.props const { chainManageConfig } = specInfo // 允许门店修改总部下发的商品 editable // 并且允许门店将总部下发的商品转为单店的商品 changeToSelf const { chainDataManageable, changeToSelf } = chainManageConfig // 可修改连锁下发 const canEditSelf = chain === 'true' && chainDataManageable // 不可编辑 const unEdit = (chain === 'true' && chainDataManageable === false && changeToSelf === false) const skuFormatList = Format.formatSkuVoList(skuTableList) const columns = [ { title: '规格', dataIndex: 'spec', }, { title: '规格条码', dataIndex: 'code', render: (text, record) => { return ( <FormItem> { getFieldDecorator(`skuCode${record.key}`, { initialValue: text }) (<Input onChange={(e) => { this.columnCodeChange(e.target.value, record) }} disabled={unEdit}></Input>) } </FormItem> ) } }, { title: '单价', dataIndex: 'price', render: (text, record) => { return ( <FormItem> { getFieldDecorator(`skuPrice${record.key}`, { rules: [{ required: true, message: '请填写商品单价' }, { validator: this.checkPrice }], initialValue: text })(<Input onChange={(e) => { this.columnPriceChange(e.target.value, record) }} disabled={unEdit}></Input>) } </FormItem> ) } }, { title: '会员价', dataIndex: 'memberPrice', render: (text, record) => { return ( <FormItem> { getFieldDecorator(`skuMemberPrice${record.key}`, { rules: [{ validator: this.checkPrice }], initialValue: text })(<Input onChange={(e) => { this.columnMemberpriceChange(e.target.value, record) }} disabled={unEdit}></Input>) } </FormItem> ) } }, { title: '期初库存数', dataIndex: 'openingInventory', render: (text, record) => { return ( record.id?<span className={styles.disable_item}>-</span>: <FormItem> { getFieldDecorator(`skuOpeningInventory${record.key}`, { rules: [ { validator: this.checkInventory }], initialValue: text })(<Input onChange={(e) => { this.columnOpeningInventoryChange(e.target.value, record) }} disabled={unEdit || record.id!== ''}></Input>) } </FormItem> ) } }, { title: '期初成本价', dataIndex: 'costPrice', render: (text, record) => { return ( record.id?<span className={styles.disable_item}>-</span>: <FormItem> { getFieldDecorator(`skuCostPrice${record.key}`, { rules: [{ validator: this.checkPrice }], initialValue: text })(<Input onChange={(e) => { this.columnCostPriceChange(e.target.value, record) }} disabled={unEdit || record.id!== ''}></Input>) } </FormItem> ) } }, { title: '当前库存数', dataIndex: 'inventory', }, { title: '冻结库存数', dataIndex: 'frozenStock', } ] const rowSelection = { onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys, selectedRows}); } } const newSpecData = selectedRows.filter(item => item.id !== '') const newLen = newSpecData.length return ( <Card title="规格设置"> <div className={styles.main}> <div className={styles.spec_item}> <FormItem {...formItemLayout} label="是否为多规格" > { getFieldDecorator('hasSku', { valuePropName: 'checked', initialValue: specInfo.hasSku })(<Switch disabled={specInfo.hasSku || unEdit} onChange={this.toggleMultiSpe.bind(this)} onClick={() => { this.hasSkuClick(specInfo.hasSku) }} />) } </FormItem> </div> { ((specInfo.hasSku || multiSpe) && selectedSkuList.length > 0) && <div className={styles.spec_list}> { selectedSkuList.map((item, index) => { return ( <div className={styles.spec_value} key={index}> <div className={styles.sv_top}> <span className={styles.sv_name}> {`规格${index + 1}(${item.name})`} </span> <span className={styles.delete} onClick={() => { this.deleteSku(item, index) }}>删除</span> </div> <div className={styles.sv_main}> { item.skuValueList.map((t, tIndex) => { return ( <Checkbox checked={t.isSelect} key={tIndex} style={{ marginRight: 30 }} onChange={(e) => { this.selectedSkuChange(e, index, tIndex, skuTableList, t.charId) }} disabled={unEdit || canEditSelf}>{t.name}</Checkbox> ) }) } </div> </div> ) }) } </div> } { (specInfo.hasSku || multiSpe) && !unEdit && !canEditSelf && <div className={styles.add_spec}> <span className={styles.add_text} onClick={this.addSpec.bind(this)}>+ 添加规格</span> </div> } { this.state.showSpecSelect && <div className={styles.spec_select}> <Select style={{ width: 200 }} placeholder="请选择规格" onChange={this.selectMoreSku.bind(this)}> { goodSkuList.map((item, index) => { return ( <Option value={item.name} key={index}>{item.name}</Option> ) }) } </Select> </div> } { !specInfo.hasSku && !multiSpe && <div className={styles.single_spec}> <div className={styles.spec_item}> <FormItem {...formItemLayout} label="单价(元)" > { getFieldDecorator('price', { rules: [{ required: true, message: '请填写商品单价' }, { validator: this.checkPrice } ], initialValue: specInfo.price })(<Input style={{ width: 200 }} disabled={unEdit} />) } </FormItem> </div> <div className={styles.spec_item}> <FormItem {...formItemLayout} label="会员价(元)" > { getFieldDecorator('memberPrice', { rules: [{ required: false, validator: this.checkPrice }], initialValue: specInfo.memberPrice })(<Input style={{ width: 200 }} disabled={unEdit} />) } </FormItem> </div> <div className={styles.spec_item}> <FormItem {...formItemLayout} label="当前库存数" > { getFieldDecorator('currentStock', { initialValue: specInfo.currentStock })(<Input style={{ width: 200 }} disabled />) } </FormItem> </div> <div className={styles.spec_item}> <FormItem {...formItemLayout} label="冻结库存" > { getFieldDecorator('frozenStock', { initialValue: specInfo.frozenStock })(<Input style={{ width: 200 }} disabled />) } </FormItem> </div> </div> } { (specInfo.hasSku || multiSpe) && <FormItem > <div className={styles.multi_spec}> <Table rowSelection={rowSelection} columns={columns} dataSource={skuFormatList} /> { (!unEdit && !canEditSelf) && <div className={styles.multi_set} onClick={this._showVolumnModal.bind(this)}> 批量设置 </div> } </div> </FormItem> } {/* 批量设置 */} { isShowVolumnPop && <div className={styles.add_spec_container}> <div className={styles.box_bg} onClick={() => this._hideVolumnModal()} ></div> <div className={styles.add_spec_box}> <div className={styles.add_title}>批量设置</div> <div className={styles.add_spec_name}> <span><i className={styles.required_symbol}>*</i>单价</span> <input type="text" value={volumnValue.price} onChange={(e) => this._priceChange(e)} /> </div> <div className={styles.add_spec_name}> <span>会员价</span> <input type="text" value={volumnValue.memberPrice} onChange={(e) => this._memberPriceChange(e)} /> </div> { newLen === 0 && <div className={styles.add_spec_name}> <span>期初库存</span> <input type="text" value={volumnValue.expectStock} onChange={(e) => this._expectStockChange(e)} /> </div> } { newLen === 0 && <div className={styles.add_spec_name}> <span>期初成本价</span> <input type="text" value={volumnValue.expectCost} onChange={(e) => this._expectCostChange(e)} /> </div> } <div className={styles.add_spec_bottom}> <div className={styles.btn_cancel} onClick={() => this._hideVolumnModal()}>取消</div> <div className={styles.btn_save} onClick={() => this._saveVolumn()}>保存</div> </div> </div> </div> } </div> </Card> ) } } export default Sepcification <file_sep>/inside-chain/src/views/shop/store-manage/pass/printSetting/columns.js export default self => [ { title: '套餐中不一菜一切的商品分类', key: 'name' }, { title: '操作', render: (h, { row }) => { return ( <a style="color:#3e76f6" onClick={self.delPrinter(row)}> 删除 </a> ) } } ] <file_sep>/inside-boss/src/container/goodsImport/reducers.js import { SET_UPLOAD } from '../../constants' const goodImportReducer = (state = {}, action) => { switch (action.type) { case SET_UPLOAD: return Object.assign({}, state, {upLoadMsg: action.data}) default: return state } } export default goodImportReducer <file_sep>/inside-boss/src/container/visualConfig/views/design/common/googsSelect.js import React, { PureComponent } from 'react'; import { Modal, Table, Input, Icon} from 'antd'; import {formatNumber, entityId} from '../utils/index' import visualApi from '@src/api/visualConfigApi' import constants from './constants' const { Column } = Table; export default class googsSelectPreview extends PureComponent { state = { shopInput:'', data: [], selectedRows: [], selectedRowKeys: [], radio: this.props.radio || false } componentDidMount() { this.getRetailGoodsList() } componentWillReceiveProps(nextProps) { // 每次重新打开子组件的时候重新请求数据 if(nextProps.isShowGoods) { this.getRetailGoodsList() } } getRetailGoodsList = ({ keyWord } = {}) => { // 零售商品列表 visualApi.getRetailGoodsList({ keyWord }).then( res=>{ this.setState({ data: res.data }) }, err=>{ console.log('err', err) } ) } handleOk = () => { const {close, getGoodsItem} = this.props const { selectedRows } = this.state if(selectedRows.length > 0) { getGoodsItem(selectedRows) } close() this.deleKeys() } handleCancel = () => { const {close} = this.props close() this.deleKeys() } deleKeys = () => { // 选中重置 this.setState({ selectedRows: [], selectedRowKeys: [] }); } onChangeShopInput = (e) => { this.setState({ shopInput: e.target.value }); } newDate = (str) => { var date, Y, M, D, h, m, s; date = new Date(Number(str)); Y = date.getFullYear() + '-'; M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes(); s = date.getSeconds(); return Y + M + D + h + m } handleKeydown = (e) => { // 回车事件 const { shopInput } = this.state if(e.keyCode == 13) { this.getRetailGoodsList({ keyWord: shopInput }) } } render() { const { shopInput, data, selectedRowKeys } = this.state for(var i = 0; i< data.length; i++ ){ data[i].key = i } const rowSelection = { selectedRowKeys, type: this.state.radio ? 'radio' : null, onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys, selectedRows }) } }; return ( <div className='zent-googsSelect-preview'> <Modal title="添加商品 > 商品选择" visible={this.props.isShowGoods} onOk={this.handleOk} onCancel={this.handleCancel} width ={800} > <Input prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="搜索商品" value={shopInput} onChange={this.onChangeShopInput} style={creatStyle()} onKeyDown={this.handleKeydown} /> <Table dataSource={data} rowSelection={rowSelection} pagination={{ pageSize: 5 }} > <Column title="商品主图" dataIndex="imagePath" key="imagePath" render={(imagePath) => ( <span> <img src={imagePath || constants.defaultGoodsImg} width='50' height='50'></img> </span> )} /> <Column title="商品名称" dataIndex="itemName" key="itemName" /> <Column title="价格" dataIndex="minPrice" key="minPrice" render={(minPrice) => ( <span> <span>{formatNumber(minPrice, true)}</span> </span> )} /> <Column title="创建时间" dataIndex="createTime" key="createTime" render={(createTime) => ( <span> <span>{this.newDate(createTime)}</span> </span> )} /> </Table> </Modal> </div> ); } } function creatStyle() { return{ width: '150px', height: '32px', margin: '0 0 20px', } } <file_sep>/inside-boss/src/container/goods/reducers.js import { INIT_DATA, FETCH_BATCH_LIST, FETCH_RECHARGE_LIST, RECHARGE_IMPORT_EVENT, SHOW_EDIT_LAYER, SET_SELECTED_COUNTER, SET_SELECTED_ROW_KEYS, BTN_LOCK, SHOW_SPIN, SET_STATUS, SET_WHITE, SET_LAYER_DEFAULT_VALUES, SET_START_VALUE, SET_END_VALUE, SET_GOODS_LIST, SET_PAGE_INDEX, SET_IS_SHOW_BRAND, SET_BRAND_LIST, SET_BRAND_ID, SET_SHOW_SPECIFICATION, SET_CATEGORY_LIST, SET_SPEC_LIST, SET_UNIT_LIST, SET_ITEM_LIST, SET_GOOD_CATEGORY_LIST, SET_GOOD_STRATEGY, SET_GOOD_FACADE, SET_COMBINED_GOODS_LIST, SET_COMBINED_GOOD_DETAIL, SET_CHILD_GOODS_RESULT, SET_TEBLE_FIELDS_LIST, SET_TABLE_FIELDS_OPTIONS, SET_TABLE_OPTION_KEY, SET_MENU_LIST, SET_MODAL_VISIBLE, SET_RESULT_DATA, SET_TABLE_HEADER, SET_MENU_LANGUAGE, SET_TWINS_FILEDID, SET_GOODS_PARAMS, SET_HISTORY_DATA, } from '../../constants' const resetStatusList = (list) => { let final = {} list.forEach((m, i) => { let str = m.substring(0, 3) switch (str) { case '未充值': final.never = '0' break case '充值成': final.success = '1' break case '充值失': final.fail = '2' break case '已红冲': final.refund = '3' break default: return } }) let arr = [] for (let key in final) { arr.push(final[key]) } const params = arr.length > 0 ? arr.join(',') : '' sessionStorage.setItem('rechargeStatusList', params) } const goodsReducer = (state = {}, action) => { switch (action.type) { case INIT_DATA: return action.data case SET_GOODS_LIST: return Object.assign({}, state, { goodsList: action.data.records, goodsListTotal : action.data.totalRecord }) case SET_PAGE_INDEX: return Object.assign({}, state, { pageNumber:action.data }) case FETCH_BATCH_LIST: return Object.assign({}, state, {batchList: action.list}) case FETCH_RECHARGE_LIST: sessionStorage.setItem('selectedList', '[]') const data = action.data const statusList = data.statusList || [] resetStatusList(statusList) return Object.assign( {}, state, { cancelRechargeCount: data.cancelRechargeCount, faiRechargeCount: data.faiRechargeCount, name: data.name, pageCount: data.pageCount, preRechargeCount: data.preRechargeCount, rechargeBatchDetailsViewList: data.rechargeBatchDetailsViewList, rechargeBatchId: data.rechargeBatchId, sucRechargeCount: data.sucRechargeCount, totalCount: data.totalCount, defaultPageSize: data.defaultPageSize, selectedRowKeys: [], currentPage: data.pageIndex || 1, statusList: data.statusList } ) case RECHARGE_IMPORT_EVENT: const args = action.data const obj = args.rechargeBatchVo || {} sessionStorage.setItem('oldBatchId', obj.id) sessionStorage.setItem('selectedList', '[]') const l = args.statusList || [] resetStatusList(l) const list = args.rechargeBatchDetailsVoList || [] return Object.assign( {}, state, { name: obj.name, rechargeBatchId: obj.id, rechargeBatchDetailsViewList: list, cancelRechargeCount: args.cancelRechargeCount, faiRechargeCount: args.faiRechargeCount, pageCount: args.pageCount, preRechargeCount: args.preRechargeCount, sucRechargeCount: args.sucRechargeCount, totalCount: args.totalCount, selectedRowKeys: [], currentPage: args.pageIndex || 1, statusList: args.statusList } ) case SHOW_EDIT_LAYER: return Object.assign({}, state, {showEditLayer: action.data}) case SET_SELECTED_COUNTER: return Object.assign({}, state, {selectedCounter: action.len}) case SET_SELECTED_ROW_KEYS: return Object.assign({}, state, {selectedRowKeys: action.selectedRowKeys}) case BTN_LOCK: return Object.assign({}, state, {btnLocker: action.data}) case SHOW_SPIN: return Object.assign({}, state, {showSpin: action.data}) case SET_STATUS: return Object.assign({}, state, {statusList: action.list}) case SET_WHITE: return Object.assign({}, state, {inWhite: action.data}) case SET_START_VALUE: return Object.assign({}, state, {startValue: action.value}) case SET_END_VALUE: return Object.assign({}, state, {endValue: action.value}) case SET_LAYER_DEFAULT_VALUES: return Object.assign({}, state, {layerDefaultvalues: action.data}) case SET_IS_SHOW_BRAND: return Object.assign({}, state, {isShowBrand:action.data}) case SET_BRAND_LIST: return Object.assign({}, state, {brandList:action.data}) case SET_BRAND_ID: return Object.assign({},state,{brandId:action.data}) case SET_SHOW_SPECIFICATION: return Object.assign({},state,{showSpecification:action.data}) case SET_CATEGORY_LIST: return Object.assign({}, state, { cateList: action.cateList, cateFlat: action.cateFlat, }) case SET_SPEC_LIST: return Object.assign({}, state, {specList:action.data}) case SET_UNIT_LIST: return Object.assign({}, state, {unitList:action.data}) case SET_ITEM_LIST: return Object.assign({}, state, {item:action.data}) case SET_GOOD_CATEGORY_LIST: return Object.assign({}, state, {goodsCategoryList:action.data}) case SET_GOOD_STRATEGY: return Object.assign({}, state, { strategy: action.data}) case SET_GOOD_FACADE: return Object.assign({}, state, { facadeService: action.data}) case SET_COMBINED_GOODS_LIST: return Object.assign({}, state, { goodCombinedList: action.data }) case SET_COMBINED_GOOD_DETAIL: return Object.assign({}, state, { goodCombinedDetail: action.data }) case SET_CHILD_GOODS_RESULT: return Object.assign({}, state, { childGoodsList: action.data }) case SET_TEBLE_FIELDS_LIST: return Object.assign({}, state, { tableFieldsList:action.data }) case SET_TABLE_FIELDS_OPTIONS: return Object.assign({}, state, { tableFieldsOptions:action.data }) case SET_TABLE_OPTION_KEY: state.tableFieldsOptions[action.data.key].selectedList = action.data.list return Object.assign({}, state) case SET_MENU_LIST: return Object.assign({},state,{menuList:action.data}) case SET_MODAL_VISIBLE: return Object.assign({},state,{modalVisible:action.data}) case SET_RESULT_DATA: return Object.assign({},state,{resultData:action.data}) case SET_TABLE_HEADER: return Object.assign({},state,{tableHeader:action.data}) case SET_MENU_LANGUAGE: return Object.assign({},state,{menuLanguage:action.data}) case SET_TWINS_FILEDID: return Object.assign({},state,{twinsFiledIdList:action.data}) case SET_GOODS_PARAMS: return Object.assign({},state,{goodsParams:action.data}) case SET_HISTORY_DATA: return Object.assign({},state,{historyDate:action.data}) default: return state } } export default goodsReducer <file_sep>/static-hercules/src/examination/utils/data.js export const resultData = { analyze: { detail: '本店日均开台率低于行业平均值,整体走势在下降,\n急需提升!开台率低,代表订单数少,营业额不高,\n有亏本的风险!', settingIcon: [ { type: 'PASS', icon: 'https://assets.2dfire.com/frontend/6052700408598b1b23934f2a1de684fe.png', url: '#', name: '点餐提醒与推荐', permission: true }, { type: 'PASS', icon: 'https://assets.2dfire.com/frontend/d6a649e2fd8bd49e7608ea532c612453.png', url: '#', name: '菜单装修', permission: false }, { type: 'PASS', icon: 'https://assets.2dfire.com/frontend/0bab5e204667c6276a9de85a00400c88.png', url: '#', name: '商品视频', permission: false }, { type: 'UPDATE', icon: 'https://assets.2dfire.com/frontend/08a13df7b2e38a92a1c028bb2ca3a389.png', url: '#', name: '二维火收银', permission: false }, { type: 'UPDATE', icon: 'https://assets.2dfire.com/frontend/08a13df7b2e38a92a1c028bb2ca3a389.png', url: '#', name: '二维火收银', permission: true } ], chart: [ { unit: '元', series: [{ simpPoints: [4.0, 1.14] }], xData: ['近30天日\n均人均消费', '预期人均消费'], type: 'BAR', title: '人均消费对比' }, { unit: '元', series: [ { data: [ 63.0, 0.0, 62.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] } ], xData: [ '2018-09-24', '2018-09-25', '2018-09-26', '2018-09-27', '2018-09-28', '2018-09-29', '2018-09-30', '2018-10-01', '2018-10-02', '2018-10-03', '2018-10-04', '2018-10-05', '2018-10-06', '2018-10-07', '2018-10-08', '2018-10-09', '2018-10-10', '2018-10-11', '2018-10-12', '2018-10-13', '2018-10-14', '2018-10-15', '2018-10-16', '2018-10-17', '2018-10-18', '2018-10-19', '2018-10-20', '2018-10-21', '2018-10-22', '2018-10-23' ], type: 'LINE_GRAPH', title: '近30天人均消费走势' }, { unit: '元', series: [{ data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }], xData: [ '2018-04', '2018-05', '2018-06', '2018-07', '2018-08', '2018-09' ], type: 'LINE', title: '近6个月人均消费走势' }, { title: '营业额对比', unit: '(万元)', type: 'LINE', xData: [ '2017.12', '2018.01', '2018.02', '2018.03', '2018.04', '2018.05' ], yData: [], series: [ { name: '营业额', data: [0, 0, 0, 0, 0, 0] } ] }, { title: '营业额对比', unit: '(万元)', type: 'LINE', xData: [ '2017.12', '2018.01', '2018.02', '2018.03', '2018.04', '2018.05' ], yData: [], series: [ { name: '新客占比', data: [ { value: -1000, sum: 20000, percent: '10%' }, { value: -1000, sum: 20000, percent: '10%' }, { value: -1000, sum: 20000, percent: '10%' }, { value: -500, sum: 20000, percent: '10%' }, { value: -1000, sum: 20000, percent: '10%' }, { value: -1000, sum: 20000, percent: '10%' } ] } ] }, { title: '营业额对比', unit: '(万元)', type: 'LINE_GRAPH', xData: [ '2009.6.12', '2009.6.13', '2009.6.14', '2009.6.15', '2009.6.16', '2009.6.17', '2009.6.18', '2009.6.19', '2009.6.20', '2009.6.21', '2009.6.22', '2009.6.24', '2009.6.25', '2009.6.26', '2009.6.27', '2009.6.28', '2009.6.29', '2009.6.30', '2009.7.1', '2009.7.2', '2009.7.3', '2009.7.4', '2009.7.5', '2009.7.6', '2009.7.7', '2009.7.8', '2009.7.9', '2009.7.10', '2009.7.11', '2009.7.12', '2009.7.13', '2009.7.14' ], series: [ { name: '1次', data: [ 10000, 12000, 13000, 15000, 18000, 15000, 10000, 12000, 13000, 15000, 18000, 15000, 10000, 12000, -13000, -15000, -18000, -15000, -10000, 12000, 13000, 15000, 18000, 15000, 10000, 12000, 13000, 15000, 18000, 15000, 10000, 12000, 13000, 15000, 18000, 15000, 10000, 12000 ] } ], interval: 5 }, { title: '营业额对比', unit: '(万元)', type: 'BAR', xData: ['近30天\n111', '预期月'], series: [ { name: '营业额', data: [40, 30] } ] }, { title: '营业额对比', unit: '(万元)', type: 'BAR_HEAP', xData: ['饿了么', '美团', '百度外卖'], yData: [], series: [ { name: '1次', data: [60, 20, 30] }, { name: '2-3次', data: [30, 30, 40] }, { name: '4-5次', data: [50, 70, 30] } ], color: ['#44cbff', '#ffd000', '#ff0000'] }, { title: '营业额对比', unit: '(万元)', type: 'BAR_CROSSWISE', yData: ['菜品名称1菜品名称1菜品名称1', '菜品名称2', '菜品名称3'], series: [ { name: '1次', data: [ { value: 60, utc: 120 }, { value: 20, utc: 130 }, { value: 60, utc: 160 } ] } ] }, { title: '近30天营业额组成', unit: '(万元)', type: 'PIE', series: [ { name: '1次', data: [ { value: 335, name: '老客老客老客老客' }, { value: 679, name: '新客新客新客新客' }, { value: 1048, name: '领卡会员领卡会员领卡会员' }, { value: 1548, name: '充值会员充值会员' }, { value: 335, name: '1老客老客老客老客' }, { value: 679, name: '1新客新客新客新客' }, { value: 1048, name: '1领卡会员领卡会员领卡会员' }, { value: 1548, name: '1充值会员充值会员' } ] } ] }, { title: '回头客占比', unit: '', type: 'PIE_ANNULAR', series: [ { name: '近30天占比', data: [{ value: 25, name: '老客' }, { value: 75, name: 'other' }] }, { name: '近15天占比', data: [{ value: 479, name: '老客' }, { value: 679, name: 'other' }] } ], color: ['#44cbff', '#ffd000', '#ff0000'] } ] }, scheme: [ { title: '1.提升客流量', child: [ { title: '1) 拉新', detail: '来的人越多,订单数就会越高', set: [ { icon: 'https://assets.2dfire.com/frontend/6052700408598b1b23934f2a1de684fe.png', title: '优惠卷', url: '', isOk: 'NO_PERMISSION' }, { icon: 'https://assets.2dfire.com/frontend/6052700408598b1b23934f2a1de684fe.png', title: '优惠卷', url: '12333', isOk: 'NEED_BUY' } ] }, { title: '2) 拉新', detail: '来的人越多,订单数就会越高', set: [ { icon: 'https://assets.2dfire.com/frontend/6052700408598b1b23934f2a1de684fe.png', title: '优惠卷', url: '', isOk: 'PASS' } ] }, { title: '3) 拉新', detail: '来的人越多,订单数就会越高' } ] }, { title: '2.提升客流量', child: [ { title: '拉新', detail: '来的人越多,订单数就会越高', btnUrl: '123333', btnTitle: '查看解决方案' } ] } ], video: [ { time: '05:02', img: 'https://assets.2dfire.com/frontend/6ddcca4f6a3d615b404efefd00d5d714.png', teacher: '柠檬草柠檬草柠檬草', title: '这是标题这是标题这是标题这是标题这是标题这是标题', browsing: '35,509', url: 'http://www.baidu.com' }, { time: '05:02', img: 'https://assets.2dfire.com/frontend/6ddcca4f6a3d615b404efefd00d5d714.png', teacher: '柠檬草柠檬草柠檬草', title: '这是标题这是标题这是标题这是标题这是标题这是标题', browsing: '35,509', url: 'http://www.baidu.com' }, { time: '05:02', img: 'https://assets.2dfire.com/frontend/6ddcca4f6a3d615b404efefd00d5d714.png', teacher: '柠檬草柠檬草柠檬草', title: '这是标题这是标题这是标题这是标题这是标题这是标题', browsing: '35,509', url: 'http://www.baidu.com' } ], releaseCase: [ { time: '2017-08-10', img: 'https://assets.2dfire.com/boss/img/publish/66854376f0d6eb0ad514ca1396805894.jpg', title: '西贝莜面1个月10万活跃会员 是怎么做到的?', browsing: '35509', praise: '12', url: 'http://www.baidu.com' }, { time: '2017-08-10', img: 'https://assets.2dfire.com/boss/img/publish/66854376f0d6eb0ad514ca1396805894.jpg', title: '西贝莜面1个月10万活跃会员 是怎么做到的?', browsing: '35509', praise: '12', url: 'http://www.baidu.com' } ], explain: '1.开台率=订单数\n2.因为桌数是相对稳定的2.因为桌数是相对稳定的2.因为桌数是相对稳定的' } export const ceshiData = { explain: 'nihao', scheme: [ { child: [ { set: [ { isOk: 'NO_PERMISSION', icon: 'https://assets.2dfire.com/boss/function/health/pad_shop_qrcode.png', title: '快餐点餐二维码', url: 'tdf-manager://2dfire.com/qrCode/kabawQrcode' }, { isOk: 'NO_PERMISSION', title: '卡详情一览', url: 'PAD_DETAIL_CARD_REPORT' }, { isOk: 'NO_PERMISSION', icon: 'https://assets.2dfire.com/boss/function/functionlist/phone_precise_marketing.png', title: '精准营销', url: 'tdf-manager://2dfire.com/memberTemp/activityList?act_type=8&action_code_brand=PHONE_BRADN_PRECISE_MARKETING&action_code_branch=&action_code_shop=PHONE_PRECISE_MARKETING' }, { isOk: 'PASS', icon: 'http://assets.2dfire.com/boss/newfunction/homepage/17034a8458afc1e66b7e2c0c137b7790.png', title: '营销方案', url: 'tdf-manager://2dfire.com/member/marketingPlanList?action_code_brand=BRAND_PHONE_MARKETING_PLAN&action_code_branch=&action_code_shop=PHONE_MARKETING_PLAN' }, { isOk: 'NO_PERMISSION', title: '赠分明细报表', url: 'CARD_DEGREE_DETAIL_REPORT' }, { isOk: 'NO_PERMISSION', icon: 'http://assets.2dfire.com/boss/newfunction/homepage/548d6663b4420a72abc0f65b6fbc0afc.png', title: '绑定银行卡', url: 'tdf-manager://2dfire.com/payment/detail' }, { isOk: 'NO_PERMISSION', title: '会员赠分', url: 'PHONE_GIVE_DEGREE' }, { isOk: 'NO_PERMISSION', icon: 'https://assets.2dfire.com/boss/newfunction/homepage/phone_game_center.png', title: '游戏中心', url: 'tdf-manager://2dfire.com/gameCenter/index' }, { isOk: 'NO_PERMISSION', title: '组合促销', url: 'PHONE_MULTI_MARKETING' }, { isOk: 'PASS', icon: 'https://assets.2dfire.com/boss/newfunction/homepage/phone_mall_employee.png', title: '员工', url: 'tdf-manager://2dfire.com/employee/index' }, { isOk: 'NO_PERMISSION', icon: 'https://assets.2dfire.com/boss/newfunction/homepage/phone_member_card.png', title: '会员管理', url: 'tdf-manager://2dfire.com/dynamicMenuPage/index?functionId=01634f06b30d11e79bf9525400a7b87d' } ], detail: '增加效益', title: '增益' }, { set: [ { isOk: 'NO_PERMISSION', title: '卡详情一览', url: 'PAD_DETAIL_CARD_REPORT' } ], detail: '就是小外卖', title: '外卖aa ' } ] } ], analyze: { detail: '', chart: [ { series: [ { name: '近30天占比', data: [{ value: 479, name: '老客' }, { value: 679, name: 'other' }] }, { name: '近15天占比', data: [{ value: 479, name: '老客' }, { value: 679, name: 'other' }] } ], type: 'PIE_ANNULAR', title: '新客占比' }, { unit: '%', series: [ { points: [ { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 }, { sum: 0, precent: '0%', value: 0 } ] } ], xData: [ '2018-03', '2018-04', '2018-05', '2018-06', '2018-07', '2018-08', '2018-09' ], type: 'LINE', title: '近6个月新客占比走势' } ] }, releaseCase: [ { browsing: '0', img: 'https://assets.2dfire.com/boss/img/dev/6ee82d27d625f6739e84fbd0a08745f4.png', time: '2017-10-13', title: '驱蚊器翁群无', url: 'https://assets.2dfire.com/boss/article/dev/0a623f97ebda41d6906e7ce187b240d7.html', praise: '0' }, { browsing: '0', img: 'https://assets.2dfire.com/boss/img/dev/d0b5e26521f27fd598331e0cec786a3d.png', time: '2017-10-16', title: '测试案例重复标签', url: 'https://assets.2dfire.com/boss/article/dev/0d4693bdbd5a473e85f5e85367a1c7a9.html', praise: '0' } ], video: [ { browsing: '200000064', img: 'https://assets.2dfire.com/boss/img/dev/bcf56b9a7cdf31a2b3a01db585d31ed7.png', teacher: '柠檬草', time: '00:02:20', title: '二维火公众号营销', url: 'https://video.2dfire.com/xiaoermedia/0196af6eebb32459071ac054014a059d.mp4' } ] } <file_sep>/static-hercules/src/fin-action/config/api.js /** * 金融支付活动模块API */ import axios from './interception' export const getToken = params => axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: params }) /* * 获取活动配置列表 */ export const getActivityList = params => axios({ method: 'GET', url: 'com.dfire.fin.activity.banner.queryPublished', params }) <file_sep>/static-hercules/src/customer/config/api.js // const {BOSS_API_URL} = require('apiConfig'); // const {DD_API_URL} = require('apiConfig'); // module.exports = { // QUERY_REPAIR_ITEMS: BOSS_API_URL+'/customer_service/v1/query_repair_items', // STAFF_ATTENDANCE:DD_API_URL+'/staff_attendance/check.do', // } import Axios from 'base/axios' const {BOSS_API_URL} = require('apiConfig'); const {DD_API_URL} = require('apiConfig'); const API = { queryRepairItems(query){ return Axios({ method: 'GET', url: BOSS_API_URL+'/customer_service/v1/query_repair_items', params:query }) }, staffAttendance(query){ return Axios({ method: 'GET', url: DD_API_URL+'/staff_attendance/check.do', params:query }) }, getQueryTodayRecord(query){ return Axios({ method: 'GET', url: DD_API_URL+'/staff_attendance/queryTodayRecord.do', params:query }) }, getId(query){ return Axios({ method:'GET', url:DD_API_URL+'/staff_attendance/exchangeIdByCode.do', params:query }) }, getQueryLastRecord(query){ return Axios({ method:'GET', url:DD_API_URL+'/staff_attendance/queryLastRecord.do', params:query }) } } export default API;<file_sep>/static-hercules/src/oasis/store/actions.js /** * Created by zyj on 2018/4/3. */ import * as types from './mutation-types' import errorToast from 'src/oasis/libs/errorToast' import { getApplyMaterials, getRegion } from 'src/oasis/config/api' const findIdIndex = (arr, id) => { let index = arr.findIndex(item => { return item.id === id }) return index >= 0 ? index : 0 } // 获取shopinfo export const getApplyInfo = ({ commit }, params) => { getApplyMaterials(params.type).then(data => { let currentShopCode = data.data.shopCode let localShopCode = '' try { localShopCode = JSON.parse(localStorage.getItem('baseInfo')).shopCode } catch (e) { localShopCode = '' } if (!params.isview) { // 判断是否为同一个用户 if (currentShopCode !== localShopCode) { commit(types.GET_APPLY_MATERIALS, data.data) // 如果有街道,但是没市,就隐藏市 if (data.data.cityId) { getArea({ commit }, { sub_area_type: "town", parent_id: data.data.cityId, id: data.data.townId }) } } else { let localbaseinfo, localarea, localphoto try { localbaseinfo = JSON.parse(localStorage.getItem('baseInfo')) } catch (e) { localbaseinfo = {} } try { localarea = JSON.parse(localStorage.getItem('area')) } catch (e) { localarea = {} } try { localphoto = JSON.parse(localStorage.getItem('photos')) } catch (e) { localphoto = {} } let combim = Object.assign({}, data.data, localarea, localbaseinfo, localphoto) commit(types.GET_APPLY_MATERIALS, combim) // 如果有街道,但是没市,就隐藏市 if (combim.cityId) { getArea({ commit }, { sub_area_type: "town", parent_id: combim.cityId, id: combim.townId }) } } } else { localStorage.removeItem('baseInfo') localStorage.removeItem('area') localStorage.removeItem('photos') commit(types.GET_APPLY_MATERIALS, data.data) } }).catch(e => { console.log(e) // errorToast.show(e.result.message) }) } // 修改店铺信息 export const modifyShopInfo = ({ commit }, params) => { commit(types.MODIFY_SHOPINFO, params) } // 修改pickerSlot export const modifyPickerSlot = ({ commit }, params) => { let index = findIdIndex(params.list, params.id) let obj = params.list[index] commit(types.MODIFY_PICKER_SLOT, [{ flex: 1, values: params.list, defaultIndex: index, value: obj.name, valueIndex: index }]) // 修改picker的默认值 commit(types.MODIFY_PICKER_CHANGE_VALUE, { type: 'province', value: { name: obj.name, id: obj.id } }) } // 点击picker上面的完成触发的事件 export const getArea = ({ commit }, params) => { // 首先清空 commit(types.MODIFY_PICKER_SLOT, []) getRegion(params.sub_area_type, params.parent_id).then(data => { let index = findIdIndex(data.data.subAreaList, params.id) commit(types.MODIFY_PICKER_SLOT, [{ flex: 1, values: data.data.subAreaList, defaultIndex: index, valueIndex: index, value: data.data.subAreaList[index].name }]) // 如果是省的话要把数据存到store里面,这样获取省的时候就不需要每次请求了 if (params.sub_area_type === "province") { commit(types.SAVE_PROVINCE_LIST, data.data.subAreaList) } if (params.sub_area_type === 'town') { if (data.data.subAreaType === 'street') { commit(types.HIDE_TOWN, true) } else { commit(types.HIDE_TOWN, false) } } let obj = data.data.subAreaList[index] commit(types.MODIFY_PICKER_CHANGE_VALUE, { type: params.sub_area_type, value: { name: obj.name, id: obj.id } }) params.callback && params.callback() }).catch(e => { // errorToast.show(e.result.message) console.log(e) }) } // 实时修改选择省市区的选相框 export const modifyPickerChangeValue = ({ commit }, params) => { commit(types.MODIFY_PICKER_CHANGE_VALUE, params) } // 修改示例图片显示状态 export const changeExamplePhoto = ({commit}, params) => { commit(types.CHANGE_EXAMPLE_PHOTO, params) }<file_sep>/inside-boss/src/components/header/index.js import React, { Component } from 'react' import styles from './style.css' class Header extends Component { render () { const title = this.props.title return ( <div className={styles.wrapper}> {title} <div className={styles.arrow}></div> </div> ) } } export default Header <file_sep>/inside-boss/src/container/customBillDetail/reducers.js import { INIT_DATA_BILL, FETCH_BATCH_LIST, FETCH_RECHARGE_LIST, RECHARGE_IMPORT_EVENT, SHOW_EDIT_LAYER, SET_SELECTED_COUNTER, SET_SELECTED_ROW_KEYS, BTN_LOCK, SHOW_SPIN, SET_STATUS, SET_LAYER_DEFAULT_VALUES, SET_START_VALUE, SET_END_VALUE } from '../../constants' const customBillReducer = (state = {}, action) => { switch (action.type) { case INIT_DATA_BILL: return action.data case FETCH_BATCH_LIST: return Object.assign({}, state, {batchList: action.list}) case FETCH_RECHARGE_LIST: sessionStorage.setItem('selectedList', '[]') const data = action.data return Object.assign( {}, state, { cancelRechargeCount: data.cancelRechargeCount, faiRechargeCount: data.faiRechargeCount, name: data.name, pageCount: data.pageCount, preRechargeCount: data.preRechargeCount, rechargeBatchDetailsViewList: data.rechargeBatchDetailsViewList, rechargeBatchId: data.rechargeBatchId, sucRechargeCount: data.sucRechargeCount, totalCount: data.totalCount, defaultPageSize: data.defaultPageSize, selectedRowKeys: [], currentPage: data.pageIndex || 1, statusList: data.statusList } ) case RECHARGE_IMPORT_EVENT: const args = action.data const obj = args.rechargeBatchVo || {} sessionStorage.setItem('oldBatchId', obj.id) sessionStorage.setItem('selectedList', '[]') const list = args.rechargeBatchDetailsVoList || [] return Object.assign( {}, state, { name: obj.name, rechargeBatchId: obj.id, rechargeBatchDetailsViewList: list, cancelRechargeCount: args.cancelRechargeCount, faiRechargeCount: args.faiRechargeCount, pageCount: args.pageCount, preRechargeCount: args.preRechargeCount, sucRechargeCount: args.sucRechargeCount, totalCount: args.totalCount, selectedRowKeys: [], currentPage: args.pageIndex || 1, statusList: args.statusList } ) case SHOW_EDIT_LAYER: return Object.assign({}, state, {showEditLayer: action.data}) case SET_SELECTED_COUNTER: return Object.assign({}, state, {selectedCounter: action.len}) case SET_SELECTED_ROW_KEYS: return Object.assign({}, state, {selectedRowKeys: action.selectedRowKeys}) case BTN_LOCK: return Object.assign({}, state, {btnLocker: action.data}) case SHOW_SPIN: return Object.assign({}, state, {showSpin: action.data}) case SET_STATUS: return Object.assign({}, state, {statusList: action.list}) case SET_START_VALUE: return Object.assign({}, state, {startValue: action.value}) case SET_END_VALUE: return Object.assign({}, state, {endValue: action.value}) case SET_LAYER_DEFAULT_VALUES: return Object.assign({}, state, {layerDefaultvalues: action.data}) default: return state } } export default customBillReducer <file_sep>/inside-chain/src/utils/string.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * 清除字符串两边空格 * @param {String} str * @return {String} */ function stringTrim(str) { return str.replace(/^\s*|\s*$/g, ''); } /** * 清除字符串左边空格 * @param {String} str * @return {String} */ function stringTrimLeft(str) { return str.replace(/^\s*/, ''); } /** * 清除字符串右边空格 * @param {String} str * @return {String} */ function stringTrimRight(str) { return str.replace(/\s*$/, ''); } /** * 字符是否以compareStr开头 * @param {String} str * @param {String} compareStr * @return {Boolean} */ function startWith(str, compareStr) { return str.indexOf(compareStr) === 0; } /** * 转换为int类型 * @param {String} str * @return {Boolean} */ function toInt(str) { var num = parseInt(str); return isNaN(num) ? 0 : num; } /** * 转换为int类型的1或0 * @param {String} str * @return {Boolean} */ function toIntBool(str) { var bool = str; if (typeof str == 'string') { bool = toInt(str); } return bool ? 1 : 0; } // polyfill startWith if (!String.prototype.startWith) { String.prototype.startWith = function (compareStr) { return startWith(this, compareStr); }; } /** * old: `type.toJson` * 字符串转为对象 * @param {String} v 需要parse的字符串 * @return {Object} */ function toJson(v) { var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; try { return JSON.parse(v) || defaultValue; } catch (e) { return {}; } } exports.stringTrim = stringTrim; exports.stringTrimLeft = stringTrimLeft; exports.stringTrimRight = stringTrimRight; exports.startWith = startWith; exports.toInt = toInt; exports.toIntBool = toIntBool; exports.toJson = toJson; exports.default = { stringTrim: stringTrim, stringTrimLeft: stringTrimLeft, stringTrimRight: stringTrimRight, startWith: startWith, toInt: toInt, toIntBool: toIntBool, toJson: toJson };<file_sep>/union-entrance/src/views/nav/navBar/initEvent.js import util from '../util' import modal from '../modal' export default function() { //切换店铺 util.getDom('#common-nav-shift-shop').addEventListener('click', function() { util.goToShiftShop() }) util.getDom('#common-nav-logout').addEventListener('click', function() { modal.notic({ title: '请注意', content: '确定要退出当前登录的账号吗?', onOk() { util.logout() } }) }) //点击导航栏每一项 const navItems = util.getDom('.nav-item', true) for (let i = 0; i < navItems.length; i++) { const item = navItems[i] const url = item.getAttribute('go') const target = item.getAttribute('target') item.addEventListener('click', function() { if (url) { if (url !== '-') { if (target === '__blank') { window.open(url) } else { util.setCookie('active', item.innerText) window.location.href = url } } } else { modal.message({ content: '正在开发中,敬请期待。如有需要,请在二维火掌柜APP进行操作', top: 100, duration: 1500 }) } }) } } <file_sep>/inside-boss/src/components/videoImport/main.js /** * Created by air on 2017/7/10. */ import React, { Component } from 'react' import styles from './style.css' import Handle from './handle' import VideoList from './videoList' import * as action from '../../action' class Main extends Component { componentDidMount(){ const t =this const { dispatch } = t.props dispatch(action.getVideoList(1 ,1)) dispatch(action.changeVideoType(1)) } render () { const {data, dispatch ,params} = this.props const {length} = data return ( <div className={styles.wraperBox}> <div className={styles.viewBox}> <Handle data={data} dispatch={dispatch} params={params}/> { (() => { if (length > 0) { return ( <VideoList data={data} dispatch={dispatch}/> ) } else { return null } })() } </div> </div> ) } } export default Main <file_sep>/inside-boss/src/utils/storage.js import nattyStorage from 'natty-storage' const storage = nattyStorage({ async: false, // 是否以异步方式使用 type: 'sessionStorage', // 缓存方式 key: 'insideboss', // !!! 唯一必选的参数,用于内部存储 tag: 'v1.0', // 缓存的标记,用于判断是否有效 duration: 1000 * 60 * 10, // 缓存的有效期长,以毫秒数指定 }) export default storage <file_sep>/inside-boss/src/components/customBill/createAlert.js import React, { Component } from 'react' import { message, Button, Modal, Spin, Select, Row, Col, Input } from 'antd' import Bill from '../customBillDetail/content' const Option = Select.Option import styles from './css/main.css' import { Link, hashHistory } from 'react-router' import cls from 'classnames' import { data } from '../customBillDetail/data' import apiNetwork from '../../api/networkApi' import { errorHandler } from '../../action' import * as action from '../../action' export default class Content extends Component { constructor(props) { super(props) this.state = { createBillName:this.props.data.type=== 'CREATE'?'':this.props.data.tmpl.name, //模板名称 createBillWidth: 80 //模板宽度 } } /** * 创建模板弹出 模板名称修改 * */ createBillNameChange(e) { this.setState({ createBillName: e.target.value }) } /** * 创建模板弹出 宽度选择 * */ createBillWidthChange(e) { this.setState({ createBillWidth: e }) } /** * 创建模板弹出 确定 * */ createHandleOk() { if (!this.state.createBillName) { message.error('请先输入模板名称') return false } const { dispatch, params, data } = this.props const { entityType ,type,importData,tmpl} = data console.log('output 1111ccc',this.props, 'entityType', entityType); apiNetwork .createPrintTmpl({ createTmplBo: JSON.stringify({ sourceId:tmpl.id, name: this.state.createBillName, width: this.state.createBillWidth, entityId:importData.entityId, sourceEntityId:tmpl.entityId }) }) .then( res => { console.log(res) hashHistory.push( `/CUSTOM_BILL/detail/main/${ res.data }?entityType=${entityType}&width=${ this.state.createBillWidth }` ) }, err => dispatch(errorHandler(err)) ) .then() } /** * 修改模板弹出 确定 * */ editHandleOk=() =>{ if (!this.state.createBillName) { message.error('请先输入模板名称') return false } const { dispatch, params, data } = this.props const { entityType,importData ,tmpl} = data console.log('output t',tmpl); apiNetwork .editTmplName({ tmplBasicBo: JSON.stringify({ id:tmpl.id , name: this.state.createBillName, entityId:importData.entityId }) }) .then( res => { if(res){ message.success('修改成功') this.props.createHandleCancel(this.state.createBillName) } }, err => dispatch(errorHandler(err)) ) } render() { const { dispatch, params, data } = this.props const { tmpl, visible,type } = data return ( <div> <Modal title={type==='CREATE'?'添加单据模板':'修改单据名称'} visible={visible} onOk={type==='CREATE'?this.createHandleOk.bind(this):this.editHandleOk.bind(this)} onCancel={this.props.createHandleCancel.bind(this,null)} bodyStyle={{ textAlign: 'center' }} > <div className={styles.add_alert_p}> <span className={styles.add_alert_name}> <i style={{ color: 'red', fontSize: '20px', verticalAlign: 'middle' }} > * </i> 模板名称: </span> <Input className={styles.add_alert_form} value={this.state.createBillName} defaultValue={type==='CREATE'?this.state.createBillName:tmpl.name} onChange={this.createBillNameChange.bind(this)} /> </div> <div className={styles.add_alert_p}> <span className={styles.add_alert_name}> 打印纸宽度: </span> <Select defaultValue={tmpl.width.toString()||'80'} className={styles.add_alert_form} onChange={this.createBillWidthChange.bind(this)} disabled={type==='EDIT'} > <Option value="80" disabled={!(tmpl.systemDef||tmpl.width==80) }>80mm</Option> <Option value="58" disabled={!(tmpl.systemDef||tmpl.width==58) }>58mm</Option> </Select> </div> </Modal> </div> ) } } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/slider/SliderPreview.js import React, { PureComponent } from 'react'; import style from'./SliderPreview.css' export default class SliderEditorPreview extends PureComponent { render() { const { config } = this.props.value; return ( <div className="zent-design-component-line-preview"> <div className={style.linePreview} style={createStyle(config)} /> </div> ); } } function createStyle(value) { const { height } = value; return { height: `${height}px`, }; } <file_sep>/static-hercules/src/login/main.js var Vue = require("vue"); var Router = require("vue-router"); var vueResource = require("vue-resource"); var App = require('./App.vue'); /** *二维码生成工具 */ import VueQriously from 'vue-qriously' Vue.use(VueQriously); Vue.use(Router); Vue.use(vueResource); Vue.http.interceptors.push((request, next) => { request.credentials = false; request.emulateHTTP = true; request.noCookie = true; next() }); var router = new Router({ routes: [{ path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "活动首页", component: require("./views/index/index.vue") }] }); if (window.tdfire == null) { window.tdfire = {} } window.tdfire.back = function (_this) { let timer = setTimeout(function () { if (tdfire.pop) { tdfire.pop() } }, 200) _this.$router.afterEach(route => { clearTimeout(timer) }) _this.$router.back() } window.createAndroidBridge = function () { if (window.bridge == null) { window.bridge = {};// 创建 bridge 对象 } if (window.tdfire.observe == undefined) { window.tdfire.observe = function (callback) { window.bridge.invoke(window.tdfire.getObservePluginSignature(), '', callback) } } if (window.tdfire.umeng == undefined) { window.tdfire.umeng = { mobclick: function (event) { window.bridge.invoke(window.tdfire.getUmengPluginSignature(), 'mobclick', null, event); } } } window.bridge.callback = { index: 0, cache: {}, invoke: function (id, args) { let key = '' + id; let callbackFunc = window.bridge.callback.cache[key]; callbackFunc(args); } } window.bridge.invoke = function (pluginName, funcName, callback, ...args) { let index = -1; // 存储 callback if (callback !== null && callback !== undefined) { window.bridge.callback.index += 1; index = window.bridge.callback.index; window.bridge.callback.cache['' + index] = callback; } // 发送消息到 native 去 window.bridge.postMessage( JSON.stringify({ "identifier": pluginName, "selector": funcName, "callbackId": index, "args": args, }) ); }; }; if (navigator.userAgent.indexOf('tdfire-Android') > -1) { window.createAndroidBridge() } new Vue({ el: '#app', router, template: "<App/>", components: { App }, });<file_sep>/static-hercules/src/ocean/main.js import Vue from 'vue' import Router from 'vue-router' import App from './App' import ShopPhoto from 'src/ocean/components/ShopPhoto.vue' import ShopInput from 'src/ocean/components/ShopInput' import ShopSelect from 'src/ocean/components/ShopSelect' import {router} from "./router" import store from './store' import {Picker} from 'mint-ui' import Toast from 'base/components/Toast.vue' // import Route from "@2dfire/utils/router"; // import {ENV} from 'apiConfig' import './scss/index.scss' // var vueResource = require("vue-resource") Vue.component('Toast', Toast) Vue.component(Picker.name, Picker) Vue.component('shop-photo', ShopPhoto) Vue.component('shop-input', ShopInput) Vue.component('shop-select', ShopSelect) Vue.use(Router) // Vue.use(vueResource) // Vue.http.headers.common['token'] = sessionStorage.getItem("token") // Vue.http.headers.common['env'] = ENV // 国际化需要语言参数 // Vue.http.headers.common['lang'] = 'zh_CN' new Vue({ el: '#app', router, store, template: "<App/>", components: { App }, })<file_sep>/inside-chain/src/const/emu-crumb.js const crumb = { shop_manage: { name: "门店管理", path: "/shop_manage" }, shop_brand: { name: "品牌管理", path: "/shop_brand" }, shop_organ: { name: "分支机构", path: "/shop_organ" }, shop_manage_view: { name: "门店管理", path: "/shop_manage", secondName: "经营概况", noQuery: true }, shop_manage_library_goods_manage: { name: "门店管理", path: "/shop_manage", secondName: "", noQuery: true }, single_shop_goods_add: { name: "门店管理", path: "/shop_manage", secondName: "", noQuery: true }, single_shop_goods_edit: { name: "门店管理", path: "/shop_manage", secondName: "编辑商品", noQuery: true }, shop_manage_library_suit_manage: { name: "门店管理", path: "/shop_manage", secondName: "", noQuery: true }, single_shop_suit_add_first_step: { name: "门店管理", path: "/shop_manage", secondName: "", noQuery: true }, single_suit_add_second_step: { name: "门店管理", path: "/shop_manage", secondName: "", noQuery: true }, shop_manage_info: { name: "门店管理", path: "/shop_manage", secondName: "店铺资料", noQuery: true }, single_suit_edit_first_step: { name:"门店管理", path:"/shop_manage_library_suit_manage", secondName:"品牌详情", noQuery: true }, single_suit_edit_second_step: { name:"门店管理", path:"/shop_manage_library_suit_manage", secondName:"品牌详情", noQuery: true }, single_shop_goods_attr: { name:"门店管理", path:"/shop_manage", secondName:"商品属性", noQuery: true }, single_shop_goods_class: { name:"门店管理", path:"/shop_manage", secondName:"商品属性", noQuery: true }, store_pass: { name: "门店管理", path: "/shop_manage", secondName: "传菜", noQuery: true }, shop_brand_info:{ name:"品牌管理", path:"/shop_brand", secondName:"品牌详情", noQuery: true }, goods_attr:{ name:"商品属性", path:"/goods_attr", secondName:"" }, goods_class:{ name:"分类管理", path:"/goods_class", secondName:"" }, goods_manage:{ name:"商品与套餐", path:"/goods_manage", secondName:"" }, goods_add:{ name:"商品与套餐", path:"/goods_manage", secondName:"添加商品" }, goods_edit:{ name:"商品与套餐", path:"/goods_manage", secondName:"编辑商品" }, add_set_base_info: { name:"商品与套餐", path:"/combo_manage", secondName:"添加套餐" }, add_set_combo_goods: { name:"商品与套餐", path:"/combo_manage", secondName:"添加套餐" }, edit_set_base_info: { name:"商品与套餐", path:"/combo_manage", secondName:"编辑套餐" }, edit_set_combo_goods: { name:"商品与套餐", path:"/combo_manage", secondName:"编辑套餐" }, combo_manage:{ name:"商品与套餐", path:"/combo_manage", secondName:"" }, set_base_info: { name:"商品与套餐", path:"/combo_manage", secondName:"添加套餐" }, menu_manage:{ name:"菜单管理", path:"/menu_manage", secondName:"" }, menu_dist:{ name:"菜单管理", path:"/menu_manage", secondName:"下发" }, dist_manage:{ name:"下发中心", path:"/dist_manage", secondName:"" }, dist_manage_history:{ name:"下发中心", path:"/dist_manage", secondName:"下发记录", noQuery: true }, dist_manage_retry:{ name:"下发中心", path:"/dist_manage", secondName:"重新下发", noQuery: true }, pay_kind_manage:{ name:"付款方式", path:"/pay_kind_manage", secondName:"" }, pay_kind_add:{ name:"付款方式", path:"/pay_kind_manage", secondName:"添加", noQuery: true }, pay_kind_edit:{ name:"付款方式", path:"/pay_kind_manage", secondName:"编辑", noQuery: true }, pay_kind_publish:{ name:"付款方式", path:"/pay_kind_manage", secondName:"下发", noQuery: true }, shop_pay_kind_manage:{ name:"门店管理", path:"/shop_manage", secondName:"", noQuery: true }, shop_pay_kind_add:{ name:"门店管理", path:"/shop_manage", secondName:"", noQuery: true }, shop_pay_kind_edit:{ name:"门店管理", path:"/shop_manage", secondName:"", noQuery: true }, pass_publish:{ name:"传菜方案", path:"/pass/scheme/list", secondName:"下发", }, cashier_monitor:{ name:"收银台监控", path:"/cashier_monitor", secondName:"", noQuery: true }, group:{ name:"分组管理", path:"/group", secondName:"", noQuery: true }, category:{ name:"分组管理", path:"/category", secondName:"", noQuery: true }, editor_group:{ name:"分组管理", path:"/manage_group", secondName:"分组编辑", noQuery: true }, role_edit:{ name:"店员职级", path:"/staff_manage", secondName:"添加职级", noQuery: true }, apply_shops:{ name:"店员职级", path:"/staff_manage", secondName:"适用门店", noQuery: true }, add_group:{ name:"分组管理", path:"/manage_group", secondName:"添加分组", noQuery:true }, staff_edit:{ name:"总部员工", path:"/chain_staff_list", secondName:"添加员工", noQuery:true }, chain_role_edit:{ name:"职级与权限", path:"/chain_role_action", secondName:"添加职级", noQuery:true }, coutom_content:{ name:"门店管理", path:"/shop_manage", secondName:"门店自定义编码和简称", noQuery:true } } export default crumb; <file_sep>/inside-boss/src/container/customBillStore/reducers.js import { SET_BILL_STORE_MODAL, SET_BILL_STORE_SHOP_LIST, SET_BILL_STORE_BRANCH, SET_BILL_STORE_PROVINCE, SET_BILL_ACTIVE_SHOP, SET_USE_STORE_LIST } from '../../constants' const updownReducer = (state = {}, action) => { switch (action.type) { case SET_BILL_STORE_MODAL: return Object.assign({}, state, { visible: action.data.visible }) case SET_BILL_STORE_SHOP_LIST: return Object.assign({}, state, { shopList: action.data }) case SET_BILL_STORE_BRANCH: return Object.assign({}, state, { branch: action.data }) case SET_BILL_STORE_PROVINCE: return Object.assign({}, state, { province: action.data }) case SET_BILL_ACTIVE_SHOP: return Object.assign({}, state, { activeShopList: action.data }) case SET_USE_STORE_LIST: return Object.assign({}, state, { useShopList: action.data }) default: return Object.assign({}, state, action.data) } } export default updownReducer <file_sep>/union-entrance/src/base/config/pre.js module.exports = { NEW_API_BASE_URL: 'https://meal.2dfire-pre.com', API_BASE_URL: 'https://gateway.2dfire-pre.com/?app_key=200800&method=', SHARE_BASE_URL: 'https://live-pre.zm1717.com', IMAGE_BASE_URL: '//ifile.2dfire.com/', API_WEB_SOCKET: 'https://websocket.2dfire-pre.com/web_socket', WEB_SOCKET_URL: 'https://websocket.2dfire-pre.com', // 根据不同环境设置不同链接地址 // PROJECT_ENV_INDEX: 'https://d.2dfire-pre.com/entrance/page/index.html', //登录页 // PROJECT_ENV_CHANGE: 'https://d.2dfire-pre.com/entrance/page/change.html', //选店页 // CHAIN_MANAGEMENT_URL: 'https://d.2dfire-pre.com/chain/page/index.html', //连锁管理页 }; <file_sep>/inside-boss/src/container/visualConfig/views/design/Design.js import React, { PureComponent } from 'react'; import find from 'lodash/find'; import uuid from 'uuid'; import assign from 'lodash/assign'; import { message } from 'antd'; import DesignPreiew from './preview/DesignPreview' import style from './design.css' import { isExpectedDesginType, } from './utils/design-type'; const UUID_KEY = '__zent-design-uuid__'; export default class Design extends PureComponent { static defaultProps = { preview: DesignPreiew, value: [], // defaultSelectedIndex: -1, // 默认选中的组件下标 prefix: 'zent', }; constructor(props) { super(props) const { value, defaultSelectedIndex } = this.props const safeValueIndex = getSafeSelectedValueIndex( defaultSelectedIndex, value ) const selectedValue = value[safeValueIndex]; this.state = { showAddComponentOverlay: false,// 是否显示添加组件的浮层 settings: {}, // 外面没传的时候用 state 上的 settings selectedUUID: this.getUUIDFromValue(selectedValue), validations: {},// 当前所有组件的 validation 信息,key 是 value 的 UUID } } setMaxCompont = (val, title) => { // 组件最大数 const { compontmaxNum } = this.props let index = 0 // 计数 if (val.length == 0) return const _valLength = val.length for (let i=0; i < _valLength; i++) { if(title == val[i].title) index++ } const maxNum = compontmaxNum[title] if(maxNum == index) { return true } } // 添加一个新组件 onAdd = (component, fromSelected) => { const { value, settings, onChange, compontmaxNum, designMode} = this.props const { editor, defaultType } = component; const instance = editor.getInitialValue() instance.canDelete = true // 是否可以删除 instance.type = editor.designType instance.title = editor.designDescription const maxNum = compontmaxNum[instance.title] if (this.setMaxCompont(value, instance.title)) { message.info(`该组件最大可以添加${maxNum}个`); return } const id = uuid(); this.setUUIDForValue(instance, id); let newValue; if(designMode == '商品分类页'){ //无论添加什么组件,只允许添加在商品分类组件上方。 newValue = this.cateValue(value, instance) } else { newValue = value.concat(instance); } onChange(newValue) this.onSelect(instance) } cateValue = (value, instance) => { const newVal = [...value]; const index = newVal.findIndex((c) => c.type == "cateList") newVal.splice(index, 0, instance) return newVal } //点击向上排序按钮事件 handleClickBySortUp = (index, e) => { const { value, onChange } = this.props e.stopPropagation(); let newValue = [...value]; if (index == 0 ) return false let temp = newValue[index - 1]; newValue[index - 1] = newValue[index]; newValue[index] = temp; onChange(newValue) } //点击向下排序按钮事件 handleClickBySortDown =(index, e) => { const { value, onChange } = this.props e.stopPropagation(); let newValue = [...value]; if (index == newValue.length - 1) return false let temp = newValue[index + 1]; newValue[index + 1] = newValue[index]; newValue[index] = temp; onChange(newValue) } // 选中一个组件 onSelect = component => { const id = this.getUUIDFromValue(component); const { showAddComponentOverlay } = this.state; if (this.isSelected(component) && !showAddComponentOverlay) { return; } this.setState({ selectedUUID: id, showAddComponentOverlay: false, }); } // 关闭组件 onCloseEditor= () =>{ this.setState({ selectedUUID: '', }); } // 删除一个组件 onDelete = index => { const { value, onChange } = this.props let newValue = [...value]; newValue.splice(index, 1) onChange(newValue) }; onComponentValueChange = (identity, diff, replace = false)=> { // 组件样式调整 const { value } = this.props; const newComponentValue = replace ? assign({ [UUID_KEY]: this.getUUIDFromValue(identity) }, diff) : assign({}, identity, diff); const newValue = value.map(v => (v === identity ? newComponentValue : v)); this.trackValueChange(newValue) }; // 调用 onChange 的统一入口,用于处理一些需要知道有没有修改过值的情况 trackValueChange(newValue, writeCache = true) { const { onChange } = this.props; onChange(newValue); } validateComponentValue = (value, prevValue, changedProps) => { const { type } = value; const { components } = this.props; const comp = find(components, c => isExpectedDesginType(c, type)); const { validate } = comp.editor; const p = validate(value, prevValue, changedProps); return p; }; render() { const { preview, value, prefix } = this.props return ( <div className={style.zentDesign}> {this.renderPreview(preview)} </div> ); } getUUIDFromValue(value) { return value && value[UUID_KEY]; } setUUIDForValue(value, id) { if (value) { value[UUID_KEY] = id; } return value; } isSelected = value => { const { selectedUUID } = this.state; return this.getUUIDFromValue(value) === selectedUUID; }; renderPreview(preview){ const { components, prefix, value, backgroundChang, backgroundImage, designMode } = this.props const {selectedUUID} = this.state const { showAddComponentOverlay, settings, validations } = this.state return React.createElement(preview, { components, prefix, value, designMode, backgroundChang, backgroundImage, showAddComponentOverlay, settings, onAddComponent: this.onAdd, handleClickBySortUp: this.handleClickBySortUp, handleClickBySortDown: this.handleClickBySortDown, selectedUUID, getUUIDFromValue: this.getUUIDFromValue, onSelect: this.onSelect, validations, onDelete: this.onDelete, onCloseEditor: this.onCloseEditor, onComponentValueChange: this.onComponentValueChange, }) } } function getSafeSelectedValueIndex(index, value) { return Math.min(index, value.length - 1) } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/mine/definition.js export default { name: 'mine', userName: '我的页面', choosable: false, config: { userInfoAlign: 'center', visualStyle: '卡片式', icons: { 会员中心: 'https://assets.2dfire.com/frontend/41b4df097e2c94b6d9678a1c664624fd.png', 待付款: 'https://assets.2dfire.com/frontend/c39a86a4752d7e4682b61975fe065a14.png', 进行中: 'https://assets.2dfire.com/frontend/a8fe06f2a9fd2d31778f3c852ac132c7.png', 已完成: 'https://assets.2dfire.com/frontend/7bdad89ffdac56c3bd397e785e3c56ec.png', 退款: 'https://assets.2dfire.com/frontend/b11dccab9a76574324ea42ff3cc7effe.png', 我的会员卡: 'https://assets.2dfire.com/frontend/ea21f0970b3fecf24d82d71c117c6420.png', 我的优惠券: 'https://assets.2dfire.com/frontend/2594320ee9012a3c8e669fabfe01faa5.png', 收货地址: 'https://assets.2dfire.com/frontend/d57d4489c19a2df11322332762a6e406.png', 个人信息: 'https://assets.2dfire.com/frontend/1972fef81801be620f28d1dd3c8a2e36.png', 代理中心: 'https://assets.2dfire.com/frontend/7e02fd5ce8e2036ff9289bcc6a6950fc.png', 我的订单: 'https://assets.2dfire.com/frontend/5947312739430077be9bdd641fa6adb2.png', }, }, } <file_sep>/inside-chain/src/const/emu-table-title.js export const goodsTableTitle = [ { name: '商品', width: '35%' }, { name: '所属分类', width: '20%' }, { name: '所属菜单', width: '15%' }, { name: '门店上架', width: '15%' }, { name: '操作', width: '15%' } ] export const singleShopTableTitle = [ { name: '商品', width: '35%' }, { name: '所属分类', width: '25%' }, { name: '商品状态', width: '25%' }, { name: '操作', width: '15%' } ] export const suitTableTitle = [ { name: '套餐', width: '35%' }, { name: '所属分类', width: '20%' }, { name: '所属菜单', width: '15%' }, { name: '门店上架', width: '15%' }, { name: '操作', width: '15%' } ] export const singleSuitTableTitle = [ { name: '套餐', width: '35%' }, { name: '所属分类', width: '25%' }, { name: '门店上架', width: '25%' }, { name: '操作', width: '15%' } ] export const suitGroupTitle = [ { name: '商品名称', width: '31%' }, { name: '规格', width: '23%' }, { name: '商品加价(¥)', width: '23%' }, { name: '限点数量', width: '23%' } ] export const suitGroupTitleChoosedAll = [ { name: '商品名称', width: '40%' }, { name: '规格', width: '30%' }, { name: '商品数量', width: '30%' } ] export const cashierMonitorTitle = [ { name:'店铺名称', width:'20%' }, { name:'门店编码', width:'20%' }, { name:'主收银软件版本', width:'20%' }, { name:'主收银运行状态', width:'20%' }, { name:'主副收银版本是否一致', width:'20%' }, ] export const shopTitle = [ { name:'名称', width:'20%' }, { name:'品牌', width:'15%' }, { name:'店铺编码', width:'15%' }, { name:'门店类型', width:'15%' }, { name:'营业状态', width:'15%' }, { name:'门店地址', width:'30%' }, ] export const roleTitle =(t)=>([ { title:'职级名称', key:'name', width:180 }, { title:'权限设置', render: (h,data)=>{ return h('div',{class:'tableRow'},[ data.row.actionGroupVOList.map(item=>{ return h('span',{class:'tableItem'},`${item.name}: ${item.rote}`) }) ],) }, }, { title:'操作', render: (h,data)=>{ return h('div',[ h('a',{ on:{ click:()=>{ t.editGroup(data.row) } }, class:'edit-button' },'编辑'), h('a',{ on:{ click:()=>{ t.delItem(data.row) } }, class:'edit-button' },'删除') ]) }, width:150 } ]) export const chainStaffTitle =(t)=>([ { title:'员工', width:'25%', render:(h,data)=>{ return h('div',{style:{overflow:'hidden',display: 'flex'}},[ h('div',{style:{float:'left',position:'relative', 'background-color': '#f1f1f1'}},[ h('img',{attrs:{src:data.avatarUrl},style:{width:'80px',height:'80px',display:'block'}}), h('div',{class:'tilt',style:{opacity: data.frozenStatus?'0.6':'0' }}), h('div',{class:'tilt',style:{opacity: data.frozenStatus?'1':'0',background:'transparent',color:'#FFF' }},'已冻结') ]), h('div',{class:'ItemStaffName'},[ h('div',{class:'itemUserName'},data.name), h('div',data.mobile ? `${data.countryCode} ${data.mobile}`:'-') ]) ]) } }, { title:'管辖范围', key:'scope', render: (h,data)=>{ return h('div',{},[ // h('div',{style:{'text-align':'left','min-width':'20%'}},[h('p',{style:{'text-align':'center'}},data.shopCount)]), // h('div',{style:{'text-align':'left','min-width':'20%'}},[h('p',{style:{'text-align':'center'}},data.brand)]), // h('div',{style:{'text-align':'left','min-width':'20%'}},[h('p',{style:{'text-align':'center'}},data.organization)]), h('div',{}, data.isAllShop?'全部门店': data.shopCount === 0 ?'无可管理门店': `${data.shopCount}家门店`), h('div',{}, data.isAllPlate?'全部品牌': data.plateCount === 0 ?'无可管理品牌': `${data.plateCount}个品牌` ), h('div',{}, data.isAllBranch?'全部分支机构': data.branchCount === 0 ?'无可管理分支结构': `${data.branchCount}个分支机构`), ]) } }, { title:'职级', key:'roleName' }, { title:'聘用类型', key:'hireType' }, { title:'入职时间', key:'entryDate' }, { title:'操作', render: (h,data)=>{ return h('div',[ h('a',{ on:{ click:()=>{ t.handleEdit(data) } }, class:'edit-button' },'编辑'), h('a',{ on:{ click:()=>{ t.deleteUser(data) } }, class:'edit-button' },'删除'), h('a',{ on:{ click:()=>{ t.handleFrozen(data) } }, class:'edit-button' },data.frozenStatus?'恢复':'冻结') ]) }, width:'15%' } ]) export const chainRoleTitle =(t)=>([ { title:'职级名称', key:'name', width:'15%' }, { title:'权限设置', render: (h,data)=>{ return h('div',{class:'chainTableRow'},[ data.actionGroupVOList.map(item=>{ return h('span',{class:'chainTableItem'},`${item.name}:${item.rote}`) }) ]) }, }, { title:'操作', render: (h,data)=>{ return h('div',[ h('a',{ on:{ click:()=>{ t.editGroup(data) } }, class:'edit-button' },'编辑'), h('a',{ on:{ click:()=>{ t.delItem(data) } }, class:'edit-button' },'删除') ]) }, width:'15%' } ]) <file_sep>/inside-boss/src/utils/getUserInfo.js import cookie from "@2dfire/utils/cookie"; import qs from "querystring"; export default isStringify => { let info = {}; try { info = JSON.parse(cookie.getItem("entrance")) || {}; } catch (e) { info = {}; } const { shopInfo, userInfo } = info; const { entityId, entityCode, industry } = shopInfo || {}; const { userId, memberId, name, countryCode } = userInfo || {}; return isStringify ? qs.stringify({ entityCode, entityId, userId, memberId, industry, userName: name, countryCode, currVer: 17 }) : info; }; <file_sep>/static-hercules/src/fm-bank/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from 'apiConfig' const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, getSessionInfo(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: params }) }, /*首页- 账户明细*/ getHomeInfo(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getHomeInfo', params: params }) }, /*商户钱包可用账户列表查询*/ accountListQuery(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.accountListQuery', params: params }) }, /*获取商户钱包提现流水列表*/ getWithdrawSerialList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.getWithdrawSerialList', data }) }, /*获取商户钱包账户收支流水列表*/ getAccountTradeList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.getAccountTradeList', data }) }, /*获取验证码*/ sendValidCode(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.sendValidCode', data }) }, /*提现申请*/ merchantWithdrawApply(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.withdrawApply', data }) }, /*获取商户提现验证码输入错误次数*/ getValidCodeErrTimes(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getValidCodeErrTimes', params: params }) }, /*获取商户钱包当天提现次数*/ getWithdrawTimes(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getWithdrawTimes', params: params }) }, /*检查提现是否需要短信验证码 2019 08 28 ADD*/ checkIsNeedValidCode(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.checkIsNeedValidCode', params: params }) }, /* *火拼拼担保交易 新增两个接口 修改三个接口 * 2019 08 08 * update1:com.dfire.fin.wallet.getHomeInfo * update2:com.dfire.fin.wallet.getAccountTradeList * update3:com.dfire.fin.wallet.withdrawApply * add1:com.dfire.fin.wallet.accountBankInfoQuery * add2:com.dfire.fin.wallet.getGuaranteeAccounts */ /*账户银行信息查询*/ accountBankInfoQuery(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.accountBankInfoQuery', params: params }) }, /*获取担保交易账户信息*/ getGuaranteeAccounts(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getGuaranteeAccounts', params: params }) }, /* * 新增接口:查询是否开通专用收款账户信息 */ checkOpenBindCard(params) { return axios({ method: 'GET', url: 'com.dfire.presell.trade.service.IBindBankAccountFacade.checkOpenBindCard', params: params }) }, /* * 新增连锁资金管理 新增两个接口 修改三个接口 * 2019 11 20 * update1: com.dfire.fin.wallet.updateChainAuthWithdraw 修改门店授权总部提现 */ /* * 新增接口:修改门店授权总部提现 */ updateChainAuthWithdraw(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.updateChainAuthWithdraw', params: params }) }, /* * 新增接口:查询是否展示授权模块 */ isShowFundManageAuthorize(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.isShowFundManageAuthorize', params: params }) }, /* * 新增接口:门店钱包查询授权总部提现 */ queryChainAuthWithdraw(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.queryChainAuthWithdraw', params: params }) }, /* * 新增接口:通用钱包提现 */ commonWalletWithdraw(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.commonWalletWithdraw', data }) }, /* * 新增接口:获取当前门店登录用户的职级 */ getUserRole(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getUserRole', params: params }) } } export default API <file_sep>/inside-chain/src/views/shop/store-manage/pass/notIssue/columns.js export default self => [ { title: '商品名称', key: 'name' }, { title: '商品分类', key: 'kindMenuName' }, { title: '操作', render: (h, { row }) => { return ( <a style="color:#3e76f6" onClick={self.delGoods(row)}> 删除 </a> ) } } ] <file_sep>/inside-boss/src/components/updown/layer.js import React, { Component } from 'react' import { Form, Input, Button, Modal } from 'antd' import cx from 'classnames' import styles from './layer.css' import * as action from '../../action' const FormItem = Form.Item const getParams = () => ({ startTime: sessionStorage.getItem('startTime'), endTime: sessionStorage.getItem('endTime'), rechargeStatusList: sessionStorage.getItem('rechargeStatusList'), pageSize: sessionStorage.getItem('pageSize'), pageIndex: sessionStorage.getItem('pageIndex'), selectedList: sessionStorage.getItem('selectedList') }) class Layer extends Component { handleSubmit = (e) => { e && e.preventDefault() const {dispatch, data, form} = this.props const params = getParams() const {rechargeBatchId} = data const {startTime, endTime, rechargeStatusList, pageSize, pageIndex} = params form.validateFieldsAndScroll((err, values) => { if (!err) { const currentItem = sessionStorage.getItem('currentItem') const rechargeBatchDetailsVo = Object.assign({}, values, JSON.parse(currentItem)) dispatch(action.btnLock({name: 'saveModifyBtn', bool: true})) dispatch(action.modifyInfo(rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, rechargeBatchDetailsVo, form)) } }) } handleCancel = () => { const {dispatch, form} = this.props dispatch(action.showEditLayer(false)) form.resetFields() } checkNum = (rule, value, callback) => { const regular = /^\w{6,30}$/ if (!!regular.test(value)) { callback() } else { if (!value) { callback() } else { callback('请填写正确的卡号!') } } } checkMoney = (rule, value, callback) => { const regular = /^[1-9]\d{0,7}$/ if (!!regular.test(value)) { callback() } else { if (!value) { callback() } else { callback('请填写正确的金额!') } } } checkMoneyPrecent = (rule, value, callback) => { const regular = /^[1-9]\d{0,7}$/ if (!!regular.test(value)) { callback() } else { if (!value) { callback() } else { callback('请填写正确的金额!') } } } checkComment = (rule, value, callback) => { const regular = /^[\S]{0,6}$/ if (!!regular.test(value) || value === undefined) { callback() } else { callback('备注过长') } } render () { const t = this const { getFieldDecorator } = t.props.form const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 } }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 } }, } const {data} = t.props const {showEditLayer, btnLocker, layerDefaultvalues} = data const {comment, cardCode, rechargeAmount,rechargeAmountPresent} = layerDefaultvalues const bool = (btnLocker && btnLocker.name === 'saveModifyBtn') ? btnLocker.bool : false return ( <Modal visible={showEditLayer} onCancel={t.handleCancel} footer={null} > <div className={styles.layer_title}>修改编辑</div> <Form className={cx(styles.form_wrapper)} onSubmit={t.handleSubmit}> <FormItem {...formItemLayout} label="备注" hasFeedback> { getFieldDecorator('comment', { rules: [{ required: false, validator: t.checkComment }], initialValue: comment })(<Input placeholder="请输入卡备注"/>) } </FormItem> <FormItem {...formItemLayout} label="卡号" hasFeedback> { getFieldDecorator('cardCode', { rules: [{ required: true, message: '请输入您的卡号!' }, { validator: t.checkNum }], initialValue: cardCode })(<Input placeholder="请输入卡号"/>) } </FormItem> <FormItem {...formItemLayout} label="充值金额(本金)" hasFeedback> { getFieldDecorator('rechargeAmount', { rules: [{ required: true, message: '请输入充值金额(本金)!' }, { validator: t.checkMoney }], initialValue: rechargeAmount })(<Input placeholder="请输入充值金额(本金)"/>) } </FormItem> <FormItem {...formItemLayout} label="充值金额(赠送金)" hasFeedback> { getFieldDecorator('rechargeAmountPresent', { rules: [{ required: true, message: '请输入充值金额(赠送金)!' }, { validator: t.checkMoneyPrecent }], initialValue: rechargeAmountPresent })(<Input placeholder="请输入充值金额(赠送金)"/>) } </FormItem> <FormItem className={cx(styles.btn_wrapper)}> <Button className={cx(styles.btn)} htmlType="submit" loading={bool}>保存修改</Button> </FormItem> </Form> </Modal> ) } } export default Form.create()(Layer) <file_sep>/inside-boss/src/container/visualConfig/views/new_design/editing/Editing.js import React, { Component } from 'react' import { connect } from 'react-redux' import { getCurrentPage, getPageDesignComponentMap } from '@src/container/visualConfig/store/selectors' import cx from 'classnames' import EditItem from './EditItem' import s from './Editing.css' @connect(state => ({ componentConfigs: state.visualConfig.design.componentConfigs, page: getCurrentPage(state), comMap: getPageDesignComponentMap(state), })) class Editing extends Component { render() { const { componentConfigs, page, comMap } = this.props const editItems = componentConfigs.map(item => ( <EditItem key={item.id} id={item.id} config={item.config} designComponent={comMap[item.name]} /> )) return <div className={s.wrapper}> <div className={s.innerWrapper}> <div className={s.pageDesc}>{page.name}</div> <div className={s.previewPanel}> <div className={s.previewHeader} /> <div className={s.previewComponents}> {editItems} </div> </div> </div> </div> } } export default Editing <file_sep>/inside-boss/src/components/goodTagEdit/editBoard.js import React, { Component } from 'react' import { Radio, Input, Popover, Form, DatePicker,LocaleProvider } from 'antd' import moment from 'moment' const FormItem = Form.Item const RadioGroup = Radio.Group const { TextArea } = Input import styles from './moduleTag.css' import * as action from '../../action' import locale from 'antd/lib/date-picker/locale/zh_CN' import 'moment/locale/zh-cn' const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } } class EditBoard extends Component { constructor(props) { super(props) this.state = { customTextErrorTip: '', // 自定义文本框的错误提示 isShowTitleEditInput: false, showDefaultInput: false, textAreaWordLength: 0, } } componentWillReceiveProps(nextProps) { this.setState({ showDefaultInput: nextProps.moduleDetail.templateType===1?false:true }) } radioCheckMap = { name: 'goodsNameType', barCode: 'goodsBarCodeType', retailPrice: 'goodsRetailPriceType', memberPrice: 'goodsMemberPriceType', unit: 'goodsUnitType', shelfLife: 'goodsPeriodType', productDate: 'goodsManufactureType', customText: 'definitionType', specifications: 'goodsSpecificationType' } textMap = { name: 'goodsNameExt', retailPrice: 'goodsRetailPriceExt', memberPrice: 'goodsMemberPriceExt', unit: 'goodsUnitExt', shelfLife: 'goodsPeriodExt', productDate: 'goodsManufactureExt', productDateContent: 'goodsManufacture', customText: 'definitionExt', specifications: 'goodsSpecificationExt' } // input框中默认的提示字段 moduleSettings = { name: '商品名称', barCode: '商品条码', specifications: '规格', retailPrice: '零售价', memberPrice: '会员价', unit: '单位', shelfLife: '保质期', productDate: '生产日期', customText: '自定义文字' } // 编辑内容为打印标题或内容的字段类型 showTitleList = [ 'name', 'specifications', 'retailPrice', 'shelfLife', 'productDate', 'memberPrice', 'unit' ] // 编辑内容为打印条码的字段类型 showBarCodeList = ['barCode'] // 编辑内容为自定义 textarea 的字段类型 showTextAreaList = ['customText'] // 限制文本框中的文字个数 handleTextareaChange(e) { const t = this if (e.target.value.length > 20) { t.setState({ customTextErrorTip: '文字长度不能超过20个' }) } else { t.setState({ customTextErrorTip: '' }) } } changeItem(content,e){ const { dispatch, moduleDetail = {}, type } = this.props switch (content.type) { case 'radio': this.setState({ isShowTitleEditInput: true }) const willChangeType = this.radioCheckMap[type] moduleDetail[willChangeType] = content.value switch (content.value) { case 1: this.setState({ showDefaultInput: true }) const willChangeText = this.textMap[type] moduleDetail[willChangeText] = this.moduleSettings[type] break case 2: this.setState({ showDefaultInput: false }) const willclearText = this.textMap[type] moduleDetail[willclearText] = 'del' break } break case 'title': const changeValue = e.target.value const willChangeText = this.textMap[type] if (changeValue === '') { moduleDetail[willChangeText] = 'del' } else { moduleDetail[willChangeText] = changeValue } break; case 'customText': const value = e.target.value if(value===''){ moduleDetail.definitionExt='del' }else{ moduleDetail.definitionExt = value } this.setState({ textAreaWordLength: e.target.value.length }) break case 'productDateContent': moduleDetail.goodsManufacture = moment(e).format('YYYY-MM-DD')==='Invalid date'?'2019-01-01':moment(e).format('YYYY-MM-DD') break case 'code': moduleDetail.goodsBarCodeType = content.value break } dispatch(action.setModuleDetail(moduleDetail)) } hiddenInput() { this.setState({ isShowTitleEditInput: false }) } render() { const { type, getFieldDecorator, showEditArea, radioCheck, moduleDetail = {}, changeCodeImg, } = this.props const radioValue = moduleDetail[radioCheck] const { showDefaultInput,textAreaWordLength } = this.state const showProductDate = (type ==='productDate') // 显示标题内容模块 const showTitle = this.showTitleList.indexOf(type) >= 0 // 显示自定义文本框模块 const showTextArea = this.showTextAreaList.indexOf(type) >= 0 // 显示条形码模块 const showBarCode = this.showBarCodeList.indexOf(type) >= 0 const {definitionExt=''} = moduleDetail const initTextAreaWordLength = definitionExt==='del'?0:definitionExt.length const titleContentAnswer = ( <div> <p> 打印出来的内容包含标题和内容两部分。如:“商品名称:绿箭口香糖” </p> </div> ) const contentAnswer = ( <div> <p>打印出来的内容仅包含内容。如:“绿箭口香糖”</p> </div> ) const showEditInputflag = radioValue === 1 ? true : false const defaultTip = moduleDetail.templateType===1?'请输入内容':'产地' return ( <div className={styles.moduleSettings}> {showEditArea && ( <div className={styles.moduleSettingsText}>模板属性</div> )} {showEditArea && ( <div className={styles.goodModuleEditArea}> <span className={styles.goodModuleEditTitle}> {this.moduleSettings[type]} </span> <div className={styles.line}></div> {showTitle && ( <div> <FormItem> {getFieldDecorator(`${type}Radio`, { initialValue: radioValue })( <RadioGroup name="radiogroup"> <div className={styles.titleContent}> <Radio name="titleCheck"onClick={this.changeItem.bind(this,{value:1,type:'radio'})} value={1} /> 打印标题和内容 <Popover placement="bottomLeft"content={titleContentAnswer}trigger="click"> <img src="https://assets.2dfire.com/frontend/63de89515818f99c5adb0023baea2861.png"onClick={this.showAnswer}/> </Popover> </div> <div className={styles.content}> <Radio name="titleCheck"onClick={this.changeItem.bind(this,{value:2,type:'radio'})} value={2}/> 只打印内容 <Popover placement="bottomLeft"content={contentAnswer}trigger="click"> <img src="https://assets.2dfire.com/frontend/63de89515818f99c5adb0023baea2861.png"onClick={this.showAnswer } /> </Popover> </div> </RadioGroup> )} </FormItem> { (showDefaultInput&&showEditInputflag || showEditInputflag) && <div className={styles.titleName}> <FormItem label="标题名称" {...formItemLayout}colon={false} > { getFieldDecorator(`temp${type}`, { initialValue: moduleDetail[this.textMap[type]]==='del'|| moduleDetail[this.textMap[type]]===''?'':moduleDetail[this.textMap[type]]||this.moduleSettings[type] })(<Input style={{ width: 200}} maxLength="20" onChange={this.changeItem.bind(this,{type:'title'})} />) } </FormItem> </div> } { showProductDate && <div className={styles.titleName}> <FormItem label="生产日期" {...formItemLayout} colon={false}> <LocaleProvider locale={locale}> <DatePicker showTime format="YYYY-MM-DD" onChange={this.changeItem.bind(this,{type:'productDateContent'})} style={{ width: 200}} defaultValue={moment(moduleDetail.goodsManufacture || new Date(), "YYYY-MM-DD")} /> </LocaleProvider> </FormItem> </div> } </div> )} { showBarCode && <div> <FormItem > {getFieldDecorator('barCode', { initialValue: radioValue })( <RadioGroup> <Radio name="barCode" className={styles.barCode} value={2} onClick={()=>{changeCodeImg(2);this.changeItem({value:2,type:'code'})} }/> 展示为条码 <br /> <Radio name="barCode" className={styles.barCode} value={3} onClick={()=>{changeCodeImg(3);this.changeItem({value:3,type:'code'})} }/> 展示为数字 <br /> <Radio name="barCode" className={styles.barCode} value={1} onClick={()=>{changeCodeImg(1);this.changeItem({value:1,type:'code'})} }/> 展示为条码+数字 </RadioGroup> )} </FormItem> </div> } { showTextArea && <div> <div className= {styles.textAreaContainer}> <FormItem {...formItemLayout} style={{width:500 }}> {getFieldDecorator(`temp${type}`, { initialValue: moduleDetail.definitionExt==='del'?'':moduleDetail.definitionExt })(<TextArea style={{ width: 400 }} maxLength="20" onChange={this.changeItem.bind(this,{type:'customText'})} rows="3" cols="40" placeholder={defaultTip}/>) } </FormItem> <p className={styles.wordNumber}>{textAreaWordLength || initTextAreaWordLength || 0}/20</p> </div> <br /> <span className={styles.customTextErrorTip}> {this.state.customTextErrorTip} </span> </div> } </div> )} </div> ) } } export default EditBoard <file_sep>/inside-boss/src/components/goodTag/main.js import React, { Component } from 'react' import {} from 'antd' import styles from './style.css' import * as action from '../../action' import { hashHistory } from 'react-router' import { Modal, message } from 'antd' import Cookie from '@2dfire/utils/cookie' const confirm = Modal.confirm const entityId = JSON.parse(Cookie.getItem('entrance')).shopInfo.entityId class Main extends Component { constructor(props) { super(props) this.state = { showCopyExcessConfirm: false, } } componentWillMount() { const { dispatch } = this.props // 获取所有模板 dispatch(action.getPriceTagModule({ param:{entityId: entityId }})) } copyModule(id) { const { dispatch,data} = this.props const moduleNum = data.priceTagModuleList.length if (moduleNum>=25) { this.warning() return } // 复制模板 dispatch(action.copyPriceTagModule({param: { id: id, entityId: entityId }})) this.success() } editModule(id) { // 编辑模板 hashHistory.push(`/PRICE_TAG_EDIT/?id=${id}&entityId=${entityId}`) } showDeleteConfirm(item) { // 删除模板 const t = this confirm({ title: '是否删除当前模板?', content: '', okText: '确认', okType: 'danger', cancelText: '取消', onOk() { t.deleteModule(item) }, onCancel() { console.log('Cancel') } }) } warning() { Modal.warning({ title: '', content: '自定义模板数量不能超过20个!' }) } success() { message.success('复制成功',1); }; // 删除调接口 deleteModule(item){ const { dispatch } = this.props const { id, entityId } = item // 删除模板 dispatch(action.updatePriceTagModule({param: { id: id, entityId: entityId, isVaild:0}})) setTimeout(() => { location.reload() }, 200) } // 模板的尺寸 moduleSize={ 1:'80mm*40mm', 2:'75mm*30mm', 3:'60mm*40mm', 4:'40mm*30mm', 5:'25mm*15mm' } // 模板图片的宽度 imageWidth={ 1:'324px', 2:'325px', 3:'243px', 4:'163px', 5:'148px' } getLocalTime(time) { const newTime = new Date(time), y = newTime.getFullYear(), m = newTime.getMonth() + 1, d = newTime.getDate() return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + newTime.toTimeString().substr(0, 8); } render() { const { data } = this.props const {priceTagModuleList=[]} = data return ( <div className={styles.goodTag}> {priceTagModuleList.map((item, key) => { return ( <div className={styles.card} key={key}> <div className={styles.cardHead}> <div className={styles.cardTitle}> {item.templateName} </div> {item.isDefault === 0 && ( <div className={styles.systemCardTag}> 系统 </div> )} {item.isDefault === 1 && ( <div className={styles.customCardTag}> 自定义 </div> )} </div> <div className={styles.cardSize}> <span>尺寸: {this.moduleSize[item.templateType]} </span> {item.isDefault === 1 && ( <span className={styles.dateTime}> { this.getLocalTime(item.createTime) } </span> )} </div> <div className={styles.cardImg}> <img src={item.templateImageUrl} style={{width:this.imageWidth[item.templateType]}}/> </div> {item.isDefault === 0 && ( <button className={styles.copyBtn} onClick={this.copyModule.bind(this,item.id)}> 复制 </button> )} {item.isDefault === 1 && ( <div className={styles.allCustomBtn}> <button className={styles.customBtn} onClick={this.editModule.bind(this,item.id)}> 编辑 </button> <button className={styles.customBtn} onClick={this.showDeleteConfirm.bind(this,item)} > 删除 </button> <button className={styles.customBtn} onClick={this.copyModule.bind(this,item.id)}> 复制 </button> </div> )} </div> ) })} </div> ) } } export default Main <file_sep>/inside-chain/src/store/modules/pass/actions.js import API_PUBLISH from '@/config/api_publish' import catchError from '@/base/catchError' import Router from "@/router"; import Obj from "@2dfire/utils/object" import Vue from 'vue'; import iView from "iview"; Vue.use(iView); let Message = iView.Message; // 获取 所有 付款方式列表 export const getPassModules = (context, params) => { let trueParams = { plateEntityId: params.plateEntityId, moduleType: 2 } API_PUBLISH.getPublishModules(trueParams).then(data => { // 获取 所有 付款方式列表 let res = data.data[0] || {}; // mock // res = { // name: 'mock品牌', // remarkRight: '2018-09-30 12:22' // } context.commit('_getPassModules', res) }).catch(e => { catchError(e) }) } <file_sep>/inside-boss/src/components/importLog/main.js /** * Created by air on 2017/7/31. */ import React, {Component} from 'react' // import cx from 'classnames' import styles from './style.css' import {Table, Pagination, Modal} from 'antd' import * as action from '../../action' import {setPageNumber} from "../../action/index"; const table_state = { pagination: false, rowKey:"id" } const pagination_state = { pageSize: 15, defaultCurrent: 1, } // const showFailResult = (logId) => { // console.log(this) // const {dispatch} = this.props; // dispatch(action.getImportLogDetail(logId, 1, 15)); // // Modal.info({ // title: '导入失败', // onOk: () => { // // }, // // content: // <div> // <p>商品导入失败,请按下方信息进行修改</p> // </div> // }) // } const ModalColumns = [ { title: 'sheet名称', dataIndex: 'sheetName', key: 'sheetName', width: '161px' }, { title: '错误行数', dataIndex: 'sortCode', key: 'sortCode', width: '161px', render: (text, record, index) => ( <span> { record.columnIndex ? <span>第{record.columnIndex}行</span> : <span>-</span> } </span> ) } , { title: '错误原因', dataIndex: 'logMessage', key: 'logMessage', width: '161px' }] class Main extends Component { constructor(props) { super(props) } state = { showModal: false, logId: '', listNo: 1, detailNo: 1 } handleCancel = () => { this.setState({ showModal: false }) } showFailResult = (logId) => { console.log(this) const {dispatch, data} = this.props; dispatch(action.getImportLogDetail(logId, 1, 15)); this.setState({ showModal: true, logId: logId, detailNo: 1 }) // const // // // Modal.info({ // title: '导入失败', // onOk: () => { // // }, // // content: // <div> // // </div> // // }) } // {/*<div>*/} // {/*<Table {...table_state} columns={this.columns} dataSource={bizLogDetailList} bordered/>*/} // {/*<Pagination className={styles.paginationBar} {...pagination_state} total={totalCount} onChange={this.changePage}/>*/} // {/*</div>*/} columns = [ { title: '序号', dataIndex: 'id', key: 'id' }, { title: '操作时间', dataIndex: 'logTime', key: 'logTime' }, { title: '事件', dataIndex: 'event', key: 'event', render: (text, record, index) => ( <span> {record.event} { record.status == 2 ? <a className={styles.showError} onClick={e => { this.showFailResult(record.id) }}>查看失败原因</a> : '' } </span> ) }, { title: '操作人', dataIndex: 'operateName', key: 'operateName' }]; changePage = (pageIndex, pageSize) => { const t = this; const {dispatch, data} = t.props; console.log(t, pageIndex, pageSize); dispatch(action.getImportLogByPage(data, pageIndex, pageSize)); this.setState({ listNo: pageIndex }) } changePageDetail = (pageIndex, pageSize) => { const t = this; const {dispatch} = t.props; console.log(pageIndex, pageSize); dispatch(action.getImportLogDetail(this.state.logId, pageIndex, pageSize)); this.setState({ detailNo: pageIndex }) } render() { const t = this const {dispatch, data} = t.props const {detail} = data; const {bizLogList, totalCount} = data; return ( <div className={styles.main_wrapper}> <div className={styles.top_line}> <div className={styles.selectedList}> <Table {...table_state} columns={this.columns} dataSource={bizLogList} bordered/> <Pagination className={styles.paginationBar} {...pagination_state} total={totalCount} onChange={this.changePage} current={this.state.listNo}/> </div> </div> {this.state.showModal ? <Modal title="导入失败" visible={this.state.showModal} onCancel={this.handleCancel} footer={null} width="660px" > <p className={styles.tipText}>商品导入失败,请按照下方提示信息进行修改</p> <Table {...table_state} size="small" columns={ModalColumns} dataSource={detail.bizLogDetailList} bordered/> < Pagination className={styles.paginationBar} {...pagination_state} total={detail.totalCount} current={this.state.detailNo} onChange={this.changePageDetail}/> </Modal> : '' } </div> ) } } export default Main <file_sep>/static-hercules/src/bindPhone/main.js import Toast from './components/toast'; import Vue from 'vue'; import router from './router'; import Router from 'vue-router'; import vueResource from 'vue-resource'; import App from './App.vue'; /** *二维码生成工具 */ import VueQriously from 'vue-qriously'; Vue.use(Toast); Vue.use(VueQriously); Vue.use(Router); Vue.use(vueResource); Vue.http.interceptors.push((request, next) => { request.credentials = false; request.emulateHTTP = true; request.noCookie = true; next(); }); router.beforeEach((to, from, next) => { document.title = to.meta.title; // 路由变换后,滚动至顶 window.scrollTo(0, 0); next(); }); if (window.tdfire == null) { window.tdfire = {}; } window.tdfire.back = function(_this) { let timer = setTimeout(function() { if (tdfire.pop) { tdfire.pop(); } }, 200); _this.$router.afterEach(route => { clearTimeout(timer); }); _this.$router.back(); }; window.createAndroidBridge = function() { if (window.bridge == null) { window.bridge = {}; // 创建 bridge 对象 } if (window.tdfire.observe === undefined) { window.tdfire.observe = function(callback) { window.bridge.invoke( window.tdfire.getObservePluginSignature(), '', callback ); }; } if (window.tdfire.umeng === undefined) { window.tdfire.umeng = { mobclick: function(event) { window.bridge.invoke( window.tdfire.getUmengPluginSignature(), 'mobclick', null, event ); } }; } window.bridge.callback = { index: 0, cache: {}, invoke: function(id, args) { let key = '' + id; let callbackFunc = window.bridge.callback.cache[key]; callbackFunc(args); } }; window.bridge.invoke = function(pluginName, funcName, callback, ...args) { let index = -1; // 存储 callback if (callback !== null && callback !== undefined) { window.bridge.callback.index += 1; index = window.bridge.callback.index; window.bridge.callback.cache['' + index] = callback; } // 发送消息到 native 去 window.bridge.postMessage( JSON.stringify({ identifier: pluginName, selector: funcName, callbackId: index, args: args }) ); }; }; if (navigator.userAgent.indexOf('tdfire-Android') > -1) { window.createAndroidBridge(); } new Vue({ el: '#app', router, template: '<App/>', components: { App } }); <file_sep>/inside-boss/src/components/cateTable/index.js import { Table } from 'antd' import React, { Component }from 'react' import styles from "../cateManage/cateList.css"; class CateTable extends Component { constructor(props) { super(props) this.state = { columns: [{ // 分类列表 表头数据定义 title: '分类名称', dataIndex: 'name', width: '30%', render: (text, row, index) => { return { children: <a href="javascript:;">{text} { row.chain && <i className={styles.chain_bg}>连锁</i> }</a> }; }, }, { title: '类型', dataIndex: 'type', width: '30%', render: (value, row, index) => { const obj = { children: value, props: {}, }; return obj }, }, { title: '操作', dataIndex: 'id', width: '40%', render: (item, row) => { return ( <div className={styles.cate_opt}> { row.tier !== 4 && !row.chain && <span className={styles.cate_add} onClick={() => props.editCate(row, 'addChild')}>新增子类</span>} { !row.chain && <span className={styles.cate_edit} onClick={() => props.editCate(row, 'edit')}>编辑</span>} <span className={styles.cate_del} onClick={() => props.deleteCate(row)}>删除</span> </div> ) }, }], } } render() { const { columns } = this.state const { dataSource } = this.props return ( <div> <Table columns={columns} dataSource={dataSource} /> </div> ) } } export default CateTable <file_sep>/inside-boss/src/container/mallActivityManager/index.js import React, { Component }from 'react' import { connect } from 'react-redux' import Main from '../../components/mall' import { initActivityList, editActivityItem } from '../../action' import Cookie from '@2dfire/utils/cookie' class container extends Component { render () { const baseInfo = this.props.baseInfo return ( <div> <Main module='activity' contentList={ this.props.activityList } initList={ this.props.initActivityList(baseInfo) } editItem={ this.props.editActivityItem(baseInfo) } /> </div> ) } } const mapStateToProps = (state) => { const { activityList = [] } = state.mallActivityManager || {} const entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) const baseInfo = { entityId: entrance.shopInfo.entityId, userId: entrance.userInfo.memberId, } return { baseInfo, activityList } } const mapDispatchToProps = { initActivityList, editActivityItem, } export default connect(mapStateToProps, mapDispatchToProps)(container) <file_sep>/inside-boss/src/container/visualConfig/views/design/utils/design-type.js import isString from 'lodash/isString'; export function isExpectedDesginType(component, expected) { const { type } = component; if( typeof type === 'string'){ return expected === type } } export function serializeDesignType(designType) { if (typeof designType === 'string') { return designType; } // if (isArray(designType)) { // return designType.join(' | '); // } throw new TypeError('designType should be a string or an array of strings'); } <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionCoupons/definition.js export default { name: 'unionCoupons', userName: '优惠券', group: '互动营销类', max: 1, config: { type: 'coupons' }, } <file_sep>/inside-boss/src/container/visualConfig/sences/retail/home.js import { currentWeixinMealUrl } from '@src/utils/env' import { getEntityId } from '@src/container/visualConfig/utils' import commonComponents from './commonComponents' const page = { name: '店铺首页', configName: 'page:home', link: () => `${currentWeixinMealUrl}/page_split/v1/retail_home/${getEntityId()}`, components: [ 'backgroundImage', ...commonComponents, ], defaults: null, } const defaults = { components: [ { type: 'banner', mode: '2', backgroundImage: null, }, { type: 'whitespace', height: 25, }, { type: 'goodsList', mode: '大图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '新品', image: null, }, }, { type: 'goodsList', mode: '详细列表', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'goodsList', mode: '双列小图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'whitespace', height: 35, }, { type: 'title', text: '更多商品', size: 'medium', textAlign: 'center', textColor: '#000000', backgroundColor: '#fff', linkType: 'page', linkGoodsId: '', linkPage: '商品分类', }, { type: 'whitespace', height: 25, }, ], } export default { ...page, defaults, } <file_sep>/inside-boss/src/container/visualConfig/store/actions/design.js import store from '@src/store' import visualApi from '@src/api/visualConfigApi' import { isString, first, isObjectAndEmpty } from '@src/container/visualConfig/utils' import types from '../actionTypes' import { getPages } from '../selectors' import { makeConfigData } from '../formatters/design' import { getShopInfo } from './common' import validate from '../tmpValidators' /* 解析 appConfig JSON string - 成功,返回对象内容 - 内容为空,返回 null - 解析失败,返回 false */ function parseConfigContent(contentString) { if (!contentString) return null try { const content = JSON.parse(contentString) // 为 null / undefined、不是对象、对象为空,都视为内容为空 if (!content || typeof content !== 'object' || !Object.keys(content).length) return null return content } catch (e) { console.log(e) return false } } /* 把当前 configData 转换成 content string - 成功:{ result: true, name: configName, content: contentString } - 失败:{ result: false, message: failedMessage } */ function stringifyConfig() { const { configName, componentConfigs } = store.getState().visualConfig.design if (!configName || !componentConfigs) return { result: false, message: '没有配置内容' } const configData = makeConfigData(componentConfigs) let content try { content = JSON.stringify(configData) } catch (e) { console.log(e) return { result: false, message: '配置格式化失败' } } return { result: true, name: configName, content } } /* 初始化装修。 在“装修页”之外触发此 action 时,需在数据加载完成后手动路由跳转至 design 页面。 configContent: appConfig JSON 字符串 场景 => 提供的参数 ------------------------------------------------------- 装修模板 / 装修备份内容 => configName、 configContent 装修指定页面 => configName 装修默认页面 => 装修数据加载失败,重新加载 => 切换页面 => configName */ export async function initDesign(configName = null, configContent = null) { store.dispatch({ type: types.DESIGN_RESET }) const state = store.getState() const currentConfigName = state.visualConfig.design.configName const pages = getPages(state) if (!configName) { configContent = null // 未指定 configName 时不允许指定 configContent configName = currentConfigName || pages[0].configName } const page = first(pages, p => p.configName === configName) if (!page) store.dispatch({ type: types.DESIGN_CONFIG_LOAD_FAILED, message: '此页面不支持装修' }) store.dispatch({ type: types.DESIGN_CONFIG_LOADING, name: configName }) // 拉取 config content if (!configContent) { const { appId, appVersionId } = getShopInfo() try { const res = await visualApi.getConfigContent({ appId, appVersionId, name: configName }) // data 为空对象代表此页面从来没进行过装修,此时应用默认 config if (res && res.data && (isString(res.data.content) || isObjectAndEmpty(res.data))) { configContent = res.data.content } else { // 响应数据不合法 return store.dispatch({ type: types.DESIGN_CONFIG_LOAD_FAILED, message: '配置加载失败' }) } } catch (e) { // 请求失败 return store.dispatch({ type: types.DESIGN_CONFIG_LOAD_FAILED, message: '配置加载失败' }) } } let configData if (configContent) { // 解析 content string configData = parseConfigContent(configContent) if (configData === false) { return store.dispatch({ type: types.DESIGN_CONFIG_LOAD_FAILED, message: '配置内容不合法' }) } else if (configData === null) { // configData 为空则填充默认值 configData = page.defaults } } else { configData = page.defaults } return store.dispatch({ type: types.DESIGN_CONFIG_LOADED, name: configName, data: configData, }) } // 保存预览数据 // 返回值:Promise => { result: true|false, message: failedMessage } export async function designPreview() { designLeavePreview() const stringifyRet = stringifyConfig() if (!stringifyRet.result) return stringifyRet const { name, content } = stringifyRet const { appId, appVersionId } = getShopInfo() // TODO: 把验证放到 editor 里 const errorMsg = validate(JSON.parse(content)) if (errorMsg) { return { result: false, message: errorMsg } } try { const res = await visualApi.preview({ appId, appVersionId, name, content }) if (!res.data) return { result: false, message: '预览二维码获取失败' } store.dispatch({ type: types.DESIGN_PREVIEW, url: res.data }) return { result: true } } catch (e) { return { result: false, message: '预览内容保存失败' } } } export function designLeavePreview() { store.dispatch({ type: types.DESIGN_LEAVE_PREVIEW }) } // 保存备份 // 返回值:Promise => { result: true|false, message: failedMessage, forceable: true|false } // 传入 force=false 时若备份失败,返回值会带上 forceable 字段,若此字段为 true,说明是因为达到上限而失败,此时可让用户选择是否加上 force=true 并重试一次。 export async function designBackup(force = false) { const stringifyRet = stringifyConfig() if (!stringifyRet.result) return stringifyRet const { name, content } = stringifyRet const { appId, appVersionId } = getShopInfo() try { const res = await visualApi.backup({ appId, appVersionId, name, content, force: force ? 1 : 0, }) return res.data ? { result: true } : { result: false, message: '备份失败' } } catch (e) { const forceable = e.message && e.message.indexOf('上限') >= 0 return { result: false, message: e.message, forceable } } } // 发布配置 // 返回值:Promise => { result: true|false, message: failedMessage } export async function designPublish() { const stringifyRet = stringifyConfig() if (!stringifyRet.result) return stringifyRet const { name, content } = stringifyRet const { appId, appVersionId } = getShopInfo() // TODO: 把验证放到 editor 里 const errorMsg = validate(JSON.parse(content)) if (errorMsg) { return { result: false, message: errorMsg } } try { const res = await visualApi.publish({ appId, appVersionId, name, content }) if (!res.data) return { result: false, message: '上架失败' } store.dispatch({ type: types.DESIGN_SAVED }) return { result: true } } catch (e) { return { result: false, message: '上架失败' } } } export async function designReset() { store.dispatch({ type: types.DESIGN_RESET }) } export function designAddComponent(name, index) { store.dispatch({ type: types.COMPONENT_ADD, name, index }) } export function designRemoveComponent(id) { store.dispatch({ type: types.COMPONENT_REMOVE, id }) } export function designMoveComponent(id, toIndex) { store.dispatch({ type: types.COMPONENT_MOVE, id, toIndex }) } export function designUpdateComponentConfig(id, config) { store.dispatch({ type: types.COMPONENT_UPDATED, id, config }) } export function designEditComponent(id) { store.dispatch({ type: types.COMPONENT_EDITING, id }) } export function designLeaveComponent() { store.dispatch({ type: types.COMPONENT_LEAVE }) } <file_sep>/inside-boss/src/container/visualConfig/store/actions/common.js import store from '@src/store' import cookie from '@2dfire/utils/cookie' export function getShopInfo() { let appId = '' let appVersionId = '' const data = JSON.parse(cookie.getItem('entrance')).shopInfo const {entityTypeId, isInLeague} = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (entityTypeId == '10' || (entityTypeId == '3' && !!isInLeague)){ // 联盟或者是联盟下的店铺 appId= '455421937959619809' appVersionId='455421937959619810' }else{ const getShopInfo = store.getState().visualConfig.shopInfo appId = getShopInfo.appId appVersionId = getShopInfo.appVersionId } return { appId, appVersionId } } <file_sep>/inside-boss/src/components/importHistory/goodsList.js import React, {Component} from 'react' import {Table, Pagination, Button, Modal} from 'antd' import styles from './style.css' import * as bridge from '../../utils/bridge' import * as action from '../../action' class GoodsList extends Component { constructor(props) { super(props) this.state = { current: 1, columns: [ { title: '导入内容', dataIndex: 'name', key: 'name', }, { title: '导入时间', dataIndex: 'date', key: 'date', }, { title: '成功/失败件数', dataIndex: 'hint', key: 'hint', }, { title: '失败信息', dataIndex: 'messageUrl', key: 'messageUrl', render: (text, record) => { return <a href={record.messageUrl}>{record.messageUrl}</a>; }, } ] } } paginationChange(pageNum) { const t = this const {dispatch, data} = t.props this.setState({ current: pageNum, }); dispatch(action.getImportHistoryList({pageNum:pageNum})) } render() { const t = this const {data} = t.props const total = data.totalRecord const records = data.records const pageNum = data.pageNum const columns = this.state.columns return (<div className={styles.wrap}> <Table dataSource={records} columns={columns} pagination={false} rowKey={records => records.id} className={styles.specificationTable} /> <div className={styles.paginationBox}> <Pagination className={styles.paginationHtml} showQuickJumper current={pageNum} total={total} defaultPageSize={10} pageSize={10} onChange={this.paginationChange.bind(this)}/> <p>共{total}条记录</p> </div> </div> ) } } export default GoodsList <file_sep>/static-hercules/src/ocean-zl/main.js import Vue from 'vue' import Router from 'vue-router' import App from './App' import toast from './components/toast/index.js' import ShopPhoto from 'src/ocean-zl/components/ShopPhoto.vue' import ShopInput from 'src/ocean-zl/components/ShopInput' import ShopSelect from 'src/ocean-zl/components/ShopSelect' import { router } from './router' import store from './store' import { Picker } from 'mint-ui' import './scss/index.scss' Vue.use(toast) Vue.component(Picker.name, Picker) Vue.component('shop-photo', ShopPhoto) Vue.component('shop-input', ShopInput) Vue.component('shop-select', ShopSelect) Vue.use(Router) new Vue({ el: '#app', router, store, template: '<App/>', components: { App } }) <file_sep>/static-hercules/src/secured-account/store/state.js export default { // 是否是修改省市区字段 isEditAddress: false, merchantInfo:{ //开户名称 accountName: "", //开户银行 accountBank: "", accountBankCode: "", //银行卡号 accountNumber: "", //开户省市 accountAddressProvince: "", accountAddressProCode: "", accountAddressCity: "", accountAddressCityCode: "", //开户支行 accountSubBank: "", accountSubBankCode:"", //手机号码 userTelNumber: "", //身份证号 idCard: "", //验证码 authCode:'', //营业执照 businessLicensePic:'' }, //底部选择弹出 picker: { showPicker: false, pickerName: '', //当前选择的字段 pickerSlots: [{ defaultIndex: 0 }, //默认选中第一个 ], pickerTitle: '', other: '', //其他需要设置的值,省份需要设置id的值 }, //底部日期选择弹出 dateNewPicker: { showPicker: false, pickerName: '', //当前选择的字段 pickerTitle: '', //当前标题 pickerValue: '', //当前选中日期值 }, //底部地址选择器 addressPicker: { showPicker: false, pickerName: '', pickerTitle: { province: {}, city: {} }, topTitle: '选择地址' }, /** * 显示状态 * detail: 查看详情,不可修改; * edit: 编辑修改,已提交之后,申请通过,并为可修改状态; * first: 第一次提交 * */ viewState: 'first', //图片展示 examplePhoto:{ img:'', isShow:false }, }<file_sep>/static-hercules/src/ocean/config/api.js // import {GATEWAY_BASE_URL, ENV} from 'apiConfig' // import Requester from 'src/base/requester' import Requester from 'src/base/interception' import {configUrl} from './configUrl' import catchError from '../libs/catchError' import 'url-search-params-polyfill' const headers = { token: sessionStorage.getItem('token'), lang: 'zh_CN' } const isToken = false const isGw = true /** * 查询开通状态 * @returns applyType: 申请类型 openStatus: 申请状态 * @constructor */ export const applyState = () => { // return Requester.get(configUrl.APPLY_STATE, {params: {}}, false) return Requester.get(configUrl.APPLY_STATE, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } /** * 营业模式 * @constructor */ export const shopKind = () => { // return Requester.post(configUrl.SHOP_KIND, {params: {}}, false) return Requester.post(configUrl.SHOP_KIND, null, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } /** * 申请资料查询 * @returns */ export const getShopInfo = () => { // return Requester.post(configUrl.GET_SHOP_INFO, {params: {}}, false) return Requester.post(configUrl.GET_SHOP_INFO, null, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } /** * 获取中国行政区 * @param sub_area_type 行政区域划分(province, city, town, street) * @param id 上级行政区域id */ export const getRegion = (sub_area_type, id) => { // return Requester.get(configUrl.GET_REGION, { // params: { // sub_area_type, // id, // need_sub_area: true // } // }, false) return Requester.get(configUrl.GET_REGION, { isGw, isToken, headers, handleError: catchError, params: { sub_area_type, id, need_sub_area: true } }).then(data => ({ data })) } /** * 获取银行 */ export const getBank = () => { // return Requester.get(configUrl.GET_BANK, {params: {}}, false) return Requester.get(configUrl.GET_BANK, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } /** * 获取开户省份 */ export const getBankProvince = (bankName) => { // return Requester.get(configUrl.GET_BANK_PROVINCE, // { // params: { // bankName // } // }, false) return Requester.get(configUrl.GET_BANK_PROVINCE, { isGw, isToken, headers, handleError: catchError, params: { bankName } }).then(data => ({ data })) } /** * 获取开户城市 */ export const getBankCity = (bankName, provinceNo) => { // return Requester.get(configUrl.GET_BANK_CITY, { // params: { // bankName, // provinceNo // } // }, false) return Requester.get(configUrl.GET_BANK_CITY, { isGw, isToken, headers, handleError: catchError, params: { bankName, provinceNo } }).then(data => ({ data })) } /** * 获取银行支行 * @param bankName 银行支行code * @param cityNo 城市id */ export const getBankSub = (bankName, cityNo) => { // return Requester.get(configUrl.GET_BANK_SUB, { // params: { // bankName, cityNo // } // }, false) return Requester.get(configUrl.GET_BANK_SUB, { isGw, isToken, headers, handleError: catchError, params: { bankName, cityNo } }).then(data => ({ data })) } /** * 发送验证码 * @param mobile 手机号码 */ export const sendCode = (mobile) => { // return Requester.get(configUrl.SEND_CODE, {params: {mobile}}, false) return Requester.get(configUrl.SEND_CODE, { isGw, isToken, headers, handleError: catchError, params: { mobile } }).then(data => ({ data })) } /** * 临时保存申请资料 * @param bluePlanInfoVo 审核信息 * @param id */ export const getSaveShopInfo = (bluePlanInfoVo, id = '') => { // return Requester.post(configUrl.GET_SAVE_SHOP_INFO, {bluePlanInfoVo, id}, {emulateJSON: true}, false) let formdata = new URLSearchParams() formdata.append('bluePlanInfoVo', bluePlanInfoVo) formdata.append('id', id) return Requester.post(configUrl.GET_SAVE_SHOP_INFO, formdata, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } /** * 临时保存申请资料 * @param bluePlanInfoVo 审核信息 */ export const getSubmitShopInfo = (bluePlanInfoVo) => { // return Requester.post(configUrl.GET_SUBMIT_SHOP_INFO, {bluePlanInfoVo}, {emulateJSON: true}, false) let formdata = new URLSearchParams() formdata.append('bluePlanInfoVo', bluePlanInfoVo) return Requester.post(configUrl.GET_SUBMIT_SHOP_INFO, formdata, { isGw, isToken, headers, handleError: catchError }).then(data => ({ data })) } <file_sep>/inside-boss/src/container/visualConfig/components/checkShopStatus/status.js import React from 'react' import PropTypes from 'prop-types' import { Layout } from '../pageParts' import s from './status.css' export function Loading() { return <Layout> <div className={s.loading}>载入中...</div> </Layout> } export function LoadFailed(props) { return <Layout> <div className={s.loadFailed}>店铺信息加载失败,<a onClick={props.retry}>点此重试</a></div> </Layout> } LoadFailed.propTypes = { retry: PropTypes.func.isRequired, } export function CanNotConfig() { return <Layout> <div className={s.canNotConfig}> <img src="https://assets.2dfire.com/frontend/d1c6655544ff586486ae23fb3f60790f.png" /> <div className={s.text}>当前未开通该功能,需在掌柜APP-高级服务商城-微店铺装修PC版开通后可正常使用</div> </div> </Layout> } <file_sep>/static-hercules/src/secured-account/router.js import Vue from 'vue' import Router from 'vue-router' import WithdrawDeposit from './views/withdraw-deposit' import PayAccount from './views/pay-account/index' import PubAccount from './views/bind-backcard/public/index' import PerAccount from './views/bind-backcard/person/index' import bankSub from './views/bank/BankSub' Vue.use(Router) export default new Router({ routes: [ { path: '*', redirect: '/pay-account' }, { path: '/withdraw-deposit', name: 'withdrawDeposit', component: WithdrawDeposit, meta: { title: '提现' } }, { path: '/pay-account', name: 'payAccount', component: PayAccount, meta: { title: '担保交易收款账户' } }, { path: '/public-account', name: 'pubAccount', component: PubAccount, meta: { title: '绑定对公账户' } }, { path: '/person-account', name: 'perAccount', component: PerAccount, meta: { title: '绑定对私账户' } }, { path: '/bank-sub', name: 'bankSub', component: bankSub, meta: { title: '选择支行' } } ] }) <file_sep>/inside-boss/src/container/visualConfig/views/new_design/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import * as actions from '@src/container/visualConfig/store/actions' import { pick } from '@src/container/visualConfig/utils' import checkShopStatus from '@src/container/visualConfig/components/checkShopStatus' import { Layout, Content } from '@src/container/visualConfig/components/pageParts' import DesignHeader from './header/DesignHeader' import ComList from './list/ComList' import Editing from './editing/Editing' import s from './index.css' @checkShopStatus @connect(state => pick(state.visualConfig.design, 'configName', 'componentConfigs', 'loadingFailedMessage')) class Design extends Component { componentWillMount() { // 若尚未执行过初始化,执行它(从页面管理、备份、模板等页面进入装修时,对应页面会先执行好初始化) if (!this.props.configName) { actions.initDesign() } } render() { const { componentConfigs, loadingFailedMessage } = this.props let content if (componentConfigs === null) content = this.statusLoading() else if (componentConfigs === false) content = this.statusLoadFailed(loadingFailedMessage) else content = this.designContent() return <Layout> <DesignHeader /> <Content className={s.content}> {content} </Content> </Layout> } statusLoading() { return <div className={s.loading}>载入中...</div> } statusLoadFailed(message) { return <div className={s.loadFailed}> {message},<a onClick={actions.loadDesignConfig}>点此重试</a> </div> } designContent() { return <div className={s.designWrapper}> <ComList /> <Editing /> </div> } } export default Design <file_sep>/static-hercules/src/reportCenter/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, getTicket(params) { return axios({ method: 'POST', url: 'com.dfire.boss.center.soa.ticket.ITicketService.grantTicket', params: { appKey: APP_KEY, ...params } }) }, getReport(params) { return axios({ method: 'POST', url: 'com.dfire.soa.datacenter.maya.service.IReportService.reportGroupForDingTalkMiniProgram', params: { appKey: APP_KEY, ...params } }) } } export default API;<file_sep>/inside-chain/src/views/shop/store-manage/pass/schemeCheck/data.js export default { total: 100, data: [ { id: '1', title: '热菜打印', ip: '10.12.22.38', goods: '未设置', status: '111' }, { id: '2', title: '热菜打印', ip: '10.45.67.56', goods: '3', status: '111' } ] } <file_sep>/inside-boss/src/container/visualConfig/sences/retail/mine.js const page = { name: '我的页面', configName: 'page:mine', components: [ 'mine', ], } export default page <file_sep>/inside-chain/.eslintrc.js //http://eslint.org/docs/user-guide/configuring module.exports = { // 表示根规则 "root": true, "extends": [ // 使用规则 "@2dfire/eslint-config-2dfire/easy", "@2dfire/eslint-config-2dfire/rules/vue-only-env", ], "settings": { "import/resolver": { "webpack": { // import规则来自webpack "config": "./build/webpack.base.conf.js" } } }, } <file_sep>/inside-boss/src/components/orderPhotos/orderList.js /** * Created by air on 2017/7/11. */ import React, { Component } from 'react' import { Pagination ,Modal ,Spin} from 'antd' import styles from './style.css' import * as action from '../../action' class VideoList extends Component { constructor (props) { super(props) this.state = { visible:false, img:'', pageNumber:1 } } paginationChange(pageNumber){ const t =this const { dispatch ,data} = t.props const { orderType,startValue,endValue} = data this.setState({ pageNumber: pageNumber, }); console.log(data) let val1 = startValue let val2 = endValue if(!val1){ val1 = '' } if(!val2){ val2 = '' } dispatch(action.getOrderList(orderType ,pageNumber,val1,val2)) } showModal = (url) => { this.setState({ visible: true, img: url, }); } hideModal = () => { this.setState({ visible: false, }); } getDate = (data) => { let time = new Date(data); let y = time.getFullYear(); let m = time.getMonth()+1; let d = time.getDate(); let h = time.getHours(); let mm = time.getMinutes(); let s = time.getSeconds(); return y+'-'+this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm)+':'+this.add0(s); } add0 = (m) => { return m<10?'0'+m:m; } render () { const t = this const { data } = t.props const { orderList ,total, showSpin} = data const { visible ,img ,pageNumber} = this.state; let orderName if(orderList[0].billType === 1){ orderName = 'Receipt slip' }else if(orderList[0].billType === 2){ orderName = 'Void slip' }else if(orderList[0].billType === 3){ orderName = 'Financial Report By Terminal Slip' }else if(orderList[0].billType === 4){ orderName = 'Sales Statistics By Terminal Slip' } return ( <Spin spinning={showSpin && showSpin.bool} tip={showSpin.content}> <div className={styles.orderListBox}> <div style={{overflow:'auto'}}> <ul className={styles.orderListUl}> <li className={styles.orderTitle}> <p>No.</p> <p>POS ID</p> <p>{orderName}</p> <p>Time</p> <p>URL</p> </li> {orderList ? orderList.map((order,index) =>{ return( <li className={styles.orderLi} key={index}> <p>{index+1}</p> <p>{order.posId}</p> <p> <img src={order.imageUrl} onClick={this.showModal.bind(this, order.imageUrl)} style={{width:'200px',marginTop:'20px'}}/> </p> <p>{this.getDate(order.orderTime)}</p> <p><a href={order.url} target="_blank">{order.url}</a></p> </li> ) }) :'' } </ul> </div> <div className={styles.paginationBox}> <Pagination className={styles.paginationHtml} showQuickJumper current={pageNumber} total={total} defaultPageSize={10} pageSize={10} onChange={this.paginationChange.bind(this)} /> <p>共{total}条记录</p> </div> <Modal visible={visible} onCancel={this.hideModal} footer={null} > <img ref="img" src={img} style={{width:'100%'}} controls="controls"/> </Modal> </div> </Spin> ) } } export default VideoList <file_sep>/inside-boss/src/container/visualConfig/views/new_design/editing/EditPlaceholderWrapper.js import React, { Component } from 'react' import PropTypes from 'prop-types' import c from 'classnames' import * as actions from '@src/container/visualConfig/store/actions' import s from './EditPlaceholderWrapper.css' class EditPlaceholderWrapper extends Component { static contextTypes = { designId: PropTypes.string.isRequired, designDefinition: PropTypes.object.isRequired, } static propTypes = { className: PropTypes.any, // 附加自定义的 className } edit = () => { actions.designEditComponent(this.context.designId) } render() { const { className } = this.props return <div className={c(s.wrapper, className)} onClick={this.edit}> <div className={s.inner}> {this.props.children} </div> </div> } } export default EditPlaceholderWrapper <file_sep>/inside-chain/src/router/index.js import Vue from 'vue'; import Router from 'vue-router'; import shopManage from '../views/shop/index.vue'; import shopManageView from '../views/shop/shop-manage/manage_view.vue'; import shopManageInfo from '../views/shop/shop-manage/manage_info.vue'; import shopManageGoodsLibraryGoodsManage from '../views/shop/store-manage/goods-library/goods-manage'; import singleShopGoodsAdd from '../views/shop/store-manage/goods-library/goods-manage/add-goods' import singleShopGoodsEdit from '../views/shop/store-manage/goods-library/goods-manage/edit-goods' import shopManageGoodsLibrarySuitManage from '../views/shop/store-manage/goods-library/suit-manage' import singleShopSuitAddFirstStep from '../views/shop/store-manage/goods-library/suit-manage/add-suit/set-first-step' import singleShopSuitAddSecondStep from '../views/shop/store-manage/goods-library/suit-manage/add-suit/set-second-step' import singleShopSuitEditFirstStep from '../views/shop/store-manage/goods-library/suit-manage/edit-suit/set-first-step' import singleShopSuitEditSecondStep from '../views/shop/store-manage/goods-library/suit-manage/edit-suit/set-second-step' import singleShopGoodsAttr from '../views/shop/store-manage/goods-attr/goods_attr' import singleShopGoodsClass from '../views/shop/store-manage/goods-class/goods_class' import shopBrand from '../views/shop/brand-manage/index.vue'; import shopBrandInfo from '../views/shop/brand-manage/brand_info.vue'; import shopOrgan from '../views/shop/organ-manage/index.vue'; import memberIndex from '../views/member/index.vue'; import goodsClass from '../views/setting/goods-class/index.vue'; import goodsAttr from '../views/setting/goods-attr/index.vue'; import goodsManage from '../views/setting/goods-manage/index.vue'; import goodsAdd from '../views/setting/goods-manage/add-goods/index.vue'; import goodsEdit from '../views/setting/goods-manage/edit-goods/index.vue' import addSetBaseInfo from '../views/setting/suit-manage/add-suit/set-firsts-tep/index.vue'; import addSetComboGoods from '../views/setting/suit-manage/add-suit/set-second-step/index.vue'; import editSetBaseInfo from '../views/setting/suit-manage/edit-suit/set-firsts-tep/index.vue'; import editSetComboGoods from '../views/setting/suit-manage/edit-suit/set-second-step/index.vue'; import menuManage from '../views/setting/menu/index.vue'; import menuDist from '../views/setting/menu/menu_dist/index.vue'; import menuGoods from '../views/setting/menu/menu_goods/index.vue'; import menuImport from '../views/setting/menu/menu_import/index.vue'; import suitManage from '../views/setting/suit-manage/index.vue'; import distManage from '../views/distCenter/index'; import distHistory from '../views/distCenter/history/index'; import distRetry from '../views/distCenter/history/retry/index'; import payKindManage from '../views/setting/pay-kind/index'; import payKindAdd from '../views/setting/pay-kind/add-pay-kind/index'; import payKindEdit from '../views/setting/pay-kind/edit-pay-kind/index'; import payKindPublish from '../views/setting/pay-kind/publish-pay-kind/index'; import shopPayKindManage from '../views/shop/cash-manage/pay-kind/index'; import shopPayKindAdd from '../views/shop/cash-manage/pay-kind/add-pay-kind/index'; import shopPayKindEdit from '../views/shop/cash-manage/pay-kind/edit-pay-kind/index'; // 传菜 import passManage from '../views/pass/index'; import passPublish from '../views/pass/publish/index'; import passRouter from './pass' import storePassRouter from './store<PASSWORD>' import shopTableManage from './shopTableManage' import manageGroup from './manageGroup' Vue.use(Router); export default new Router({ routes: [ { path: '*', redirect: '/shop_manage' }, { path: "/shop_manage", name: "shopManage", title: "门店管理", component: shopManage }, { path: "/shop_manage_view", name: "shopManageView", title: "经营概况", component: shopManageView }, { path: "/shop_manage_info", name: "shopManageInfo", title: "店铺资料", component: shopManageInfo },{ path: "/shop_manage_library_goods_manage", name: "shopManageLibraryGoodsManage", title: "商品库-商品管理", component: shopManageGoodsLibraryGoodsManage, },{ path: "/shop_manage_library_suit_manage", name: "shopManageLibrarySuitManage", title: "商品库-套餐管理", component: shopManageGoodsLibrarySuitManage, }, { path: "/single_shop_goods_add", name: "singleShopGoodsAdd", title: "", component: singleShopGoodsAdd }, { path: "/single_shop_goods_edit", name: "singleShopGoodsEdit", title: "", component: singleShopGoodsEdit },{ path: "/single_shop_suit_add_first_step", name: "singleShopSuitAddFirstStep", title: "", component: singleShopSuitAddFirstStep },{ path: "/single_suit_add_second_step", name: "singleShopSuitAddSecondStep", title: "", component: singleShopSuitAddSecondStep },{ path: "/single_suit_edit_first_step", name: "singleShopSuitEditFirstStep", title: "", component: singleShopSuitEditFirstStep },{ path: "/single_suit_edit_second_step", name: "singleShopSuitEditSecondStep", title: "", component: singleShopSuitEditSecondStep },{ path: "/single_shop_goods_attr", name: "singleShopGoodsAttr", title: "商品库-商品属性", component: singleShopGoodsAttr },{ path: "/single_shop_goods_class", name: "singleShopGoodsClass", title: "商品库-商品分类", component: singleShopGoodsClass },{ path: "/shop_brand", name: "shopBrand", title: "品牌管理", component: shopBrand }, { path: "/shop_brand_info", name: "shopBrandInfo", title: "品牌详情", component: shopBrandInfo }, { path: "/shop_organ", name: "shopOrgan", title: "分支机构", component: shopOrgan }, { path: "/member_index", name: "memberIndex", title: "员工管理", component: memberIndex }, { path: "/goods_manage", name: "goodsManage", title: "商品管理", component: goodsManage }, { path: "/goods_class", name: "goodsClass", title: "分类管理", component: goodsClass }, { path: "/goods_attr", name: "goodsAttr", title: "商品属性", component: goodsAttr },{ path: "/goods_add", name: "goodsAdd", title: "添加商品", component: goodsAdd },{ path: "/goods_edit", name: "goodsEdit", title: "编辑商品", component: goodsEdit },{ path: "/combo_manage", name: "suitManage", title: "套餐属性", component: suitManage }, { //新增套餐基本信息开发用 path: "/add_set_base_info", name: "addSetBaseInfo", title: "套餐基本信息开发用", component: addSetBaseInfo }, { //新增设置套餐商品开发用 path: "/add_set_combo_goods", name: "addSetComboGoods", title: "设置套餐商品开发用", component: addSetComboGoods }, { //编辑套餐基本信息开发用 path: "/edit_set_base_info", name: "editSetBaseInfo", title: "套餐基本信息开发用", component: editSetBaseInfo }, { //编辑设置套餐商品开发用 path: "/edit_set_combo_goods", name: "editSetComboGoods", title: "设置套餐商品开发用", component: editSetComboGoods }, { path: "/menu_manage", name: "menuManage", title: "菜单管理", component: menuManage }, { path: "/menu_dist", name: "menuDist", title: "菜单下发", component: menuDist }, { path: "/menu_goods", name: "menuGoods", title: "菜单商品", component: menuGoods }, { path: "/menu_import", name: "menuImport", title: "菜单商品导入", component: menuImport }, { path: "/dist_manage", name: "distManage", title: "下发中心", component: distManage }, { path: "/dist_manage_history", name: "distHistory", title: "下发记录", component: distHistory }, { path: "/dist_manage_retry", name: "distRetry", title: "重新下发", component: distRetry }, { path: "/pay_kind_manage", name: "payKindManage", title: "付款方式", component: payKindManage }, { path: "/pay_kind_edit", name: "payKindEdit", title: "编辑付款方式", component: payKindEdit }, { path: "/pay_kind_add", name: "payKindAdd", title: "添加付款方式", component: payKindAdd }, { path: "/pay_kind_publish", name: "payKindPublish", title: "付款方式下发", component: payKindPublish }, { path: "/shop_pay_kind_manage", name: "shopPayKindManage", title: "付款方式", component: shopPayKindManage }, { path: "/shop_pay_kind_edit", name: "shopPayKindEdit", title: "编辑付款方式", component: shopPayKindEdit }, { path: "/shop_pay_kind_add", name: "shopPayKindAdd", title: "添加付款方式", component: shopPayKindAdd }, { path: "/pass_manage", name: "passManage", title: "传菜管理", component: passManage }, { path: "/pass_publish", name: "passPublish", title: "传菜下发", component: passPublish }, ...passRouter, ...storePassRouter, ...shopTableManage, ...manageGroup ] }); <file_sep>/inside-chain/src/store/formats/goods.js /** * * @param res * @author * */ const goodsFormat = { /********************************************商品分类********************************************************/ //商品分类单条记录 进行格式化 formatGoodClassSingleList: function (titles, item, deep) { // console.log('formatGoodClassSingleList before:',item,titles) let title_ = titles; let curItem = { entityId: item.entityId, id: item.id,// item: {},//表项内容 list: item.subList, isOpen: false, isAddSub: item.addSub, isInclude: item.isInclude, deep: deep, } title_.map((title, index) => { if (title.type != 'operate') { if (title.id == 1) { curItem.item[title.id] = item.name } if (title.id == 2) { curItem.item[title.id] = (item.isInclude == 0) ? '商品分类' : '套餐分类' } } else { if (curItem.item[title.id] == undefined) { curItem.item[title.id] = {} } for (let key in title.operates) { //新增子类 if (key == 0) { if (!!item.addSub) { curItem.item[title.id][title.operates[key].id] = { disabled: false } } else { curItem.item[title.id][title.operates[key].id] = { disabled: true } } if (deep >= 3) { console.log(item.name, 'deep', deep, title.operates[key]); curItem.item[title.id][title.operates[key].id] = { disabled: true, disableType: 'transparent', } console.log(curItem.item[title.id][title.operates[key].id]) } } else if (key == 1) {//编辑 // if(curItem.list && curItem.list.length>0){ // curItem.item[title.id][title.operates[key].id] = { // disabled: true // } // } } else {//删除 // if (curItem.list && curItem.list.length > 0) { // curItem.item[title.id][title.operates[key].id] = { // disabled: true, // } // } // if (!item.addSub) { // curItem.item[title.id][title.operates[key].id] = { // disabled: true, // } // } } } } }) // console.log('formatGoodClassSingleList after:',item) return curItem; }, //格式化商品分类 主要用于界面的列表展示 formatGoodClassList: function (params) { let {titles, arr, deep} = params if (arr == undefined) return; for (let i = 0; i < arr.length; i++) { arr[i] = this.formatGoodClassSingleList(titles, arr[i], deep) if (arr[i].list != undefined) { var ss = this.formatGoodClassList({ titles: titles, arr: arr[i].list, deep: deep + 1 }) arr[i].list = ss; } else { } } return arr; }, // /****************************************商品加料************************************************************/ formatGoodFeedListItem: function (titles, item) { // console.log('formatGoodFeedListItem',item) let tmpItem = { id: item.kindMenuId, entityId: item.entityId, parent: { contents: { 1: { content: item.kindMenuName } }, operations: { 11: {//添加 disable: false, }, 12: {//编辑 disable: false, }, 13: { // disable: (item.additionMenuList && item.additionMenuList.length > 0) ? true : false, } } }, child: [] } if (!item.additionMenuList) item.additionMenuList = []; item.additionMenuList.map(child => { // console.log('child',child) tmpItem.child.push({ id: child.menuId, entityId: item.entityId, contents: { 1: { content: child.menuName, }, 2: { content: child.menuPrice.toFixed(2) } }, operations: { 11: {//添加 disable: true, disableType: 'transparent',//hidden transparent default }, 12: {//编辑 disable: false, disableType: 'transparent', }, 14: { disable: false, }, } }) }) return tmpItem }, formatGoodFeedList: function (titles, list) { // console.log('formatGoodFeedList list') for (let i = 0; i < list.length; i++) { // console.log('formatGoodFeedList list',i,list[i]) list[i] = this.formatGoodFeedListItem(titles, list[i]); } // console.log('formatGoodFeedList list',list) return list; }, /****************************************商品备注************************************************************/ formatGoodRemarkListItem: function (titles, item) { let tmpItem = { id: item.id, entityId: item.entityId, parent: { contents: { 1: { content: item.name } }, operations: { // 11:{ // disable:!item.isAdd, // }, // 12:{ // disable:!item.isEdit, // }, 13: { // disable: (item.tasteList && item.tasteList.length > 0) ? true : false, } } }, child: [] } if (!item.tasteList) item.tasteList = []; item.tasteList.map(child => { // console.log('child',child) tmpItem.child.push({ id: child.id, entityId: item.entityId, kindTasteId: item.kindTasteId, contents: { 1: { content: child.name, }, }, operations: { 11: { disable: true, disableType: 'transparent' }, 12: { disable: false, disableType: 'transparent' }, 13: { disable: false }, } }) }) // console.log('tmpItem:',tmpItem) return tmpItem }, formatGoodRemarkList: function (titles, list) { for (let i = 0; i < list.length; i++) { list[i] = this.formatGoodRemarkListItem(titles, list[i]); } // console.log(list) return list; }, } export default goodsFormat; <file_sep>/inside-boss/src/container/visualConfig/views/design/tempConfig.js // 记录一个临时的 config 内容,以在多个页面间传递 const storage = window.sessionStorage const nameKey = 'visual_config_temp_config' const contentKey = 'visual_config_temp_content' export default { get() { const name = storage.getItem(nameKey) || null const content = storage.getItem(contentKey) || null storage.removeItem(nameKey) storage.removeItem(contentKey) if (name && content) { return [name, content] } else { return [] } }, set(name, content) { storage.setItem(nameKey, name) storage.setItem(contentKey, content) } } <file_sep>/static-hercules/build/webpack.base.conf.js var path = require('path') var config = require('../config') var utils = require('./utils') // var px2rem = require('postcss-px2rem') var px2rem = require('postcss-pxtorem') var projectRoot = path.resolve(__dirname, '../') var glob = require('glob') const webpack = require('webpack') var options = process.argv for (var i = options.length - 1; i >= 0; i--) { if (options[i] && options[i].indexOf('NODE_ENV') > -1) { process.env.NODE_ENV = options[i].split('=')[1] } } var env = process.env.NODE_ENV || 'dev' var getEntry = function() { var entry = {} var pages = glob.sync('./page/*.html') pages.forEach(function(name) { var key = name.slice(7, name.length - 5) var path = './src/' + key + '/main.js' entry[key] = path }) return entry } /** * <EMAIL> 2017/07/31 * 打包配置说明: * config中partialPackage可配置是否部分打包 * 当开启部分打包功能时,需要将currentProject设置成在开发页面的名称 * 如:当前开发页面meetgame.html,则设置currentProject='meetgame' * 当关闭部分打包功能时,不需要做任何设置 */ var currentProject = ['fm-bank', 'fm-bank-chain'] var entries = {} if (config.dev.partialPackage) { // entries[currentProject] = "./src/" + currentProject + "/main.js"; currentProject.forEach(function(item) { entries[item] = './src/' + item + '/main.js' }) } else { entries = getEntry() } module.exports = { current: currentProject, // 当前开发项目 // entry: { // // example: './src/example/main.js', // eatlive: './src/eatlive/main.js', // // 刮刮乐游戏 // lottery: './src/lottery/main.js', // // 店长奖励查询 // managerReword: './src/managerReword/main.js', // // 七夕游戏 // meetgame: './src/meetgame/main.js' // }, entry: entries, output: { path: config.build.assetsRoot, publicPath: env === 'dev' ? config.dev.assetsPublicPath : config.build.assetsPublicPath, filename: '[name].js' }, resolve: { extensions: ['', '.js', '.vue'], fallback: [path.join(__dirname, '../node_modules')], alias: { vue: 'vue/dist/vue.js', src: path.resolve(__dirname, '../src'), assets: path.resolve(__dirname, '../src/assets'), base: path.resolve(__dirname, '../src/base'), components: path.resolve(__dirname, '../src/components'), apiConfig: path.resolve(__dirname, '../src/base/config/' + env) } // TODO: 合理利用 alias 减少引用文件路径 }, resolveLoader: { fallback: [path.join(__dirname, '../node_modules')] }, plugins: [ new webpack.DefinePlugin({ __ENV__: JSON.stringify(env) }) ], module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', exclude: file => { return ( /node_modules/.test(file) && !/\.vue\.js/.test(file) && !/@2dfire(.+?)share/.test(file) ) } }, { test: /\.json$/, loader: 'json' }, { test: /\.html$/, loader: 'vue-html' }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', query: { limit: 7000, name: 'images/[name].[hash:7].[ext]' } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url', query: { limit: 6000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }, babel: { presets: ['es2015'], plugins: ['transform-runtime'] }, vue: { loaders: utils.cssLoaders() /* autoprefixer 添加浏览器兼容的css前缀 设置规则参考地址: (官方)https://github.com/postcss/autoprefixer (中文)http://www.ydcss.com/archives/94, px2rem, 参考地址: https://www.npmjs.com/package/postcss-px2rem 推荐写法: 所有px会自动被转化为rem, 不需要转换的 请写成大写的 PX 原生写法: 使用注释的形式规定是否需要转换,会有点问题,解决办法参见https://github.com/vuejs/vue-loader/issues/227 */ /* postcss: [ px2rem({remUnit: 37.5}), require('autoprefixer')({ browsers: ['last 2 versions', 'Android > 4', 'iOS > 6', 'Safari > 6'] }) ]*/ }, postcss: [ px2rem({ rootValue: 37.5, // unitPrecision: 5, // 转换成rem后的小数点位数 propList: ['*'], // 需要转换的css属性列表 minPixelValue: 1.1 // 设置一个最小值,小于这个值就不会被专程rem }), require('autoprefixer')({ browsers: ['last 2 versions', 'Android > 4', 'iOS > 6', 'Safari > 6'] }) ] } <file_sep>/inside-boss/src/container/visualConfig/store/actions/index.js import store from '@src/store' import visualApi from '@src/api/visualConfigApi' import types from '../actionTypes' import { getShopInfo } from './common' import { initDesign } from './design' export * from './design' export function loadBaseInfo() { store.dispatch({ type: types.SHOP_INFO_RESET }) visualApi.getShopInfo().then( data => { store.dispatch({ type: types.SHOP_INFO_LOADED, data }) const { canConfig } = getShopInfo() if (canConfig) { loadCustomPages(true) } else { store.dispatch({ type: types.CUSTOM_PAGES_NOT_LOAD }) } }, () => store.dispatch({ type: types.SHOP_INFO_LOAD_FAILED }), ) } // ================================== export function loadCustomPages(reset = false) { const { appId, appVersionId } = getShopInfo() if (reset) store.dispatch({ type: types.CUSTOM_PAGES_RESET }) visualApi.getCustomPages({ appId, appVersionId }).then( data => store.dispatch({ type: types.CUSTOM_PAGES_LOADED, data }), () => store.dispatch({ type: types.CUSTOM_PAGES_LOAD_FAILED }), ) } export function addCustomPage(data) { const { appId, appVersionId } = getShopInfo() const { pageName, shareImage, shareText } = data return visualApi.addCustomPage({ appId, appVersionId, pageName, shareImage, shareText }) .then( res => { if (res && res.data) { return { result: true } } else { return { result: false, message: '创建失败' } } }, e => ({ result: false, message: e.message }), ) } export function updateCustomPage(pageCode, updates) { const { appId, appVersionId } = getShopInfo() const { pageName, shareImage, shareText } = updates return visualApi.updateCustomPage({ appId, appVersionId, pageCode, pageName, shareImage, shareText }) .then( res => { if (res && res.data) { return { result: true } } else { return { result: false, message: '更新失败' } } }, e => ({ result: false, message: e.message }), ) } export function removeCustomPage(pageCode) { return visualApi.removeCustomPage({ pageCode }) .then( res => { if (res && res.data) { return { result: true } } else { return { result: false, message: '更新失败' } } }, e => ({ result: false, message: e.message }), ) } // ================================== export function loadBackups() { const { appId, appVersionId } = getShopInfo() store.dispatch({ type: types.BACKUPS_RESET }) visualApi.getBackups({ appId, appVersionId }).then( data => store.dispatch({ type: types.BACKUPS_LOADED, data }), () => store.dispatch({ type: types.BACKUPS_LOAD_FAILED }) ) } // 返回值:Promise => true 还原成功;false 还原失败 export function recoverBackup(item) { return visualApi.getConfigContent({ configId: item.configId }) .then( res => { if (res && res.data && res.data.content) { initDesign(item.name, res.data.content) return true } return false }, () => false, ) } // 返回值:Promise => true 删除成功;false 删除失败 export function removeBackup(item) { return visualApi.removeBackup({ configId: item.configId }) .then( res => { loadBackups() return res && res.data }, () => { loadBackups() return false } ) } // ================================== export function loadTemplates() { store.dispatch({ type: types.TEMPLATES_RESET }) return visualApi.getTemplates().then( data => store.dispatch({ type: types.TEMPLATES_LOADED, data }), () => store.dispatch({ type: types.TEMPLATES_LOAD_FAILED }), ) } // 返回值:Promise => true 还原成功;false 还原失败 export function useTemplate(item) { return visualApi.getConfigContent({ preConfigAppId: item.appId, preConfigAppVersionId: item.appVersionId, }).then( res => { if (res && res.data && res.data.content) { // 目前只有首页内容有模板 initDesign('page:home', res.data.content) return true } return false }, () => false, ) } <file_sep>/inside-boss/src/components/itemList/main.js import React, { Component } from 'react' import { Cascader, Input, Table, Modal, message, Popconfirm } from 'antd' import styles from './style.css' import * as action from '../../action' import * as bridge from '../../utils/bridge' import { hashHistory } from 'react-router' const Search = Input.Search class Main extends Component { constructor(props) { super(props) this.state = { selectedRowKeys: [], current: 1, tableData: [], selectedCategoryId: '', keyword: '', isShowConfirmModal: false, deleteValue: [], changeCate: false, deleteTip: '', delType: '', entityType: null, dissolutionTip: '', dissolutionList: [], disolutedata: {} } } componentWillMount() { const { data, dispatch } = this.props // entityType: 0=单店 1=连锁总部 2=连锁下的门店 3=分公司 4=商圈 const { entityType } = bridge.getInfoAsQuery() dispatch(action.getItemList({ pageSize: 20, pageIndex: 1 })) dispatch(action.getGoodCategory()) dispatch(action.getGoodStrategy()) if (entityType == 2) { dispatch( action.getFacadeService({ param: JSON.stringify({ entityType }) }) ) } this.setState({ entityType }) } componentWillReceiveProps(nextProps) { this.setState({ disolutedata: nextProps.data.childGoodsList }) } options = [] columns = [ { title: '商品', key: '1', render: (text, record) => ( <div className={styles.title}> <img className={styles.img} src={ record.imageUrl || 'https://assets.2dfire.com/frontend/eae523b1a01aba73903009489818b177.png' } ></img> <div className={styles.ml10}> <div className={styles.titleContent}> {record.name}{' '} {record.hasSku && ( <div className={styles.hasSku}>多</div> )}{' '} {record.chain && ( <div className={styles.chain}>连锁</div> )} </div> <div className={styles.titleCode}> 商品编码:{record.code} </div> </div> </div> ) }, { title: '所属分类', dataIndex: 'kindMenuName' }, { title: '单价(元)', dataIndex: 'scopePrice' }, { title: '会员价(元)', dataIndex: 'scopeMemberPrice' }, { title: '结账单位', dataIndex: 'account' }, { title: '库存数', dataIndex: 'currentStock' }, { title: '保质期(天)', render: (text, record) => { const { data } = this.props const { strategy = {} } = data const strategyLeng = Object.keys(strategy).length > 0 const hasStrategy = strategyLeng && strategy.itemShelfLifeConfig == '1' const { entityType } = this.state // 保质期策略:itemShelfLifeConfig, 1: 有设置保质期管理策略, 2:无保质期策略 // entityType == 2 && record.chain :门店下发商品 return ( <span> {entityType == 2 && record.chain ? this.issuedPreview(record, hasStrategy) : this.strategyPriew(record, hasStrategy)} </span> ) } }, { title: '是否为称重商品', dataIndex: 'isTwoAccount' }, { title: '是否打折', dataIndex: 'isRatio' }, { title: '商品介绍', width: 150, dataIndex: 'detail', render: (text, record) => ( <span className={styles.detail}> {' '} {this.strSubstring(record.detail)}{' '} </span> ) }, { title: '操作', key: 'action', render: (text, record) => ( <span> <a onClick={this.goEdit.bind( this, record.id, record.chain )} > 编辑 </a> <div className={styles.divider}></div> <a onClick={this.showModal.bind(this, record, 'single')}> 删除 </a> </span> ) } ] strSubstring = (str = '') => { const len = str.length if (len > 50) return str.substring(0, 50) + '...' return str } CateSearch = true issuedPreview = (record, bloon) => { const { data } = this.props const { facadeService } = data // changeToSelf: 允许门店下发商品转自建 if (facadeService.changeToSelf) { return ( <span> {bloon && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } else { return ( <span> {!!record.itemShelfLifeConfig && record.itemShelfLifeConfig == '1' && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } } strategyPriew = (record, bloon) => { // isShelfLife 1:有保质期, 0:无保质期 return ( <span> {bloon && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } onChange(value) { const { data, dispatch } = this.props document.getElementById('search').value = '' this.setState({ selectedCategoryId: value[value.length - 1], keyword: '', current: 1 }) if (this.CateSearch) { dispatch( action.getItemList({ pageSize: 20, pageIndex: 1, keyword: '', categoryId: value[value.length - 1] }) ) } this.CateSearch = true } showModal(value, type) { const t = this const { dispatch } = t.props let itemIdList = [] let idList = [] // 如果是从列表中单个删除,value传过来的是一个对象,如果批量删除,value传来的是一个id数组 // 请求参数 id列表 itemIdList = typeof value == 'object' && value.constructor === Array ? value : [value.id] dispatch(action.getChildGoodResult({ itemType: 0, itemIdList })) setTimeout(function() { const { disolutedata = {} } = t.state if (disolutedata.pass === 0) { t.setState({ dissolutionTip: disolutedata.cause, dissolutionList: disolutedata.causeItemVOList || [] }) t.warning() } else if (disolutedata.pass === 1) { if (type === 'single') { t.setState({ deleteTip: `删除商品后,将同步删除供应链端该商品信息!您确认要删除 ${value.name} 吗?` }) idList.push(value.id) } else { if (t.state.selectedRowKeys.length === 0) { message.error('请先选择商品再进行删除操作') return } t.setState({ deleteTip: `删除商品后,将同步删除供应链端该商品信息!您确认要删除吗?` }) idList = value } t.setState({ isShowConfirmModal: true, deleteValue: idList, delType: type }) } }, 200) } handleCancel() { this.setState({ isShowConfirmModal: false }) } del() { const { data, dispatch } = this.props const page = this.state.delType === 'single' ? this.state.current : 1 dispatch( action.deleteItem({ idList: this.state.deleteValue, pageSize: 20, pageIndex: page, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ selectedRowKeys: [], deleteValue: [], isShowConfirmModal: false, current: page }) } searchItem(value) { const { data, dispatch } = this.props const { selectedCategoryId } = this.state this.setState({ keyword: value, selectedCategoryId: '', current: 1 }) // this.CateSearch = false // if (document.getElementsByClassName('ant-cascader-picker-clear')[0]) { // document // .getElementsByClassName('ant-cascader-picker-clear')[0] // .click() // } document.getElementById('search').value = value dispatch( action.getItemList({ pageSize: 20, pageIndex: 1, keyword: value, categoryId: selectedCategoryId }) ) } showChangeCate(type) { if (this.state.selectedRowKeys.length === 0 && type !== 'cancel') { message.error('请先选择商品再进行换分类操作') return } this.setState({ changeCate: !this.state.changeCate, changeToCate: '' }) } setChangeCate(value) { this.setState({ changeToCate: value[value.length - 1] }) } changeCateSave() { if (this.state.selectedRowKeys.length === 0) { message.error('请先选择商品') return } if (!this.state.changeToCate) { message.error('请先选择分类') return } const { data, dispatch } = this.props dispatch( action.changeCateSave({ idList: this.state.selectedRowKeys, changeCategoryId: this.state.changeToCate, pageSize: 20, pageIndex: 1, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ changeCate: !this.state.changeCate, current: 1, selectedRowKeys: [] }) } goEdit(id, chain) { hashHistory.push(`/ITEM_EDIT/item?id=${id}&chain=${chain}`) } goImportPage() { hashHistory.push(`/ITEM_IMPORT/item`) } goManageCate() { this.props._switchTab() } exportItems() { const { data, dispatch } = this.props dispatch(action.exportItems({ menu_ids: this.state.selectedRowKeys })) } kk() { this.setState({ changeCate: false, changeToCate: '' }) } warning() { Modal.warning({ title: <p>{this.state.dissolutionTip}</p>, content: ( <div className={styles.itemList}> {this.state.dissolutionList.map((item, key) => { return ( <p key={key}> <span>{item.name}</span> {/* <a>查看详情</a> */} </p> ) })} </div> ) }) } render() { const { data, dispatch } = this.props let selectList = [] let changeCategoryList = [] if (data.goodsCategoryList.categoryList.length > 0) { selectList = JSON.stringify(data.goodsCategoryList.categoryList) selectList = selectList .replace(/"categoryId"/g, '"value"') .replace(/"categoryName"/g, '"label"') .replace(/"categoryList"/g, '"children"') selectList = JSON.parse(selectList) changeCategoryList = selectList.filter( value => value.chain === false ) } const rowSelection = { selectedRowKeys: this.state.selectedRowKeys, onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys }) console.log( `selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows ) } } const pagination = { current: this.state.current, defaultPageSize: 20, total: data.item.totalRecord || 0, showTotal: total => { ;`Total ${total} items` }, onChange: page => { // this.setState({ tableData: [] }); dispatch( action.getItemList({ pageSize: 20, pageIndex: page, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ current: page }) } } return ( <div className={styles.baseInfo_wrapper}> <div> <Cascader className={styles.cascaderId} size="large" options={selectList} onChange={this.onChange.bind(this)} placeholder="全部分类" /> <Search id="search" className={styles.search} size="large" placeholder="商品名称/条形码" onSearch={this.searchItem.bind(this)} style={{ width: 200 }} /> <div className={styles.exportButton} onClick={this.exportItems.bind(this)} > 商品信息导出 </div> <div className={styles.importButton} onClick={this.goImportPage.bind(this)} > 商品导入 </div> </div> <div> <div className={styles.relative}> <Table className={styles.table} pagination={pagination} rowSelection={rowSelection} columns={this.columns} dataSource={data.item.itemList} rowKey="id" /> <div className={styles.batchActionsPosition}> <div className={styles.batchActions} onClick={this.showChangeCate.bind(this)} > 换分类 </div> {this.state.changeCate && ( <div> <div className={styles.cover} onClick={this.kk.bind(this)} ></div> <div className={styles.changeCateWrapper}> <div className={styles.changeCateTitle}> <span>换分类</span> <span className={styles.goCate} onClick={this.goManageCate.bind( this )} > 管理分类 </span> </div> <Cascader size="large" options={changeCategoryList} onChange={this.setChangeCate.bind( this )} placeholder="请选择分类" /> <div className={styles.action}> <Popconfirm placement="topLeft" title={ '是否更换选中商品的分类?' } onConfirm={this.changeCateSave.bind( this )} okText="确定" cancelText="取消" > <span className={ styles.changeCateSave } > 保存 </span> </Popconfirm> <span className={ styles.changeCateCancel } onClick={this.showChangeCate.bind( this, 'cancel' )} > 取消 </span> </div> </div> </div> )} <div className={styles.batchActions} onClick={this.showModal.bind( this, this.state.selectedRowKeys )} > 删除 </div> </div> </div> </div> <Modal title="确认弹窗" visible={this.state.isShowConfirmModal} onOk={() => this.del()} onCancel={() => this.handleCancel()} > {this.state.deleteTip} </Modal> </div> ) } } export default Main <file_sep>/union-entrance/src/config/env.js export default __ENV__ === 'dev' ? 'daily' : __ENV__ <file_sep>/inside-boss/src/components/noOwnerCoupon/setList.js /** * Created by air on 2018/3/14. */ /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import {Table, Icon} from 'antd' import styles from './style.css' import * as action from "../../action"; const columns = [ { title: '操作时间', dataIndex: 'time', key: 'time' }, { title: '操作对象(券)', dataIndex: 'coupon', key: 'coupon', }, { title: '操作人', dataIndex: 'setUser', key: 'setUser', }, { title: '操作类型', dataIndex: 'type', key: 'type', }, { title: '操作成功张数', dataIndex: 'number', key: 'number', }, ]; class setList extends Component { constructor(props) { super(props); } componentDidMount() { this.changePage(1) } changePage(page, pageSize) { const {data, dispatch} = this.props dispatch(action.noOwnerSetList({ pageNumber: page})) } back() { const {data, dispatch} = this.props dispatch(action.isShowSetPage(false)) } componentWillReceiveProps(nextProps) {} // nextBtn() { const {data} = this.props if(data.setList.length<20){ return false; } const pageNumber = Number( data.setPageNumber) + 1 this.changePage(pageNumber) } //上一页 preBtn() { const {data} = this.props if(data.setPageNumber<=1){ return false } const pageNumber = data.setPageNumber>1?( Number( data.setPageNumber) - 1): data.setPageNumber this.changePage(pageNumber) } //首页 firstBtn() { const {data} = this.props if( data.setPageNumber===1){ return false; } this.changePage(1) } render() { const {data} = this.props const pagination = { current: data.setPageNumber, defaultPageSize: 20, pageSize: 20, total: data.setListLeg, onChange: this.changePage.bind(this) }; return ( <div> <div className={styles.handleBox2}> <h3 className={styles.setListTitle}> <span style={{cursor:'pointer'}} onClick={this.back.bind(this)}><Icon type="left-circle" className={styles.setListBack}/>返回 </span> / 操作日志 </h3> <Table columns={columns} dataSource={data.setList} bordered pagination={false} rowKey={(record) => `${record.id}`} /> {(!!data.setList&&data.setList.length >= 20)||data.setPageNumber>1? (<div className={styles.pageBox}> <ul className="ant-pagination" unselectable="unselectable"> <li title="上一页" className={data.setPageNumber<=1?'ant-pagination-disabled ant-pagination-prev':'ant-pagination-prev'} aria-disabled="true"> <a className="ant-pagination-item-link" onClick={this.preBtn.bind(this)}></a> </li><span className={data.setPageNumber>1?styles.pageBtn:styles.page} onClick={data.setPageNumber>=1?this.firstBtn.bind(this):''}>首页</span>{data.setPageNumber||1}<span className={styles.page}>末页</span> <li title="下一页" tabIndex="0" className={data.setList.length<20?'ant-pagination-disabled ant-pagination-next':'ant-pagination-next'} aria-disabled="false"> <a className="ant-pagination-item-link" onClick={this.nextBtn.bind(this)}></a> </li> </ul> </div>):''} </div> </div> ) } } export default setList <file_sep>/inside-boss/src/container/couponPush/index.js /** * Created by air on 2017/7/10. */ import React, { Component }from 'react' import Main from '../../components/couponPush/main' import { connect } from 'react-redux' class couponPushContainer extends Component { render () { const {params,data,dispatch} = this.props return ( <div> <Main data={data} dispatch={dispatch} params={params}/> </div> ) } } const mapStateToProps = (state) => { return { data: state.couponPush, } } const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(couponPushContainer) <file_sep>/inside-boss/src/components/noOwnerCoupon/set.js /** * Created by air on 2018/3/14. */ /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import {Select, Input, Button} from 'antd' import styles from './style.css' import {message, Modal} from "antd/lib/index"; import * as bridge from "../../utils/bridge"; import saveAs from "../../utils/saveAs"; import {errorHandler, showSpin} from "../../action"; import api from "../../api/index"; const Option = Select.Option class Set extends Component { constructor(props) { super(props); this.state = { couponId: '', start: '', end: '', coupon: [] } } /** * 选择优惠券 * */ changeCoupon(e) { if (!e) { return false } this.setState({couponId: e}); } /** * 输入优惠券起始号段 * */ numStartChange(e) { this.setState({start: e.target.value}); } /** * 输入优惠券起始号段 * */ numEndChange(e) { this.setState({end: e.target.value}); } /** * @param type * @param message * @param key * */ submitInfo(type, message, key) { const that = this; const {data} = this.props const {exportActiveErrorUrl, exportStopErrorUrl,importData} = data if (!message) { message = [type === 'active' ? '当前优惠券中有已核销/已过期的券,无法激活' : '当前优惠券中有已核销/已过期的券'] } Modal.confirm({ title: `${type === 'active' ? '批量激活成功' : '批量停用失败'}`, content: ( <div style={{margin: '0px 0 0 -40px'}}> <p style={{marginTop: '20px'}}>{message}</p> </div> ), onOk() { const url = ((type === 'active') ? exportActiveErrorUrl : exportStopErrorUrl )+ `?key=${key}&app_key=${importData.app_key}` that.handleExport(url); that.setState({couponId: '', start: '', end: ''}); }, confirmLoading: true, className: 'ant-confirm-info', iconType: 'info-circle', cancelText: '取消', okText: `${type === 'active' ? '导出激活失败结果' : '导出停用失败结果'}`, maskClosable: true, width: 520 }); } /** * 批量操作 * @param type 批量操作类型 active批量激活 stop批量停用 * */ batchProcessing(type) { if (!this.state.couponId) { message.error('请先选择优惠券') return false } if (!this.state.start || !this.state.end) { message.error('请先选择优惠券号段') return false } if (type === 'active') { this.toActive(type) } else if (type === 'stop') { this.toStop(type) } } /** * 批量激活 * @param type 批量操作类型 active批量激活 stop批量停用 * */ toActive(type) { const {dispatch} = this.props const that = this; api.noOwnerCouponActive({ couponId: this.state.couponId, start: this.state.start, end: this.state.end }).then( res => { if (res.succeed) { message.success('批量激活成功!') } else { that.submitInfo(type, res.message, res.key); } }, err => { console.log(err) dispatch(errorHandler(err)) } ) } /** * 批量停用 * @param type 批量操作类型 active批量激活 stop批量停用 * */ toStop(type) { const {dispatch} = this.props const that = this; api.noOwnerCouponStop({ couponId: this.state.couponId, start: this.state.start, end: this.state.end }).then( res => { if (res.succeed) { message.success('批量停用成功!') } else { that.submitInfo(type, res.message, res.key); } }, err => { console.log(err) dispatch(errorHandler(err)) } ) } handleExport(url) { const t = this const {token} = bridge.getInfoAsQuery() t.setState({ exportLock: true }) const {isRecharge, rechargeBatchId} = this.props.data if (!!isRecharge && !rechargeBatchId) { message.warn('没有选择有效的文件!') setTimeout(() => { t.setState({ exportLock: false }) }, 2000) return } saveAs(url, token).then( filename => { message.success('导出成功!') }, // 成功返回文件名 err => { if (err.code === 0) { if (err.errorCode === '401') { bridge.callParent('logout') return } message.error(err.message || '导出失败') } } ).then(e => this.setState({exportLock: false})) } /** * 获取优惠券 * */ getCoupon(e) { const {data, dispatch} = this.props api.noOwnerGetCoupon({ type: 'ALL' }).then( res => { this.setState({coupon: res}); }, err => { dispatch(errorHandler(err)) } ).then(e => { }) } render() { const that = this const {data, dispatch, params} = this.props const {coupon} = data.select return ( <div> <h3 className={styles.h3}>券码管理</h3> <div className={styles.handleBox}> <div className={styles.main_p}> <span className={styles.main_title}>选择优惠券:</span> <Select showSearch value={that.state.couponId} optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} className={styles.select} onFocus={that.getCoupon.bind(that)} onSelect={that.changeCoupon.bind(that)}> {this.state.coupon.map((val) => { return <Option value={val.id} key={val.id}>{val.name}</Option> })} </Select> </div> <p className={styles.main_p}> <span className={styles.main_title}>搜索优惠券号段:</span> <Input className={styles.input2} value={that.state.start} onChange={that.numStartChange.bind(that)}/> - <Input className={styles.input2} value={that.state.end} onChange={that.numEndChange.bind(that)}/> <Button className={styles.btn_primary} type="primary" onClick={that.batchProcessing.bind(that, 'active')}>批量激活</Button> <Button className={styles.set_btn} onClick={that.batchProcessing.bind(that, 'stop')}>批量停用</Button> </p> </div> </div> ) } } export default Set <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/banner/TmpPreview.js import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import style from './TmpPreview.css' export default class ConfigPreview extends PureComponent { static propTypes = { value: PropTypes.object, }; modePriew = () => { const { config } = this.props.value return (config.mode == '1' ? <img className={style.configLogo} src='https://assets.2dfire.com/frontend/4fd023969fc79ca01056fa728be7b685.png'/> : <div className={style.configInfo}> <div className={style.top}> <img className={style.configInfoLogo} src='https://assets.2dfire.com/frontend/4fd023969fc79ca01056fa728be7b685.png'/> <div className={style.configAdress}>二维火智能超市(教工路店)</div> </div> <div className={style.main}> <div className={style.company}> <p className={style.time}>营业时间:周一至周日9:00-22:00</p> <p><span className={style.environment} />二维火科技大厦</p> </div> </div> </div> ) } render() { const { value } = this.props const { config } = value return ( <div className={style.configPreview} > <div className={cx(style.configBanner, 'desigeCove')} style={createStyle(config)} /> {this.modePriew()} </div> ) } } function createStyle(value) { const { mode } = value return { height: mode == '1' ? '140px' : '190px', backgroundImage: value.backgroundImage ? `url(${value.backgroundImage})` : "url('https://assets.2dfire.com/frontend/63b8d3cc92e8047f9fca0c1fdc8a9f31.png')", } } <file_sep>/inside-boss/src/container/orderPhotos/reducers.js import { // SET_VIDEO_LIST, // INIT_VIDEO_DATA, CHANGE_ORDER_TYPE, SET_ORDER_START_VALUE, SET_ORDER_END_VALUE, SET_ORDER_LIST, SHOW_SPIN, INIT_ORDER_DATA, SET_INVOICE_CODE } from '../../constants' export default (state = {}, action) => { switch (action.type) { case INIT_ORDER_DATA: return action.data case CHANGE_ORDER_TYPE : return Object.assign({},state ,{ orderType : action.data }) case SET_ORDER_START_VALUE: return Object.assign({}, state, {startValue: action.value}) case SET_ORDER_END_VALUE: return Object.assign({}, state, {endValue: action.value}) case SET_INVOICE_CODE: return Object.assign({}, state, {invoiceCode: action.value}) case SET_ORDER_LIST: return Object.assign({}, state, { orderList: action.data.records, length : action.data.records.length, total : action.data.totalRecord }) case SHOW_SPIN: return Object.assign({}, state, {showSpin: action.data}) default: return state } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/goodsRanking/definition.js export default { name: 'goodsRanking', userName: '商品排行', group: '基础类', max: 3, config: { ranking: '综合排序', rankingLimit: 2, mode: '大图', showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '新品', image: null, }, }, } <file_sep>/static-hercules/src/alipay-agent/lang/zh.js export default { // top-header 里面设置title,key为路由的名字 pageTitle: { '/redirect': '特约商户申请', '/index': '支付宝特约商户', '/input': '支付宝特约商户', '/auth/auditing/auditing': '支付宝特约商户', '/auth/sign/sign': '支付宝特约商户', '/auth/fail/fail': '支付宝特约商户', '/auth/success/success': '支付宝特约商户' } } <file_sep>/inside-boss/src/container/visualConfig/sences/retail/goodsList.js import { currentWeixinMealUrl } from '@src/utils/env' import { getEntityId } from '@src/container/visualConfig/utils' const page = { name: '商品分类页', configName: 'page:goodsList', link: () => `${currentWeixinMealUrl}/page_split/v1/goods_list/${getEntityId()}?industry=3`, components: [ // 核心组件 'cateList', // 附加组件 'backgroundImage', 'banner', 'pictureAds', 'title', 'coupons', 'searchInput', 'announce', 'hotline', 'whitespace', ], defaults: { components: [ { type: 'cateList' }, ], }, } export default page <file_sep>/inside-chain/README.md # static-chain PC连锁商家管理后台 ### 使用框架版本注意 - vue 2.x - iview 2.x 如果要升级代码框架或UI框架,慎重。 ### 项目开发注意 1. 组件化开发 注意使用已有组件,及组件的组合使用,避免重复造简单的轮子,节约开发时间。 2. 状态管理 vuex提供简单方便的状态管理方法,请在需要存储数据的地方全部用上,避免组件多层嵌套传递,以免冒泡复杂。 注意将必要的状态存储在store内,以便状态的控制和改变 3. 业务逻辑写哪里 所有的业务逻辑请写在actions内,包括api请求/数据format等 4. 计算属性 多使用计算属性,避免在html中做过多的计算 5. 组件的开发 组件要加上必要的注释说明,方便其他开发者使用或者优化修改 ### 组件列表及简介 列举一些常用的组件 > 组件目录src/components base-** 系列 - base-img 图片居中平铺组件,在img-box中有引用 - base-labels 项目中多用于展示标签的地方,灰色腰圆标签样式,可显示右侧"X"按钮,冒泡方法on-del - base-xxx-verify 基础验证组件,冒泡verify方法,未通过验证冒泡false,通过则冒泡true - base-verify 基础验证组件的集合,通过props: type来判断实际需要哪个验证组件 - base-modal 基础弹窗组件,包括一个弹窗header/body/footer,用法见组件内部注释 - base-search-bar 基础输入框组件,包含一个左侧输入框,右侧留一个slot 步骤条组件 步骤条组件由两个组件组成分别是 base-steps 和 base-step 组件组成 usage import BaseSteps from "@/components/step/base-steps"; import BaseStep from "@/components/step/base-step"; <BaseSteps :current="current" class="mb-20px"> <BaseStep>1</BaseStep> <BaseStep>2</BaseStep> <BaseStep>3</BaseStep> </BaseSteps> 按钮组件 - button-add 腰圆红边白底,带右侧加号按钮,多用于添加标签等场景 - button-refresh 刷新按钮组件,提供一个圆形带阴影及刷新图标的按钮,有点击事件 列表用展示组件 - list-card 列表卡片显示,卡片式容器 图片显示组件 - img-box 显示图片用,提供基础无图片样式、虚线边框 树形组件 - tree/node 树形展示组件,提供点击和展开事件冒泡,返回触发节点。 - select-tree 带选择框的属性列表组件,提供选中时的change事件 ### 额外的render 为了改造原有iview组件显示的不足,增加了一些render函数来增加显示的内容 - tab-badge 详细说明及使用方法见 `src/base/tab-badge.js` 文件内 <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/backgroundImage/BackgroundImage.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { Button } from 'antd'; import { ImageUpload } from '@src/container/visualConfig/components/editing' import s from './BackgroundImage.css' export default class BackgroundImage extends Component { static propTypes = { PreviewWrapper: PropTypes.func.isRequired, EditorWrapper: PropTypes.func.isRequired, EditPlaceholderWrapper: PropTypes.func.isRequired, editing: PropTypes.bool.isRequired, config: PropTypes.string, onUpdate: PropTypes.func.isRequired, } onUpload = url => this.props.onUpdate(url) render() { const { EditorWrapper, EditPlaceholderWrapper, editing } = this.props return <div> <EditPlaceholderWrapper className={s.placeholderWrapper}>{this.placeholder()}</EditPlaceholderWrapper> {editing ? <EditorWrapper arrow={false}>{this.editor()}</EditorWrapper> : null} </div> } editor() { const { config } = this.props return <div className={s.editor}> <div className={s.label}>页面背景图:</div> <div> <ImageUpload current={config} onUpload={this.onUpload} /> <Button type="primary" className={s.resetBtn} onClick={() => this.onUpload(null)}>重置</Button> <div className={s.desc}>建议尺寸:750x1334px,尺寸不匹配时,图片进行压缩或拉伸铺满显示</div> </div> </div> } placeholder() { return <div className={s.placeholder}> <img src="https://assets.2dfire.com/frontend/b08d744e284b62f8d50c06afa14a4685.png" /> <span>背景图</span> </div> } } <file_sep>/inside-chain/src/views/shop/store-manage/pass/schemeCheck/columns.js export default self => [ { title: '商品名称', key: 'name' }, { title: '商品分类', key: 'kindMenuName' }, { title: '状态', key: 'status', render(h, { row }) { const { isKDS, isPrint, relatedNum } = row if (relatedNum > 0) { return ( <span class="pass-scheme-columns-action" onClick={self.showSettingModal(row)}> 已关联 {relatedNum}个 </span> ) } if (isKDS) { return <span>KDS</span> } if (isPrint <= 0) { return <span>不出单商品</span> } if (!isKDS && relatedNum <= 0) { return ( <span class="pass-scheme-columns-action" onClick={self.showSettingModal(row)}> 未设置 </span> ) } return <span>未设置</span> } } ] <file_sep>/static-hercules/src/ele-account/mixins/scheme.js export default { methods: { payInfoLink(item) { let {tradeType, orderId} = item /*消费类型,订单号存在*/ if (tradeType === 1) { if (orderId) { window.location.href = `tdf-manager://2dfire.com/member/payInfo?orderId=${orderId}&totalPayId=` } else { this.$alert({ content: '此账单还未经过收银员的同意,暂时无法查看详情哦', confirmText: "我知道了" }) } } } } }<file_sep>/inside-boss/src/utils/sortBy.js /** * 对数组进行排序 */ var WEEKS = { '周一': 1, '星期一': 1, '周二': 2, '星期二': 2, '周三': 3, '星期三': 3, '周四': 4, '星期四': 4, '周五': 5, '星期五': 5, '周六': 6, '星期六': 6, '周日': 7, '星期日': 7, '星期天': 7 } var WEEKS = { '周一': 1, '星期一': 1, '周二': 2, '星期二': 2, '周三': 3, '星期三': 3, '周四': 4, '星期四': 4, '周五': 5, '星期五': 5, '周六': 6, '星期六': 6, '周日': 7, '星期日': 7, '星期天': 7 } var MONTHS = { '一月': 1, '1月': 1, '二月': 2, '2月': 2, '三月': 3, '3月': 3, '四月': 4, '4月': 4, '五月': 5, '5月': 5, '六月': 6, '6月': 6, '七月': 7, '7月': 7, '八月': 8, '8月': 8, '九月': 9, '9月': 9, '十月': 10, '10月': 10, '十一月': 11, '11月': 11, '十二月': 12, '12月': 12 } function sortBy (index) { return function (o, p) { var a, b if (typeof o === 'object' && typeof p === 'object' && o && p) { a = o[index] b = p[index] if (a === b) { return 0 } if (WEEKS[a] && WEEKS[b]) { return WEEKS[a] < WEEKS[b] ? -1 : 1 } if (MONTHS[a] && MONTHS[b]) { return MONTHS[a] < MONTHS[b] ? -1 : 1 } if (typeof a === typeof b) { return a < b ? -1 : 1 } return typeof a < typeof b ? -1 : 1 } else { throw ('sort object error!') } } } module.exports = sortBy <file_sep>/inside-boss/README.md # 商家管理后台 - 掌故业务内嵌 ## 项目背景 - 将掌柜业务线相关业务(不含报表)单独维护 - 前端使用React、Redux构建,项目入口:`/src/title.js` ## 注意 本项目使用[7秒部署](http://git.2dfire-inc.com/union/union-scripts)方案,提交前需要先在本地执行`npm run build`完成编译再提交。 ## 项目使用 ### 启动 ``` npm run start ``` ### 编译 ``` npm run build ``` ### 部署 ``` npm run deplou ``` ## 兼容性 - IE10、Edge、Chrome、Safari、Firefox ## 获得帮助 - 亚麻: <EMAIL> <file_sep>/inside-chain/src/const/emu-settingTabs.js const tab = [ { name: "商品管理", path: "/goods_manage" }, { name: "套餐管理", path: "/combo_manage" }, { name: "分类管理", path: "/goods_class" }, { name: "商品属性", path: "/goods_attr" }, { name: "菜单管理", path: "/menu_manage", child: [ '/menu_goods', '/menu_import' ] } ] export default tab; <file_sep>/inside-boss/src/container/visualConfig/views/new_design/list/ComItem.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import c from 'classnames' import { getPageDesignComponentMap, getDesignComponentCount } from '@src/container/visualConfig/store/selectors' import * as actions from '@src/container/visualConfig/store/actions' import s from './ComItem.css' @connect((state, props) => ({ definition: getPageDesignComponentMap(state)[props.name].definition, count: getDesignComponentCount(state, props.name), })) class ComItem extends Component { static propTypes = { name: PropTypes.string.isRequired, } // 是否还能往页面上添加此组件 get addable() { const { definition, count } = this.props return !definition.max || count < definition.max } add = () => { if (!this.addable) return actions.designAddComponent(this.props.name, null) } render() { const { addable } = this const { userName } = this.props.definition return <div className={c(s.wrapper, !addable && s.disable)} onClick={this.add}>{userName}</div> } } export default ComItem <file_sep>/inside-chain/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue'; import VueResource from 'vue-resource'; import Cookie from '@2dfire/utils/cookie' import App from './App'; import router from './router'; import iView, {Message} from 'iview'; import Vuex from 'vuex' import 'iview/dist/styles/iview.css'; // 使用 CSS import store from "./store"; import { ENV } from "apiConfig"; Vue.use(VueResource); Vue.use(iView); Vue.use(Vuex); Vue.prototype.$Message = Message Vue.config.productionTip = false; // 环境参数 pre/publish Vue.http.headers.common['env'] = ENV; // 国际化需要语言参数 Vue.http.headers.common['lang'] = 'zh_CN'; // token放在header,网关接口需要令牌,登录接口除外 let token = '' if(Cookie.getItem('entrance') != undefined){ token = encodeURIComponent(JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).token) } Vue.http.headers.common['token'] = token; Vue.prototype.$ToFixed = function(num){ return parseInt(num * 100) / 100 } /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App }, }); router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/hotline/definition.js export default { name: 'hotline', userName: '客服电话', max: 3, config: { mode: '1', backgroundColor: '#f5f5f5', textAlign: 'left', textColor: '#5a5a5a', }, } <file_sep>/static-hercules/src/secured-account/store/mutation.js import Vue from 'vue' import * as types from './mutation-types' export default { //底部弹出选择 [types.PICKER_CHANGE](state, payload) { state.picker = {...state.picker, ...payload} }, //底部弹出日期选择 [types.DATE_PICKER_CHANGE](state, payload) { state.dateNewPicker = {...state.picker, ...payload} }, //底部弹出地址选择器 [types.ADDRESS_PICKER_CHANGE](state, payload) { state.addressPicker = { ...state.picker, ...payload } }, // 修改商户信息 [types.MODIFY_MERCHANT](state, payload) { Vue.set(state.merchantInfo, payload.type, payload.value) }, //修改当前编辑状态 [types.CHANGE_EXAMPLE_PHOTO](state, payload) { state.examplePhoto = {...state.examplePhoto, ...payload} }, //修改当前编辑状态 [types.CHANGE_VIEWSTATE](state, payload) { state.viewState = payload }, }<file_sep>/inside-chain/src/views/shop/store-manage/pass/scheme/goodsManage/columns.js import Good from '../../common/good' export default self => [ { type: 'selection', width: 60, align: 'center' }, { title: '商品', key: 'name', render(h, { row }) { return <Good data={row} /> } }, { title: '所属分类', key: 'moduleKindName' }, { title: '操作', render: (h, { row }) => { return ( <a style="color:#3e76f6" onClick={self.delGoods(row)}> 删除 </a> ) } } ] <file_sep>/inside-boss/src/store.js import thunkMiddleware from 'redux-thunk' import { createStore, applyMiddleware, compose } from 'redux' import createReducer from './reducerLoader' // 支持 redux 调试工具 // http://extension.remotedev.io/#usage const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const configureStore = (initialState = {}) => { const middleware = [ thunkMiddleware ] const store = createStore( createReducer(), initialState, composeEnhancers( applyMiddleware(...middleware) ) ) store.asyncReducers = {} return store } const initialState = {} const store = configureStore(initialState) export default store <file_sep>/inside-boss/src/components/customBillDetail/addPicture.js /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import styles from './css/main.css' import * as bridge from '../../utils/bridge' import axios from 'axios' import {errorHandler} from '../../action' class AddPicture extends Component { constructor(props) { super(props) } submitImg() { let file = document.getElementById('upload_file').files[0] this.imgUpload(file) } // 图片上传到oss imgUpload(file) { const {dispatch, params} = this.props let that = this let formData = new FormData() formData.append('file', file) formData.append('projectName', 'OssImg') formData.append('path', 'customizebill') axios .post('/api/uploadfile', formData, { isUploadImg: true }) .then(response => { that.props.AddUploadLogo({ img: response, index: that.props.index }) }) .catch(err => { dispatch(errorHandler(err)) }) } delLogo() { this.props.AddUploadLogo({img: '', index: this.props.index}) } render() { const t = this const {data} = t.props // 是否是编辑页面 // 编辑页显示右上角删除按钮 const isEdit = window.location.hash.indexOf('detail')> 0 return ( <span> {(() => { if (!isEdit) { return ( <span className={styles.logoImg}> {data.type} <img src={data.value}/> </span> ) } else { if (!data.value) { return ( <label className={styles.btnType2}> <input type="file" accept="image/*" onChange={this.submitImg.bind(this)} id="upload_file" /> <div className={styles.chooseFile} ref="chooseAndUpload"> 上传图片 </div> </label> ) } else { return ( <span className={styles.logoImg}> <span className={styles.closeImg} onClick={this.delLogo.bind(this)} /> <img src={data.value}/> </span> ) } } })()} </span> ) } } export default AddPicture <file_sep>/static-hercules/src/wechat-direct-con/libs/rules.js // 字符串长度2~10 const twoToTen = /^\w{2,10}$/ // 字符串长度1~15 const oneToFifteen = /^\w{1,15}$/ // 字符串1~40 const oneToForty = /^\w{1,40}$/ // 验证手机 const checkTel = /^[1][0-9]{10}$/ export const ruleList = { /*** * 小微升级 */ merchantNum: { isRequired: true, types: 'number', name: '商户号' }, merchantType: { isRequired: true, types: 'text', name: '主体类型' }, businessLicensePic: { isRequired: true, types: 'img', name: '营业执照照片' }, businessLicenseNum: { isRequired: true, types: 'text', name: '营业执照注册号' }, merchantName: { isRequired: true, types: 'text', name: '商户名称' }, registerAddress: { isRequired: true, types: 'text', name: '注册地址' }, corporationName: { isRequired: true, types: 'text', name: '法人名称' }, businessStartTime: { isRequired: true, types: 'text', name: '开始时间' }, businessEndTime: { isRequired: true, types: 'text', name: '结束时间' }, businessLicenseType: { isRequired: true, types: 'text', name: '营业执照类型' }, qualification: { isRequired: true, types: 'text', name: '特殊资质' }, orgPhoto: { isRequired: true, types: 'text', name: '组织机构代码证照片' }, orgNo: { isRequired: true, types: 'text', name: '组织机构代码' }, orgStartTime: { isRequired: true, types: 'text', name: '组织机构有效期开始时间' }, orgEndTime: { isRequired: true, types: 'text', name: '组织机构有效期结束时间' }, businessAccountName: { isRequired: true, types: 'text', name: '开户名称' }, businessAccountBank: { isRequired: true, types: 'text', name: '开户银行' }, businessAccountNumber: { isRequired: true, types: 'number', name: '银行卡号' }, businessAccountAddressProvince: { isRequired: true, types: 'text', name: '开户省' }, businessAccountAddressCity: { isRequired: true, types: 'text', name: '开户市' }, businessAccountSubBank: { isRequired: true, types: 'text', name: '开户支行' }, }; /*** * 小微商户部分表单提交 */ export const ruleXwList = { shopName: { isRequired: true, types: 'text', name: '门店名称' }, detailAddress: { isRequired: true, types: 'text', name: '详细地址' }, shopLicensePic: { isRequired: true, types: 'text', name: '店铺门头照' }, shopEnvironmentPic: { isRequired: true, types: 'img', name: '店铺环境照' }, serviceTel: { isRequired: true, types: 'tel', name: '客服电话' }, serviceType: { isRequired: true, types: 'text', name: '服务类型' }, idCardFront: { isRequired: true, types: 'img', name: '身份证正面' }, idCardReverse: { isRequired: true, types: 'img', name: '身份证反面' }, idCardName: { isRequired: true, types: 'text', name: '身份证姓名' }, idCardNumber: { isRequired: true, types: 'id', name: '证件号码' }, startDate: { isRequired: true, types: 'text', name: '开始时间' }, endDate: { isRequired: true, types: 'text', name: '结束时间' }, userSimpleName: { isRequired: true, types: 'twoToThirty', name: '商户简称' }, accountName: { isRequired: true, types: 'text', name: '开户名称' }, accountBank: { isRequired: true, types: 'text', name: '开户银行' }, accountNumber: { isRequired: true, types: 'number', name: '银行卡号' }, accountAddressProvince: { isRequired: true, types: 'text', name: '开户省' }, accountAddressCity: { isRequired: true, types: 'text', name: '开户市' }, accountSubBank: { isRequired: true, types: 'text', name: '开户支行' }, userTelNumber: { isRequired: true, types: 'mobile', name: '手机号码' }, userEmailNumber: { isRequired: true, types: 'email', name: '联系邮箱' } }; /*** * 修改银行卡部分表单提交 */ export const ruleUpdateBankList = { accountBank: { isRequired: true, types: 'text', name: '开户银行' }, accountNumber: { isRequired: true, types: 'number', name: '银行卡号' }, accountAddressProvince: { isRequired: true, types: 'text', name: '开户省' }, accountAddressCity: { isRequired: true, types: 'text', name: '开户市' }, accountSubBank: { isRequired: true, types: 'text', name: '开户银行支行' } }; /*** * 修改银行卡部分表单提交--企业商户 */ export const ruleUpdateUpgradeBankList = { businessAccountBank: { isRequired: true, types: 'text', name: '开户银行' }, businessAccountNumber: { isRequired: true, types: 'number', name: '银行卡号' }, businessAccountAddressProvince: { isRequired: true, types: 'text', name: '开户省' }, businessAccountAddressCity: { isRequired: true, types: 'text', name: '开户市' }, businessAccountSubBank: { isRequired: true, types: 'text', name: '开户银行支行' } }; /*** * 修改联系信息部分表单提交 */ export const ruleUpdateContractList = { userSimpleName: { isRequired: true, types: 'twoToThirty', name: '商户简称' }, userTelNumber: { isRequired: true, types: 'mobile', name: '手机号' }, userEmailNumber: { isRequired: true, types: 'email', name: '联系邮箱' } }; /** * 表单验证 * @param val 用户输入的值 * @param dataVal ruleList对应的key * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ export const inputIsOk = function (val, dataVal) { let data = ruleList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return {data: true} } if (data.types === 'boolean') { if (typeof val !== 'boolean') { return {data: false, message: data.name + '不能为空'} } } else { if (!val) { return {data: false, message: data.name + '不能为空'} } } //类型判断 let returnData; switch (data.types) { case "number"://验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break; case 'mobile'://验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break; case "tel"://验证电话 returnData = getMatchResult(/^[0-9]{5,15}$/, val, data.name) break; case 'email': returnData = getMatchResult(/(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name) break; case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break; default: returnData = {data: true} } return returnData } /** * 表单验证小微商户部分 * @param val 用户输入的值 * @param dataVal ruleList对应的key * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ export const inputXwIsOk = function (val, dataVal) { let data = ruleXwList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (data.types === 'boolean') { if (typeof val !== 'boolean') { return { data: false, message: data.name + '不能为空' } } } else { if (!val) { return { data: false, message: data.name + '不能为空' } } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 表单验证修改银行卡部分 * */ export const inputUpdateBankIsOk = function (val, dataVal) { let data = ruleUpdateBankList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (!val) { return { data: false, message: data.name + '不能为空' } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 表单验证修改银行卡部分--企业商户 * */ export const inputUpdateUpgradeBankIsOk = function (val, dataVal) { let data = ruleUpdateUpgradeBankList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (!val) { return { data: false, message: data.name + '不能为空' } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 表单验证修改联系信息部分 * */ export const inputUpdateContractIsOk = function (val, dataVal) { let data = ruleUpdateContractList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (!val) { return { data: false, message: data.name + '不能为空' } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 根据类型判断 */ const getSwitchMatchResult = (val, data) => { let returnData; switch (data.types) { case "number": //验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break; case 'mobile': //验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break; case "tel": //验证电话(3-20位数字|连字符) returnData = getMatchResult(/^([0-9-]){3,20}$/, val, data.name) break; case 'email': returnData = getMatchResult(/(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name) break; case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break; case 'id': // 证件号码 returnData = getMatchResult(/(^[0-9]{15}$)|(^[0-9]{17}([0-9]|X|x)$)/, val, data.name) break; case 'twoToThirty': // 2-30 returnData = getMatchResult(/^([A-Za-z0-9]{2,30})|([\u4e00-\u9fa5]{1,15})|([\u4e00-\u9fa5][\w\W]{2})$/, val, data.name) break; case 'bankCardId': // 银行卡 returnData = getMatchResult(/^[623501|621468|620522|625191|622384|623078|940034|622150|622151|622181|622188|955100|621095|620062|621285|621798|621799|621797|22199|621096|62215049|62215050|62215051|62218849|62218850|62218851|621622|623219|621674|623218|621599|623698|623699|623686|621098|620529|622180|622182|622187|622189|621582|623676|623677|622812|622810|622811|628310|625919|625368|625367|518905|622835|625603|625605|518905]/, val, data.name) break; default: returnData = { data: true } } return returnData } /** * 返回正则效验结果 * @param reg 正则效验规则 * @param val 值 * @param name 效验字段名字 * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ const getMatchResult = (reg, val, name) => { let r; r = val.match(reg); if (r == null) { return {data: false, message: '请上传正确的' + name} } else { return {data: true} } } <file_sep>/inside-chain/src/store/modules/components/cashierMonitor.js import Requester from '@/base/requester' import catchError from '@/base/catchError' import API from '@/config/api_batch.js' import Obj from '@2dfire/utils/object' import Vue from 'vue'; import iView from "iview"; Vue.use(iView); let Message = iView.Message; const cashierMonitor = { namespaced: true, state:{ tableList:[], filterList:[], pageList:{ total:'', list:[] } }, actions: { //获取连锁下门店 getAllShops({dispatch},params){ API.getAllShops().then(res=>{ if(!Obj.isEmpty(res.data.length)){ dispatch('getCashierInfo',{ ...params, option:{ entityIdList:JSON.stringify(res.data.map( item => item.entityId )) } }) } }).catch(e=>{ catchError(e) }) }, //获取收银信息 getCashierInfo({commit},params){ const { pageNum, pageSize, option } = params API.getCashDeviceInfo(option).then(res=>{ let data = [] if(!Obj.isEmpty(res.data)){ res = res.data res.map(item=>{ data.push({ name:item.shopName, code:item.shopCode, version:item.cashVersion, status:item.online, consistent: item.consistent, statusVal:item.online?'1':'0', versionVal: item.cashVersion === 0 ? '2': item.consistent?'1':'0' }) }) } let startNum = (pageNum - 1 ) * pageSize commit('_getCashierInfo',data) commit('_setFilterList',data) let obj = { total: data.length, list: [].concat(data).splice(startNum,pageSize) } commit('_setPageList',obj) }).catch(e=>{ catchError(e) }) }, //分页 changePage({commit, getters}, params){ const { pageNum, pageSize } = params let arr = [].concat(getters.getFilterList) let startNum = (pageNum - 1 ) * pageSize let list = arr.splice(startNum,pageSize) commit('_changePage',list) }, //查询 filterCashierInfo({commit, getters},params){ const {search, status, version, pageNum, pageSize} = params let startNum = (pageNum - 1 ) * pageSize let arr = [].concat(getters.getAllList) let filterArr = arr.filter(item=>{ if( item.name.includes(search) && item.status.includes(status==='-1'?'':status) && item.consistent.includes(version==='-1'?'':version) ){ return item } }) let obj = { total: filterArr.length, list: [].concat(filterArr).splice(startNum,pageSize) } commit('_setFilterList',filterArr) commit('_setPageList',obj) } }, getters: { getPageList(state){ return state.pageList }, getAllList(state){ return state.tableList }, getFilterList(state){ return state.filterList } }, mutations: { _getCashierInfo(state,data){ state.tableList = [].concat(data) }, _setFilterList(state,data){ state.filterList = [].concat(data) }, _setPageList(state,data){ state.pageList = Object.assign({},data) }, _changePage(state,data){ state.pageList.list = [].concat(data) } } } export default cashierMonitor <file_sep>/inside-chain/src/const/emu-nav.js const nav = { "10b122c7c401432780933a74e1e13856": { icon: "icon-home", url: "", name: "机构管理", id: "1" }, "c2b7e33d6d9746f8ae5b03d14c79e2a4": { icon: "", url: "/shop_manage", name: "门店管理", id: "2" }, "1e3b733a006447c2a9f9652894394dd4": { icon: "", url: "/shop_brand", name: "品牌管理", id: "3" }, "2e2<KEY>": { icon: "", url: "/shop_organ", name: "分支机构", id: "4" }, "1d724f444e9f42539c67f2335c11f75b": { icon: "icon-setting", url: "", name: "开店设置", id: "5" }, "e85ce385b84c45f488a44f2e88bbda45": { icon: "", url: "/goods_manage", name: "商品和套餐", id: "6" }, "fe4e37f6c18944e9bb815baad329e254": { icon: "", url: "/pass", name: "传菜", id: 7 }, "a9b708df7850429c9a433b5a9fa4e025": { icon: "", url: "", name: "收银设置", id: 8 }, "ab4820bf41684d619e09f427caed2245": { icon: "", url: "/pay_kind_manage", name: "付款方式", id: 9 }, "8db8e74377bd4249b133cbe508d64779": { icon: "icon-member", url: "", name: "员工管理", id: 10 }, "d62b40c137bb4980a6b2425cb1772649": { icon: "icon-order", url: "", name: "订单中心", id: 11 }, "eb2079bb6f714ccc914f5789a8b4e9af": { icon: "", url: "/dist_manage", name: "下发中心", id: "12" }, "d454f5f50c14487e821d0bda2c955fc2": { icon: "icon-package", url: "", name: "钱包管理", id: 13 }, "dc89c75946c2478ea5ced2b7f007e732": { icon: "icon-message", url: "", name: "消息中心", id: 14 }, "696568aacb254cc0a9ffb4566f25addf": { icon: "", url: "/headquarters_staff", name: "总部员工", id: 17 }, "7346ba8a955b475ab088ebf16bffe083": { icon: "", url: "/staff_manage", name: "门店员工", id: 18 }, "eeea647aae234cbc8ae57c41082fa554": { icon: "", url: "/group", name: "分组管理", id: 15 }, "48fc807ac01c4eb68b36072159eb7194": { icon: "icon-cashier", url: "/cashier_monitor", name: "收银台监控", id: 16 } } export default nav <file_sep>/static-hercules/src/ele-account/filters/index.js import tools from '../utils/tools' import {payMap, tradeMap, payStatusMap, payStatusSymbolMap, symbolColorMap} from '../constants' import {dateFormat} from "@2dfire/utils/date"; export default { fen2yuan(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.divide(value, 100, decimals) }, number(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.number(value, decimals) }, money(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.number(tools.divide(value, 100), decimals) }, formatPayType(value) { return payMap[value] || '' }, formatTradeType(value) { return tradeMap[value] || '' }, formatPayStatusStr(value) { return payStatusMap[value] || '' }, formatPayStatusSymbol(value) { return payStatusSymbolMap[value] || '' }, symbolColor(value) { return symbolColorMap[value] || '' }, amountColor(value) { if (!tools.isNumber(value)) { return 'c-ff0033' } if (parseFloat(value) >= 0) { return 'c-ff0033' } else { return 'c-00cc33' } }, date(value, reg) { if (!value) return "" return dateFormat(new Date(value), reg) } } <file_sep>/static-hercules/src/secured-account/filters/index.js import tools from '../utils/tools' import { withdrawStatusMap, withdrawStatusColorMap } from '../constants' import { dateFormat } from '@2dfire/utils/date' export default { fen2yuan(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.divide(value, 100, decimals) }, number(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.number(value, decimals) }, money(value, decimals = 2) { if (!value) return new Number(0).toFixed(decimals) return tools.number(tools.divide(value, 100), decimals) }, subStr(value) { return value.substr(-4) }, withdrawStatusStr(value) { return withdrawStatusMap[value] || '' }, withdrawStatusColor(value) { return withdrawStatusColorMap[value] || '' }, date(value, reg) { if (!value) return '' return dateFormat(new Date(value), reg) }, replaceStr(value){ return value.replace( /^(.+)(.{4})$/, "**** **** *** ***** $2" ) } } <file_sep>/union-entrance/src/views/nav/defaultConfig.js export default { logo: { icon: 'https://assets.2dfire.com/frontend/11dfef885ad8f93b77397febcdd8e127.png', name: '商家管理后台' }, // 需要logo模块 navBar: true, // 需要导航栏模块 accountBar: { icon: 'https://assets.2dfire.com/frontend/efc0bc4b8617669f9722c4a5be419cc7.png', name: '我的账户', arrow: 'https://assets.2dfire.com/frontend/b8253aea45e20bc6c116ca1e01ad7a6e.png' }, // 需要'我的账户'模块 paddingTop: false // 需要自动为body增加上内边距模块 } <file_sep>/static-hercules/src/alipay-agent/libs/rules.js export const ruleList = { /*** * 特约商户资料提交 */ alipayAccount: { isRequired: true, types: 'text', name: '支护宝账号' }, linkman: { isRequired: true, types: 'text', name: '联系人姓名' }, mobile: { isRequired: true, types: 'mobile', name: '联系人手机号' }, email: { isRequired: true, types: 'email', name: '常用邮箱' }, industryType: { isRequired: true, types: 'text', name: '经营类目' }, shopPhoto: { isRequired: true, types: 'img', name: '店铺门头照' } } /** * 特约商户资料提交表单验证 * @param val 用户输入的值 * @param dataVal ruleList对应的key * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ export const inputValIsOk = function(val, dataVal) { let data = ruleList[dataVal] if (typeof val === 'string') { val = val.replace(/(^\s*)|(\s*$)/g, '') //去空格 } //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (data.types === 'boolean') { if (typeof val !== 'boolean') { return { data: false, message: data.name + '不能为空' } } } else { if (!val) { return { data: false, message: data.name + '不能为空' } } } //类型判断 let returnData = getSwitchMatchResult(val, data) return returnData } /** * 表单验证修改联系信息部分 * */ /** * 根据类型判断 */ const getSwitchMatchResult = (val, data) => { let returnData switch (data.types) { case 'number': //验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break case 'mobile': //验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break case 'tel': //验证电话(3-20位数字|连字符) returnData = getMatchResult(/^([0-9-]){3,20}$/, val, data.name) break case 'email': returnData = getMatchResult( /(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name ) break case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break case 'id': // 证件号码 returnData = getMatchResult( /(^[0-9]{15}$)|(^[0-9]{17}([0-9]|X|x)$)/, val, data.name ) break case 'twoToThirty': // 2-30 returnData = getMatchResult( /^([A-Za-z0-9]{2,30})|([\u4e00-\u9fa5]{1,15})|([\u4e00-\u9fa5][\w\W]{2})$/, val, data.name ) break case 'bankCardId': // 银行卡 returnData = getMatchResult( /^[623501|621468|620522|625191|622384|623078|940034|622150|622151|622181|622188|955100|621095|620062|621285|621798|621799|621797|22199|621096|62215049|62215050|62215051|62218849|62218850|62218851|621622|623219|621674|623218|621599|623698|623699|623686|621098|620529|622180|622182|622187|622189|621582|623676|623677|622812|622810|622811|628310|625919|625368|625367|518905|622835|625603|625605|518905]/, val, data.name ) break default: returnData = { data: true } } return returnData } /** * 返回正则效验结果 * @param reg 正则效验规则 * @param val 值 * @param name 效验字段名字 * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ const getMatchResult = (reg, val, name) => { let r r = val.match(reg) if (r == null) { return { data: false, message: '请上传正确的' + name } } else { return { data: true } } } <file_sep>/inside-boss/src/container/visualConfig/components/Loading/index.js import React from 'react' import PropTypes from 'prop-types' import { Modal, Spin } from 'antd' import s from './index.css' export default function Loading(props) { const { tip } = props return <Modal visible={true} closable={false} footer={null} centered={true} wrapClassName={s.modal} width="auto"> <Spin size="large" tip={tip} /> </Modal> } Loading.propTypes = { tip: PropTypes.string, } Loading.defaultProps = { tip: '载入中...', } <file_sep>/static-hercules/src/staff-management/main.js var Vue = require("vue"); var VueRouter = require("vue-router"); var vueResource = require("vue-resource"); var Scss = require('./scss/index.scss'); var App = require('./App.vue'); var InfoInput = require('./components/info-input.vue'); var InfoSelect = require('./components/info-select.vue'); import FireUi from '@2dfire/fire-ui' import { Picker, Popup } from 'mint-ui' import '@2dfire/fire-ui/dist/index.css' import {router} from "./router" import store from './store' Vue.use(FireUi) Vue.use(VueRouter); Vue.use(vueResource); Vue.use(Scss); Vue.component('info-input', InfoInput); Vue.component('info-select', InfoSelect); Vue.component(Picker.name, Picker) Vue.component(Popup.name, Popup) Vue.http.options.credentials = true; new Vue({ el: '#app', router, store, template: "<App/>", components: { App }, }); <file_sep>/inside-boss/src/container/priceTag/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import Main from '../../components/goodTag/main' class goodTagContainer extends Component { constructor(props) { super(props) } render() { const { data, dispatch } = this.props return <Main data={data} dispatch={dispatch} /> } } const mapStateToProps = state => ({ data: state.priceTag }) const mapDispatchToProps = dispatch => ({ dispatch }) export default connect( mapStateToProps, mapDispatchToProps )(goodTagContainer) <file_sep>/inside-chain/src/const/emu-groups-lib.js const Tab = [ { name: "分组管理", path: "/group", title:'', children: [ '/single_shop_goods_add', '/single_shop_goods_edit', ] }, { name: "类别管理", path: "/category", title:'可创建类别便于分组进行分类:例如可创建类别【门店位置】,用于归类机场店分组、火车站店分组、景区店分组等', children: [ '/single_shop_suit_add_first_step', '/single_suit_add_second_step', '/single_suit_edit_first_step', '/single_suit_edit_second_step' ] }, ] export default Tab <file_sep>/inside-chain/src/tools/eslint-config-2dfire-base/index.js const baseGlobals = require('./globals'); const globals = Object.keys(baseGlobals).reduce((p, key) => { p[key] = false; return p; }, {}); module.exports = { extends: ['eslint:recommended'] .concat([ // './rules/best-practices', './rules/errors', './rules/node', './rules/style', './rules/variables', './rules/es6', './rules/imports', './easy', ].map(require.resolve)), globals, parserOptions: { ecmaVersion: 2017, sourceType: 'module', ecmaFeatures: { experimentalObjectRestSpread: true, }, }, rules: { strict: 'error', }, }; <file_sep>/static-hercules/src/ocean/config/configUrl.js import {APP_KEY} from 'apiConfig' const getBaseUrl = (method) => { const appKey = sessionStorage.getItem("appKey"); if (appKey) { /*兼容74版本之前 绑定银行卡->绿洲*/ return `app_key=${appKey}&method=${method}` } else { return `app_key=${APP_KEY}&method=${method}` } } let getUrl = obj => obj.mock ? obj.mockUrl : getBaseUrl(obj.url) let configList = { /** * 查询开通状态 * */ APPLY_STATE: { url: 'com.dfire.boss.center.soa.pay.service.IAuditBluePlanService.getEntityOpenStatus', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 营业模式 * */ SHOP_KIND: { url: 'com.dfire.soa.boss.center.shop.service.IActiveShopService.getOperationModeV2', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false, }, /*** * 省份选择 * */ GET_REGION: { url: 'com.dfire.soa.boss.center.base.service.ISystemService.getAreaInfo', mockUrl: '', mock: false, daily: false }, /** * 开户银行选择 * */ GET_BANK: { url: 'com.dfire.boss.center.soa.pay.service.IBankService.getBanks', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false, daily: false }, /** * 开户省份 * */ GET_BANK_PROVINCE: { url: 'com.dfire.boss.center.soa.pay.service.IBankService.getProvince', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false, daily: false }, /** * 开户城市 * */ GET_BANK_CITY: { url: 'com.dfire.boss.center.soa.pay.service.IBankService.getCities', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 开户银行支行选择 * */ GET_BANK_SUB: { url: 'com.dfire.boss.center.soa.pay.service.IBankService.getSubBanks', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 发送验证码 * */ SEND_CODE: { url: 'com.dfire.boss.center.soa.pay.service.IAuditBluePlanService.sendSubmitSmsCode', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 申请资料查询 * */ GET_SHOP_INFO: { url: 'com.dfire.boss.center.soa.pay.service.IAuditBluePlanService.getAuditInfo', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 临时保存申请资料 * */ GET_SAVE_SHOP_INFO: { url: 'com.dfire.boss.center.soa.pay.service.IAuditBluePlanService.saveApply', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false }, /** * 提交申请资料 * */ GET_SUBMIT_SHOP_INFO: { url: 'com.dfire.boss.center.soa.pay.service.IAuditBluePlanService.submitApply', mockUrl: '/api/com.dfire.soa.audit.service.BlueOcean.getEntityOpenStatus', mock: false } }; module.exports = { // 购买详情页 configUrl: (() => { let ConfigUrl = {}; for (let key in configList) { ConfigUrl[key] = getUrl(configList[key]) } return ConfigUrl })() } <file_sep>/static-hercules/src/wechat-direct-con/router.js var Router = require("vue-router"); export var router = new Router({ routes: [{ path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "微信支付特约商户", component: require("./views/index/index.vue") }, { path: "/input/:step", name: "inputs", title: "小微商户", component: require("./views/xiaowei/Input.vue"), children: [{ path: 'first', component: require("./views/xiaowei/InputInformation.vue") }, { path: 'second', component: require("./views/xiaowei/WeChatAudit.vue") }, { path: 'third', component: require("./views/xiaowei/ScanCodeSigning.vue") }, { path: 'fourth', component: require("./views/xiaowei/InfoStartUsing.vue") } ] }, { path: "/merchants/:step", name: "upgrademerchants", title: "升级普通商户", component: require("./views/upgrademerchants/Input.vue"), children: [{ path: 'first', component: require("./views/upgrademerchants/InputInfo.vue") }, { path: 'second', component: require("./views/upgrademerchants/WeChatAudit.vue") }, { path: 'third', component: require("./views/upgrademerchants/ScanCodeSiging.vue") }, { path: 'fourth', component: require("./views/upgrademerchants/InfoStartUsing.vue") } ] }, { path: "/merchantinfo", name: "merchantinfo", title: "商户信息", component: require("./views/upgrademerchants/MerchantInfo.vue") }, { path: "/merchantupgradeinfo", name: "merchantupgradeinfo", title: "商户升级信息", component: require("./views/upgrademerchants/MerchantUpgradeInfo.vue") }, { path: "/editbankcard", name: "editbankcard", title: "修改收款银行卡", component: require("./views/edit/EditBankCard.vue") }, { path: "/edituserinfo", name: "edituserinfo", title: "修改商户信息", component: require("./views/edit/EditUserInfo.vue") } ] }); router.beforeEach((to, from, next) => { // console.log(to,from,next); // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() })<file_sep>/inside-boss/src/container/goods/init.js import { currentAPIUrlPrefix, currentEnvString } from '../../utils/env' const protocol = (currentEnvString === 'PUBLISH' ? 'https://' : 'http://') const templateDomainPrefix = (currentEnvString === 'PUBLISH' || currentEnvString === 'PRE' ? 'ifile' : 'ifiletest') const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query) => { const {entityId, entityType='0', userName, memberId, userId, industry} = query; //零售 if(industry === 3){ var options = { 'item': { industry, entityType, importUrl: currentAPIUrlPrefix + 'merchant/import/v1/menus', importData: { ...APP_AUTH, entityId: "12345678", memberId: memberId, userId: '9993000559496cd70159496cd7580001' }, exportUrl: currentAPIUrlPrefix + 'merchant/export/v1/menus', exportData: { ...APP_AUTH, entityId: entityId, memberId: memberId, userId: userId }, pageNumber:1, templateFile: protocol + templateDomainPrefix + '.2dfire.com/template/merchant/excelImportMenuForRetail.xls', newTemplateFile: 'https://download.2dfire.com/template_file/sku%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.zip', exportBtnText: '导出商品信息', addCateBtnText: '添加分类', isRecharge: false, showSpin: { boole: false, content: '' }, item: { itemList: [], totalRecord: 0 }, childGoodsList:{}, goodsCategoryList: { categoryList: [] } } } //餐饮 }else { var options = { 'item': { industry, importUrl: currentAPIUrlPrefix + 'merchant/import/v1/menus', importData: { ...APP_AUTH, entityId: "12345678", memberId: memberId, userId: '9993000559496cd70159496cd7580001' }, exportUrl: currentAPIUrlPrefix + 'merchant/export/v1/menus', exportData: { ...APP_AUTH, entityId: entityId, memberId: memberId, userId: userId }, pageNumber:1, // templateFile: protocol + templateDomainPrefix + '.2dfire.com/template/merchant/excelImportMenu.xls', templateFile: `https://download.2dfire.com/template_file/excelImportMenu.xls`, exportBtnText: '导出商品信息', isRecharge: false, showSpin: { boole: false, content: '' }, modalVisible:{ boole: false, modalType:'select', }, resultData:null, goodsParams:{ keyWord:'', kindId: '' } } } } return options[key] }; <file_sep>/static-hercules/src/secured-account/main.js import Vue from 'vue' import App from './App' import router from './router' import MaskLayer from './components/mask-layer' import ScrollLoading from './components/scroll-loading' import ShopPhoto from 'src/secured-account/components/ShopPhoto.vue' import ShopInput from 'src/secured-account/components/ShopInput' import ShopSelect from 'src/secured-account/components/ShopSelect' import store from './store' import { Picker } from 'mint-ui' import toast from './components/toast/index.js' import confirm from './components/confirm/index.js' import filters from './filters/index' import './scss/index.scss' Object.keys(filters).map(key => { Vue.filter(key, filters[key]) }) Vue.use(toast) Vue.use(confirm) Vue.component('info-photo', ShopPhoto) Vue.component('info-input', ShopInput) Vue.component('info-select', ShopSelect) Vue.component('MaskLayer', MaskLayer) Vue.component('ScrollLoading', ScrollLoading) Vue.component(Picker.name, Picker) Vue.config.productionTip = false router.beforeEach((to, from, next) => { document.title = to.meta.title // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, store, template: '<App/>', components: { App } }) <file_sep>/inside-boss/src/components/goodsProperty/format.js const Format = { /** * 格式化规格列表 * @param data */ formatSpec(data) { const result = [] if(data.length>0) { data.forEach( item => { const { name, charId='', skuValueList=[], status } = item const list = [] if(skuValueList.length > 0) { skuValueList.forEach(function(item) { const { name, status, charId='', charPropertyId='' } = item list.push({ name: name, enable: status, id: charId, propertyId: charPropertyId, }) }) } result.push({ name, id: charId, list, idFold: false, enable: status, }) }) return result } return data }, /** * 更新规格列表 * @param data 规格列表 * @param specId 列表Id */ updateSpecList(data=[], specId) { data.forEach( item => { const { id, list=[] } = item if(list.length > 0) { list.forEach(function(value) { let status = value.enable if(value.id === specId) { value.enable = status === 0 ? 1 : 0 } }) } let status = item.enable if(id === specId) { status = status === 0 ? 1 : 0 } item.enable = status }) return data }, /** * 格式化分类列表 * @param data */ formatCateList(data) { let result = [] let tier = 1 if(data.length > 0) { data.forEach( (item, i) => { let list = [] const {categoryName, categoryId, categoryList = [], code='', groupCategoryId='', parentId='', chain=false } = item if(categoryList.length>0) { list = this.recursionCate(categoryList, tier) } const obj = { tier, code, id: categoryId, key: categoryId, type: '商品分类', name: categoryName, groupCategoryId, parentId, chain, } if(list.length > 0) { obj.children = list } result.push(obj) }) return result } return data }, /** * 递归分类列表 * @param data * @param tier 级别 */ recursionCate(data, tier) { const result = [] tier += 1 data.forEach( item => { let list = [] const {categoryName, categoryId, categoryList = [], code='', parentId='', groupCategoryId='', chain=false} = item if(categoryList.length>0) { list = this.recursionCate(categoryList, tier) } const obj = { tier, code, id: categoryId, key: categoryId, name: categoryName, type: '商品分类', groupCategoryId, parentId, chain, } if(list.length > 0) { obj.children = list } result.push(obj) }) return result }, /** * 商品分类扁平化 * @param data */ formatCateListFlat(data) { let result = [] if(data.length > 0) { result = this.recursionFlat(data, result) return result } return data }, /** * 一个递归的函数,用来处理商品分类 * @param data * @param result * @returns {*} */ recursionFlat(data, result) { data.forEach( (item, i) => { const {categoryName, categoryId, categoryList = [], chain, code=''} = item result.push({ name: categoryName, id: categoryId, chain, code, }) if(categoryList.length>0) { this.recursionFlat(categoryList, result) } }) return result } } export default Format <file_sep>/inside-boss/build.sh #!/usr/bin/env bash npm update @2dfire/union-scripts npm install NODE_ENV=production node ./node_modules/@2dfire/union-scripts/bin/union-scripts build NODE_ENV=production node ./node_modules/@2dfire/union-scripts/bin/union-scripts deploy $1 <file_sep>/inside-boss/src/components/goodCombinedEdit/combinedDetailTable.js import { Table, Input, Icon, Button, Popconfirm, Modal } from 'antd' import React, { Component } from 'react' import s from './combinedDetailTable.css' import * as action from '../../action' import Format from './format' class EditableCell extends React.Component { state = { value: this.props.value, editable: false } handleChange = e => { const value = e.target.value this.setState({ value }) } check = () => { this.setState({ editable: false }) if (this.props.onChange) { this.props.onChange(this.state.value) } } edit = () => { this.setState({ editable: true }) } render() { const { value, editable } = this.state return ( <div className="editable-cell"> {editable ? ( <div > <Input value={value} onChange={this.handleChange} onPressEnter={this.check} /> <Icon type="check" className="editable-cell-icon-check" onClick={this.check} /> </div> ) : ( <div style={{width:'200px',height:'20px'}}> {value || ' '} <div onClick={this.edit} style={{ width: '100%', height: '100%' }} ></div> </div> )} </div> ) } } class EditableTable extends React.Component { constructor(props) { super(props) this.state = { showDelModal: false } this.columns = [ { title: '商品名称', dataIndex: 'itemName' }, { title: '规格', dataIndex: 'skuDesc' }, { title: '单位', dataIndex: 'unitName' }, { title: '组合数量', dataIndex: 'num', render: (text, record) => ( <div> {record.flag !== 1 && ( <Input style={{ width: '100px', border: '0' }} defaultValue={record.num} onBlur={this.onCellChange.bind(this, record)} ></Input> )} {record.flag === 1 && <span>{record.num}</span>} </div> ) }, { title: '单价', dataIndex: 'price' }, { title: '小计', dataIndex: 'subtotal', }, { title: '库存', dataIndex: 'currentStock' }, { title: '操作', key: 'action', render: (text, record) => ( <a onClick={this.showDelModal.bind(this, record)}>删除</a> ) } ] } childItems = [] openNumInput(){ } onCellChange(record,e){ const value = parseInt(e.target.value) const {dataSource=[]} = this.props const target = dataSource.find(item => item.itemId === record.itemId ) if (target) { const index = dataSource.indexOf(target) dataSource[index].num=value dataSource[index].subtotal = value * target.price const { dispatch } = this.props dispatch(action.setSelectCombinedGoodsList(dataSource)) } } onDelete = key => { const dataSource = [...this.state.dataSource] this.setState({ dataSource: dataSource.filter(item => item.key !== key) }) } cancelDelSpecGood() { this.setState({ showDelModal: false }) } showDelModal(record) { this.setState({ showDelModal: true, willDelGood: record }) } delSpecGood() { const { willDelGood } = this.state const { dispatch, dataSource = [] } = this.props const result = dataSource.findIndex(v => { return v.skuId == willDelGood.skuId }) const len = dataSource.length dataSource.splice(result, 1) dataSource.splice(len - 1, 1) dispatch(action.setSelectCombinedGoodsList(dataSource)) this.setState({ showDelModal: false }) } render() { const { dataSource = [] } = this.props const formatCombinedDetailSource = Format.formatCombinedDetailSource( dataSource ) const { showDelModal } = this.state const columns = this.columns return ( <div className={s.combinedGoodsDetailTable}> <Table bordered dataSource={formatCombinedDetailSource} columns={columns} /> <Modal title="确认弹窗" visible={showDelModal} onOk={() => this.delSpecGood()} onCancel={() => this.cancelDelSpecGood()} > 确定要删除吗? </Modal> </div> ) } } export default EditableTable <file_sep>/static-hercules/src/ocean/libs/rules.js // 字符串长度2~10 const twoToTen = /^\w{2,10}$/ // 字符串长度1~15 const oneToFifteen = /^\w{1,15}$/ // 字符串1~40 const oneToForty = /^\w{1,40}$/ // 验证手机 const checkTel = /^[1][0-9]{10}$/ export const ruleList = { /*** * step1 */ shopName: { isRequired: true, types: 'text', name: '店铺名称' }, shopSimpleName: { isRequired: true, types: 'text', name: '店铺简称' }, shopKind: { isRequired: true, types: 'text', name: '营业模式' }, merchantType: { isRequired: true, types: 'text', name: '商户类型' }, shopPhone: { isRequired: true, types: 'tel', name: '店铺电话' }, provinceName: { isRequired: true, types: 'text', name: '省' }, cityName: { isRequired: true, types: 'text', name: '市' }, townName: { isRequired: true, types: 'text', name: '区' }, detailAddress: { isRequired: true, types: 'text', name: '详细地址' }, contactName: { isRequired: true, types: 'text', name: '联系人姓名' }, contactMobile: { isRequired: true, types: 'mobile', name: '联系人手机号' }, contactEmail: { isRequired: true, types: 'email', name: '邮箱' }, // ====================== /** * step2 * */ corporationName: { isRequired: true, types: 'text', name: '法人姓名' }, corporationLinkTel: { isRequired: true, types: 'mobile', name: '联系电话' }, certificateType: { isRequired: true, types: 'text', name: '证件类型' }, certificateNum: { isRequired: true, types: 'text', name: '证件号码' }, certificateFrontPic: { isRequired: true, types: 'img', name: '证件照片正面' }, certificateBackPic: { isRequired: true, types: 'img', name: '证件照片反面' }, creditCode: { isRequired: true, types: 'text', name: '统一社会信用代码' }, businessLicenseName: { isRequired: true, types: 'text', name: '营业执照名称' }, businessLicensePic: { isRequired: true, types: 'text', name: '营业执照' }, otherCertificationPic: { isRequired: false, types: 'text', name: '其他证明' }, businessCert: { isRequired: false, types: 'img', name: '开户许可证照片' }, // ============================ /** * step3 * */ accountType: { isRequired: true, types: 'text', name: '账户类型' }, accountName: { isRequired: true, types: 'text', name: '开户人名称' }, bankName: { isRequired: true, types: 'text', name: '开户银行' }, bankProvince: { isRequired: true, types: 'text', name: '开户省份' }, bankProvinceId: { isRequired: false, }, bankCity: { isRequired: true, types: 'text', name: '开户城市' }, bankCityId: { isRequired: false }, bankSubName: { isRequired: true, types: 'text', name: '开户支行' }, idType: { isRequired: true, types: 'text', name: '开户人证件类型' }, idNumber: { isRequired: true, types: 'text', name: '开户人证件号码' }, idCardFrontPic: { isRequired: true, types: 'img', name: '开户人证件照片正面' }, idCardBackPic: { isRequired: true, types: 'img', name: '开户人证件照片反面' }, bankCode: { isRequired: false, }, bankSubCode: { isRequired: false, }, accountMobile: { isRequired: true, types: 'mobile', name: '收款银行账号预留手机' }, accountNumber: { isRequired: true, types: 'text', name: '收款银行账号' }, // ================================== /** * step4 * */ // needMaterial: { // isRequired: true, // types: 'boolean', // name: '是否需要支付宝台牌物料' // }, doorPic: { isRequired: true, types: 'img', name: '门头照' }, checkoutCounterPic: { isRequired: true, types: 'img', name: '收银台' }, shopEvnPic: { isRequired: true, types: 'img', name: '店内环境照' }, otherPlatformPic: { isRequired: true, types: 'img', name: '其他平台图片' }, smsCode: { isRequired: true, types: 'text', name: '验证码' } }; /** * 表单验证 * @param val 用户输入的值 * @param dataVal ruleList对应的key * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ export const inputIsOk = function (val, dataVal) { let data = ruleList[dataVal] //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return {data: true} } if (data.types === 'boolean') { if (typeof val !== 'boolean') { return {data: false, message: data.name + '不能为空'} } } else { if (!val) { return {data: false, message: data.name + '不能为空'} } } //类型判断 let returnData; switch (data.types) { case "number"://验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break; case 'mobile'://验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break; case "tel"://验证电话 returnData = getMatchResult(/^[0-9]{5,15}$/, val, data.name) break; case 'email': returnData = getMatchResult(/(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name) break; case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break; default: returnData = {data: true} } return returnData } /** * 返回正则效验结果 * @param reg 正则效验规则 * @param val 值 * @param name 效验字段名字 * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ const getMatchResult = (reg, val, name) => { let r; r = val.match(reg); if (r == null) { return {data: false, message: '请上传正确的' + name} } else { return {data: true} } } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/goods/index.js import Editor from './GoodsEditor.js' import Preview from './GoodsPreview.js' export default { type: Editor.designType, editor: Editor, preview: Preview }; <file_sep>/static-hercules/src/base/utils/LikeCookie.js import AppUtil from './AppUtil' export default { setItem (key, value) { AppUtil.setToken(value) } }<file_sep>/inside-chain/src/tools/feed-back-auto/utils.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.filterOptions = exports.createHide = exports.createShowWithLevel = exports.createShow = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _eventEmitter = require('./eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 产生参数 * @param {String|Object} arg1 message或是options * @param {Function|null} callback 回调 * @param {Object} defaultOptions 默认参数 * @return {Object} 可以召唤弹窗的完整参数 */ function filterOptions() { var arg1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var callback = arguments[1]; var defaultOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callbackOptions = typeof callback === 'function' ? { callback: callback } : {}; if (typeof arg1 === 'string') { return _extends({}, defaultOptions, { content: arg1 }, callbackOptions); } if ((typeof arg1 === 'undefined' ? 'undefined' : _typeof(arg1)) === 'object') { return _extends({}, defaultOptions, arg1, callbackOptions); } throw new Error('arg1 不是字符串也不是对象'); } /** * 创建show方法 * @param {String} type 弹窗类型 * @param {Object} options 默认参数 * @return {Function} show方法 */ function createShow(type, options) { /** * show方法 * @param {String|Object} arg1 message或是options * @param {Function|null} callback 回调 * @return {Void} */ return function show(arg1, callback) { return _eventEmitter2.default.show(type, filterOptions(arg1, callback, options)); }; } /** * 创建show方法, 第二个参数为level * @param {String} type 弹窗类型 * @param {String} level 弹窗级别 * @return {Function} show方法 */ function createShowWithLevel(type, level) { return createShow(type, { level: level }); } function createHide(type) { return function hide() { _eventEmitter2.default.hide(type); }; } exports.createShow = createShow; exports.createShowWithLevel = createShowWithLevel; exports.createHide = createHide; exports.filterOptions = filterOptions;<file_sep>/union-entrance/src/config/api_getUser.js import Requester from '@/base/requester' import API from '@/config/api' import Object from '@2dfire/utils/object' export default token => new Promise((resolve, reject) => { let params = { menuVersion: 11 //菜单版本号 } const headers = { token: token, } Requester.get(API.GET_USER_INFO, { params: params, headers: headers }) .then(data => { // 数据处理 let datas = data.data console.log(datas) var userInfo = { name: datas.name, picture: datas.picture || 'https://assets.2dfire.com/frontend/31648f04d3ceb9ce7b776bb46c729d0c.png', mobile: datas.mobile, countryCode: datas.countryCode, userId: datas.userId, memberId: datas.membereId } if (datas.entityVo) { var shopInfo = { entityId: datas.entityVo.entityId, entityName: datas.entityVo.entityName, entityType: datas.entityVo.entityType, industry: datas.entityVo.industry, loginEntityId: datas.loginEntityId, entityTypeId: datas.entityVo.entityTypeId, isInLeague: datas.entityVo.isInLeague, logo: datas.entityVo.logo || 'https://assets.2dfire.com/frontend/8ffcc382dc07323a2dc4cb8f2c6ef468.png', roleName: '' } if (!Object.isEmpty(datas.roleVo)) { shopInfo.roleName = datas.roleVo.roleName } if (datas.entityVo.entityCode) { shopInfo.entityCode = datas.entityVo.entityCode } } if (datas.rootMenuList) { var menuIdList = [] datas.rootMenuList.forEach(function (item) { menuIdList.push(item.menuId) }) } // 将登陆有关的信息存入到entrance中 // const entrance = { // userInfo: userInfo, // shopInfo: shopInfo, // menuIdList: menuIdList, // loginType: datas.loginType // } // Cookie.setItem("entrance", JSON.stringify(entrance)); let entrance = { userInfo: userInfo, shopInfo: shopInfo, menuIdList: menuIdList, token: token } // 判断为手机号登录 if (datas.loginType == 2) { entrance.loginType = datas.loginType } else { entrance.loginType = 1 } resolve(entrance) //self.jump('welcome.html') }) .catch(e => { //self.$Message.error(e.result.message) reject(e) }) }) <file_sep>/static-hercules/src/marketPlan/router.js import Vue from 'vue'; import Router from 'vue-router'; import Index from './views/index/index.vue'; import Detail from './views/detail/index.vue'; import Preview from './views/preview/index.vue'; Vue.use(Router); export default new Router({ routes: [ { path: '*', redirect: '/index' }, { path: "/index", name: "index", component: Index }, { path: "/detail", name: "detail", component: Detail }, { path: "/preview", name: "preview", component: Preview }, ] })<file_sep>/inside-chain/src/store/modules/components/shop-select.js import Requester from '@/base/requester' import catchError from '@/base/catchError' import API from '@/config/api' import Obj from '@2dfire/utils/object' import Vue from 'vue'; import iView from "iview"; import Cookie from '@2dfire/utils/cookie' Vue.use(iView); let shopInfo = { entityId:'' } if(Cookie.getItem('entrance') != undefined){ shopInfo = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).shopInfo } let Message = iView.Message; const shopSelect = { namespaced: true, state: { shops:[], shopFilter: { keyword: '', areas: [], area_show: [], brands: [], joinModes: [ { name: '全部', entityId: '-1', }, { name: '加盟', entityId: 0, }, { name: '直营', entityId: 1, }, { name: '合作', entityId: 2, }, { name: '合营', entityId: 3, }, ], organs: [], organs_show: [], organs_checked: [], areas_checked: [], showFilterOrgan: true, // 选中的品牌id selected_brand: '', // 选中的加盟类型 默认全部 -1 selected_join: '-1', // 选中的组织id selected_organ: '', // 省id selected_provinceId: '', // 城市id selected_cityId: '', // 区县id selected_townId: '', //applyType applyType:'', //类别ID categoryIds:[], //分组ID groupIds:[], excludeCategoryId:'', currentGroupId:'' }, shopList: [], category:[] }, mutations: { _getShops(state, shops) { state.shops = [].concat(shops) }, _selectBrand(state, brands) { state.shopFilter.brands = brands }, _setBrand(state, selected_brand) { state.shopFilter.selected_brand = selected_brand }, _selectJoinModes(state, joinModes) { state.shopFilter.joinModes = joinModes }, _setJoinType(state, selected_join) { state.shopFilter.selected_join = selected_join }, _selectOrgan(state, organs) { state.shopFilter.organs_show = organs }, _selectArea(state, areas) { state.shopFilter.areas = areas }, _setOrgan(state, organ) { state.shopFilter.selected_organ = organ }, _setOrganChecked(state, organs_checked) { state.shopFilter.organs_checked = organs_checked }, _setAreasChecked(state, areas_checked) { state.shopFilter.areas_checked = areas_checked }, _setAreas(state, areas) { state.shopFilter.areas = areas }, _setAllArea(state) { state.shopFilter.selected_provinceId = ''; state.shopFilter.selected_cityId = ''; state.shopFilter.selected_townId = ''; }, _setProvinceId(state, id) { state.shopFilter.selected_provinceId = id; state.shopFilter.selected_cityId = ''; state.shopFilter.selected_townId = ''; }, _setCityId(state, id) { state.shopFilter.selected_cityId = id; state.shopFilter.selected_townId = ''; }, _setTownId(state, id) { state.shopFilter.selected_townId = id }, _setKeyword(state, word) { state.shopFilter.keyword = word; }, _clearFilter(state) { state.shopFilter.selected_brand = ''; state.shopFilter.selected_organ = ''; state.shopFilter.selected_provinceId = ''; state.shopFilter.selected_cityId = ''; state.shopFilter.selected_townId = ''; state.shopFilter.selected_join = '-1'; state.shopFilter.applyType = ''; state.shopFilter.categoryIds = []; state.shopFilter.groupIds = []; }, _setHideOrgan(state) { state.shopFilter.showFilterOrgan = false; }, _setAllShops(state, shops) { state.shops = shops }, _setShopList(state, list) { state.shopList = list }, _clearShopList(state) { state.shopList = [] }, _setNoSearchItems(state, res) { state.noSearchItems = res }, _setApplyType(state,data){ state.shopFilter.applyType = data }, _category(state,data){ state.category = [].concat(data) }, _categoryIds(state,data){ state.shopFilter.categoryIds = [].concat(data) }, _groupIds(state,data){ state.shopFilter.groupIds = [].concat(data) }, _excludeids(state,data){ console.log(data) state.shopFilter.excludeCategoryId=data.itemClassId state.shopFilter.currentGroupId=data.itemId } }, actions: { // 选择品牌 selectBrand(context, entityId) { let brands = context.state.shopFilter.brands.concat(); brands.map(v => { if (v.entityId == entityId) { v.active = true; } else { v.active = false; } }); context.commit('_selectBrand', brands) context.commit('_setBrand', entityId) context.dispatch('initShops'); }, // 选择品牌 selectJoin(context, entityId) { let modes = context.state.shopFilter.joinModes.concat(); modes.map(v => { if (v.entityId == entityId) { v.active = true; } else { v.active = false; } }); console.log('modes:',modes) context.commit('_selectJoinModes', modes) context.commit('_setJoinType', entityId) context.dispatch('initShops'); }, // 获取筛选项品牌 getFilterBrands(context, params) { // let data = [ // { // name: '外婆家', // entityId: '123' // }, // { // name: '炉鱼', // entityId: '223' // }, // ] Requester.get(API.GET_ALL_BRANDS, {params: params}).then(data => { console.log('bnrands:', data) let true_data = []; if (data.data && data.data.length > 0) { true_data.push({ name: '全部', entityId: '' }) data.data.map(v => { true_data.push({ name: v.name, entityId: v.entityId }) }) } else { true_data.push({ name: '全部', entityId: '' }) } context.commit('_selectBrand', true_data) }).catch(e => { catchError(e); }); }, setApplyType({commit},params){ commit('_setApplyType',params) }, // 获取筛选项 - 分支机构 getOrganMap(context, params) { Requester.get(API.GET_ORGAN_MAP).then(data => { let true_data = data.data; let formate_data = [{ branchName: '全部', entityId: '', children: true_data }] if (Obj.isEmpty(data)) { context.commit('_setHideOrgan'); } context.commit('_selectOrgan', true_data); context.commit('_setOrganChecked', formate_data); }).catch(e => { catchError(e); }); }, //获取分类分组 getCategory({commit},params){ // API.getBaseGroup({req:JSON.stringify({})}) Requester.post(API.GET_BASE_GROUP,{req:JSON.stringify({})},{emulateJSON: true}) .then((res)=> { console.log(res.data) let calssList = {} res.data.map(item=>{ if(calssList[item.categoryId]){ calssList[item.categoryId].groupList.push({ entityId:item.id, name:item.name, categoryId:item.categoryId }) }else{ calssList[item.categoryId] = { categoryId:item.categoryId, categoryName:item.categoryName, activeId:'', groupList:[{ entityId:'', name:'全部', categoryId:item.categoryId }].concat([{ entityId:item.id, name:item.name, categoryId:item.categoryId }]) } } }) if(params.itemClassId){ delete calssList[params.itemClassId] } console.log(Object.values(calssList)) commit('_category',Object.values(calssList)) }).catch(e=>{ catchError(e) }) }, // 获取筛选项 - 区域 getArea(context) { Requester.get(API.GET_ALL_AREAS).then(data => { console.log('get', data); let true_data = [{ id: '', name: '全部', type: 'all', subList: data.data }] context.commit('_setAreas', data.data); context.commit('_setAreasChecked', true_data) }).catch(e => { catchError(e); }); }, // 筛选商家 - 选择机构 selectOrgan(context, item) { let organs = context.state.shopFilter.organs_show.concat(); let organs_checked = context.state.shopFilter.organs_checked.concat(); let sub_organs = []; organs.map(v => { console.log('entityId', v.entityId, item.entityId) if (v.entityId == item.entityId) { if (v.children && v.children.length > 0) { sub_organs = v.children; organs_checked.push(item) console.log(organs_checked) context.commit('_setOrganChecked', organs_checked) } else { v.active = true; sub_organs = organs; } console.log('sub', sub_organs) } }) context.commit('_selectOrgan', sub_organs) context.commit('_setOrgan', item.entityId) context.dispatch('initShops'); }, // 筛选商家 -选择区域 selectArea(context, item) { let areas = context.state.shopFilter.areas.concat(); let areas_checked = context.state.shopFilter.areas_checked.concat(); let sub_areas = []; areas.map(v => { if (v.id == item.id) { if (v.subList && v.subList.length > 0) { sub_areas = v.subList; areas_checked.push(item) console.log(areas_checked) context.commit('_setAreasChecked', areas_checked) } else { v.active = true; sub_areas = areas; } console.log('sub', sub_areas) } }); context.commit('_selectArea', sub_areas) if (item.type == 'province') { context.commit('_setProvinceId', item.id) } else if (item.type == 'city') { context.commit('_setCityId', item.id) } else if (item.type == 'town') { context.commit('_setTownId', item.id) } else { context.commit('_setAllArea') } context.dispatch('initShops'); }, //筛选分组 selectFilterGroup({commit,state,dispatch},item){ let categoryIds = [] let groupIds = [] let category = state.category.concat() category.map(i=>{ if(i.categoryId === item.categoryId){ i.activeId = item.entityId } i.activeId !== ''?groupIds.push(i.activeId):'' i.activeId !== ''?categoryIds.push(i.categoryId):'' }) commit('_category',category) commit('_categoryIds',categoryIds) commit('_groupIds',groupIds) dispatch('initShops'); }, excludeids({commit},params){ commit('_excludeids',params) }, // 地区/机构 方法类似 // 机构筛选项-选择回退 backOrgan(context, params) { let organs_checked = context.state.shopFilter.organs_checked.concat(); console.log(organs_checked.length, params.index) let new_organ = organs_checked.splice(0, params.index + 1) context.commit('_setOrganChecked', new_organ) context.commit('_selectOrgan', params.item.children) context.commit('_setOrgan', params.item.entityId) context.dispatch('initShops'); }, // 地区/机构 方法类似 // 机构筛选项-选择回退 backArea(context, params) { let areas_checked = context.state.shopFilter.areas_checked.concat(); let item = params.item; console.log(areas_checked.length, params.index) let new_organ = areas_checked.splice(0, params.index + 1) context.commit('_setAreasChecked', new_organ) context.commit('_selectArea', params.item.subList) if (item.type == 'province') { context.commit('_setProvinceId', item.id) } else if (item.type == 'city') { context.commit('_setCityId', item.id) } else if (item.type == 'town') { context.commit('_setTownId', item.id) } else { context.commit('_setAllArea') } context.dispatch('initShops'); }, // 清空筛选项 clearFilter(context) { context.commit('_clearFilter') context.commit('_getShops',[]) }, initShops(context) { console.log('init shops') context.dispatch('getShops', {}); }, // 获取商家列表 getShops(context, params) { console.log('get shops') // 获取筛选项 let filter = context.state.shopFilter; let filter_params = { plateEntityId: filter.selected_brand, provinceId: filter.selected_provinceId, cityId: filter.selected_cityId, townId: filter.selected_townId, branchEntityId: filter.selected_organ, joinMode: filter.selected_join, applyType: filter.applyType, // categoryIds:filter.categoryIds, groupIdList:filter.groupIds, excludeCategoryId:filter.excludeCategoryId, currentGroupId:filter.currentGroupId, } console.log('filter_params: ',params,filter_params) // 整个参数 params = Object.assign(params, filter_params,{brandEntityId:shopInfo.entityId}) if (filter.keyword) { params.keyword = filter.keyword } console.log(params) Requester.post(API.QUERY_ALL_CHAIN_SHOP_LIST, {req: JSON.stringify(params)},{emulateJSON: true}).then(data => { // 数据处理 // ... console.log('empty?', Obj.isEmpty(data.data)) let true_data = { total: 0, shops: [] } // if (!Obj.isEmpty(data.data)) { // let dealImg = new Img.imageUtil() // true_data.total = data.data.total; // data.data.list.map(v => { // true_data.shops.push({ // entityId: v.entityId, // // title: v.name, // code: v.code, // desc: v.plateName || '-', // phone: v.phone1 || '-', // linkman: v.linkman || '-', // employeeAmount: v.employeeAmount, // foundDate: v.foundDate || '-', // status: '', // image: v.shopImg || '', // // image: v.shopImg && dealImg.getRectImageUrl({imageUrl: v.shopImg}) || '', // // type: joinModeIcon[v.joinMode], // address: v.address || '-', // }) // }) // } if(!Obj.isEmpty(data.data)){ context.commit('_getShops', data.data); }else{ context.commit('_getShops', []); } // 提交mutation }).catch(e => { catchError(e); }); }, checkAllShop(context, type) { let shopList = context.state.shops.concat(); if(type){ shopList.map(item=>{ if(item.isExclude == '-1'){ item.checked = true } }) }else{ shopList.map(item=>{ if(item.isExclude == '-1'){ item.checked = false } }) } context.commit('_setAllShops', shopList) }, checkOneShop(context, params){ let shopList = context.state.shops.concat(); shopList.map(item=>{ if(item.entityId == params.entityId){ if(params.type){ item.checked = true } else{ item.checked = false } } }) context.commit('_setAllShops', shopList) }, // 选中一个门店 selectShop(context, params) { let tmp_list = context.state.shopList.concat(); tmp_list.map(item => { if (item.entityId === params.entityId) { item.active = !item.active } }) context.commit('_setShopList', tmp_list) }, // 取消选择一个门店 cancelShop(context, params) { let tmp_list = context.state.shopList.concat(); tmp_list.splice(params.index, 1); context.commit('_setShopList', tmp_list) }, // 将选择组件中的门店加入下发的门店列表内 joinShop(context, params) { // 所有门店列表 let shop_list = params.concat(); // 已选的门店列表 let ori_list = context.state.shopList.concat(); // 临时存储选中门店列表 let tmp_list = []; // 选择门店总数 let allCount = 0; // 重复门店数量 let repeatCount = 0; // 要提交的门店列表 let new_list = []; // 计算选中的门店数 shop_list.map(v => { if (v.checked) { // 获取选中的门店,推入临时列表中 tmp_list.push({ name: v.name, entityId: v.entityId, active: false }); allCount++; v.checked = false; } }); // 计算重复的门店数 tmp_list.map((w, i) => { ori_list.map(u => { if (u.name === w.name) { repeatCount++; } }) }); // 合并已选和新选的门店 new_list = ori_list.concat(tmp_list); // 判断三种情况 全部重复、部分重复、无重复 if (repeatCount === allCount) { Message.info("您添加了" + allCount + "个门店,其中重复" + repeatCount + "个,已自动为您合并。") } else if (repeatCount > 0 && repeatCount !== allCount) { // 选择门店去重 let hash = {}; new_list = new_list.reduce(function (item, next) { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []); Message.info("您添加了" + allCount + "个门店,其中重复" + repeatCount + "个,已自动为您合并。") context.commit('_setShopList', new_list) } else { context.commit('_setShopList', new_list) } }, // 清空所选门店 clearShops(context) { context.commit('_clearShopList'); }, // 清空所选门店 setNoSearchItems(context, params) { let noSearchItems = false; console.log('setNoSearchItems',params.goodsName, params.goodsName, params) if(!params.goodsName && !params.kindId){ noSearchItems = true; } context.commit('_setNoSearchItems', noSearchItems); }, }, getters: { data(state) { return state; }, shopFilter(state) { return state.shopFilter }, shops(state) { return state.shops }, shopList(state) { return state.shopList }, noSearchItems(state) { return state.noSearchItems }, categoryList(state){ return state.category } } }; export default shopSelect; <file_sep>/static-hercules/src/wechat-direct-con/libs/hintToast.js /** * Created by zyj on 2018/4/13. */ /** * 动态添加css * @param code css样式 * */ const _loadCssCode = function (code) { let style = document.createElement('style'); style.type = 'text/css'; style.rel = 'stylesheet'; style.appendChild(document.createTextNode(code)); let head = document.getElementsByTagName('head')[0]; head.appendChild(style); }; export default { show(content) { let dom = document.getElementsByClassName('hint-toast') if (dom && dom.length) { dom[0].classList.remove('hide') } else { let para = document.createElement("div") para.innerHTML = ` <div class="mask"></div> <div class="main"> <div class="title">提示</div> <div class="content">${content}</div> <button class="btn">确定</button> </div> ` para.className = 'hint-toast' para.getElementsByTagName('button')[0].onclick = () => { dom[0].classList.add('hide') } para.querySelector('.mask').onclick = () => { dom[0].classList.add('hide') } _loadCssCode(`.hint-toast .mask { position: fixed; top: 0; left: 0; bottom: 0; right: 0; background: rgba(0, 0, 0, 0.5); } .hint-toast .main { background: rgba(255, 255, 255, 0.9); border-radius: 13PX; width: 270PX; height: 144PX; position: fixed; top: 50%; left: 50%; margin-top: -72PX; margin-left: -135PX; text-align: center; } .hint-toast .main .title { font-size: 15PX; color: #333333; letter-spacing: 0; text-align: center; line-height: 20PX; margin-top: 20PX; } .hint-toast .main .content { font-size: 13PX; color: #666666; letter-spacing: 0; text-align: center; line-height: 18PX; height: 40px; padding: 0 15PX; margin-top: 15PX; } .hint-toast .main .btn { display: block; border: 0; background: transparent; font-size: 15px; color: #0088FF; letter-spacing: 0; text-align: center; line-height: 44PX; border-top: 1px solid #C8C7CC; width: 100%; } `); document.body.appendChild(para) } } }<file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/pictureText/pictureTextPreview.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Carousel } from 'antd'; // debugger import style from './pictureTextPreview.css' export default class pictureTextPreview extends PureComponent { static propTypes = { value: PropTypes.object, // 用来和 Design 交互 design: PropTypes.object, }; state= { defaultImg: 'https://img.yzcdn.cn/public_files/2018/03/08/837f3d12e14b299778ae5fea5c05a3a3.png' } textPriew = () => { return <div className={style.listText}>aaa</div> } initPreiw = () => { const { config } = this.props.value const { mode, items } = config const { defaultImg} = this.state return( items.map((item) => mode == '文字导航'? <div style={createStyle(config)} className={style.listText}>{item.text}</div>: <div className={style.pictureTextInfo} style={createStyle(config)}> <img className={style.pictureTextLi} style={createStyle(config)} src={item.picture ? item.picture : defaultImg} /> {mode == '图文导航' && <p className={style.pictureTextName}>{ item.text }</p>} </div> ) ) } render() { return ( <div className="zent-design-component-pictureText-preview"> <div className={style.pictureTextList}> {this.initPreiw()} </div> </div> ); } } function createStyle(config) { const { items, textColor } = config const pictureWidth = 375 const pictureLiWidth = (pictureWidth / items.length) - (3 * (items.length - 1)) return { width: items.length ==1 ? `${pictureWidth}px` : `${pictureLiWidth}px`, color: textColor } } <file_sep>/union-entrance/src/views/nav/util/cookie.js import cookie from '@2dfire/utils/cookie' const getCookie = function(name, isParse = true) { let res = cookie.getItem(name) if (isParse) { try { res = JSON.parse(res) || {} } catch (e) { return {} } } return res } const setCookie = (name, value) => { cookie.setItem(name, value) } const clearCookies = function() { cookie.clear() } export default { getCookie, setCookie, clearCookies, delCookie: cookie.removeItem } <file_sep>/inside-boss/src/components/goodCombinedEdit/baseInfo.js import React, { Component } from 'react' import { Form, Select, Input, Switch, Cascader, Upload, Icon, Message } from 'antd' import Card from './card' import classnames from 'classnames' import styles from './baseInfo.css' import Format from './format' import UploadImage from '../goodEdit/uploadImage' import * as action from "../../action"; import { currentIMGUrl } from '../../utils/env' import * as bridge from '../../utils/bridge' const Option = Select.Option const FormItem = Form.Item; const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 }, }; class BaseInfo extends Component { constructor(props) { super(props) this.state = { // 新建分类弹窗展示 isShowAddCatePop: false, // 新建单位弹窗展示 // isShowAddUnitPop: false, // 运费模版 freightOptions: [ { label: '统一运费', value: '1' }, { label: '运费模版', value: '2' } ], // 新建分类信息 newCate: { classifyId: '', // 销售额归类 parentId: '', // 上级分类 categoryName: '', // 商品分类 cateCode: '' // 分类编码 }, // 新建单位信息 newUnit: '', templateMode: 0 } } // 显示/隐藏商品分类选择浮层的回调 onPopupVisibleChange(value) { const { entityType, goodCategory, dispatch } = this.props let selfCategory = [] if (value && entityType !== '1') { selfCategory = { categoryList: Format.formatSelfCategory( goodCategory.categoryList ) } dispatch(action.setGoodCategory(selfCategory)) } } _refresh(type) { const { dispatch } = this.props if (type === 'kind') { dispatch(action.getGoodCategory()) Message.info('商品分类刷新成功') } else { dispatch(action.getGoodUnitList()) Message.info('结账单位刷新成功') } } // 上级分类 _handleAddCateSelect(e) { const { newCate } = this.state newCate.parentId = e.target.value this.setState({ newCate }) } // 展示新建分类或者新建单位弹窗 _showKindOrUnitModal(type) { if (type === 'kind') { this.setState({ isShowAddCatePop: true }) } else if (type === 'unit') { this.setState({ isShowAddUnitPop: true }) } } // 关闭新建分类或者新建单位弹窗 _hideKindOrUnitModal(type) { if (type === 'kind') { this.setState({ isShowAddCatePop: false }) } else if (type === 'unit') { this.setState({ isShowAddUnitPop: false }) } } // 上传商品主图 uploadHeadPicture(info) { const { headPicture, dispatch } = this.props if (info.file.status === 'done') { const fullPath = info.file.response.data const path = fullPath.split(currentIMGUrl)[1] const newImg = { fullPath, id: '', isValid: 1, path: path, sortCode: headPicture.length + 1 } headPicture.push(newImg) dispatch(action.setHeadPicture(headPicture)) } } /** * 修改分类编码 */ _changeCateCode(e) { const { newCate } = this.state newCate.cateCode = e.target.value this.setState({ newCate }) } // 销售额归属分类 _handleAddCateClassify(e) { const { newCate } = this.state newCate.classifyId = e.target.value this.setState({ newCate, chargingMode: 0 }) } // 关闭新建分类或者新建单位弹窗 _hideKindOrUnitModal(type) { if (type === 'kind') { this.setState({ isShowAddCatePop: false }) } else if (type === 'unit') { this.setState({ isShowAddUnitPop: false }) } } // 新建分类 _addNewCategory() { const { dispatch } = this.props const { newCate } = this.state const { cateCode, categoryName, classifyId, parentId } = newCate const params = { industry: 3, req: JSON.stringify({ code: cateCode, name: categoryName, parentId: parentId, groupCategoryId: classifyId }) } dispatch(action.addNewCategory(params)) this._hideKindOrUnitModal('kind') } /** * 改变商品分类 */ _changeCateName(e) { const { newCate } = this.state newCate.categoryName = e.target.value this.setState({ newCate }) } /** * 检查运费输入是否合法 */ checkFreightCost(rule, value, callback) { const reg = /^\d*(?:\.\d{0,2})?$/ if (value) { const valueStr = value.toString() if ((!reg.test(valueStr.trim()) || valueStr.split('.')[0].length > 6 )) { callback('运费只能输入数字并且整数位最多六位,小数位最多保留两位') } } callback() } // 切换快递运费 freightTypeChange(value) { // console.log(value,'value') const { baseInfo,dispatch} = this.props if (value === '2') { baseInfo.freightType = 2 } else { baseInfo.freightType = 1 } baseInfo.freightNumber = null dispatch(action.setCombinedGoodDetail(baseInfo)) } freightModelChange(value) { const { freightTemplate = [], baseInfo, setFieldsValue } = this.props const template = freightTemplate.filter(item => item.idStr == value) const mode = template[0].chargingMode baseInfo.freightDescription = template[0].description baseInfo.freightModelName = template[0].name this.setState({ templateMode: mode }) // 切换运费模版时 子项数量只为空 setFieldsValue({ ['freightNumber']: null }) } // 运费模版聚焦的回调 freightModeFocus() { const { freightTemplate = [] } = this.props if (freightTemplate.length === 0) { Message.error('你还未配置运费模板,请前往掌柜APP配置') } } render() { const { goodCategory = [], headPicture = [], getFieldDecorator, baseInfo = {}, unitList=[], freightTemplate = [] } = this.props console.log(headPicture, 'headPicture') const { isShowAddCatePop, newCate, uploadData } = this.state const categoryList = Format.formatCatogoryList(goodCategory) const cateFlat = Format.formatCateListFlat( goodCategory.categoryList || [] ) const freightType = baseInfo.freightType?baseInfo.freightType:1 const defaultFreightType = freightType?freightType.toString():'1' const {scopeCategoryId = ''} = baseInfo const defaultCategory = scopeCategoryId.split('/') const res = unitList.filter(t => t.name === '件') || [] const defaultUnitId = res[0]?res[0].id:'' return ( <Card title="基本信息"> <div className={styles.main}> <div className={styles.main_left}> <div className={classnames([styles.good_category],[styles.mb_10])} > <FormItem label="商品分类" {...formItemLayout}> {getFieldDecorator('categoryEntry', { rules: [ { required: true, message: '请选择商品分类' } ], initialValue: defaultCategory })( <Cascader style={{ width: 200 }} placeholder="选择商品分类" options={categoryList.children} onPopupVisibleChange={this.onPopupVisibleChange.bind(this)} /> )} <div className={styles.unit_right}> <span className={styles.refresh}onClick={() => {this._refresh('kind')}} >刷新</span> <span className={styles.split}>|</span> <span className={styles.new}onClick={() => { this._showKindOrUnitModal('kind')}}>新建分类</span> </div> </FormItem> </div> <div className={classnames([styles.good_name],[styles.mb_10])}> <FormItem label="商品名称" {...formItemLayout}> {getFieldDecorator('name', { rules: [ { required: true, message: '请填写商品名称' }, { validator: null } ], initialValue: baseInfo.name })( <Input style={{ width: 200 }}maxLength="21" /> )} </FormItem> </div> <div className={classnames([styles.good_unit],[styles.mb_10])}> <FormItem label="结账单位" {...formItemLayout}> {getFieldDecorator('accountId', { initialValue: baseInfo.accountId || defaultUnitId })( <Select style={{ width: 200 }} placeholder={baseInfo.account} disabled={baseInfo.account ? true : false }> {unitList.map((item, index) => { return ( <Option value={item.id}key={index}>{item.name}</Option> ) })} </Select> )} </FormItem> </div> <div className={classnames([styles.good_code],[styles.mb_10] )}> <FormItem label="商品条码" {...formItemLayout}> {getFieldDecorator('code', { initialValue: baseInfo.code })( <Input style={{ width: 200 }} maxLength="20"/> )} </FormItem> </div> <div className={classnames([styles.good_extra],[styles.mb_10])}> <FormItem label="可作为赠品" {...formItemLayout}> {getFieldDecorator('isGive', { valuePropName: 'checked', initialValue: baseInfo.isGive === 1 })(<Switch />)} </FormItem> </div> <div className={classnames([styles.good_freight],[styles.mb_10])}> <FormItem label="快递运费" {...formItemLayout}> {getFieldDecorator('freightType', { initialValue: defaultFreightType })( <Select style={{ width: 200 }}onChange={this.freightTypeChange.bind(this )} > {this.state.freightOptions.map( (item, index) => { return ( <Option value={item.value} key={index} >{item.label} </Option> ) } )} </Select> )} </FormItem> </div> {freightType == 1 && ( <div className={classnames([styles.good_freight],[styles.mb_10])}> <FormItem label="运费(元)" {...formItemLayout}> {getFieldDecorator('freightCost', { rules: [ { required: true, message: '运费不能为空' }, { validator: this.checkFreightCost } ], initialValue:baseInfo.freightNumber || 0 })(<Input style={{ width: 200 }}/>)} </FormItem> </div> )} {freightType === 2 && ( <div className={classnames([styles.good_freight],[styles.mb_10] )}> <FormItem label="运费模版" {...formItemLayout}> {getFieldDecorator('freightModelId', { initialValue: baseInfo.freightModelId })( <Select style={{ width: 200 }} onChange={this.freightModelChange.bind(this)} onFocus={this.freightModeFocus.bind(this)}> {freightTemplate.map( (item, index) => { return ( <Option value={item.idStr} key={index}>{item.name}</Option> ) } )} </Select> )} </FormItem> </div> )} </div> <div className={styles.main_right}> <div className={styles.good_picture}> <FormItem label="商品主图" {...formItemLayout}> <Upload {...UploadImage()} className={styles.picture_upload} accept=".png,.jpeg,.jpg,.gif" listType="picture-card" showUploadList={false} onChange={this.uploadHeadPicture.bind(this)} // beforeUpload={this.beforeUpload.bind(this)} // disabled={unEdit} > {headPicture.filter(t => t.isValid === 1).length < 5 && ( <Icon type="plus" style={{fontSize: 40,marginTop: 10 }} /> )} </Upload> <div className={styles.upload_list}> {headPicture.map((item, index) => { return item.isValid === 1 ? ( <div className={styles.img_item} key={index} > <img className={styles.image} src={item.fullPath}/> {<div className={styles.mask}></div>} {<Icon type="delete" style={{ fontSize: 20, color: '#fff' }} className={ styles.icon_delete } onClick={() => {this.deleteImg(index) }}/>} </div> ) : null })} </div> <div className={styles.upload_tips}> 至多添加5张图片;图片格式为png,jpeg,jpg,gif;建议使用png格式图片,以保证最佳效果;上传彩色图片;建议图片尺寸为5:4 </div> </FormItem> </div> </div> </div> {/* 商品分类添加弹窗 */} {isShowAddCatePop && ( <div className={styles.add_cate_container}> <div className={styles.add_cate_bg} onClick={() => this._hideKindOrUnitModal('kind')}/> <div className={styles.add_cate_box}> <div className={styles.add_cate_title}> 商品分类添加 </div> <div className={styles.add_base_conf}>基础设置</div> <div className={styles.add_cate_item}> <span>商品分类</span> <input type="text" value={newCate.categoryName || ''} onChange={this._changeCateName.bind(this)}/> </div> <div className={styles.add_cate_item}> <span>上级分类</span> <Select placeholder="无上级分类" onChange={this._handleAddCateSelect.bind(this)} style={{ width: 200 }}> <option value="">无上级分类</option> {cateFlat.map(item => { return ( <Option value={item.id}key={item.id}> {item.name}</Option> ) })} </Select> </div> <div className={styles.add_cate_item}> <span>分类编码</span> <input type="text" value={newCate.cateCode || ''} onChange={this._changeCateCode.bind(this)}/> </div> <div className={styles.add_high_conf}>高级设置</div> <div className={styles.add_cate_item}> <span>销售额归到其他分类</span> <Select placeholder="不设置" style={{ width: 200 }} onChange={this._handleAddCateClassify.bind( this )}> <Option value="">不设置</Option> {cateFlat.map(item => { return ( <Option value={item.id} key={item.id}>{item.name} </Option> ) })} </Select> </div> <div className={styles.add_cate_bottom}> <div className={styles.btn_cancel}onClick={() =>this._hideKindOrUnitModal('kind')}>取消</div> <div className={styles.btn_save}onClick={() => this._addNewCategory()}> 保存 </div> </div> </div> </div> )} </Card> ) } } export default BaseInfo <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/title/TitleEditor.js import React, {Component} from 'react' import { Radio, Button, Input, Icon } from 'antd'; import { SketchPicker } from 'react-color'; import visualApi from '@src/api/visualConfigApi' import style from './TitleEditor.css' import { DesignEditor, ControlGroup } from '../../editor/DesignEditor'; import GoogsSelect from '../../common/googsSelect' import Dropdown from '../../common/dropdown' import BanckgrondSelect from '../../common/banckgrondSelect' const RadioGroup = Radio.Group; export default class TitleEditor extends DesignEditor { constructor(props) { super(props); this.state= { isSketchPicker: false, isSketchPickerbg: false, isShowImgUpload: false, isShowGoods: false, goodsNames: [], } } componentDidMount() { const { config } = this.props.value; const { linkGoodsId } = config this.getSpecifyRetailGoodsList(linkGoodsId) } getSpecifyRetailGoodsList(id) { // 通用接口,通过ID来查询信息接口 visualApi.getSpecifyRetailGoodsList({ idList: [id] }).then( res=>{ this.setState({ goodsNames: res.data }) }, err=>{ console.log('err', err) } ) } onChange = (str, val) => { const { value, onChange } = this.props; const {config} = value onChange(value, {config:{ ...config, [str]: val.target.value }}) } showSkentPick = (str) => { this.setState({ [str]: !this.state[str] }) } handleChangeComplete = (str, color) => { // 拾色器的回调 const { value, onChange } = this.props; const {config} = value onChange(value, {config:{ ...config, [str]: color.hex }}) } onChangeInput = (e) => { // 输入框 const { value, onChange } = this.props; const { config } = value const val = e.target.value.trim() if(val.length > 20) { return } value.titleWordLeng = val.length config.text = val onChange(value, {config:{ ...config, text: val }}) } close = () => { this.setState({ isShowImgUpload: false, isShowGoods: false, }) } _onChangGoods = () => { this.setState({ isShowGoods: true }) } getGoodsItem = (data) => { // 商品选择 const { value, onChange } = this.props; const { config } = value this.setState({ goodsNames:data }) onChange(value, {config:{ ...config, linkGoodsId: data[0].itemId }}) } _selectLink = (data) => { // 页面链接选择 const { value, onChange } = this.props; const {config} = value onChange(value, {config:{ ...config, linkPage: data }}) } getlinkGoodsName = (id, index) => { const { goodsNames } = this.state let name; goodsNames.find((c) => { if(id == c.itemId) { name = c.itemName } }) return <div onClick={this._onChangGoods} className={style.link}> {name ? name : '选择商品的链接'} <Icon type="down" /></div> } render() { const { value, prefix, validation, onChange } = this.props; const { config } = value const { textColor, backgroundColor, text, linkGoodsId } = config const { isSketchPicker, isSketchPickerbg, isShowGoods } = this.state return ( <div className={`${prefix}-design-component-line-editor`}> <GoogsSelect getGoodsItem={this.getGoodsItem} isShowGoods={isShowGoods} close={this.close} radio /> <div className={style.componentTitleEditor}> <ControlGroup label="标题内容:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titleInput}> <input className={style.input} placeholder='请输入标题内容' value={text} type="text" onChange={(e) => this.onChangeInput(e)} /> <p className={style.wordNumber}>{value.titleWordLeng}/20</p> </div> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文字大小:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.size} className={style.controlGroupControl} onChange={(e) => this.onChange('size', e)}> <Radio name="size" value='large'>大</Radio> <Radio name="size" value='medium'>中</Radio> <Radio name="size" value='small'>小</Radio> </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本位置:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.textAlign} className={style.controlGroupControl} onChange={(e) => this.onChange('textAlign', e)}> <Radio name="textAlign" value='left'>居左</Radio> <Radio name="textAlign" value='center'>居中</Radio> </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{backgroundColor: textColor}} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPicker')} type="primary" /> {isSketchPicker && <SketchPicker color={textColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('textColor', e)} />} </div> </div> <div className={style.componentTitleEditor}> <ControlGroup label="背景颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <BanckgrondSelect value = {value} onChange = {onChange} backgroundColor = {backgroundColor} isSketchPickerbg= {isSketchPickerbg} showSkentPick = {this.showSkentPick} /> </div> <div className={style.componentTitleEditor}> <ControlGroup label="链接:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.linkType} className={style.controlGroupControl} onChange={(e) => this.onChange('linkType', e)}> <Radio name="linkType" value='goods'>商品</Radio> <Radio name="linkType" value='page'>页面</Radio> </RadioGroup> {value.config.linkType == 'goods' ? this.getlinkGoodsName(linkGoodsId) : <Dropdown className={style.link} selectLink={this._selectLink} current={value.config.linkPage} />} </div> </div> ) } static designType = 'title'; static designDescription = '标题'; static designTemplateType = '基础类'; static getInitialValue() { return { titleWordLeng: 0, config: { type: 'title', text: '', // 标题内容。必填。1 ~ 25个字。 size: 'medium', // 标题大小。可选值:large、medium、small textAlign: 'left', // 文字对齐方式。可选值:left、center(注意,不支持 right) textColor: '#000000', // 文字颜色 backgroundColor: '#fff', // 背景色 linkType: 'goods', // 链接到哪里。可选值:goods(商品)、page(页面) linkGoodsId: '', // 链接到的商品 id,在 linkType 为 goods 时有效。可不填 linkPage: '', // 链接到的页面路径,在 linkType 为 page 时有效。可不填 } } } } <file_sep>/static-hercules/src/sweep-face/utils/index.js import api from '../api' const FACE_PHONE = 'FACE_PHONE' const { warning: warningDialog } = require('../../base/components/dialogs/events') import { isAndroid } from '../../base/utils/tool' export const setItem = function(key, value) { try { value = typeof value === 'string' ? value : JSON.stringify(value) } catch (e) { value = '' } sessionStorage.setItem(key, value) } export const getItem = function(key) { try { return JSON.parse(sessionStorage.getItem(key)) || {} } catch (e) { return {} } } export const getFace = function(name) { const info = getItem(FACE_PHONE) return name ? info[name] : info } export const setFace = function(info) { setItem(FACE_PHONE, { ...getFace(), ...(info || {}) }) } export const getServerImgPath = function(fileName) { return `face/food/${fileName}` } export const getUploadedImgUrl = function(name) { return `https://img.2dfire.com/${name}` } export const delFace = function() { sessionStorage.removeItem(FACE_PHONE) } export const uploadImg = function(file, config) { const { success, fail } = config || {} let data = new FormData() const fileName = file.name console.log(fileName) compress(file, 0.8, function(err, img) { if (err) { console.log(err) warningDialog.showError('服务器抖了一下') return } // 接下来就可以用 ajax 提交 fromdData // data.append('ImgBlob', img); data.append('FilePart', img) data.append('path', fileName) api.uploadImg(data).then( res => { success && success(res) }, err => { fail && fail(err) } ) }) } export const getPhotoOrientation = function(img) { var orient EXIF.getData(img, function() { orient = EXIF.getTag(this, 'Orientation') }) return orient } export const compress = function(file, quality, callback) { if (!window.FileReader || !window.Blob) { return errorHandler('您的浏览器不支持图片压缩')() } var reader = new FileReader() var mimeType = file.type || 'image/jpeg' reader.onload = createImage reader.onerror = errorHandler('图片读取失败!') reader.readAsDataURL(file) function createImage() { var dataURL = this.result var image = new Image() image.onload = compressImage image.onerror = errorHandler('图片加载失败') image.src = dataURL } function compressImage() { var canvas = document.createElement('canvas') var ctx var dataURI var result const orient = getPhotoOrientation(this) // const orient = 6; const w = this.naturalWidth const h = this.naturalHeight const base_w = 600 const base_h = 800 console.log('orient:', orient) if (w > h) { console.log('横向图') canvas.width = base_w canvas.height = (base_w * h) / w } else { console.log('纵向图') canvas.height = base_h canvas.width = (base_h * w) / h } ctx = canvas.getContext('2d') if (orient == 6) { ctx.save() //保存状态 let cw = Number(ctx.canvas.width) let ch = Number(ctx.canvas.height) canvas.width = ch canvas.height = cw ctx.translate(ch / 2, cw / 2) //设置画布上的(0,0)位置,也就是旋转的中心点 ctx.rotate((90 * Math.PI) / 180) //把画布旋转90度 // 执行Canvas的drawImage语句 ctx.drawImage(this, -cw / 2, -ch / 2, cw, ch) //把图片绘制在画布translate之前的中心点, ctx.restore() //恢复状态 } else if (orient == 8) { ctx.save() //保存状态 let cw = Number(ctx.canvas.width) let ch = Number(ctx.canvas.height) canvas.width = ch canvas.height = cw ctx.translate(ch / 2, cw / 2) //设置画布上的(0,0)位置,也就是旋转的中心点 ctx.rotate((270 * Math.PI) / 180) //把画布旋转90度 // 执行Canvas的drawImage语句 ctx.drawImage(this, -cw / 2, -ch / 2, cw, ch) //把图片绘制在画布translate之前的中心点, ctx.restore() //恢复状态 } else { // 执行Canvas的drawImage语句 ctx.drawImage(this, 0, 0, canvas.width, canvas.height) } dataURI = canvas.toDataURL(mimeType, quality) result = dataURIToBlob(dataURI) callback(null, result) } function dataURIToBlob(dataURI) { var type = dataURI.match(/data:([^;]+)/)[1] var base64 = dataURI.replace(/^[^,]+,/, '') var byteString = atob(base64) var ia = new Uint8Array(byteString.length) for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i) } return new Blob([ia], { type: type }) } function errorHandler(message) { return function() { var error = new Error('Compression Error:', message) callback(error, null) } } } export const getCapture = function() { return isAndroid() ? 'camera' : false } export function chooseImage(config) { const { success, fail } = config || {} wx.chooseImage({ count: 1, // 默认9 success(res) { const localId = res.localIds[0] wx.getLocalImgData({ localId, success(res) { let localData = res.localData if (localData.indexOf('data:image') !== 0) { //判断是否有这样的头部 localData = 'data:image/jpeg;base64,' + localData } const base64 = localData .replace(/\r|\n/g, '') .replace('data:image/jgp', 'data:image/jpeg') success && success(base64) }, fail(e) { fail && fail(e, 'getLocalImgData') } }) }, fail(e) { fail && fail(e, 'chooseImage') } }) } //base64转换为file文件 export function base64ToFile(dataURI) { let arr = dataURI.split(',') let mime = arr[0].match(/:(.*?);/)[1] let suffix = mime.split('/')[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File( [u8arr], `${Math.random() .toString(36) .substr(2)}.${suffix}`, { type: mime } ) // const type = dataURI.match(/data:([^;]+)/)[1] // const base64 = dataURI.replace(/^[^,]+,/, '') // const byteString = atob(base64) // // const ia = new Uint8Array(byteString.length) // for (let i = 0; i < byteString.length; i++) { // ia[i] = byteString.charCodeAt(i) // } // return new Blob([ia], { // type: type // }) } <file_sep>/inside-boss/src/components/goods/modalTemplate.js import React, { Component } from 'react'; import { Modal, Button, Checkbox, Table, Popover, Icon, Radio, Progress, Pagination } from 'antd' import style from './style.css' import { recursionClass } from './data' import * as action from '../../action' import moment from 'moment' const CheckGroup = Checkbox.Group const RadioGroup = Radio.Group; const histroyColumns =(props)=>([ { title: '导入时间', dataIndex: 'createTime', key: 'createTime', render:(text,record)=>{ return moment(record.createTime).format('YYYY-MM-DD HH:mm:ss') }, width:180 },{ title: '导入结果', render:(text,record)=>{ return( <span> <span>新增<span className = {style.Bcolor} >{record.successAdd}</span>条</span>, <span>更新<span className = {style.Bcolor} >{record.successUpdate}</span>条</span>, <span>失败<span className = {style.Bcolor} >{record.failed}</span>条</span> </span> ) } },{ title: '导入成功文件', dataIndex: 'successFilePath', key: 'successFilePath', width:120, render:(text,record)=>{ if(record.successFilePath){ return( <a className = {style.Bcolor} onClick={()=>props.handleExport(record.successFilePath)}>{moment(record.createTime).format('YYYY-MM-DD')}.xls</a> ) } } },{ title: '导入失败文件', dataIndex: 'failedFilePath', key: 'failedFilePath', width:120, render:(text,record)=>{ if(record.failedFilePath){ return( <a className = {style.Bcolor} onClick={()=>props.handleExport(record.failedFilePath)}>{moment(record.createTime).format('YYYY-MM-DD')}.xls</a> ) } } } ]) const columns = [ { title: '商品名称', dataIndex: 'showColumn1', key: 'showColumn1', width:100 }, { title: '编码', dataIndex: 'showColumn2', key: 'showColumn2', width:100 }, { title: '错误位置', dataIndex: 'rowNum', key: 'rowNum', width:100, render: (text, record)=>{ return record.rowNum ? `第${record.rowNum}行`:'' } }, { title: '错误信息', dataIndex: 'failMsg', key: 'failMsg', render: (text, record) => { let message = '' try { // message = JSON.parse(record.failMsg)[0].message || '' message = JSON.parse(record.failMsg).map((i,index)=>{ return <p key={index} >{i.message}</p> }) } catch (error) { console.log(error) } return message }, }, ] const ModalTemplate = { select:(props)=>{ const { handleBack, handleCancel, handleChange, state, selectAll, templateSelect, ok, data } = props const { arr, type } = state const list = data.menuList && data.menuList.length ? recursionClass(data.menuList):[] const height = (Math.min(10,list.length || 0) + 1) * 34 return( <div className={style.templateSelectWarp}> <div className={style.templateSelectAll}> <Checkbox checked={type} onChange={templateSelect} >空白模板</Checkbox> </div> <div className={style.templateSelectAll}> <Checkbox checked={!type} onChange={templateSelect} >商品模板</Checkbox> <Popover placement="bottomLeft" overlayStyle={{width:225}} content = '下载的表格中将包含已选分类下的商品信息,便于进行商品的批量修改。'> <Icon style={{ fontSize: 16, paddingLeft: 12, verticalAlign: 'middle' }} type="question-circle-o" /> </Popover> </div> <div className={style.templateSelectAllWarp} style={ {height: type?'0':`${height}px` }} > <div className={style.templateSelectItem} onChange={selectAll.bind(null,list)}><Checkbox disabled={type} checked={arr.length !== 0 && arr.length === list.length }>全选</Checkbox></div> <div className={ style.templateSelectGroup}> <CheckGroup onChange = {handleChange.bind(null,list)} value={arr} > { list && list.length && list.map(item=>{ return( <div key={item.id} className={style.templateSelectItem}> <Checkbox disabled={type} value={item.id}>{item.name}</Checkbox> </div> ) }) } </CheckGroup> </div> </div> <div> <p className={style.templateExplanation}>注意事项:</p> <p className={style.templateExplanation}>1.请仔细阅读下载模板中的填表说明后再进行填写</p> <p className={style.templateExplanation}>2.请勿随意更改模板表头</p> <p className={style.templateExplanation}>3.不同门店混合使用同一份模板导入时,请保证导入门店的表头设置与模板表头保持一致</p> </div> <div style={{textAlign:'right',marginTop:'10px'}}> <Button onClick={handleBack} >上一步</Button> <Button onClick={handleCancel} style={{marginLeft:'10px'}} >取消</Button> <Button onClick={()=>ok(arr)} style={{marginLeft:'10px'}} type="primary" >确定</Button> </div> </div> ) }, history:(props)=>{ const { paginationChange, state, data } = props const resultList = data.historyDate const total = resultList && resultList.total ? resultList.total : 0 return( resultList && resultList.data && resultList.data.length ? <div> <div style={{marginBottom:'10px',border:'1px solid #e9e9e9'}}> <Table scroll={{y:240}} bordered pagination={false} columns = { histroyColumns(props) } dataSource = { resultList.data }></Table> </div> <div className={style.paginationBox}> <Pagination size="small" className={style.paginationHtml} showQuickJumper current={state.pageIndex} total={total} defaultPageSize={10} pageSize={10} onChange={paginationChange} /> <p>共{total}条记录</p> </div> </div>: <Table scroll={{y:240}} bordered pagination={false} columns = { histroyColumns(props) } dataSource = { [] }></Table> ) }, result:(props)=>{ const { resultList, handleCancel } = props return ( resultList && resultList.finished ? <div> <div className={style.resultTitle}>本次共导入<span style={{color:'#108ee9'}}> {resultList.total} </span>条记录,其中:</div> { (resultList.successAdd || resultList.successUpdate) ? <div className={style.resultSuccess} style={{borderBottom: '1px solid #ccc'}}> <Icon className={style.resultIcon} type="check-circle-o" /> <span>新增<span style={{color:'#108ee9'}}> {resultList.successAdd} </span>条记录,更新<span style={{color:'#108ee9'}}> {resultList.successUpdate} </span>条记录</span> </div>: null } { resultList.failed ? <div style={{height:'35px'}}> <Icon className={style.resultIcon} style={{color:'#f04134'}} type="close-circle-o" /> <span>失败<span style={{color:'#108ee9'}}> {resultList.failed} </span>条记录,请仔细检查修改后,重新选择文件导入</span> </div> : null } { resultList.failed && resultList.failMsg ? <div className={style.resultTableWarp}> <Table size='small' scroll={{y:124}} bordered pagination={false} columns = { columns } dataSource = { resultList.failMsg }></Table> </div> : null } <div style={{overflow:'hidden'}}> { resultList.failedFilePath && <Popover overlayStyle={{width:225}} trigger="hover" content = '可导出含【导入失败原因】列的表格,修改后可重新导入' placement= 'rightTop' > <a href={resultList.failedFilePath || ''} style={{color: '#108ee9'}}>下载纠错模板<Icon className={style.recoveryTemplate} type="question-circle-o" /></a> </Popover> } <Button onClick={handleCancel} style={{float:'right'}} type="primary" >我知道了</Button> </div> </div> : <Progress percent={resultList.percent} status={resultList.percent >= 100 ?'success':'active'} /> ) } } class view extends Component { constructor(){ super() this.state = { arr:[], type:true, pageIndex: 1 } } templateSelect=(e)=>{ if(e.target.checked){ this.setState(()=>({type:!this.state.type})) } } handleChange=(list,value)=>{ this.setState(()=>({ arr:value, checkedAll:value.length === list.length })) } selectAll=(list,e)=>{ let checked = e.target.checked if(checked){ this.setState(()=>({arr:list.map(i=>i.id),checkedAll:checked})) }else{ this.setState(()=>({arr:[],checkedAll:checked})) } } ok = (arr)=>{ this.props.handleOk(this.state.type?[]:arr) this.setState(()=>({arr:[]})) } handleCancel = ()=>{ if(this.props.modalType == 'result' && this.props.resultList && !this.props.resultList.finished) return this.props.dispatch(action.setModalVisible({boole:false,modalType:''})) this.setState(()=>({arr:[]})) } handleReload = ()=>{ this.props.dispatch(action.setModalVisible({boole:false,modalType:''})) setTimeout(() => { window.location.reload() }, 800); } handleExport=(url)=>{ if(url) window.location.href = url } selectTitle(modalType='select'){ return { result: this.props.resultList && this.props.resultList.finished ?'导入结果':'商品模板导入中...', history:'历史导入记录', select:'模板选择' }[modalType] } paginationChange = (pageIndex)=>{ this.setState(()=>({pageIndex})) const plateEntityId = this.props.data.brandId || '' this.props.dispatch(action.getImportResultList(plateEntityId,pageIndex)) } render(){ const { show = false, modalType = '', resultList } = this.props const title = this.selectTitle(modalType) return( <div> {ModalTemplate[modalType]?( <Modal closable={ !(modalType == 'result' && resultList && !resultList.finished) } title={title} visible={show} style={{minWidth:'650px',height:'600px'}} footer={null} onCancel = {this.handleCancel} > { ModalTemplate[modalType]({...this,...this.props}) } </Modal>):''} </div> ) } } export default view<file_sep>/inside-chain/src/const/emu-table-setting.js const Tab = [ { name: "桌位管理", path: "/shop_table_manage", children: [ '/list', '/add', '/edit' ] }, { name: "区域管理", path: "/shop_area_manage", children: [ '/list', ] }, // { // name: "收银模式", // path: "" // }, { // name: "收银单据", // path: "" // }, { // name: "单据语言", // path: "" // } ] export default Tab <file_sep>/inside-boss/src/container/memberInformation/reducers.js import { // INIT_DATA, // FETCH_BATCH_LIST, // FETCH_RECHARGE_LIST, RECHARGE_IMPORT_EVENT, SET_MEMBER_EXPORT, // SHOW_EDIT_LAYER, // SET_SELECTED_COUNTER, // SET_SELECTED_ROW_KEYS, // BTN_LOCK, // SHOW_SPIN, // SET_STATUS, // SET_LAYER_DEFAULT_VALUES, // SET_START_VALUE, // SET_END_VALUE, INIT_MEMBER_DATA, LIST_INIT_DATA } from '../../constants' // const resetStatusList = (list) => { // let final = {} // list.forEach((m, i) => { // let str = m.substring(0, 3) // switch (str) { // case '未充值': // final.never = '0' // break // case '充值成': // final.success = '1' // break // case '充值失': // final.fail = '2' // break // case '已红冲': // final.refund = '3' // break // default: // return // } // }) // // let arr = [] // for (let key in final) { // arr.push(final[key]) // } // const params = arr.length > 0 ? arr.join(',') : '' // sessionStorage.setItem('rechargeStatusList', params) // } const memberInformationReducer = (state = {}, action) => { switch (action.type) { case INIT_MEMBER_DATA: return action.data // case FETCH_BATCH_LIST: // return Object.assign({}, state, {batchList: action.list}) // case FETCH_RECHARGE_LIST: // sessionStorage.setItem('selectedList', '[]') // const data = action.data // const statusList = data.statusList || [] // resetStatusList(statusList) // return Object.assign( // {}, // state, // { // cancelRechargeCount: data.cancelRechargeCount, // faiRechargeCount: data.faiRechargeCount, // name: data.name, // pageCount: data.pageCount, // preRechargeCount: data.preRechargeCount, // rechargeBatchDetailsViewList: data.rechargeBatchDetailsViewList, // rechargeBatchId: data.rechargeBatchId, // sucRechargeCount: data.sucRechargeCount, // totalCount: data.totalCount, // defaultPageSize: data.defaultPageSize, // selectedRowKeys: [], // currentPage: data.pageIndex || 1, // statusList: data.statusList // } // ) case RECHARGE_IMPORT_EVENT: const args = action.data return Object.assign( {}, state, { memberImportErrorList : args.errorList, totalCount : args.failCnt, defaultPageSize : 50, currentPage :1 } ) case SET_MEMBER_EXPORT: let res = action.data return Object.assign( {}, state, { exportBtn : res.exportMemberSwitch, } ) case LIST_INIT_DATA: return Object.assign( {}, state, { defaultPageSize : action.data } ) // case SHOW_EDIT_LAYER: // return Object.assign({}, state, {showEditLayer: action.data}) // case SET_SELECTED_COUNTER: // return Object.assign({}, state, {selectedCounter: action.len}) // case SET_SELECTED_ROW_KEYS: // return Object.assign({}, state, {selectedRowKeys: action.selectedRowKeys}) // case BTN_LOCK: // return Object.assign({}, state, {btnLocker: action.data}) // case SHOW_SPIN: // return Object.assign({}, state, {showSpin: action.data}) // case SET_STATUS: // return Object.assign({}, state, {statusList: action.list}) // case SET_START_VALUE: // return Object.assign({}, state, {startValue: action.value}) // case SET_END_VALUE: // return Object.assign({}, state, {endValue: action.value}) // case SET_LAYER_DEFAULT_VALUES: // return Object.assign({}, state, {layerDefaultvalues: action.data}) default: return state } }; export default memberInformationReducer <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/title/TmpEditor.js import React from 'react' import { Radio, Button, Icon } from 'antd' import { SketchPicker } from 'react-color' import visualApi from '@src/api/visualConfigApi' import style from './TmpEditor.css' import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor' import GoogsSelect from '@src/container/visualConfig/views/design/common/googsSelect' import Dropdown from '@src/container/visualConfig/views/design/common/dropdown' import BanckgrondSelect from '@src/container/visualConfig/views/design/common/banckgrondSelect' const RadioGroup = Radio.Group export default class TitleEditor extends DesignEditor { constructor(props) { super(props) this.state = { isSketchPicker: false, isSketchPickerbg: false, isShowImgUpload: false, isShowGoods: false, goodsNames: [], announWordLeng: props.value.config.text.length, } } componentDidMount() { const { config, } = this.props.value const { linkGoodsId, } = config this.getSpecifyRetailGoodsList(linkGoodsId) } getSpecifyRetailGoodsList(id) { // 通用接口,通过ID来查询信息接口 visualApi.getSpecifyRetailGoodsList({ idList: [id], }).then( res => { this.setState({ goodsNames: res.data, }) }, err => { console.log('err', err) }, ) } configChang = (obj) => { const { value, onChange } = this.props onChange(value, { config: { ...value.config, ...obj, }, }) } changeGroup = (str, val) => { this.configChang({ [str]: val.target.value, }) } showSkentPick = (str) => { this.setState({ [str]: !this.state[str], }) } handleChangeComplete = (str, color) => { // 拾色器的回调 this.configChang({ [str]: color.hex, }) } onChangeInput = (e) => { // 输入框 const val = e.target.value.trim() if (val.length > 20) { return } // TODO: 这句虽然不合法,但是不能删,删了文本框就不能输入中文 this.props.value.config.text = val this.setState({ announWordLeng: val.length, }) this.configChang({ text: val, }) } close = () => { this.setState({ isShowImgUpload: false, isShowGoods: false, }) } _onChangGoods = () => { this.setState({ isShowGoods: true, }) } getGoodsItem = (data) => { // 商品选择 this.configChang({ linkGoodsId: data[0].itemId, }) } _selectLink = (data) => { // 页面链接选择 this.configChang({ linkPage: data, }) } getlinkGoodsName = (id, index) => { const { goodsNames } = this.state const name = (goodsNames.find(c => id === c.itemId) || {}).itemName return <div onClick = {this._onChangGoods} className = {style.link}> {name || '选择商品的链接'} <Icon type = "down" /> </div> } render() { const { value, prefix, validation, onChange, } = this.props const { config, } = value const { textColor, backgroundColor, text, linkGoodsId, } = config const { isSketchPicker, isSketchPickerbg, isShowGoods, announWordLeng, } = this.state return ( <div className={`${prefix}-design-component-line-editor`}> <GoogsSelect getGoodsItem={this.getGoodsItem} isShowGoods={isShowGoods} close={this.close} radio /> <div className={style.componentTitleEditor}> <ControlGroup label="标题内容:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titleInput}> <input className={style.input} placeholder='请输入标题内容' value={text} type="text" onChange={(e) => this.onChangeInput(e)} /> <p className={style.wordNumber}>{announWordLeng}/20</p> </div> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文字大小:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.size} className={style.controlGroupControl} onChange={(e) => this.changeGroup('size', e)}> <Radio name="size" value='large'>大</Radio> <Radio name="size" value='medium'>中</Radio> <Radio name="size" value='small'>小</Radio> </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本位置:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.textAlign} className={style.controlGroupControl} onChange={(e) => this.changeGroup('textAlign', e)}> <Radio name="textAlign" value='left'>居左</Radio> <Radio name="textAlign" value='center'>居中</Radio> </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{ backgroundColor: textColor }} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPicker')} type="primary" /> {isSketchPicker && <SketchPicker color={textColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('textColor', e)} />} </div> </div> <div className={style.componentTitleEditor}> <ControlGroup label="背景颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <BanckgrondSelect value = {value} onChange = {onChange} backgroundColor = {backgroundColor} isSketchPickerbg= {isSketchPickerbg} showSkentPick = {this.showSkentPick} /> </div> <div className={style.componentTitleEditor}> <ControlGroup label="链接:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.linkType} className={style.controlGroupControl} onChange={(e) => this.changeGroup('linkType', e)}> <Radio name="linkType" value='goods'>商品</Radio> <Radio name="linkType" value='page'>页面</Radio> </RadioGroup> {value.config.linkType == 'goods' ? this.getlinkGoodsName(linkGoodsId) : <Dropdown className={style.link} selectLink={this._selectLink} current={value.config.linkPage} />} </div> </div> ) } static designType = 'title'; static designDescription = '标题'; static designTemplateType = '基础类'; static getInitialValue() { return { config: { type: 'title', text: '', // 标题内容。必填。1 ~ 25个字。 size: 'medium', // 标题大小。可选值:large、medium、small textAlign: 'left', // 文字对齐方式。可选值:left、center(注意,不支持 right) textColor: '#000000', // 文字颜色 backgroundColor: '#fff', // 背景色 linkType: 'goods', // 链接到哪里。可选值:goods(商品)、page(页面) linkGoodsId: '', // 链接到的商品 id,在 linkType 为 goods 时有效。可不填 linkPage: '', // 链接到的页面路径,在 linkType 为 page 时有效。可不填 }, } } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionRelativeShops/TmpEditor.js import React from 'react'; import { DesignEditor } from '@src/container/visualConfig/views/design/editor/DesignEditor'; export default class BannerPreview extends DesignEditor { render(){ const { prefix } = this.props; return ( <div className={`${prefix}-design-component-config-editor`}> </div> ) } } <file_sep>/inside-boss/src/container/visualConfig/views/design/common/banckgrondSelect.js import React, { PureComponent } from 'react'; import cx from 'classnames'; import { Button } from 'antd'; import { SketchPicker } from 'react-color'; import style from './banckgrondSelect.css' export default class BanckgrondSelect extends PureComponent { state = { type: 'SketchPicker', isShow: false, backgroundColor:null } banckgrondChang = (str) => { const { value, onChange } = this.props; const {config} = value if(str == 'SketchPicker'){ this.setState({ isShow: !this.state.isShow }) } else { this.setState({ isShow: false }) config.backgroundColor = 'transparent' onChange(value, {config}) } this.setState({ type: str }) } handleChangeComplete = (str, color) => { // 拾色器的回调 const { value, onChange } = this.props; const {config} = value config[str] = color.hex onChange(value, {config}) } render() { const { type, isShow } = this.state const { value } = this.props; const { config } = value const { backgroundColor } = config return ( <div className={style.titlePickColor}> <div className={cx(style.btn, type == 'SketchPicker' && style.boder)} onClick={() => this.banckgrondChang('SketchPicker')}> <Button style={{backgroundColor: backgroundColor}} className={style.pickColorBtn} type="primary" /> </div> <div className={cx(style.transparent, type == 'transparent' && style.boder)} onClick={() => this.banckgrondChang('transparent')}> <img src='https://assets.2dfire.com/frontend/b9caea53ef5ec57c1578928f0e0caf36.png' /> </div> {isShow && <SketchPicker color={backgroundColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('backgroundColor', e)} /> } </div> ); } } <file_sep>/inside-boss/src/container/rootContainer/SideMenu/index.js import React, { Component } from 'react' import styles from '../style.css' import { Menu } from 'antd' import store from '../store' import { observer } from 'mobx-react' const SubMenu = Menu.SubMenu const Item = Menu.Item @observer export default class extends Component { componentDidMount() { store.getMenuList() } loopMenu = list => list.map(item => { let { children, menuName, pageType, menuId } = item //高铁和掌柜的优惠券批量发放不一样 if ( pageType === 'PC_ISSUE_COUPON' || pageType === 'PC_BRAND_ISSUE_COUPON' ) { pageType = 'PC_BRAND_ISSUE_COUPON' } if (pageType === this.getPath()) { this.activeItem = item this.openKey = [item.parentId] } if (pageType === 'node') { return children && children.length ? ( <SubMenu key={menuId} title={menuName}> {this.loopMenu(children)} </SubMenu> ) : null } return ( <Item key={pageType} info={item}> {menuName} </Item> ) }) selectMenu = ({ item }) => { const info = item.props.info || {} this.activeItem = info store.linkRoute(info) } getMenu = list => { if (!this.menu || !this.menu.length) { this.menu = this.loopMenu(list) } return this.menu } menuChange = keys => { this.openKey = keys this.forceUpdate() } componentDidUpdate() { store.setHeader(this.activeItem) } getPath = () => { const pathname = this.props.pathname || '' if (pathname.indexOf('/') > -1) { return pathname.substring(0, pathname.indexOf('/')) } this.pathname = pathname return pathname } render() { const pathname = this.getPath() if (!pathname) { this.activeItem = null } const { menuList } = store const menu = this.getMenu(menuList) return ( <div className={styles.menu}> {menu && ( <Menu mode="inline" theme="dark" selectedKeys={[pathname]} onSelect={this.selectMenu} openKeys={this.openKey} onOpenChange={this.menuChange} > {menu} </Menu> )} </div> ) } } <file_sep>/inside-boss/src/constants/index.js export const GLOBAL_MESSAGE_SUCCESS = 'platform/App/GLOBAL_MESSAGE_SUCCESS' export const GLOBAL_MESSAGE_ERROR = 'platform/App/GLOBAL_MESSAGE_ERROR' export const GLOBAL_LOADING = 'platform/App/GLOBAL_LOADING' export const GLOBAL_LOADING_HIDE = 'platform/App/GLOBAL_LOADING_HIDE' // Chart Legend 发生修改 export const SET_LEGEND_CHANGE = 'platform/Reports/SET_LEGEND_CHANGE' export const RECEIVE_CHARTS_LEGEND = 'platform/Reports/RECEIVE_CHARTS_LEGEND' export const SET_CHARTS_LEGEND = 'platform/Reports/SET_CHARTS_LEGEND' // 初始化图标数据与拉取数据 export const RECEIVE_CHARTS_CONSTRUCT = 'platform/Reports/RECEIVE_CHARTS_CONSTRUCT' export const RECEIVE_CHARTS_DATA = 'platform/Reports/RECEIVE_CHARTS_DATA' export const FORM_INIT = 'platform/Reports/FORM_INIT' //获取查询参数列表 export const GET_REPORT = 'platform/Reports/GET_REPORT' //点击查询,获取图表数据 export const RECEIVE_SEARCH_ARGS = 'platform/Reports/RECEIVE_SEARCH_ARGS' //点击查询,获取图表数据 export const RECEIVE_UNION_SELECT = 'platform/Reports/RECEIVE_UNION_SELECT' //点击查询,获取图表数据 export const SET_SEARCH_BUTTON_STATE = 'platform/Reports/SET_SEARCH_BUTTON_STATE' //点击查询,获取图表数据 //导入导出&&批量充值 export const INIT_DATA = 'inside-boss/goods/INIT_DATA' export const INIT_DATA_IMPORT_HISTORY = 'inside-boss/importHistory/INIT_DATA_IMPORT_HISTORY' export const EXPORT_DATA = 'inside-boss/goods/EXPORT_DATA' export const FETCH_BATCH_LIST = 'inside-boss/goods/FETCH_BATCH_LIST' export const FETCH_RECHARGE_LIST = 'inside-boss/goods/FETCH_RECHARGE_LIST' export const SHOW_EDIT_LAYER = 'inside-boss/goods/SHOW_EDIT_LAYER' export const RESEST_VIEW = 'inside-boss/goods/RESEST_VIEW' export const SET_SELECTED_COUNTER = 'inside-boss/goods/SET_SELECTED_COUNTER' export const SET_SELECTED_ROW_KEYS = 'inside-boss/goods/SET_SELECTED_ROW_KEYS' export const BTN_LOCK = 'inside-boss/goods/BTN_LOCK' export const SHOW_SPIN = 'inside-boss/goods/SHOW_SPIN' export const SET_STATUS = 'inside-boss/goods/SET_STATUS' export const SET_WHITE = 'inside-boss/goods/SET_WHITE' export const SET_LAYER_DEFAULT_VALUES = 'inside-boss/goods/SET_LAYER_DEFAULT_VALUES' export const SET_START_VALUE = 'inside-boss/goods/SET_START_VALUE' export const SET_END_VALUE = 'inside-boss/goods/SET_END_VALUE' export const SET_TEBLE_FIELDS_LIST = 'inside-boss/goods/SET_TEBLE_FIELDS_LIST' export const SET_TABLE_FIELDS_OPTIONS = 'inside-boss/goods/SET_TABLE_FIELDS_OPTIONS' export const SET_TABLE_OPTION_KEY = 'inside-boss/goods/SET_TABLE_OPTION_KEY' export const SET_MENU_LIST = 'inside-boss/goods/SET_MENU_LIST' export const SET_MODAL_VISIBLE = 'inside-boss/goods/SET_MODAL_VISIBLE' export const SET_RESULT_DATA = 'inside-boss/goods/SET_RESULT_DATA' export const SET_TABLE_HEADER = 'inside-boss/goods/SET_TABLE_HEADER' export const SET_MENU_LANGUAGE = 'inside-boss/goods/SET_MENU_LANGUAGE' export const SET_TWINS_FILEDID = 'inside-boss/goods/SET_TWINS_FILEDID' export const SET_GOODS_PARAMS = 'inside-boss/goods/SET_GOODS_PARAMS' export const SET_HISTORY_DATA = 'inside-boss/goods/SET_HISTORY_DATA' export const SET_GOODS_LIST='inside-boss/goods/SET_GOODS_LIST' export const SET_PAGE_INDEX='inside-boss/goods/SET_PAGE_INDEX' export const SET_IS_SHOW_BRAND='inside-boss/goods/SET_IS_SHOW_BRAND' export const SET_BRAND_LIST='inside-boss/goods/SET_BRAND_LIST' export const SET_BRAND_ID='inside-boss/goods/SET_BRAND_ID' export const SET_SHOW_SPECIFICATION='inside-boss/goods/SET_SHOW_SPECIFICATION' // 高铁-交路信息导入导出 export const INIT_ROUTE_DATA='inside-boss/routeInfoImport/INIT_ROUTE_DATA' export const SET_ROUTE_LIST='inside-boss/routeInfoImport/SET_ROUTE_LIST' export const SET_CUR_INDEX='inside-boss/routeInfoImport/SET_CUR_INDEX' // 高铁-车次时刻信息导入导出 export const INIT_TRAIN_DATA='inside-boss/trainInfoImport/INIT_TRAIN_DATA' export const SET_TRAIN_LIST='inside-boss/trainInfoImport/SET_TRAIN_LIST' export const SET_CUR_NUM='inside-boss/trainInfoImport/SET_CUR_NUM' //商品导入导出-下载商品模板 export const INIT_TYPE_DATA = 'inside-boss/downComm/INIT_TYPE_DATA' export const CHECKED_TYPE = 'inside-boss/downComm/CHECKED_TYPE' export const DEL_TABLE_ITEM = 'inside-boss/downComm/DEL_TABLE_ITEM' export const ADD_CATEGORY = 'inside-boss/downComm/ADD_CATEGORY' //商品导入导出-上传商品导入文件 export const INIT_UPLOAD_DATA = 'inside-boss/uploadComm/INIT_UPLOAD_DATA' //商品导入导出-导入日志 export const INIT_LOG_DATA = 'inside-boss/importLog/INIT_LOG_DATA' export const INIT_IMPORT_LOG_DATA = 'inside-boss/importLog/INIT_IMPORT_LOG_DATA' export const INIT_LOG_DETAIL_DATA = 'inside-boss/importLog/INIT_LOG_DETAIL_DATA' export const GET_IMPORT_LOG_DATA = 'inside-boss/importLog/GET_IMPORT_LOG_DATA' // 导入视频 export const SET_VIDEO_LIST = 'inside-boss/videoImport/SET_VIDEO_LIST' export const INIT_VIDEO_DATA = 'inside-boss/videoImport/INIT_VIDEO_DATA' export const CHANGE_VIDEO_TYPE = 'inside-boss/videoImport/CHANGE_VIDEO_TYPE' //会员信息导入导出 export const RECHARGE_IMPORT_EVENT = 'inside-boss/memberInformation/RECHARGE_IMPORT_EVENT' export const INIT_MEMBER_DATA = 'inside-boss/memberInformation/INIT_MEMBER_DATA' export const LIST_INIT_DATA = 'inside-boss/memberInformation/LIST_INIT_DATA' export const SET_MEMBER_EXPORT = 'inside-boss/memberInformation/SET_MEMBER_EXPORT' //商品图片管理 export const INIT_PICTURE_DATA = 'inside-boss/goodsPicture/INIT_PICTURE_DATA' export const DETAIL_CHANGE = 'inside-boss/goodsPicture/DETAIL_CHANGE' export const SET_PICTURE_LIST = 'inside-boss/goodsPicture/SET_PICTURE_LIST' export const LIST_DUPLICATED_ITEMS = 'inside-boss/goodsPicture/LIST_DUPLICATED_ITEM' export const GET_DUPLICATED_ITEMS = 'inside-boss/goodsPicture/GET_DUPLICATED_ITEMS' export const BACK_TO_PICTURE_LIST = 'inside-boss/goodsPicture/BACK_TO_PICTURE_LIST' export const SET_PICTURE_DETAIL_LIST = 'inside-boss/goodsPicture/SET_PICTURE_DETAIL_LIST' export const SET_PAGE_NUMBER = 'inside-boss/goodsPicture/SET_PAGE_NUMBER' export const SET_SEARCH_NAME = 'inside-boss/goodsPicture/SET_SEARCH_NAME' export const EDIT_TEMPLATE = 'inside-boss/goodsPicture/EDIT_TEMPLATE' export const TEMPLATE_DETAIL_DATA = 'inside-boss/goodsPicture/TEMPLATE_DETAIL_DATA' export const TEMPLATE_LIST = 'inside-boss/goodsPicture/TEMPLATE_LIST' //订单存照 export const INIT_ORDER_DATA = 'inside-boss/orderPhotos/INIT_ORDER_DATA' export const CHANGE_ORDER_TYPE = 'inside-boss/orderPhotos/CHANGE_ORDER_TYPE' export const SET_ORDER_START_VALUE = 'inside-boss/orderPhotos/SET_ORDER_START_VALUE' export const SET_ORDER_END_VALUE = 'inside-boss/orderPhotos/SET_ORDER_END_VALUE' export const SET_ORDER_LIST = 'inside-boss/orderPhotos/SET_ORDER_LIST' export const SET_INVOICE_CODE = 'inside-boss/orderPhotos/SET_INVOICE_CODE' //发放优惠券 export const INIT_COUPON_DATA = 'inside-boss/couponPush/INIT_COUPON_DATA' export const INIT_COUPON_TYPE = 'inside-boss/couponPush/INIT_COUPON_TYPE' export const GET_BATCH_LIST = 'inside-boss/couponPush/GET_BATCH_LIST' export const SET_OLD_BATCH_ID = 'inside-boss/couponPush/SET_OLD_BATCH_ID' export const RECHARGE_LIST = 'inside-boss/couponPush/RECHARGE_LIST' export const CHANGE_STATUS = 'inside-boss/couponPush/CHANGE_STATUS' export const CHANGE_COUPON_TYPE = 'inside-boss/couponPush/CHANGE_COUPON_TYPE' export const VISIBLE = 'inside-boss/couponPush/VISIBLE' export const SHOW = 'inside-boss/couponPush/SHOW' //高铁日常监控 export const SET_HIGH_MONITOR = 'inside-boss/highMonitor/SET_HIGH_MONITOR' export const INIT_HIGH_MONITOR = 'inside-boss/highMonitor/INIT_HIGH_MONITOR' //自定义单据 export const INIT_DATA_BILL = 'inside-boss/customBillStore/INIT_DATA_BILL' export const SET_BILL_STORE_MODAL = 'inside-boss/customBillStore/SET_BILL_STORE_MODAL' export const SET_BILL_STORE_SHOP_LIST = 'inside-boss/customBillStore/SET_BILL_STORE_SHOP_LIST' export const SET_BILL_STORE_BRANCH = 'inside-boss/customBillStore/SET_BILL_STORE_BRANCH' export const SET_BILL_STORE_PROVINCE = 'inside-boss/customBillStore/SET_BILL_STORE_PROVINCE' export const SET_BILL_ACTIVE_SHOP = 'inside-boss/customBillStore/SET_BILL_ACTIVE_SHOP' export const SET_ALL_TMPL_TYPE = 'inside-boss/customBillStore/SET_ALL_TMPL_TYPE' export const SET_TYPE_TMPL_LIST = 'inside-boss/customBillStore/SET_TYPE_TMPL_LIST' export const SET_TYPE_TMPL_TITLE = 'inside-boss/customBillStore/SET_TYPE_TMPL_TITLE' export const SET_USE_STORE_LIST = 'inside-boss/customBillStore/SET_USE_STORE_LIST' export const SET_ENTITY_TYPE = 'inside-boss/customBillStore/SET_ENTITY_TYPE' //不记名优惠券 export const SET_NO_OWNER_COUPON='inside-boss/noOwnerCoupon/SET_NO_OWNER_COUPON' export const INIT_NO_OWNER_COUPON='inside-boss/noOwnerCoupon/INIT_NO_OWNER_COUPON' export const SET_NO_OWNER_COUPON_LIST='inside-boss/noOwnerCoupon/SET_NO_OWNER_COUPON_LIST' export const SET_NO_OWNER_PAGE_NUM='inside-boss/noOwnerCoupon/SET_NO_OWNER_PAGE_NUM' export const SET_SEARCH_PARAM='inside-boss/noOwnerCoupon/SET_SEARCH_PARAM' export const IS_SHOW_SET_PAGE='inside-boss/noOwnerCoupon/IS_SHOW_SET_PAGE' export const SET_NO_OWNER_SET_LIST='inside-boss/noOwnerCoupon/SET_NO_OWNER_SET_LIST' export const SET_NO_SET_PAGE_NUM='inside-boss/noOwnerCoupon/SET_NO_SET_PAGE_NUM' // 商品分类 export const SET_CATEGORY_LIST='inside-boss/retailmanage/SET_CATE_LIST' export const SET_SPEC_LIST='inside-boss/retailmanage/SET_SPEC_LIST' export const SET_UNIT_LIST='inside-boss/retailmanage/SET_UNIT_LIST' // 商品列表 export const SET_ITEM_LIST='inside-boss/retailmanage/SET_ITEM_LIST' // 删除操作判断是否是组合商品子商品或者下发商品 export const SET_CHILD_GOODS_RESULT='inside-boss/retailmanage/setConfirmGoodsResult' // 商品策略 export const SET_GOOD_STRATEGY = 'inside-boss/goodEdit/SET_GOOD_STRATEGY' // 上传是否成功 export const SET_UPLOAD='inside-boss/retailmanage/SET_UPLOAD' // 商品编辑 export const SET_GOOD_ITEM_DETAIL = 'inside-boss/goodEdit/SET_GOOD_ITEM_DETAIL' export const SET_GOOD_CATEGORY_LIST = 'inside-boss/goodEdit/SET_GOOD_CATEGORY_LIST' export const SET_GOOD_FACADE = 'inside-boss/goodEdit/SET_GOOD_FACADE' export const SET_GOOD_SKU_LIST = 'inside-boss/goodEdit/SET_GOOD_SKU_LIST' export const SET_GOOD_STEP_LENGTH = 'inside-boss/goodEdit/SET_GOOD_STEP_LENGTH' export const SET_GOOD_UNIT_LIST = 'inside-boss/goodEdit/SET_GOOD_UNIT_LIST' export const SET_FREIGHT_TEMPLATE = 'inside-boss/goodEdit/SET_FREIGHT_TEMPLATE' export const SET_SELECTED_SKU_LIST = 'inside-boss/goodEdit/SET_SELECTED_SKU_LIST' export const SET_SKU_TABLE_DATA = 'inside-boss/goodEdit/SET_SKU_TABLE_DATA' export const SET_GOOD_HEAD_PICTURE = 'inside-boss/goodEdit/SET_GOOD_HEAD_PICTURE' export const SET_GOOD_DETAIL_PICTURE = 'inside-boss/goodEdit/SET_GOOD_DETAIL_PICTUR' //导入履历 export const SET_IMPORT_HISTORY_LIST='inside-boss/importHistory/SET_IMPORT_HISTORY_LIST' export const SET_IMPORT_PAGE_NUM='inside-boss/importHistory/SET_IMPORT_PAGE_NUM' // 组合商品 export const SET_COMBINED_GOODS_LIST='inside-boss/retailmanage/SET_COMBINED_GOODS_LIST' export const SET_COMBINED_GOOD_DETAIL='inside-boss/combinedGoodsEdit/SET_COMBINED_GOOD_DETAIL' export const SET_SELECT_COMBINED_LIST='inside-boss/combinedGoodsEdit/SET_SELECT_COMBINED_LIST' export const SET_CHILD_SPEC_ITEMS='inside-boss/combinedGoodsEdit/SET_CHILD_SPEC_ITEMS' export const SET_SELECT_GOODS_SPEC='inside-boss/combinedGoodsEdit/SET_SELECT_GOODS_SPEC' export const SET_FORAMT_SPEC_GOODS='inside-boss/combinedGoodsEdit/SET_FORAMT_SPEC_GOODS' //自定义标签生成图片 export const SET_GOOD_TAG_IMAGE='inside-boss/goodTagEdit/SET_GOOD_TAG_IMAGE' // 商品标价签获取所有模板 export const SET_PRICE_TAG_MODULE='inside-boss/priceTag/SET_PRICE_TAG_MODULE' // 获取标签模板详情 export const SET_MODULE_DETAIL='inside-boss/goodTagEdit/SET_MODULE_DETAIL' // 更新模板后的结果返回 用来验证模板名称是否重名 export const SET_UPDATE_MODULE_RESULT='inside-boss/goodTagEdit/SET_UPDATE_MODULE_RESULT' <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/cate/index.js import Editor from './CateEditor.js' import Preview from './CatePreview.js' export default { type: Editor.designType, editor: Editor, preview: Preview }; <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/cateList/TmpEditor.js // 商品分类 编辑组件 import React from 'react' import { Radio, Checkbox, Row, Col } from 'antd' import style from './TmpEditor.css' const RadioGroup = Radio.Group export default class CateEditor extends React.PureComponent { constructor(props) { super(props) this.state = { showFields: ['商品名称', '商品价格', '下单按钮',], } } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } selecteTier = (val) => { this.configChang({seeLevel: val.target.value}) } _radioCheck = (str, e) => { const { value } = this.props; const { config } = value let target = e.target.value const orderButton = Object.assign({}, config.orderButton) orderButton[str] = target this.configChang({orderButton}) } _checkboxChange = (item, e) => { let showFields = ['商品名称', '商品价格', '下单按钮'] if(e.target.checked) { // 选中 showFields.push(item) } else { showFields = showFields.filter(v => v != item) } this.configChang({showFields}) } render() { const { value } = this.props const { config } = value const { seeLevel, orderButton } = config const { showFields } = this.state let isShopButton = config.showFields.indexOf('下单按钮') > -1 // 是否显示商品按钮 return ( <div className={style.cate_editor_container}> <div className={style.tier_radio}> <div className={style.tier_title}>展示层级:</div> <RadioGroup value={1} onChange={this.selecteTier} className={style.tier_radio_group}> {/* <Radio name="mode" value={2}>二级分类</Radio> */} <Radio name="mode" value={1}>一级分类</Radio> </RadioGroup> <br/> <div className={style.show_content}> <div className={style.tier_title}>显示内容:</div> <div className={style.content_box}> { showFields.map((item, i) => <Checkbox defaultChecked={true} key={i} disabled={ item === '下单按钮' ? false : true } className={style.rankEditorCheckbox} onChange={(e) => this._checkboxChange(item, e)}> { item } <br/> </Checkbox> )} { isShopButton && <div className={style.show_order_btn}> <RadioGroup value={orderButton.mode} className={style.controlGroupControl} onChange={(e) => this._radioCheck('mode', e)}> <Radio name="mode" value='立即下单'>立即下单</Radio> <Radio name="mode" value='加入购物车'>加入购物车</Radio> </RadioGroup> <br/> {orderButton.mode == '立即下单' ? <RadioGroup value={orderButton.orderStyle} className={style.controlGroupControl} onChange={(e) => this._radioCheck('orderStyle', e)}> <Radio name="orderStyle" value='1'>样式一</Radio> <Radio name="orderStyle" value='2'>样式二</Radio> </RadioGroup> : <RadioGroup value={orderButton.cartStyle} className={style.controlGroupControl} onChange={(e) => this._radioCheck('cartStyle', e)}> <Radio name="cartStyle" value='1'>样式一</Radio> <Radio name="cartStyle" value='2'>样式二</Radio> <Radio name="cartStyle" value='3'>样式三</Radio> </RadioGroup>} </div> } </div> </div> </div> </div> ) } static designType = 'cateList' static designDescription = '分类商品' static getInitialValue() { return { config: { seeLevel: '1', // 显示的分类层级。2 则显示二级分类;1 则只显示一级分类 type: 'cateList', showFields: ['商品名称', '商品价格', '下单按钮'],// 可使用值:名称、价格、下单按钮 / 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) orderButton: { // 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) mode: '加入购物车', // 可选值:下单按钮、加入购物车 orderStyle: '1', // 立即下单按钮样式。可选值:'1'、'2'。仅在 mode=立即下单 时生效 cartStyle: '1', // 加入购物车按钮样式。可选值:'1'、'2'、'3'。仅在 mode=加入购物车 时生效 }, } } } } <file_sep>/inside-boss/src/utils/bridge.js import { hashHistory } from 'react-router' import getUserInfo from './getUserInfo' // import cookie from '@2dfire/utils/cookie' import { logout } from './jump' /** * 从 iframe 取参数集合 * @returns {object} */ export function getParamsObject() { const { query } = hashHistory.getCurrentLocation() return query || {} } export function getInfoAsQuery() { const { shopInfo, userInfo, token } = getUserInfo() const { name, ...rest } = userInfo || {} return { ...shopInfo, ...rest, currVer: 17, token, userName: name } } /** * 从 iframe 取某个参数 * @param {string} key * @returns {*|undefined} */ export function getParam(key) { const { query } = hashHistory.getCurrentLocation() return query.hasOwnProperty(key) ? query.key : undefined } export function callParent(method) { let key = 'INSIDEBOSS:' let origin = '*' switch (method || 'test') { case 'logout': logout() key += 'LOGOUT' break case 'TEST': key += 'TEST' break default: break } parent.top.window.postMessage(key, origin) } <file_sep>/inside-boss/src/components/updown/filter.js import React, { Component } from 'react' import { DatePicker, Checkbox, Button, Message } from 'antd' import cx from 'classnames' import styles from './filter.css' import * as action from '../../action' const CheckboxGroup = Checkbox.Group class DateRange extends Component { state = { endOpen: false } disabledStartDate = (startValue) => { const endValue = this.state.endValue if (!startValue || !endValue) { return false } return startValue.valueOf() > endValue.valueOf() } disabledEndDate = (endValue) => { const startValue = this.state.startValue; if (!endValue || !startValue) { return false; } return endValue.valueOf() <= startValue.valueOf() } onStartChange = (value) => { let val = new Date(value) val = val.valueOf() val = String(val) // console.log(val); val = val.substr(0, val.length - 3) val = `${val}000` // console.log(val); const {dispatch} = this.props sessionStorage.setItem('startTime', val) dispatch(action.setStartValue(value)) } onEndChange = (value) => { let val = new Date(value) val = val.valueOf() val = String(val) // console.log(val); val = val.substr(0, val.length - 3) val = `${val}000` // console.log(val); const {dispatch} = this.props sessionStorage.setItem('endTime', val) dispatch(action.setEndValue(value)) } handleStartOpenChange = (open) => { if (!open) { this.setState({endOpen: true}) } } handleEndOpenChange = (open) => { this.setState({endOpen: open}) } render () { const {data} = this.props const {endOpen} = this.state const {startValue, endValue} = data return ( <div className="cf"> <div className={styles.date_start}>开始时间</div> <DatePicker disabledDate={this.disabledStartDate} showTime format="YYYY-MM-DD HH:mm:ss" value={startValue} placeholder="请选择开始时间" size='large' onChange={this.onStartChange} onOpenChange={this.handleStartOpenChange} style={{marginRight: 150}} /> <div className={styles.date_end}>结束时间</div> <DatePicker disabledDate={this.disabledEndDate} showTime format="YYYY-MM-DD HH:mm:ss" value={endValue} placeholder="请选择结束时间" size='large' onChange={this.onEndChange} open={endOpen} onOpenChange={this.handleEndOpenChange} /> </div> ) } } class Status extends Component { plainOptions () { const {preRechargeCount, sucRechargeCount, faiRechargeCount, cancelRechargeCount} = this.props.data return [ `未充值(${preRechargeCount})`, `充值成功(${sucRechargeCount})`, `充值失败(${faiRechargeCount})`, `已红冲(${cancelRechargeCount})` ] } onChange = (checkedValues) => { let final = {} checkedValues.forEach((m, i) => { let str = m.substring(0, 3) switch (str) { case '未充值': final.never = '0' break case '充值成': final.success = '1' break case '充值失': final.fail = '2' break case '已红冲': final.refund = '3' break default: return } }) let arr = [] for (let key in final) { arr.push(final[key]) } const params = arr.length > 0 ? arr.join(',') : '' sessionStorage.setItem('rechargeStatusList', params) const {dispatch} = this.props dispatch(action.setStatus(checkedValues)) } render () { const t = this const {data} = t.props const {statusList} = data return ( <div className={styles.status_wrapper}> <p className={styles.status_text}>充值状态</p> <div className={styles.status_checkbox}> <CheckboxGroup options={t.plainOptions()} onChange={t.onChange} value={statusList}/> </div> </div> ) } } class FilterButton extends Component { render () { const {data, dispatch, onSearch} = this.props const {btnLocker} = data const bool = (btnLocker && btnLocker.name === 'searchBtn') ? btnLocker.bool : false return <Button type="primary" className={cx(styles.primaryButton)} loading={bool} onClick={e => { e.preventDefault() onSearch(data, dispatch) }}>查询</Button> } } class Filter extends Component { onSearch (data, dispatch) { dispatch(action.btnLock({name: 'searchBtn', bool: true})) const {rechargeBatchId} = data if (!rechargeBatchId) { Message.warning('请选择有效文件') setTimeout(() => { dispatch(action.btnLock({name: 'search', bool: false})) }, 2000) } else { const startTime = sessionStorage.getItem('startTime') const endTime = sessionStorage.getItem('endTime') const rechargeStatusList = sessionStorage.getItem('rechargeStatusList') const pageSize = 50 const pageIndex = 1 const tag = 'fromSearchBtn' dispatch(action.fetchRechargeList({ rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, tag })) } } render () { const {data, dispatch} = this.props return ( <div className={styles.filter_wrapper}> <DateRange data={data} dispatch={dispatch}/> <Status data={data} dispatch={dispatch}/> <FilterButton data={data} dispatch={dispatch} onSearch={this.onSearch}/> </div> ) } } export default Filter <file_sep>/inside-boss/src/container/visualConfig/store/tmpValidators.js import * as bridge from '@src/utils/bridge' export default function validate(content) { try { return executeValidate(content) } catch (e) { if (e.validateMessage) { return e.validateMessage } else { throw e } } } function executeValidate(content) { // entityType: 0=单店 1=连锁总部 2=连锁下的门店 3=分公司 4=商圈 const { industry, entityType } = bridge.getInfoAsQuery() if (industry == 3 && (entityType == 0 || entityType == 2)){ //bare 组件 if (content.nav) validateNav(content.nav) // 非 bare 组件 if (content.components) { content.components.forEach(com => { const componentValidator = validators[com.type] if (componentValidator) componentValidator(com) }) } } } // 使用方式: // 在发现错误的地方,failed(message) function failed(message) { const err = new Error('validate_failed') err.validateMessage = message throw err } const validators = { title(c) { if (!c.text || c.text.length > 20) { failed('标题组件:标题内容应在 1 ~ 20 个字之间') } }, coupons(c) { if (c.source === 'manualAdd') { if (!c.items.length) failed('优惠券组件:请选择优惠券') if (c.items.length > 6) failed('优惠券组件:最多选择 6 张优惠券') } }, announce(c) { if (!c.text || c.text.length > 20) { failed('公告信息:信息内容应在 1 ~ 20 个字之间') } }, goodsList(c) { if (!c.goodsList.length) { failed('商品列表:请选择商品') } if (c.showFields.indexOf('角标') !== -1 && c.subscript.type === 'image' && !c.subscript.image) { failed('商品列表:请上传角标图片') } }, goodsRanking(c) { if (c.showFields.indexOf('角标') !== -1 && c.subscript.type === 'image' && !c.subscript.image) { failed('商品排行:请上传角标图片') } }, pictureAds(c) { if (!c.items.length) failed('图片广告:请添加图片') if (c.items.length > 5) failed('图片广告:最多添加 5 张图片') c.items.forEach((item, i) => { const no = i + 1 if (!item.picture) failed(`图片广告 第${no}项:请上传图片`) }) }, pictureTextNav(c) { if (!c.items.length) failed('图文导航:请添加导航项') if (c.items.length > 5) failed('图文导航:最多添加 4 个导航项') c.items.forEach((item, i) => { const no = i + 1 if (c.mode === '图片导航' || c.mode === '图文导航') { if (!item.picture) failed(`图文导航 第${no}项:请上传图片`) } if (c.mode === '文字导航' || c.mode === '图文导航') { if (!item.text) failed(`图文导航 第${no}项:请填写文字内容`) } }) }, } function validateNav(nav) { if (nav.mode === '经典展开式') { if (!nav.expandItems.length) failed('展开式导航:至少要有1个导航项') if (nav.expandItems.length > 10) failed('展开式导航:不能超过10个导航项') nav.expandItems.forEach((item, i) => { const no = i + 1 if (!item.icon) failed(`展开式导航 第${no}项:请上传图标`) if (!item.linkPage) failed(`展开式导航 第${no}项:请选择要跳转的页面`) }) } else if (nav.mode === 'app式') { if (!nav.appItems.length) failed('App式导航:至少要有1个导航项') if (nav.appItems.length > 10) failed('App式导航:不能超过4个导航项') nav.appItems.forEach((item, i) => { const no = i + 1 if (!item.defaultIcon) failed(`App式导航 第${no}项:请上传默认图标`) if (!item.highlightIcon) failed(`App式导航 第${no}项:请上传高亮图标`) if (!item.linkPage) failed(`App式导航 第${no}项:请选择要跳转的页面`) }) } } <file_sep>/inside-boss/src/components/mall/dialog/index.js import React, { Component } from 'react' import styles from './index.css' import { Upload, Icon, message, Radio, Button } from 'antd' import uploadFile from '../../../utils/uploadFile' import { getRectImageUrl } from '../../../utils/image' const Dragger = Upload.Dragger function getBase64(img, callback) { const reader = new FileReader() reader.addEventListener('load', () => callback(reader.result)) reader.readAsDataURL(img) } const RadioGroup = Radio.Group function filterFile(file, type) { let t1 = 'banner' if (file === 'activity') { t1 = '活动' } let t2 = '新增' if (type === 2) { t2 = '编辑' } const data = { theme: t2 + t1, title: t1 + '标题', img: t1 + '图片' } return data } class Main extends Component { constructor(props) { super(props) this.state = { // 表单数据 type: 0, form: { title: '', url: '', img: '', isSelected: 0 }, // 展示用图片 imageUrl: '' } } componentWillReceiveProps(nextProps) { if (nextProps.form && nextProps.form.id) { const form = this.state.form this.setState({ type: 2, form: { ...form, ...nextProps.form }, imageUrl: nextProps.form.img }) } else { this.setState({ type: 1 }) } } beforeUpload(file) { if (file && file.size && file.size / (1024 * 1024) > 3) { message.warning('您上传的图片太大,请压缩后再试') return false } } // 图片上传 updateImage(info) { const status = info.file.status if (status !== 'uploading') { console.log(info.file, info.fileList) } if (status === 'done') { message.success(`${info.file.name} 上传成功`) const { response = {} } = info.file if (response && response.code === 1 && response.data) { this.updateForm({ img: getRectImageUrl(response.data, { w: 750, h: 260 }) }) getBase64(info.file.originFileObj, imageUrl => { this.setState({ imageUrl }) }) } } else if (status === 'error') { message.error(`${info.file.name} 上传失败`) } } // 切换状态 上架/下架 updateStatus = e => { this.updateForm({ isSelected: e.target.value }) } // 更新标题输入框 updateTitle = e => { this.updateForm({ title: e.target.value }) } // 更新链接输入框 updateUrl = e => { this.updateForm({ url: e.target.value }) } // 更新form数据 updateForm(data = {}) { const form = this.state.form const updatedForm = { ...form, ...data } this.setState({ form: updatedForm }) } // 取消 cancel() { this.props.updateDialog() this.setState({ type: 0, form: { title: '', url: '', img: '', isSelected: 0 }, imageUrl: '' }) } // 保存 change() { const _this = this const { form = {}, type } = this.state const callback = () => { _this.setState({ type: 0, form: { title: '', url: '', img: '', isSelected: 0 }, imageUrl: '' }) } this.props.changeContent({ form, type, callback }) } render() { const { form, type, imageUrl } = this.state const { file, status = 0 } = this.props const header = filterFile(file, type) const draggerProps = uploadFile() return status ? ( <div className={styles.dialog}> <div className={styles.cover} /> <div className={styles.panel}> <h5 className={styles.uddTop}>{header.theme}</h5> <div className={styles.uddPan}> <div className={styles.uddBox}> <div className={styles.uddItem}> <span>{header.title}</span> <input type="text" className={styles.inputText} value={form.title} maxLength="30" onChange={this.updateTitle.bind(this)} /> <div className={styles.tipText}>标题最多为30个字符</div> </div> </div> <div className={styles.uddBox}> <div className={styles.uddItem}> <span>链接地址</span> <input type="text" className={styles.inputText} value={form.url} onChange={this.updateUrl.bind(this)} /> <div className={styles.tipText}> 只支持微信公众号链接或者二维火链接 </div> </div> </div> <div className={styles.uddBox}> <div className={styles.uddItem}> <span>{header.img}</span> <div className={styles.imageDragger}> <div className={styles.imageUrl} style={{ backgroundImage: 'url(' + imageUrl + ')', backgroundSize: 'cover', backgroundPosition: 'center' }} /> <Dragger {...draggerProps} previewVisible={false} beforeUpload={this.beforeUpload.bind(this)} onChange={this.updateImage.bind(this)} /> </div> <div className={styles.tipText}>图片尺寸建议为750*260px</div> </div> </div> <div className={styles.uddBox}> <div className={styles.uddItem}> <span>是否上架</span> <div className={styles.groundSelect}> <RadioGroup onChange={this.updateStatus.bind(this)} value={form.isSelected} > <Radio value={0}>否</Radio> <Radio value={1}>是</Radio> </RadioGroup> </div> </div> </div> </div> <div className={styles.bottom}> <Button className={styles.uddButton} onClick={this.cancel.bind(this)} > 取消 </Button> <Button className={styles.uddButton} onClick={this.change.bind(this, form)} type="primary" > 保存 </Button> </div> </div> </div> ) : null } } export default Main <file_sep>/inside-boss/src/container/visualConfig/components/checkShopStatus/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import { loadBaseInfo } from '@src/container/visualConfig/store/actions' import { getBaseInfoStatus } from '@src/container/visualConfig/store/selectors' import { Loading, LoadFailed, CanNotConfig } from './status' import cookie from '@2dfire/utils/cookie' /* 根据店铺状态显示提示信息,仅在店铺可配置的情况下挂载、渲染被装饰的组件。 使用方法: @checkShopStatus class SomeComponent { ... } */ export default function checkShopStatus(WrappedComponent) { return function Decorated(props) { return <ShopStatusWrapper> <WrappedComponent {...props} /> </ShopStatusWrapper> } } @connect(state => ({ baseInfoStatus: getBaseInfoStatus(state), shopInfo: state.visualConfig.shopInfo, })) class ShopStatusWrapper extends Component { componentWillMount() { // baseInfo 未载入或载入失败时,执行加载 if (!this.props.baseInfoStatus) { loadBaseInfo() } } render() { const { baseInfoStatus, shopInfo } = this.props const data = JSON.parse(cookie.getItem('entrance')).shopInfo const { entityTypeId, isInLeague } = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (baseInfoStatus === null) return <Loading /> if (baseInfoStatus === false) return <LoadFailed retry={loadBaseInfo} /> if (entityTypeId == '10' || (entityTypeId == '3' && isInLeague)) return this.props.children if (!shopInfo.canConfig) return <CanNotConfig /> // 仅在 shopInfo 可用且允许配置时渲染实际页面内容 return this.props.children } } <file_sep>/inside-boss/src/components/customBillDetail/right.js import React, { Component } from 'react' import { Select, Checkbox, Input, Button } from 'antd' const { TextArea } = Input const Option = Select.Option import styles from './css/main.css' import cls from 'classnames' import { message } from 'antd/lib/index' export default class Right extends Component { constructor(props) { super(props) this.state = { placeholder: { '1_1': '1倍宽*1倍高', '1_2': '1倍宽*2倍高', '2_1': '2倍宽*1倍高', '2_2': '2倍宽*2倍高', // '2_4': '2倍宽*4倍高', '4_4': '4倍宽*4倍高' }, align: { left: 'LEFT', center: 'CENTER', right: 'RIGHT' } } this.getOptionHtml = this.getOptionHtml.bind(this) this.getAlign = this.getAlign.bind(this) } //字体下拉框html内容获取 getOptionHtml() { let option = [] for (let i in this.state.placeholder) { option.push( <Option value={i} key={i}> {this.state.placeholder[i]} </Option> ) } return option } //字体对齐方式html内容获取 getAlign() { const { activeItem } = this.props.data let align = [] for (let i in this.state.align) { align.push( <span key={i} className={cls( styles.align_box, styles[`align_${i}`], activeItem.style === this.state.align[i] ? styles.align_active : '' )} onClick={this.alignSelect.bind(this, this.state.align[i])} /> ) } return align } /** * 对齐方式 * @param type 对齐方式值LEFT/CENTER/RIGHT * */ alignSelect(type) { try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].style = type this.props.editState({ data: data }) } catch (e) { message.error('修改失败') } } /** * 字体大小 * @param fontSize 字体大小 1_1 * */ fontSelectChange(fontSize) { try { let font = fontSize.split('_') let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].dWidth = Number(font[0]) data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].dHigh = Number(font[1]) this.props.editState({ data: data }) } catch (e) { message.error('修改失败') } } /** * 添加前缀 * */ prefixChange(e) { let val = e.target.value try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].prefix = val this.props.editState({ data: data }) } catch (e) { message.error('修改失败') } } /** * 添加前缀 * */ valueChange(e) { let val = e.target.value try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].value = val this.props.editState({ data: data }) } catch (e) { message.error('修改失败') } } /** *添加下划线 * @param type ADD 添加 DEL 删除 * */ editCutOff(type) { try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj let nextIndex = Number(activeItemIndex) + 1 if (type === 'ADD') { data.tmplVo.itemRowVoList[activeItemIndex].nextIsDashed = true if ( data.tmplVo.itemRowVoList[nextIndex].columnList[0].itemCode === 'I_DASHED' ) { data.tmplVo.itemRowVoList[nextIndex].columnList[0].showType = 'SHOW' } else { const cutOffLine = { columnList: [ { charNum: 0, dHigh: 1, dWidth: 1, id: "0", index: 0, itemCode: 'I_DASHED', name: '虚线', optionList: [], parentId: '0', prefix: '', showType: 'SHOW', style: 'CENTER', type: 'IT_OTHER', value: '', widthPct: 100 } ], nextIsDashed: false } data.tmplVo.itemRowVoList.splice(nextIndex, 0, cutOffLine) } this.props.editState({ data: data, activeItemIndex: '', activeColumnIndex: '' }) } else if (type === 'DEL') { data.tmplVo.itemRowVoList[activeItemIndex - 1].nextIsDashed = false if ( data.tmplVo.itemRowVoList[nextIndex - 1].columnList[0].itemCode === 'I_DASHED' ) { data.tmplVo.itemRowVoList.splice(nextIndex - 1, 1) // data.tmplVo.itemRowVoList[nextIndex-1].columnList[0].showType = 'HIDDEN' } this.props.editState({ data: data, activeItemIndex: '', activeColumnIndex: '' }) } } catch (e) { message.error('修改失败') } } /** * 添加空白行 * */ addEmpty() { try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj const cutOffLine = { columnList: [ { charNum: 0, font: '1_1', id: "0", index: 0, itemCode: 'I_EMPTY', name: '空白行', optionList: [], parentId: '0', prefix: '', showType: 'SHOW', style: 'LEFT', type: '', value: '', widthPct: 100 } ], nextIsDashed: false } data.tmplVo.itemRowVoList.splice( Number(activeItemIndex) + 1, 0, cutOffLine ) let blankIndex = Number(activeItemIndex) + 1; this.props.editState({ data: data},blankIndex) } catch (e) { message.error('修改失败') } } /** * 删除空白行 * */ delEmpty() { try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj if ( data.tmplVo.itemRowVoList[activeItemIndex].columnList[0].itemCode !== 'I_EMPTY' ) { message.error('当前选中的行不是空行,不能删除') return false } data.tmplVo.itemRowVoList.splice(Number(activeItemIndex), 1) this.props.editState({ data: data, activeItemIndex: '', activeColumnIndex: '' }) } catch (e) { message.error('修改失败') } } /** * 添加自定义内容 * */ editCustom(e) { let val = e.target.value // console.log(e.target.value.replace("\n","2222")) try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj if ( data.tmplVo.itemRowVoList[activeItemIndex].columnList[0].itemCode === 'I_EMPTY' ) { data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].value = val this.props.editState({ data: data }) } else { message.error('当前选中的行不是空行,无法加入自定义内容') } } catch (e) { message.error('修改失败') } } /** * 可选内容 * */ optionSelect(e) { try { let obj = Object.assign({}, this.props.data) const { activeItemIndex, activeColumnIndex, data } = obj data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].optionList = data.tmplVo.itemRowVoList[activeItemIndex].columnList[ activeColumnIndex ].optionList.map(val => { if (e.includes(val.value)) { return { ...val, choice: true } } else { return { ...val, choice: false } } }) this.props.editState({ data: data }) // this.setState({ data: data }) } catch (e) { message.error('修改失败') } } render() { const { data, dispatch, params } = this.props const { activeItem, nextIsDashed } = data let font = activeItem.dWidth && activeItem.dHigh ? '' + activeItem.dWidth + '_' + activeItem.dHigh : '1_1' return ( <ul className={styles.right}> <li> <div className={styles.right_title}>字体</div> <Select showSearch placeholder={this.state.placeholder[font]} optionFilterProp="children" value={font} onChange={this.fontSelectChange.bind(this)} filterOption={(input, option) => option.props.children .toLowerCase() .indexOf(input.toLowerCase()) >= 0 } className={styles.right_input} > {this.getOptionHtml()} </Select> </li> <li> <div className={styles.right_title}>对齐</div> <div>{this.getAlign()}</div> </li> {(() => { if (!!activeItem.optionList && activeItem.optionList.length > 0) { let optionList = activeItem.optionList let activeOption = optionList.map(val => { if (!!val.choice) { return val.value } }) return ( <li> <div className={styles.right_title}>可选内容</div> <Checkbox.Group style={{ width: '100%' }} defaultValue={activeOption} onChange={this.optionSelect.bind(this)} > {activeItem.optionList.length > 0 && activeItem.optionList.map((val, index) => { return ( val.itIsOption && ( <p className={styles.right_select} key={index}> <Checkbox value={val.value} checked={!!val.choice}> {val.name} </Checkbox> </p> ) ) })} </Checkbox.Group> </li> ) } })()} {(() => { if ( !activeItem.fixedText && activeItem.itemCode !== 'I_EMPTY' && activeItem.itemCode !== 'I_DASHED' ) { return ( <li> <div className={styles.right_title}>前缀</div> <Input value={activeItem.prefix} className={styles.right_input} onChange={this.prefixChange.bind(this)} maxLength="10" /> </li> ) } })()} {(() => { if (activeItem.fixedText) { return ( <li> <div className={styles.right_title}>文字内容</div> <Input value={activeItem.value} className={styles.right_input} onChange={this.valueChange.bind(this)} /> </li> ) } })()} {(() => { if (activeItem.itemCode === 'I_EMPTY') { return ( <li> <div className={styles.right_title}>自定义内容</div> <TextArea value={activeItem.value} className={cls(styles.right_input,styles.right_textArea)} onChange={this.editCustom.bind(this)} maxLength="150" /> </li> ) } })()} <li> <Button className={cls(styles.right_input, styles.right_btn)} onClick={this.addEmpty.bind(this)} > 在下方增加空行 </Button> </li> {nextIsDashed ? ( '' ) : ( <li> <Button className={cls(styles.right_input, styles.right_btn)} onClick={this.editCutOff.bind( this, activeItem.itemCode !== 'I_DASHED' ? 'ADD' : 'DEL' )} > {activeItem.itemCode !== 'I_DASHED' ? '在下方添加分隔符' : '删除分隔符'} </Button> </li> )} {activeItem.itemCode !== 'I_EMPTY' ? ( '' ) : ( <li> <Button className={cls(styles.right_input, styles.right_btn)} onClick={this.delEmpty.bind(this)} > 删除空行 </Button> </li> )} </ul> ) } } <file_sep>/static-hercules/src/approval/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; import router from "@2dfire/utils/router" const API = { getData(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.activiti.service.IApprovalClientService.getApprovalAttachment', params: { appKey: APP_KEY, process_instance_id: router.route.query["process_instance_id"], ...params } }) } } export default API;<file_sep>/static-hercules/src/secured-account/store/getters.js const getters = { getMerchantInfo(state){ return state.merchantInfo }, bankSub(state){ return { bankCode:state.merchantInfo.accountBankCode, bankCityId:state.merchantInfo.accountAddressCityCode } }, applyStep(state){ return { 2:[ //开户人姓名 'accountName', //身份证号 'idCard', //开户银行 'accountBank', //银行卡号 'accountNumber', //开户省市 'accountAddressProvince', 'accountAddressCity', //开户支行 'accountSubBank', //手机号码 'userTelNumber', //验证码 'authCode', //营业执照 'businessLicensePic', ], 1:[ 'accountName', //开户银行 'accountBank', //银行卡号 'accountNumber', //开户省市 'accountAddressProvince', 'accountAddressCity', //开户支行 'accountSubBank', //手机号码 'userTelNumber', //验证码 'authCode', //营业执照 'businessLicensePic', ] } }, clearList(){ return[ //开户人姓名 'accountName', //身份证号 'idCard', //开户银行 'accountBank', 'accountBankCode', //银行卡号 'accountNumber', //开户省市 'accountAddressProvince', 'accountAddressProCode', 'accountAddressCity', 'accountAddressCityCode', //开户支行 'accountSubBank', 'accountSubBankCode', //手机号码 'userTelNumber', //验证码 'authCode', //营业执照 'businessLicensePic', ] }, getAccountSubBank(state){ return state.merchantInfo.accountSubBank } } export default getters <file_sep>/static-hercules/src/give-key/router.js var Router = require("vue-router"); export var router = new Router({ routes: [{ path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "签到领激活码", component: require("./views/index.vue") }, { path: "/details", name: "details", title: "活动详情", component: require("./views/details.vue") }, { path: "/signin", name: "signin", title: "签到", component: require("./views/signin.vue") }, { path: "/successful", name: "successful", title: "升级成功", component: require("./views/successful.vue") }] }); router.beforeEach((to, from, next) => { // console.log(to,from,next); // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) <file_sep>/inside-chain/src/config/api_pay.js // 付款方式 import {API_BASE_URL} from "apiConfig"; import Requester from '@/base/requester' import {GW} from '@2dfire/gw-params'; const AND = '&' + GW; const API = { /** * 获取付款方式 * opEntityId 被操作门店ID * kind 支付类型,全部-1 * name 支付名称 * */ getKindPayList(params) { console.log('getKindPayList') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.getKindPayList" + AND, { // params: { // opEntityId: params.opEntityId, // kind: params.kind, // name: params.name // } params: params } ) }, /** * 获取付款方式 下拉列表用 */ getPayKindListForSelect() { console.log('getPayKindListForSelect') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.getKindList" + AND, ) }, /** * 获取付款方式 */ checkAlipayPayment(params) { console.log('checkAlipayPayment') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.checkAlipayPayment" + AND, { params: params } ) }, /** * 修改支付宝优惠开关 */ updateAlipayPayment(params) { console.log('updateAlipayPayment') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.updateAlipayPayment" + AND, { params: params } ) }, /** * 保存支付方式-新建/编辑 * * opEntityId 被操作门店ID * id 新增不传,编辑必传 * kind 支付类型,全部-1 * name 支付名称 * isInclude 是否计入实收 * isOpenCashDrawer 是否打开钱箱 * voucherForms [] 代金券 * id 新增不传,编辑删除必传 * amount 面值 * sellPrice 售价 * isValid 是否删除。0删除,1不删除 */ saveKindPay(params) { console.log('saveKindPay') return Requester.post( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.saveKindPay" + AND, params, { emulateJSON: true } ) }, /** * 删除付款方式 * * opEntityId ,门店id * id: 付款方式id */ deleteKindPay(params) { console.log('deleteKindPay') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.deleteKindPay" + AND,{ params: params } ) }, /** * 获取付款方式详情 * * opEntityId 被操作门店ID * id 付款方式id */ getPayKindInfo(params) { console.log('getPayKindInfo') return Requester.get( API_BASE_URL + "com.dfire.soa.tradeconf.api.pay.service.IKindPayService.getKindPayDetail" + AND,{ params: params } ) } } export default API; <file_sep>/inside-chain/src/store/modules/components/chainRoleManage.js import Requester from '@/base/requester' import catchError from '@/base/catchError' import API from '@/config/api.js' import Obj from '@2dfire/utils/object' import Vue from 'vue'; import iView from "iview"; import router from "@/router"; import Cookie from '@2dfire/utils/cookie' import Tools from '@/base/tools' import { userHireType } from '@/const/emu-joinModeIcon' Vue.use(iView) const Spin = iView.Spin const config = { render: (h) => { return h('div', [ h('Icon', { 'style': 'animation: ani-demo-spin 1s linear infinite', props: { type: 'load-c', size: 18 } }), h('div', 'Loading') ]) } } const Message = iView.Message const Modal = iView.Modal let shopInfo = { entityId:'', entityType:'', industry:'' } let entrance = [] if(Cookie.getItem('entrance') != undefined){ shopInfo = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).shopInfo entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) } const chainRoleManage = { namespaced: true, state: { allChainStaffList:[], staffList:[], chainStaffList:[], listShopRoles:[], querySyntheList:{ branchsVo:{ all:true, userSynthesizeVos: [] }, platesVo:{ all:true, userSynthesizeVos: [] }, shopsVo:{ all:true, userSynthesizeVos: [] } }, querySumpleList:{}, filter:{ searchValue:'', roleId:'-1' }, chainRoleList:[], cacheRoleList:[] }, mutations: { _getStaffList(state,data){ state.chainStaffList = Object.assign({},data) }, _staffList(state,data){ state.staffList = [].concat(data) }, _allStaffList(state,data){ state.allChainStaffList = [].concat(data) }, _getListShopRoles(state,data){ state.listShopRoles = [].concat(data) }, _searchValueChange(state,data){ state.filter.searchValue = data }, _changeRoleID(state,data){ state.filter.roleId = data }, _querySyntheList(state,data){ state.querySyntheList = Object.assign( {}, data) }, _querySumpleList(state,data){ state.querySumpleList = Object.assign( {}, data) }, _getAllActionGroupList(state,data){ state.chainRoleList = [].concat(data) }, _clearGroupList(state,data){ state.chainRoleList = [].concat(data) }, _cacheRoleList(state,data){ state.cacheRoleList = [].concat(data) }, _clearFilter(state){ state.filter = { searchValue: '', roleId: '-1' } } }, actions:{ //获取总部员工列表 getStaffList({commit, state},params){ const { pageIndex, pageSize } = params const startNum = ( pageIndex - 1 ) * pageSize const filter = state.filter let newData = [] let new_data = [] const req = { entityId:shopInfo.entityId } Requester.get(API.GET_QUERY_USER_LINE_INFO,{params:{...req}}).then(res=>{ if(Obj.isEmpty(!res.data)){ newData = [] res.data.map(item=>{ newData.push({ avatarUrl: item.avatarUrl||'', branchCount: item.branchCount, countryCode: item.countryCode, entityId: item.entityId||'', entryDate: item.entryDate?Tools.formatDateByStamp(item.entryDate):'-', frozenStatus: item.frozenStatus, hireType: userHireType[item.hireType] || '-', isAllBranch: item.isAllBranch, isAllPlate: item.isAllPlate, isAllShop: item.isAllShop, isValid: item.isValid, lastVer: item.lastVer, mobile: item.mobile||'', name: item.name||'', roleId: item.roleId||'', roleName: item.roleName||'', shopCount: item.shopCount, userId: item.userId||'', userName: item.userName||'', plateCount: item.plateCount }) }) new_data = newData.filter(item=>{ return (((Obj.isString(item.name)?item.name.includes(filter.searchValue):false) || (Obj.isString(item.mobile)?item.mobile.includes(filter.searchValue):false)) && (filter.roleId === '-1'? true : item.roleId === filter.roleId)) }) let obj = { total: new_data.length, list: [].concat(new_data).splice( startNum,pageSize ) } commit('_getStaffList',obj) commit('_staffList',new_data) commit('_allStaffList',newData) } }).catch(e=>{ catchError(e) }) }, //连锁员工冻结 updateFrozenStatus({dispatch},params){ const req = { id: params.id, entityId: shopInfo.entityId, frozenStatus:params.frozenStatus, appKey: '200800' } Requester.get(API.UPDATE_FROZEN_STATUS,{params:{...req}}).then(res=>{ if(res.data){ Message.info(params.frozenStatus?'冻结成功':'恢复成功') dispatch('getStaffList',params.pageState) } }).catch(e=>{ catchError(e) }) }, //连锁员工删除 deteleThoroughUser({dispatch},params){ const req = { userId: params.id, entityId: shopInfo.entityId } Requester.get(API.DETELE_THOROUGH_USER,{params:{...req}}).then(res=>{ if(res.data){ Message.info('删除成功') dispatch('getStaffList',params.pageState) } }).catch(e=>{ catchError(e) }) }, //获取店铺职权 getListShopRoles({commit},params = false){ const req = { entityId: shopInfo.entityId, containUser: params, } Requester.get(API.GET_LIST_SHOP_ROLES_NEW,{params:{...req}}).then(res=>{ commit('_getListShopRoles',res.data) }).catch(e=>{ catchError(e) }) }, //新增员工信息 insertChainUserInfo({commit},params){ const req = { entityId: shopInfo.entityId, ...params } // Requester.post(API.INSERT_CHAIN_USER,{...req},{emulateJSON: true}).then(res=>{ Requester.post(API.INSERT_CHAIN_USER,{completeDTO: JSON.stringify(req) },{emulateJSON: true}).then(res=>{ router.push('/chain_staff_list') }).catch(e=>{ catchError(e) }) }, //修改员工信息 updateChainUserInfo({commit},params){ const req = { entityId: shopInfo.entityId, ...params } // Requester.post(API.INSERT_CHAIN_USER,{...req},{emulateJSON: true}).then(res=>{ Requester.post(API.UPDATE_CHAIN_USER,{completeDTO: JSON.stringify(req) },{emulateJSON: true}).then(res=>{ router.push('/chain_staff_list') }).catch(e=>{ catchError(e) }) }, //获取员工高级设置 getQuerySynthesize({commit},params = ''){ const req = { entityId: shopInfo.entityId, userId: params } Requester.get(API.GET_QUERY_SYNTHE_SIZE,{params:{...req}}).then(res=>{ let data = {} if(!Obj.isEmpty(res.data)){ data = { branchsVo:{ all:res.data.branchsVo.all, userSynthesizeVos: Obj.isEmpty(res.data.branchsVo.userSynthesizeVos)?[]:res.data.branchsVo.userSynthesizeVos, }, platesVo:{ all:res.data.platesVo.all, userSynthesizeVos: Obj.isEmpty(res.data.platesVo.userSynthesizeVos)?[]:res.data.platesVo.userSynthesizeVos }, shopsVo:{ all:res.data.shopsVo.all, userSynthesizeVos: Obj.isEmpty(res.data.shopsVo.userSynthesizeVos)?[]:res.data.shopsVo.userSynthesizeVos } } } commit('_querySyntheList',data) }).catch(e=>{ // catchError(e) Modal.error({ title: "请注意", content: e.result && e.result.message, okText: "刷新", onOk() { window.location.reload(); } }); }) }, //获取员工基本信息 getQueryBaseInfo({commit},params = ''){ const req = { entityId: shopInfo.entityId, userId: params // userId: entrance.userInfo.userId } Requester.get(API.GET_QUERY_SUMPLE_INFO,{params:{...req}}).then(res=>{ if(res.data){ const data = { avatarUrl: Obj.isEmpty(res.data.avatarUrl)? '' : res.data.avatarUrl, entityId: Obj.isEmpty(res.data.entityId)? '' : res.data.entityId, entryDate: res.data.entryDate?Tools.formatDateByStamp(res.data.entryDate):'', frozenStatus: Obj.isEmpty(res.data.frozenStatus)? '' : res.data.frozenStatus, hireType: Obj.isEmpty(res.data.hireType)? '' : res.data.hireType, isValid: Obj.isEmpty(res.data.isValid)? '' : res.data.isValid, lastVer: Obj.isEmpty(res.data.lastVer)? '' : res.data.lastVer, name: Obj.isEmpty(res.data.name)? '' : res.data.name, roleId: Obj.isEmpty(res.data.roleId)? '' : res.data.roleId, roleName: Obj.isEmpty(res.data.roleName)? '' : res.data.roleName, userId: Obj.isEmpty(res.data.userId)? '' : res.data.userId, userName: Obj.isEmpty(res.data.userName)? '' : res.data.userName, mobile: Obj.isEmpty(res.data.mobile)? '' : res.data.mobile, idCard: Obj.isEmpty(res.data.idCard)? '' : res.data.idCard, sex: Obj.isEmpty(res.data.sex)? '' : `${res.data.sex}`, staffImageDTO:{ avatarUrl:Obj.isEmpty(res.data.avatarUrl)? '' : res.data.avatarUrl, backImgUrl:Obj.isEmpty(res.data.backImgUrl)? '' : res.data.backImgUrl, frontImgUrl:Obj.isEmpty(res.data.frontImgUrl)? '' : res.data.frontImgUrl, }, } commit('_querySumpleList',data) } }).catch(e=>{ // catchError(e) Modal.error({ title: "请注意", content: e.result && e.result.message, okText: "刷新", onOk() { window.location.reload(); } }); }) }, //更改筛选字段 searchValueChange({commit},params){ commit('_searchValueChange',params) }, //更改roleId changeRoleID({commit,dispatch},params){ commit('_changeRoleID',params.value) dispatch('searchStaff',params.pageState) }, // 模糊搜索 searchStaff({commit,state},params){ const staffList = state.allChainStaffList const filter = state.filter const { pageIndex , pageSize } = params const startNum = (pageIndex - 1 ) * pageSize let new_Date = [] new_Date = staffList.filter(item=>{ return (((Obj.isString(item.name)?item.name.includes(filter.searchValue):false) || (Obj.isString(item.mobile)?item.mobile.includes(filter.searchValue):false)) && (filter.roleId === '-1'? true : item.roleId === filter.roleId)) }) let obj = { total: new_Date.length, list: [].concat(new_Date).splice(startNum,pageSize) } commit('_staffList',new_Date) commit('_getStaffList',obj) }, //分页 changePage({commit,state},params){ const staffList = state.staffList const { pageIndex , pageSize } = params const startNum = (pageIndex - 1 ) * pageSize let obj = { total: staffList.length, list: [].concat(staffList).splice(startNum,pageSize) } commit('_getStaffList',obj) }, //职级查询 getRoleDetalList({commit},params = ''){ const req = { code: shopInfo.entityType, industry:shopInfo.industry, } Spin.show(config) Requester.get(API.GET_ROLE_DETAL_LIST,{params:{...req}}).then(res=>{ let dataList = [] if(!Obj.isEmpty(res.data)){ res.data.map(i=>{ dataList.push({ name:i.name, id:i.id, actionGroupVOList:i.actionGroupVOList.map(j=>{ j.rote = (j.totalCount === 0 ? 0 : Math.round(j.actionCount / j.totalCount * 100)) + '%' return j }) }) }) } Spin.hide() commit('_cacheRoleList',dataList) commit('_getAllActionGroupList',dataList.filter(i=>{ return Obj.isString(i.name)?i.name.includes(params):false } )) }).catch(e=>{ Spin.hide() catchError(e) }) }, //删除职级 deleteRole({commit,dispatch},params){ let req = { entityId:shopInfo.entityId, loginEntityId:shopInfo.entityId, userId:entrance.userInfo.userId, } Requester.get(API.DELETE_ROLE,{ params: { roleId: params.id, reqParamStr: JSON.stringify( req )}}).then( res =>{ Message.info('删除成功') dispatch('getRoleDetalList',params.value) }).catch(e=>{ catchError(e) }) }, //职级搜索 filterRoleList({commit,state},params){ const roleList = state.cacheRoleList let newData = [] newData = roleList.filter(i=>{ return Obj.isString(i.name)?i.name.includes(params):false }) commit('_getAllActionGroupList',newData) }, //清空列表 clearGroupList({commit}){ commit('_clearGroupList',[]) }, clearFilter({commit}){ commit('_clearFilter') } }, getters: { getChainStaffList(state){ return state.chainStaffList }, listShopRoles(state){ return state.listShopRoles }, getQuerySyntheList(state){ return state.querySyntheList }, querySumpleList(state){ return state.querySumpleList }, getAllActionGroupList(state){ return state.chainRoleList } } } export default chainRoleManage<file_sep>/static-hercules/build.sh #!/usr/bin/env bash envtype=$1 #git pull # npm --registry https://registry.npm.taobao.org install npm install npm run build NODE_ENV=$envtype npm run gulp $envtype # if [ $envtype == 'dev' ] ; then # echo -e "\033[31m 开始上传到日常服务器 \033[0m" # ncftpput -R -v -u dihuo -p dihuo 10.1.6.60 d2/$myPath release/min/* # # echo -e "\033[31m 清除服务器缓存 \033[0m" # echo -e "\033[31m 上传完毕,如有问题联系<EMAIL> \033[0m" # echo -e "\033[31m 如未安装ncftp , 请先安装。 mac : brew install ncftp \033[0m" # fi # 保留打包信息 只用dev pre daily # if [[ $envtype = 'dev' ]] || [[ $envtype = 'pre' ]] || [[ $envtype = 'daily' ]]; then # echo -e "<pre>build at: $(date)\nbranch: $(git rev-parse --abbrev-ref HEAD)\ncommit: $(git log --pretty=oneline -1)</pre>" > ./release/min/build_info.html # fi <file_sep>/inside-chain/src/store/modules/setting/actions.js import * as types from './mutation-types' import catchError from '@/base/catchError' import { apiGetBrandList, apiFilterGoodsList, apiGetCategory, apiDeleteGoods, apiFilterSuit, apiDeleteSuit, apiGetGoodsDetail, apiGetSelectList, apiGetGoodsLabelList, apiGetSuitBaseInfo, apiAddGoodsItem, apiModifyGoodsItem, apiGetOrderUnit, apiGetSuitLabelList, apiGetSuitGoods, apiGetSuitItems, apiSaveSuitBaseInfo, apiSaveSuitItems } from '@/config/api_setting.js' // 获取品牌列表 export const getBrandList = ({commit}) => { apiGetBrandList().then(data => { let arr = [] if (!!data.data && data.data.length) { arr = data.data.map(item => { return { name: item.name, entityId: item.entityId, canManage: item.canManage, defaultPlate: item.defaultPlate } }) } commit(types.GET_BRAND_LIST, arr) }).catch(e => { catchError(e) }) } // 获取商品/套餐 分类列表(下拉选择框) export const getCategoryList = ({commit}, params) => { return new Promise((resolve, reject) => { let {isInclude, plateEntityId, opEntityId, type} = params console.log(params) apiGetCategory(isInclude, plateEntityId, opEntityId).then(data => { if (type === 'suitGoods') { commit(types.GET_SUIT_GOODS_CATEGORY_LIST, data.data) } else { commit(types.GET_CATEGORY_LIST, data.data) } resolve(true) }).catch(e => { catchError(e) reject(e) }) }) } // 获取商品列表 export const getGoodsList = ({commit}, params) => { let {plateEntityId, kindId, keyWord, pageNum, pageSize, opEntityId} = params // 先置空 if (!!opEntityId) { commit(types.GET_SINGLE_GOODS_LIST, []) } else { commit(types.GET_CHAIN_GOODS_LIST, []) } apiFilterGoodsList( plateEntityId, kindId, keyWord, pageNum, pageSize, opEntityId ).then(data => { // 判断是单店还是连锁 if (!!opEntityId) { commit(types.GET_SINGLE_GOODS_LIST, data.data) } else { commit(types.GET_CHAIN_GOODS_LIST, data.data) } }).catch(e => { catchError(e) }) } // 删除商品 export const deleteGoods = ({commit}, params) => { let {plateEntityId, idList, opEntityId, kindId, keyWord, pageSize} = params apiDeleteGoods(plateEntityId, idList, opEntityId).then(data => { !!data.data && getGoodsList({commit}, {plateEntityId, kindId, keyWord, pageNum: 1, pageSize, opEntityId}) }).catch(e => { catchError(e) }) } // 获取新增/编辑商品时候各个select的内容 export const getGoodsSelectList = ({commit}, params) => { let {opEntityId, plateEntityId, itemId, type} = params apiGetSelectList(opEntityId, plateEntityId).then(data => { commit(types.GET_GOODS_SELECT_LIST, data.data) // 如果是编辑的话就要去请求商品的默认值 if (type === 'edit') { getGoodsDetail({commit}, {opEntityId, plateEntityId, itemId}) } }).catch(e => { catchError(e) }) } // 获取商品标签列表 export const getGoodsLableList = ({commit}, params) => { let {opEntityId, plateEntityId} = params apiGetGoodsLabelList(opEntityId, plateEntityId).then(data => { commit(types.GET_GOODS_LABEL_LIST, data.data) }).catch(e => { catchError(e) }) } // 获取商品详情 export const getGoodsDetail = ({commit}, params) => { let {itemId, plateEntityId, opEntityId} = params // 先清空之前的数据 commit(types.CLEAR_GOODS_DETAIL_FROM_BACK) apiGetGoodsDetail(itemId, plateEntityId, opEntityId).then(data => { commit(types.GET_GOODS_DETAIL, data.data) commit(types.MERGE_GOODS_DETAIL, data.data) }).catch(e => { catchError(e) }) } // 清空商品详情 export const clearGoodsDetail = ({commit}) => { commit(types.CLEAR_GOODS_DETAIL_FROM_BACK) } // 新增商品 export const addGoodsItem = ({commit}, params) => { let { opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude, callback } = params apiAddGoodsItem(opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude).then(data => { // 清空传递给后端的参数 if (data.data) { commit(types.CLEAR_GOODS_DETAIL_TO_BACK) callback && callback() } }).catch(e => { catchError(e) }) } // 清除detail的数据 export const clearGoodsDetailToBack = ({commit}) => { commit(types.CLEAR_GOODS_DETAIL_TO_BACK) commit(types.CLEAR_GOODS_DETAIL_FROM_BACK) } // 修改商品 export const modifyGoodsItem = ({commit}, params) => { let { opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude, callback } = params apiModifyGoodsItem(opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude).then(data => { // 清空传递给后端的参数 commit(types.CLEAR_GOODS_DETAIL_TO_BACK) // 清空点击编辑时候从后端拿到的数据 commit(types.CLEAR_GOODS_DETAIL_FROM_BACK) callback && callback() }).catch(e => { catchError(e) }) } // 修改新增/编辑商品传递给后端的那些参数 detailToBack export const changeGoodsItemVal = ({commit}, params) => { commit(types.CHANGE_GOODS_VAL, params) } // 获取套餐列表 export const getSuitList = ({commit}, params) => { let {opEntityId, plateEntityId, kindId, keyWord, pageIndex, pageSize} = params apiFilterSuit( opEntityId, plateEntityId, keyWord, kindId, pageIndex, pageSize ).then(data => { if (!!opEntityId) { commit(types.GET_SINGLE_SUIT_LIST, data.data) } else { commit(types.GET_CHAIN_SUIT_LIST, data.data) } }).catch(e => { catchError(e) }) } // 删除套餐 export const deleteSuit = ({commit}, params) => { let {plateEntityId, kindId, keyWord, pageSize, suitId, opEntityId} = params apiDeleteSuit(opEntityId, suitId, plateEntityId).then(data => { !!data.data && getSuitList({commit}, {opEntityId, plateEntityId, kindId, keyWord, pageIndex: 1, pageSize}) }).catch(e => { catchError(e) }) } // 获取新增/编辑时候套餐的点菜单位select列表 export const getOrderUnitSelectList = ({commit}) => { return new Promise((resolve, reject) => { apiGetOrderUnit().then(data => { commit(types.GET_ORDER_UNIT_SELECT_LIST, data.data) resolve(true) }).catch(e => { catchError(e) reject(e) }) }) } // 获取套餐的标签列表 export const getSuitLableList = ({commit}, params) => { let opEntityId = params.opEntityId apiGetSuitLabelList(opEntityId).then(data => { commit(types.GET_SUIT_LABEL_LIST, data.data) }).catch(e => { catchError(e) }) } // 获取套餐内的商品列表 export const getSuitGoodsList = ({commit}, params) => { let {plateEntityId, kindId, keyWord, pageNum, pageSize, opEntityId, callback} = params commit(types.GET_SUIT_GOODS_LIST, []) apiGetSuitGoods( plateEntityId, kindId, keyWord, pageNum, pageSize, opEntityId ).then(data => { commit(types.GET_SUIT_GOODS_LIST, data.data) callback && callback() }).catch(e => { catchError(e) callback && callback() }) } // 修改新增/编辑套餐基本信息的值 export const changeSuitBaseInfoVal = ({commit}, params) => { commit(types.CHANGE_SUIT_BASEINFO_VAL, params) } // 初始化套餐基本信息 export const clearSuitBaseInfo = ({commit}) => { commit(types.CLEAR_SUIT_BASEINFO) } // 获取套餐基本信息 export const getSuitBaseInfoDetail = ({commit}, params) => { let {opEntityId, suitId} = params // 初始化套餐基本信息 commit(types.CLEAR_SUIT_BASEINFO) apiGetSuitBaseInfo(opEntityId, suitId).then(data => { commit(types.STORAGE_SUIT_BASEINFO, data.data) }).catch(e => { catchError(e) }) } // 获取套餐分组信息 export const getSuitGroupList = ({commit}, params) => { let {opEntityId, suitId, callback} = params apiGetSuitItems(opEntityId, suitId).then(data => { callback && callback(data.data) }).catch(e => { catchError(e) }) } // 新增/编辑套餐基本信息 export const saveSuitBaseInfo = ({commit}, params) => { let { opEntityId, plateEntityId, suitId, suitName, account, accountId, kindMenuId, memberPrice, price, suitCode, acridLevel, recommendLevel, specialTagId, status, mainPicture, detail, detailImgList, isChangePrice, isAllowDiscount, isBackAuth, startNum, isTakeout, isReserve, discountInclude, callback } = params mainPicture = mainPicture.map(item => { let obj = { path: item.path, sortCode: item.sortCode, isValid: item.isValid } if(item.id){ obj.id = item.id } return obj }) detailImgList = detailImgList.map(item => { let obj = { path: item.path, sortCode: item.sortCode, isValid: item.isValid } if(item.id){ obj.id = item.id } return obj }) apiSaveSuitBaseInfo(suitId, suitName, account, accountId, kindMenuId, Number(memberPrice), Number(price), suitCode, acridLevel, recommendLevel, specialTagId, status, mainPicture, detail, detailImgList , isChangePrice, isAllowDiscount, isBackAuth, startNum, isTakeout, isReserve, discountInclude, opEntityId, plateEntityId, callback).then(data => { // 初始化套餐基本信息 commit(types.CLEAR_SUIT_BASEINFO) callback && callback(data.data) }).catch(e => { catchError(e) }) } // 保存套餐分组信息 export const saveSuitGroupList = ({commit}, params) => { let {opEntityId, suitId, groupList, callback} = params // 这里是过滤后端不需要的字段 let arr = groupList.map(item => { let itemList = item.itemList && item.itemList.map(data => { let obj2 = { itemId: data.itemId, discountValue: data.discountValue, num: data.num || 0, isValid: data.isValid } if(data.specDetailId){ obj2.specDetailId = data.specDetailId } if(data.id){ obj2.id = data.id } return obj2 }) let obj = { name: item.name, num: item.num, isRequired: item.isRequired, isValid: item.isValid, itemList: itemList || [] } if(item.id){ obj.id = item.id } return obj }) apiSaveSuitItems(opEntityId, suitId, arr).then(data => { callback && callback() }).catch(e => { catchError(e) }) } <file_sep>/inside-chain/src/store/modules/setting/mutation-types.js // 获取品牌列表 export const GET_BRAND_LIST = 'GET_BRAND_LIST' // 获取商品/套餐 分类选项框列表 export const GET_CATEGORY_LIST = 'GET_CATEGORY_LIST' // 获取连锁商品列表 export const GET_CHAIN_GOODS_LIST= 'GET_CHAIN_GOODS_LIST' // 获取单店商品列表 export const GET_SINGLE_GOODS_LIST = 'GET_SINGLE_GOODS_LIST' // 商品点击新增/编辑时候获取每个select里面的内容 export const GET_GOODS_SELECT_LIST = 'GET_GOODS_SELECT_LIST' // 获取商品标签列表 export const GET_GOODS_LABEL_LIST = 'GET_GOODS_LABEL_LIST' // 清空商品详情 export const CLEAR_GOODS_DETAIL_FROM_BACK = 'CLEAR_GOODS_DETAIL_FROM_BACK' // 清空新增/编辑商品传递给后端的那些参数 detailToBack export const CLEAR_GOODS_DETAIL_TO_BACK = 'CLEAR_GOODS_DETAIL_TO_BACK' // 获取商品详情 export const GET_GOODS_DETAIL = 'GET_GOODS_DETAIL' // 点击编辑时候将获取到的商品详情复制给detailToBack export const MERGE_GOODS_DETAIL = 'MERGE_GOODS_DETAIL' // 修改新增/编辑时候传递给后端的值,也就是state里面detailToBack的值 export const CHANGE_GOODS_VAL = 'CHANGE_GOODS_VAL' // 获取连锁套餐列表 export const GET_CHAIN_SUIT_LIST = 'GET_CHAIN_SUIT_LIST' // 获取单店套餐列表 export const GET_SINGLE_SUIT_LIST = 'GET_SINGLE_SUIT_LIST' // 获取新增/编辑时候点菜单位的select列表 export const GET_ORDER_UNIT_SELECT_LIST = 'GET_ORDER_UNIT_SELECT_LIST' // 获取套餐的标签列表 export const GET_SUIT_LABEL_LIST = 'GET_SUIT_LABEL_LIST' // 获取套餐内的商品 export const GET_SUIT_GOODS_LIST = 'GET_SUIT_GOODS_LIST' // 获取套餐内的商品分类列表 export const GET_SUIT_GOODS_CATEGORY_LIST = 'GET_SUIT_GOODS_CATEGORY_LIST' // 新增或者编辑套餐时候修改套餐基本信息的值 export const CHANGE_SUIT_BASEINFO_VAL = 'CHANGE_SUIT_BASEINFO_VAL' // 清空套餐基本信息 export const CLEAR_SUIT_BASEINFO = 'CLEAR_SUIT_BASEINFO' // 将接口返回的值赋予套餐的detailBaseInfoToBack export const STORAGE_SUIT_BASEINFO = 'STORAGE_SUIT_BASEINFO' <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionPage/unionPage.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { Button, Radio, Input, Modal } from 'antd'; import ImgUpload from '@src/container/visualConfig/views/design/common/imgUpload' import { SketchPicker } from 'react-color' import cookie from '@2dfire/utils/cookie' import s from './unionPage.css' const RadioGroup = Radio.Group; export default class unionPage extends Component { static propTypes = { PreviewWrapper: PropTypes.func.isRequired, EditorWrapper: PropTypes.func.isRequired, EditPlaceholderWrapper: PropTypes.func.isRequired, editing: PropTypes.bool.isRequired, config: PropTypes.object, onUpdate: PropTypes.func.isRequired, } state = { visible: false, isSketchPicker: false, isShowImgUpload: false, title: '', backgroundType: 'color', backgroundColor: 'transparent', backgroundImage:null, shape: null, disabled: true, announWordLeng: 0 } componentDidMount() { const { config } = this.props const { title, backgroundType, backgroundColor, backgroundImage } = config this.setState({ title, backgroundType, backgroundColor, backgroundImage, announWordLeng: !title ? 0 : title.length, shape: title == null ? 'square' : 'round' }) } onChangeInput = (e) => { // 输入框 const val = e.target.value.trim() if (val.length > 20) { return } this.setState({ title: val, announWordLeng: val.length }) } handleChangeComplete = (color) => { // 拾色器的回调 this.setState({ backgroundColor: color.hex }) } configChang = (obj) => { const { title, backgroundType, backgroundColor, backgroundImage, shape, announWordLeng } = this.state const { config, onUpdate } = this.props // 这里的title为什么设置 null 和 '',是因为用null表示商家名称,''表示固定名称不输入 let setTitle = '' if( shape == 'round') { if(announWordLeng > 0){ setTitle = title } } else { setTitle = null } onUpdate({ ...config, title: setTitle, backgroundType, backgroundColor, backgroundImage }) this.setState({ visible: false, isSketchPicker: false, }); } changeGroup = (val) => { this.setState({ shape: val.target.value, disabled: val.target.value == 'round' ? false : true }) } changeColor = (val) => { this.setState({ backgroundType: val.target.value, }) } showIsVisible = () => { this.setState({ visible: true }) } handleCancel = () => { this.setState({ visible: false, }); }; showSkentPick = (str) => { this.setState({ isSketchPicker: !this.state.isSketchPicker, }) } _getImg = (data) => { // 获取图片 this.setState({ backgroundImage: data }) } imgClose = () => { this.setState({ isShowImgUpload: false }) } showImgUpload = () => { this.setState({ isShowImgUpload: true }) } isUnionShop = () => { const data = JSON.parse(cookie.getItem('entrance')).shopInfo const { entityTypeId, isInLeague } = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (entityTypeId == '3' && !!isInLeague){ // 联盟或者是联盟下的店铺 return false } return true } render() { return <div> {this.isUnionShop() && <Button onClick={this.showIsVisible} className={s.placeholderWrapper}>页面基本信息配置</Button>} {this.editor()} </div> } editor() { const { visible, isSketchPicker, isShowImgUpload, shape, title, backgroundType, backgroundColor, disabled, announWordLeng } = this.state return( <Modal title={'页面基本信息配置'} width ={800} visible={visible} footer={null} onOk={this.handleOk} onCancel={this.handleCancel} > <div className={s.editor}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.imgClose} /> <div className={s.label}>标题名称:</div> <div className={s.componentTitleEditor}> <div className={s.radioGroup}> <RadioGroup value={shape} className={s.controlGroupControl} onChange={(e) => this.changeGroup(e)}> <Radio name="shape" value='square'>显示商家名称</Radio> <Radio name="shape" value='round'>显示固定名称</Radio> </RadioGroup> </div> <div className={s.titleInput}> <input disabled ={disabled} className={s.input} placeholder='请输入标题内容' value={ !title ? '' : title } type="text" onChange={(e) => this.onChangeInput(e)} /> <p className={s.wordNumber}>{announWordLeng}/20</p> </div> </div> <div className={s.label}>背景配置:</div> <div className={s.componentTitleEditor}> <div className={s.changImg}> <div className={s.radioGroup}> <RadioGroup value={backgroundType} className={s.controlGroupControl} onChange={this.changeColor}> <Radio name="shape" value='image'>使用背景图片</Radio> </RadioGroup> <Button disabled={backgroundType == 'color'} icon="picture" onClick={this.showImgUpload} className={s.uploadImg}>上传背景图片</Button> </div> </div> <div> <div className={s.radioGroup}> <RadioGroup value={backgroundType} className={s.controlGroupControl} onChange={this.changeColor}> <Radio name="shape" value='color'>使用固定颜色</Radio> </RadioGroup> <div className={s.titlePickColor}> <Button disabled={backgroundType == 'image'} style={{ backgroundColor: backgroundColor }} className={s.pickColorBtn} onClick={this.showSkentPick} type="primary" /> {isSketchPicker && <SketchPicker color={backgroundColor} className={s.titleSketchPicker} onChangeComplete={(color) => this.handleChangeComplete(color)} />} </div> </div> </div> </div> <div className={s.save}> <Button onClick={this.configChang} type="primary">确认</Button> </div> </div> </Modal> ) } } <file_sep>/static-hercules/src/marketPlan/config/interception.js import {API_BASE_URL} from "apiConfig"; import axios from 'axios'; // import sessionStorage from "@2dfire/utils/sessionStorage.js"; import handleError from '../utils/catchError' // 超时时间 axios.defaults.timeout = 30000 // http请求拦截器 axios .interceptors .request .use(config => { config.url = API_BASE_URL + config.url; config.params = Object.assign({}, config.params); return config }, error => { return Promise.reject(error) }) // http响应拦截器 axios .interceptors .response .use(res => { // 响应成功关闭loading let data = res.data if (data.code === 1) { return data.data } else { handleError(data) return Promise.reject(res) } }, error => { handleError(error.data) return Promise.reject(error) }) export default axios<file_sep>/static-hercules/src/examination/config/axios.js /* * @Author: Octree * @Date: 2017-04-05 11:00:09 * @Last Modified by: Octree * @Last Modified time: 2017-06-01 10:03:36 */ import axios from 'axios' import {loading} from "./loading"; import {GATEWAY_BASE_URL, ENV, APP_KEY} from "apiConfig"; const Loading = new loading(); import sessionStorage from "@2dfire/utils/sessionStorage"; import {GW} from '@2dfire/gw-params' import qs from 'qs' const GWObject = qs.parse(GW) // 超时时间 axios.defaults.timeout = 30000 const ERROR_TYPES = { UNDEFINED_TOKEN: "undefined_token", // 未定义token CANCLED: "cancled", // 被取消 NETWORK_FAIL: "network_fail", // 网络失败 RESULT_FAIL: "result_fail" // 结果失败 }; /** * http请求拦截器 * */ axios .interceptors .request .use(config => { let token = sessionStorage.getItem("token"); if (token) { config.headers.common['token'] = token; } config.headers.common['env'] = config.env|| ENV; config.params.token = token || ''; config.params.method = config.url || ''; config.params.app_key = APP_KEY; config.url = GATEWAY_BASE_URL; config.params = Object.assign({}, config.params, GWObject) /** 是否需要加载动画 */ if (config.loading) { Loading.loadingStart(config.loading || false); } return config }, error => { return Promise.reject(error) }) /** * http响应拦截器 * */ axios .interceptors .response .use(response => { let data = response.data // 响应成功关闭loading if (response.config && response.config.loading) { Loading.loadingEnd(response.config.loading || false); } if (data.code === 1) { return data.data } else { return Promise.reject({ errorType: ERROR_TYPES.RESULT_FAIL, result:data, response }); } }, error => { return Promise.reject(error) }); export default axios <file_sep>/inside-chain/src/config/api_table.js import {API_BASE_URL} from 'apiConfig' import Requester from '@/base/requester-http' import catchError from '@/base/catchError' import {GW} from '@2dfire/gw-params' import router from '@2dfire/utils/router' function withEntityId() { return '&' + GW + '&' + 'entity_id=' + getEntityId() } export function getEntityId() { return router.route.query.entityId } async function http(url, config) { try { const res = await Requester.get(API_BASE_URL + url, config) const {code} = res if (code === 1) { return { ...res.data, success: true } } } catch (e) { catchError(e) return { success: false } } } /** * 门店桌位/区域相关api */ export default { //连锁、门店传菜列表 getAreaList: params => http( 'com.dfire.soa.cashplatform.client.service.IAreaClientService.listArea' + withEntityId(), { params } ), getAreaAll: params => http( 'com.dfire.soa.cashplatform.client.service.IAreaClientService.listAllArea' + withEntityId(), { params } ), addArea: params => http( 'com.dfire.soa.cashplatform.client.service.IAreaClientService.addArea' + withEntityId(), { params } ), updateArea: params => http( 'com.dfire.soa.cashplatform.client.service.IAreaClientService.updateArea' + withEntityId(), { params } ), delArea: params => http( 'com.dfire.soa.cashplatform.client.service.IAreaClientService.removeArea' + withEntityId(), { params } ), getTableList: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.listSeat' + withEntityId(), { params } ), updateSeatArea: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.updateSeatArea' + withEntityId(), {params} ), delTables: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.removeSeat' + withEntityId(), {params} ), importSeatExcel: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.importSeatExcel' + withEntityId(), {params} ), addSeat: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.addSeat' + withEntityId(), {params} ), updateSeat: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.updateSeat' + withEntityId(), {params} ), getSeatDetail: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.getSeatDetail' + withEntityId(), {params} ), getStencilUrl: params => http( 'com.dfire.soa.cashplatform.client.service.ISeatClientService.getStencilUrl' + withEntityId(), {params} ) } <file_sep>/inside-chain/src/const/emu-distTabs.js const tab = [ { name: "下发记录", path: "/dist_manage" }, // { // name: "门店权限", // path: "" // }, ] export default tab; <file_sep>/inside-boss/src/container/visualConfig/store/selectors.js /* 类似 Vuex 里的 getter 一组纯函数的计算方法,返回二次处理过的 state / definition 内容 组件使用 selector 时,应将其放到 redux connect() 里,让其内容通过 props 传递进来, 以保证数据更新时组件能够重新渲染。(不需要读取 state 的 selector 除外) 详见 <https://github.com/reduxjs/reselect> 例子: function someSelector(state) { return state.visualConfig.xxx } @connect(state => ({ someValue: someSelector(state) })) class SomeComponent extends Component { render() { return <div>{{this.props.someValue}}</div> } } */ import { createSelector } from 'reselect' import { first, arr2obj, isObject, oneOf, count } from '@src/container/visualConfig/utils' import sences from '@src/container/visualConfig/sences' import cookie from '@2dfire/utils/cookie' /** * 返回基本信息的加载状态 * null: 加载中/待加载, true: 加载成功,false: 加载失败 */ export const getBaseInfoStatus = createSelector( [ state => state.visualConfig.shopInfo.loadingStatus, state => state.visualConfig.customPages.loadingStatus, ], (shopInfoStatus, customPagesStatus) => { if (shopInfoStatus && customPagesStatus) return true if (shopInfoStatus === false || customPagesStatus === false) return false return null }, ) /** * 返回当前 sence 的定义 */ export function getCurrentSence(state) { // 目前就一种 sence,直接返回 const data = JSON.parse(cookie.getItem('entrance')).shopInfo const { entityTypeId, isInLeague } = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (entityTypeId == '10' || (entityTypeId == '3' && !!isInLeague)){ // 联盟或者是联盟下的店铺 return sences[1] } return sences[0] } /** * 返回当前场景下各页面(包括各自定义页面)的数据(在页面定义基础上补充信息) * 数组的第一项为默认要装修的页面 */ export const getPages = createSelector( [ getCurrentSence, state => state.visualConfig.customPages.list, ], (sence, customPages) => { if (!sence || !customPages) return [] return [ ...sence.pages.map(makeSysemPageData), ...customPages.map(pageData => makeCustomPageDate(sence, pageData)), ] }, ) function makeSysemPageData(page) { return { // page definition ...page, // extra data isSystem: true, createTime: null, viewCount: null, } } function makeCustomPageDate(sence, pageData) { return { // custom page definition name: pageData.name, configName: `page:custom:${pageData.code}`, link: () => pageData.url, manageable: true, ...sence.customPage, // extra data isSystem: false, pageCode: pageData.code, createTime: pageData.createTime, viewCount: pageData.viewCount, shareText: pageData.shareText, shareImage: pageData.shareImage, } } /** * 按顺序返回当前装修页面下各 design component 的 name pair * return [ [origName, aliasName], ... ] */ const getPageDesignComponentNamePairs = createSelector( [ getPages, state => state.visualConfig.design.configName, ], (pages, currentConfigName) => { const page = first(pages, p => p.configName === currentConfigName) if (!page) return [] return page.components.map(item => ( isObject(item) ? [Object.keys(item)[0], Object.values(item)[0]] : [item, item] )) }, ) /** * 按顺序返回当前装修页面下各 design component 的 alias name */ export const getPageDesignComponentNames = createSelector( [getPageDesignComponentNamePairs], namePairs => namePairs.map(i => i[1]), ) /** * 返回当前装修页面下的 design components * { aliasName: designComponent } */ export const getPageDesignComponentMap = createSelector( [getPageDesignComponentNamePairs], namePairs => arr2obj( namePairs, ([comName, aliasComName]) => { // 避免循环依赖,在函数内容引入 components 列表 const designComponents = require('@src/container/visualConfig/designComponents').default // eslint-disable-line return [aliasComName, first(designComponents, c => c.definition.name === comName)] }, ), ) /** * 返回分组后的 design components 名称列表 * * 返回值: * groups = [ * { * name: 'groupName', * list: [ * componentName, // 此为 aliasName * ... * ] * }, * ... * ] */ export const getPageDesignComponentGroups = createSelector( [ getPageDesignComponentNames, getPageDesignComponentMap, ], (comNames, pageDesignComponentMap) => { const groups = [ // { name: '', list: [ name, ... ] }, // ... ] comNames.forEach(name => { const def = pageDesignComponentMap[name].definition if (!def.choosable) return // 只把 choosable 的组件纳入分组 const groupName = def.group let group = first(groups, g => g.name === groupName) if (!group) { group = { name: groupName, list: [] } groups.push(group) } group.list.push(name) }) return groups }, ) /** * 返回指定组件被使用了几次 * getComponentCount(state, comName) => number */ export const getDesignComponentCount = createSelector( [ state => state.visualConfig.design.componentConfigs, (state, comName) => comName, ], (componentConfigs, comName) => componentConfigs.filter(c => c.name === comName).length, ) /** * 返回正在装修的页面的定义 */ export const getCurrentPage = createSelector( [ getPages, state => state.visualConfig.design.configName, ], (pages, currentConfigName) => first(pages, p => p.configName === currentConfigName), ) /** * 判断指定 id 的组件是否处于编辑状态 */ export const getComponentEditing = createSelector( [ (state, id) => id, state => state.visualConfig.design.editingId, ], (id, editingId) => id === editingId, ) /** * 计算出可以插入组件的 index 区间(仅限 position=null 的组件,其他组件都是自动确定位置的) * 最后一个 position=top 的组件之后 ~ 第一个 position=bottom/fixed 的组件之前,是插入 position=null 的组件的有效位置 */ export const getInsertableRange = createSelector( [ getPageDesignComponentMap, state => state.visualConfig.design.componentConfigs, ], (comMap, configs) => { // 判断指定 index 的组件是否是自然排序的 const getPosition = item => comMap[item.name].definition.position const startIndex = count(configs, item => getPosition(item) === 'top') const endIndex = configs.length - count(configs, item => oneOf(getPosition(item), 'bottom', 'fixed')) return [startIndex, endIndex] }, ) /** * 计算出把组件移动到的 index 区间(仅限 position=null 的组件,其他组件都是自动确定位置的) */ export const getMoveableRange = createSelector( [getInsertableRange], insertableRange => [insertableRange[0], insertableRange[1] - 1], ) <file_sep>/inside-boss/src/components/mall/index.js import React, { Component } from 'react' import styles from './index.css' import { Pagination, Button, Input, message, Modal, Tooltip } from 'antd'; import Dialog from './dialog' import { bridgeItem } from '../../format/mall'; const ModalConfirm = Modal.confirm; function filterModule(module) { let data = { addButton: '新增banner', file: 'banner', } if (module === 'activity') { data = { addButton: '新增活动', file: 'activity' } } return data } function checkForm(form = {}) { return form.title ? form.url ? form.img ? '' : '图片' : '链接' : '标题' } class Main extends Component { constructor(props) { super(props) this.state = { page: 1, size: 20, // 0:正常模式 1:排序模式 mode: 0, // 弹窗状态是否开启 dialogStatus: 0, dialogForm: {}, // 临时保存列表 peList: [], peVos: {}, visible: false } } componentWillMount() { const page = this.state.page this.initList(page) } componentWillReceiveProps(nextProps) { if (nextProps && nextProps.contentList && nextProps.contentList.length) { this.setState({ peList: JSON.parse(JSON.stringify(nextProps.contentList)) || [], peVos: {}, }) } } // 获取列表 initList(page) { const size = this.state.size this.props.initList({ page, size }) } // 切换序号模式 普通 or 排序 updateSort() { const mode = this.state.mode this.setState({ mode: mode === 1 ? 0 : 1 }) } updateIndex(index, e) { const { peList, peVos } = this.state if (peList[index]) { peVos[index] = true peList[index].index = e.target.value this.setState({ peVos, peList, }) } } // 保存序号变动 changeIndex() { const _this = this const { peVos, peList } = this.state const editList = Object.keys(peVos).map((e) => { if (peList[e]) { return bridgeItem(peList[e]) } }) this.props.editBannerIndex({ data: { editList }, success: () => { message.success('修改序号成功') _this.setState({ peVos: {}, }) }, failure: () => { message.error('修改序号失败') // 序列数据还原 const contentList = _this.props.contentList _this.setState({ peList: JSON.parse(JSON.stringify(contentList)) || [], peVos: {}, }) } }) this.updateSort() } // 切换内容变更弹窗 updateDialog(form) { const dialogStatus = this.state.dialogStatus const data = { dialogStatus: !dialogStatus, } if (form) { data.dialogForm = form } else { data.dialogForm = {} } this.setState(data) } // 保存内容变更 changeContent({ form, type = 1, callback }) { const _this = this const tip = checkForm(form) if (!tip) { this.props.editItem({ data: { form: bridgeItem(form), type, }, success: () => { message.success('保存成功') const page = _this.state.page this.initList(page) callback && callback() }, failure: (err) => { if (err && !err.code && err.errorCode === '1002') { message.warning(err.message) } else { message.error('保存失败') } } }) this.updateDialog() } else { message.warning(`${tip}不允许为空`) } } changeItem({ data, success, failure }) { this.props.editItem({ data, success, failure }) } // 编辑 editItem(data = {}) { this.updateDialog(data) } // 切换 上架下架 switchItem(data = {}) { const _this = this this.changeItem({ data: { form: bridgeItem(data), type: data.isSelected ? 4 : 3, }, success: () => { const page = _this.state.page _this.initList(page) }, failure: (err) => { if (err && !err.code && err.errorCode === '1002') { message.warning(err.message) } } }) } // 删除 deleteItem(data = {}) { const _this = this this.changeItem({ data: { form: bridgeItem(data), type: 5, }, success: () => { const page = _this.state.page _this.initList(page) }, }) } // 置顶/取消置顶 stickItem(data = {}) { const _this = this if (data.isSelected) { this.changeItem({ data: { form: bridgeItem(data), type: data.isTop ? 7 : 6, }, success: () => { const page = _this.state.page _this.initList(page) }, failure: (err) => { if (err && !err.code && err.errorCode === '1002') { message.warning(err.message) } } }) } else { message.warning('请先上架再进行置顶与取消操作') } } showDialog(e) { const _this = this ModalConfirm({ title: '删除', content: '确定删除该条记录', centered: true, onOk() { return new Promise((resolve, reject) => { _this.deleteItem(e) setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); }).catch(() => console.log('Oops errors!')); }, onCancel() {}, }) } render() { const { mode, size, dialogStatus, dialogForm, peList } = this.state const { module, contentList = [] } = this.props const header = filterModule(module) const totalNum = contentList.length ? contentList[0].totalNum : 0 return ( <div className={ styles.mainWrapper }> <Dialog { ...{ file: header.file, status: dialogStatus, form: dialogForm, }} updateDialog={ this.updateDialog.bind(this) } changeContent={ this.changeContent.bind(this) } /> <div className={ styles.mwTop }> { module === 'banner' && contentList.length ? mode === 1 ? ( <Button className={ styles.mwBtn } type='primary' onClick={ this.changeIndex.bind(this) }>保存</Button> ) : ( <Button className={ styles.mwBtn } type='primary' onClick={ this.updateSort.bind(this) }>调整排序</Button> ) : null } <Button className={ styles.mwBtn } type='primary' onClick={ this.updateDialog.bind(this) }>{ header.addButton }</Button> </div> <div className={ styles.mwPan }> <div className={ styles.mwTit }> <ul> <li>顺序</li><li>头图</li><li>标题</li><li>链接</li><li>操作</li><li>状态</li> </ul> </div> <div className={ styles.mwTxt }> { peList.map((e, i) => ( <ul key={e.id}> <li> { module === 'banner' ? mode === 1 ? ( <Input className={ styles.mwIndex } value={ e.index } onChange={ this.updateIndex.bind(this, i) } /> ) : e.index : e.udInde } </li> <li className={ styles.mwImg }><div className={ styles.img } style={{ backgroundImage: 'url(' + e.img + ')', backgroundSize: 'cover', backgroundPosition: 'center' }}></div></li> <li className={ styles.mwTxtEll }> <Tooltip placement="topLeft" title={ e.title }> { e.title } </Tooltip> </li> <li className={ styles.mwTxtEll }> <Tooltip placement="topLeft" title={ e.url }> { e.url } </Tooltip> </li> <li className={ styles.mwOpe }> <div className={ styles.mwOpeList }> <div className={ styles.mwOpeItem } onClick={ this.editItem.bind(this, e) }>编辑</div> <div className={ styles.mwOpeItem } onClick={ this.switchItem.bind(this, e) }> { e.isSelected ? '下架' : '上架' } </div> <div className={ styles.mwOpeItem } onClick={ this.showDialog.bind(this, e) }>删除</div> { module === 'activity' ? ( <div className={ styles.mwOpeItem } onClick={ this.stickItem.bind(this, e) }> <span className={ !e.isSelected ? styles.forbidden : '' }>{ e.isTop ? '取消置顶' : '置顶 ' }</span> </div> ) : null } </div> </li> <li>{ e.isSelected ? '有效' : '无效' }</li> </ul> )) } </div> <div className={ styles.mwPagination }> <Pagination defaultCurrent={1} pageSize={ size } showTotal={() => `共 ${ totalNum } 条,每页 ${size} 条`} total={ totalNum || 1 } onChange={ this.initList.bind(this) } /> </div> </div> </div> ) } } export default Main <file_sep>/static-hercules/src/shop/api/index.js import http from 'base/requester' import { GW } from '@2dfire/gw-params' const { GATEWAY_BASE_URL } = require('apiConfig') function createApi(url, config) { const { method = 'post', ...rest } = config || {} return params => http[method]( GATEWAY_BASE_URL + `?method=${url}&app_key=200017&${GW}&`, params, { emulateJSON: true, ...rest }, false ) } export default { // 助力 help: createApi('com.dfire.soa.cloudcash.activity.bindPhone'), //获取验证码 getVerCode: createApi('com.dfire.boss.center.soa.authcode.send'), //验证验证码 verifyCCode: createApi('com.dfire.boss.center.soa.authcode.verify'), //活动创建 createActivity: createApi('com.dfire.soa.cloudcash.activity.shareActivity'), //分享成功后激活该活动 activate: createApi('com.dfire.soa.cloudcash.activity.activate'), //获取获赠记录 getHistory: createApi('com.dfire.soa.cloudcash.activity.reward') } <file_sep>/static-hercules/src/fm-bank-chain/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from 'apiConfig' const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, getSessionInfo(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: params }) }, /* * 新增接口:获取当前门店登录用户的职级 */ getUserRole(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getUserRole', params: params }) }, /*获取门店委托提现明细列表*/ getShopWithdrawDetail(data) { return axios({ method: 'POST', url: 'com.dfire.fin.chain.getShopWithdrawDetail', data }) }, /*获取总部委托提现记录列表*/ getChainWithdrawRecordList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.chain.getChainWithdrawRecordList', data }) }, /*获得授权门店钱包信息列表*/ getShopWalletInfoList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.chain.getShopWalletInfoList', data }) }, /*统计要提现的门店的总金额和总条数*/ statChainPreApplyInfo(data) { return axios({ method: 'POST', url: 'com.dfire.fin.chain.statChainPreApplyInfo', data }) }, /*获得授权门店钱包账户总余额*/ getTotalWalletAmt(params) { return axios({ method: 'GET', url: 'com.dfire.fin.chain.getTotalWalletAmt', params }) }, /*总部发起门店钱包提现申请*/ authShopWithdrawApply(data) { return axios({ method: 'POST', url: 'com.dfire.fin.chain.authShopWithdrawApply', data }) }, /*首页- 账户明细*/ getHomeInfo(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.getHomeInfo', params: params }) }, /*商户钱包可用账户列表查询*/ accountListQuery(params) { return axios({ method: 'GET', url: 'com.dfire.fin.wallet.accountListQuery', params: params }) }, /*获取商户钱包提现流水列表*/ getWithdrawSerialList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.getWithdrawSerialList', data }) }, /*获取商户钱包账户收支流水列表*/ getAccountTradeList(data) { return axios({ method: 'POST', url: 'com.dfire.fin.wallet.getAccountTradeList', data }) }, } export default API <file_sep>/union-entrance/src/router/index.js import Vue from 'vue'; import Router from 'vue-router'; import LoginEntrance from '@/views/login'; import LoginPwd from '@/views/login/password'; import LoginUser from '@/views/login/user'; import Login from '@/views/login/login'; import MainEntrance from '@/views/main'; import Index from '@/views/main/index/index.vue'; import Qrcode from '@/views/main/qrcode'; import Reimburse from '@/views/main/reimburse'; import ReimburseDetail from '@/views/main/reimburse/reimburse_detail'; import ReimburseWholeDetail from '@/views/main/reimburse/reimburse_whole_detail'; import ReimburseWholeInvoice from '@/views/main/reimburse/reimburse_whole_invoice'; import Employee from '@/views/main/employee'; import ImportBatch from '@/views/main/employee/importBatch'; import ImportLog from '@/views/main/employee/importLog'; import Meal from '@/views/main/meal'; import Invoice from '@/views/main/invoice'; import InvoiceDetail from '@/views/main/invoice/invoice_detail'; import InvoiceWholeDetail from '@/views/main/invoice/invoice_whole_detail'; Vue.use(Router); export default new Router({ routes: [{ path: '*', redirect: '/main/index' }, { path: '/main', name: 'main', component: MainEntrance, redirect: '/main/index', children: [{ path: 'index', name: "主页", component: Index }, { path: 'password', component: LoginPwd, }, { path: 'user', component: LoginUser, }, { path: 'qrcode', name: "企业码", component: Qrcode }, { path: 'reimburse', name: "报销管理", component: Reimburse }, { path: 'reimburse_detail', name: "报销单详情", component: ReimburseDetail }, { path: 'reimburse_whole_detail', name: "报销单批量审核", component: ReimburseWholeDetail }, { path: 'reimburse_whole_invoice', name: "申请开整单发票", component: ReimburseWholeInvoice }, { path: 'meal', name: "餐补管理", component: Meal }, { path: 'employee', name: "员工管理", component: Employee }, { path: 'invoice', name: "发票管理", component: Invoice }, { path: 'invoice_detail', name: "开票申请详情", component: InvoiceDetail }, { path: 'invoice_whole_detail', name: "开票申请详情", component: InvoiceWholeDetail }, { path: 'employee_importBatch', name: "员工批量导入", component: ImportBatch }, { path: 'employee_importLog', name: "批量导入历史记录", component: ImportLog }] }, { path: '/login', name: 'Login', component: LoginEntrance, redirect: '/login/index', children: [{ path: 'index', component: Login, }] }, ], }); <file_sep>/static-hercules/src/final-statement/config/api.js import axios from './interception' import { APP_KEY } from 'apiConfig' import qs from 'qs' const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, /*/////////////////////////////////////销售数据上报///////////////////////////////////// */ /*当月数据合计*/ getDataTotal(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.getSalesDataPageHeader', params: data }) }, /*上报列表*/ getDataList(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.getSalesDataPageList', params: data }) }, /* 总的详情页 */ getDetailsTotal(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.getSalesDataTotalPage', params: data }) }, /*数据上报 */ getReported() { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.addSalesDataPage' }) }, /*录入数据*/ saveInputData(data) { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client..sales.service.ISalesDataClientService.addSalesData', data: qs.stringify(data) }) }, /*编辑页面 */ getEditData(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.editSalesDataPage', params: data }) }, /*修改销售数据 */ updataPage(data) { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataClientService.editSalesData', data: qs.stringify(data) }) }, /*/////////////////////////////////////销售数据审核///////////////////////////////////// */ /*筛选信息 */ getSelInfo() { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.getFilterFloorAndFormat' }) }, /*门店列表 */ getShopList(param) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.getShopList', params: param }) }, /*提交修改数据 */ saveUpdata(data) { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.editAuditSalesData', data: qs.stringify(data) }) }, /*按天 */ getAuditDay(data) { return axios({ method: 'POST', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.oneKeyConfirmByDay', data: qs.stringify(data) }) }, /*按店 */ getAuditShop(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.oneKeyConfirmByShop', params: data }) }, /*审核编辑页面 */ auditEdit(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.editAuditSalesDataPage', params: data }) }, /*按天审核列表页 */ auditDayList(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.selectByDayList', params: data }) }, /*按店审核列表页 */ auditShopList(data) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.selectByShopList', params: data }) }, /** * 按天导出销售数据 * @param {object} payload * @property {string} email * @property {string} time */ exportSaleDataByDay(payload) { return axios({ method: 'GET', url: 'com.dfire.soa.mis.center.client.sales.service.ISalesDataAuditClientService.exportSaleDataByDay', params: payload }) } } export default API // 34412 99227031 <file_sep>/static-hercules/src/shop/main.js var Vue = require('vue') var VueRouter = require('vue-router') var vueResource = require('vue-resource') var App = require('./App.vue') import Toast from './components/toast'; import AnalysisUI from '@2dfire/analysis-ui' import openApp from '@2dfire/vue-OpenApp' sessionStorage.setItem('project','hercules_shop') sessionStorage.setItem('product','') Vue.use(openApp) Vue.use(AnalysisUI) Vue.use(Toast, { defaultType: 'center', duration: 2500, wordWrap: false, width: 'auto' }) Vue.use(VueRouter) Vue.use(vueResource) Vue.http.options.credentials = false Vue.http.headers.common['env'] = 'f39d79f58d68411cb4d680a8c8b86d9d' var router = new VueRouter({ routes: [ { path: '*', redirect: '/index' }, { path: '/index', name: 'index', title: '试用升级', component: require('./views/index') }, { path: '/share', name: 'share', title: '试用分享', component: require('./views/share') }, { path: '/history', name: 'history', title: '获赠记录', component: require('./views/history') }, { path: '/help', name: 'help', title: '助力', component: require('./views/help') } ] }) router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: '<App/>', components: { App } }) <file_sep>/inside-boss/src/components/noOwnerCoupon/search.js /** * Created by air on 2018/3/14. */ /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import {Select, Input, Button, Popover, Icon, DatePicker, Table} from 'antd' const { RangePicker } = DatePicker; import styles from './style.css' import {message, Modal} from "antd/lib/index"; import saveAs from '../../utils/saveAs' import * as bridge from "../../utils/bridge"; import * as action from "../../action"; import {setNoOwnerCouponPageNum} from "../../action"; import api from "../../api"; import {errorHandler} from "../../action"; const Option = Select.Option class Search extends Component { constructor(props) { super(props); this.state = { couponId: '', start: '', end: '', store: '', status: '', // ============= nowTimestamp: Date.parse(new Date()), timeStart: null, timeEnd: null, timeStartTimestamp: null, timeEndTimestamp: null, coupon: [], searchTimeType: 'CANCEL_TIME', timeTypeSelect:[{ type: 'CANCEL_TIME', name: '核销时间' }, { type: 'EXPORT_TIME', name: '导出时间' }] } } /** * 选择优惠券 * */ changeCoupon(type, e) { if (!e) { return false } const data = {}; data[type] = e; this.setState(data); } /** * 输入优惠券起始号段 * */ numStartChange(e) { this.setState({start: e.target.value}); } /** * 输入优惠券起始号段 * */ numEndChange(e) { this.setState({end: e.target.value}); } /** * 查询时间类型选择 * */ changeTimeType(type,e) { this.setState({searchTimeType: e}); } /** * 时间选择 * @param type timeStart开始时间,timeEnd结束时间 * @param date 时间 * @param dateString 时间string格式 * */ timeChange(type, date, dateString) { if(date.length>=2){ date=[ new Date(date[0]._d.getFullYear(),date[0]._d.getMonth(),date[0]._d.getDate(),0,0,0), new Date(date[1]._d.getFullYear(),date[1]._d.getMonth(),date[1]._d.getDate(),23,59,59)]; }else { date=[null,null] } const datas = {}; datas['timeStart'] =date[0]; datas[`timeStartTimestamp`] =date[0]? Date.parse(date[0])/1000:null; datas['timeEnd'] = date[1]; datas[`timeEndTimestamp`] =date[1]? Date.parse(date[1])/1000:null; this.setState(datas); } /** * 报表查询 * */ statementSearch() { if (!this.state.couponId) { message.error('请先选择优惠券') return false } const {data, dispatch} = this.props const {couponId, start, end, store, status, timeStart, timeEnd,searchTimeType} = this.state dispatch(action.setSearchParam({ couponId, startNum: start, endNum: end, store, couponStatus: status, timeStart: Date.parse(timeStart)/1000, timeEnd: Date.parse(timeEnd)/1000, searchTimeType })); dispatch(action.noOwnerCouponSearch( { couponId, startNum: start, endNum: end, store, couponStatus: status, timeStart: Date.parse(timeStart)/1000, timeEnd: Date.parse(timeEnd)/1000, searchTimeType, pageNumber: 1 } )) } /** *导出报表 * */ exportStatement() { const state = this.state if (!state.couponId) { message.error('请先选择优惠券') return false } const {data} = this.props const {exportStatementUrl, importData} = data this.handleExport(exportStatementUrl + `?app_key=${importData.app_key}&couponId=${state.couponId}&startNum=${state.start}&endNum=${state.end}&store=${state.store}&couponStatus=${ state.status}&timeStart=${Date.parse(state.timeStart)/1000 || ''}&timeEnd=${Date.parse(state.timeEnd)/1000 || ''}&searchTimeType=${state.searchTimeType || ''}`) } /** * 获取优惠券 * */ getCoupon(e) { const {data, dispatch} = this.props api.noOwnerGetCoupon({ type: 'ALL' }).then( res => { this.setState({coupon: res}); }, err => { dispatch(errorHandler(err)) } ).then(e => { }) } handleExport(url) { const t = this const {token} = bridge.getInfoAsQuery() t.setState({ exportLock: true }) const {isRecharge, rechargeBatchId} = this.props.data if (!!isRecharge && !rechargeBatchId) { message.warn('没有选择有效的文件!') setTimeout(() => { t.setState({ exportLock: false }) }, 2000) return } saveAs(url, token).then( filename => { message.success('导出成功!') }, // 成功返回文件名 err => { if (err.code === 0) { if (err.errorCode === '401') { // bridge.callParent('logout') return } message.error(err.message || '导出失败') } } ).then(e => this.setState({exportLock: false})) } render() { const that = this const {data} = this.props const {coupon, status, store} = data.select return ( <div> <div className={styles.handleBox}> <div className={styles.main_p}> <div className={styles.block}> <span className={styles.main_title}>选择优惠券:</span> <Select showSearch value={that.state.couponId} optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} className={styles.st_select1} onFocus={that.getCoupon.bind(that)} onSelect={that.changeCoupon.bind(that, 'couponId')}> {this.state.coupon.map((val) => { return <Option value={val.id} key={val.id}>{val.name}</Option> })} </Select> </div> <div className={styles.block}> <span className={styles.main_title2}>优惠券序列号:</span> <Input className={styles.input2} value={that.state.start} onChange={that.numStartChange.bind(that)}/> - <Input className={styles.input2} value={that.state.end} onChange={that.numEndChange.bind(that)}/> </div> <div className={styles.block}> <span className={styles.main_title2}>核销门店:</span> <Select className={styles.st_select} showSearch value={that.state.store} optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} onChange={that.changeCoupon.bind(that, 'store')}> {store.map((val) => { return <Option value={val.id} key={val.id}>{val.name}</Option> })} </Select> </div> </div> <div className={styles.main_p}> <span className={styles.main_title}>优惠券状态:</span> <Select className={styles.st_select} showSearch value={that.state.status} optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} onChange={that.changeCoupon.bind(that, 'status')}> {status.map((val) => { return <Option value={val.id.toString()} key={val.id}>{val.name}</Option> })} </Select> <div className={styles.block}> <Select className={styles.select_title} value={that.state.searchTimeType} optionFilterProp="children" onChange={that.changeTimeType.bind(that, 'timeType')} > {that.state.timeTypeSelect.map((val) => { return <Option value={val.type} key={val.type}>{val.name}</Option> })} </Select> <span className={styles.split}>:</span> {/*<span className={styles.main_title2}>核销时间:</span>*/} <RangePicker format="YYYY-MM-DD" placeholder={['开始时间', '结束时间']} onChange={that.timeChange.bind(this,null)} disabledDate={(currentDate) => Date.parse(currentDate) > that.state.nowTimestamp + 86400} /> {/*<DatePicker value={that.state.timeStart}*/} {/*onChange={that.timeChange.bind(this, 'timeStart')}*/} {/*disabledDate={(currentDate) => Date.parse(currentDate) > that.state.nowTimestamp + 86400}*/} {/*className={styles.date}*/} {/*/>*/} {/*-*/} {/*<DatePicker value={that.state.timeEnd}*/} {/*className={styles.date}*/} {/*onChange={that.timeChange.bind(this, 'timeEnd')}*/} {/*disabledDate={(currentDate) => {*/} {/*return Date.parse(currentDate) >= that.state.nowTimestamp + 86400 || Date.parse(currentDate) <= that.state.timeStartTimestamp*/} {/*}}*/} {/*/>*/} </div> <Button className={styles.btn_primary} type="primary" onClick={that.statementSearch.bind(that)}>查询</Button> <Button className={styles.btn_primary2} type="primary" onClick={that.exportStatement.bind(that)}>导出报表</Button> </div> </div> </div> ) } } export default Search <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/pictureTextNav/definition.js export default { name: 'pictureTextNav', userName: '图文导航', group: '基础类', max: 5, config: { mode: '图片导航', textColor: '#000000', items: [ // ===== format ===== { picture: '', text: '', linkType: 'goods', linkGoodsId: '', linkPage: '', }, // ===== defaults ===== { picture: '', text: '导航一', linkType: 'goods', linkGoodsId: '', linkPage: '', }, { picture: '', text: '导航二', linkType: 'goods', linkGoodsId: '', linkPage: '', }, { picture: '', text: '导航三', linkType: 'goods', linkGoodsId: '', linkPage: '', }, ], }, } <file_sep>/inside-boss/src/container/mallActivityManager/reducers.js import ActionTypes from '../../action/type' import { formatActivityList } from '../../format/mall' export default (state = {}, action) => { switch (action.type) { case ActionTypes.FETCH_ACTIVITY_LIST_SUCCESS: const list = formatActivityList(action.data) return Object.assign({}, state, { activityList: list }) default: return state } } <file_sep>/inside-chain/src/store/modules/menu/getters.js const getters = { allMenuList: (state) => { return state.allMenuList }, // 复用菜单列表 reuseMenuList(state) { return state.reuseMenuList }, goodsList(state) { return state.goodsList }, unSubmitGoods(state) { return state.unSubmitGoods }, menuInfo(state) { return state.menuInfo }, resultBackup(state) { return state.resultBackup }, typeList(state) { return state.typeList }, goodsOfMenuTotal(state) { return state.goodsOfMenuTotal }, goodsOfMenu(state) { return state.goodsOfMenu }, goodsKinds(state) { return state.goodsKinds }, goodsKindsSingle(state) { return state.goodsKindsSingle }, goodsPrice(state) { return state.goodsPrice }, kindMenuTree(state) { return state.kindMenuTree }, goodsOfMenuSimple(state){ return state.goodsOfMenuSimple }, goodsOfMenuSimpleTotal(state){ return state.goodsOfMenuSimpleTotal }, allSimpleItem(state) { return state.allSimpleItem }, unSubmitGoods(state) { return state.unSubmitGoods }, resultBackup(state) { return state.resultBackup }, publishType(state) { return state.publishType }, publishTimeType(state) { return state.publishTimeType }, publishMenus(state) { return state.publishMenus }, noSearchItems(state) { return state.noSearchItems } } export default getters <file_sep>/static-hercules/src/ocean/store/actions.js /** * Created by zyj on 2018/4/3. */ import * as types from './mutation-types' // import errorToast from 'src/oasis/libs/errorToast' // import {getApplyMaterials, getRegion} from 'src/oasis/config/api' // 修改店铺信息 export const modifyShopInfo = ({commit}, params) => { commit(types.MODIFY_SHOPINFO, params) } // 修改保存的id export const saveInputId = ({commit}, params) => { commit(types.SAVE_INPUT_ID, params) } // 修改店铺补充信息(表单不需要提交) export const supplementShopInfo = ({commit}, params) => { commit(types.SUPPLEMENT_SHOPINFO, params) } //底部弹出选择 export const pickerChange = ({commit}, params) => { commit(types.PICKER_CHANGE, params) } //查询并更新已填写的数据 export const updataShopInfo = ({commit}, params) => { commit(types.UPDATA_SHOPINFO, params) } // 修改当前编辑状态 export const changeViewState = ({commit}, params) => { commit(types.CHANGE_VIEWSTATE, params) } // 修改示例图片显示状态 export const changeExamplePhoto = ({commit}, params) => { commit(types.CHANGE_EXAMPLE_PHOTO, params) } // 修改编辑状态 export const changeSubStatus = ({commit}, params) => { commit(types.CHANGE_SUB_STATUS, params) }<file_sep>/inside-boss/src/components/downComm/treeList.js /** * Created by air on 2017/7/11. */ import React, {Component} from 'react' import {Input, Tree, Modal} from 'antd' import styles from './style.css' import * as action from '../../action' const TreeNode = Tree.TreeNode; const Search = Input.Search; class TreeList extends Component { constructor(props) { super(props) this.state = { } this.count = 0 } componentDidUpdate () { console.log(this.props) const {data} = this.props const {treeData, tableData} = data if(treeData.length == 1 && this.count < 1) { this.autoChecked(treeData, tableData) this.count++; } } onExpand = (expandedKeys) => { this.setState({ expandedKeys, autoExpandParent: false, }); } dataList = []; generateList = (data) => { for (let i = 0; i < data.length; i++) { const node = data[i]; const key = node.key; const title = node.title; this.dataList.push({key, title: title}); if (node.child) { this.generateList(node.child, node.key); } } // this.autoChecked(data) }; autoChecked = (data, tableData) => { const t = this; const {dispatch} = t.props // if(data.length == 1 && data.child.length == 1 && data.child[0].child.length == 1) { let tmp = []; let tmpTable = []; if (data){ if(data.length == 1){ // console.log(data.length,data[0].key,'11111') tmp.push(data[0].key.toString()); if(data[0].child && data[0].child.length == 1){ // console.log(data[0].child.length ,data[0].child[0].key,'22222') tmp.push(data[0].child[0].key.toString()); if(data[0].child[0].child && data[0].child[0].child.length == 1){ // console.log(data[0].child[0].child.length ,data[0].child[0].child[0].key,'33333') tmp.push(data[0].child[0].child[0].key.toString()); tmpTable.push( { key: data[0].child[0].child[0].key.toString(), type: data[0].child[0].child[0].title + ' (' + data[0].title + ' -> ' + data[0].child[0].title + ')', } ) } } } if(tmp.length == 3){ dispatch(action.checkedType(tmp)) dispatch(action.delTableItem(tmpTable)) } } // } } //获取父key getParentKey = (key, tree) => { let parentKey; for (let i = 0; i < tree.length; i++) { const node = tree[i]; if (node.child) { if (node.child.some(item => item.key === key)) { parentKey = node.key; } else if (this.getParentKey(key, node.child)) { parentKey = this.getParentKey(key, node.child); } } } return parentKey; }; //获取父title getParentTitle = (key, tree) => { let parentKey; let parentTitle; for (let i = 0; i < tree.length; i++) { const node = tree[i]; if (node.child) { if (node.child.some(item => item.key === key)) { parentKey = node.key; parentTitle = node.title; } else if (this.getParentKey(key, node.child)) { parentKey = this.getParentKey(key, node.child); parentTitle = this.getParentTitle(key, node.child); } } } return parentTitle; }; //筛选框输入值 回车或点击右侧放大镜 搜索分类 onSearch = (e) => { const t = this; console.log(e) const {data, dispatch} = t.props; const value = e; const {treeData} = data; // dispatch(action.getCategory(data,value)); // console.log(e,value,treeData); const expandedKeys = this.dataList.map((item) => { if (item.title.indexOf(value) > -1) { let expandedKey = ''; if(this.getParentKey(item.key, treeData)){ // console.log() expandedKey = this.getParentKey(item.key, treeData).toString() } return expandedKey; } return null; }).filter((item, i, self) => item && self.indexOf(item) === i); if(!e){ this.setState({ expandedKeys: [], searchValue: value, autoExpandParent: true, }); }else{ this.setState({ expandedKeys, searchValue: value, autoExpandParent: true, }); } } onCheck = (checkedKeys, e) => { const t = this; const {dispatch, data} = t.props const {treeData, checkedList, tableData} = data let tmpList = []; let tmp = []; for (var j = 0; j < checkedKeys.length; j++) { for (var k = 0; k < this.dataList.length; k++) { if (checkedKeys[j] == this.dataList[k].key && e.checkedNodes[j].props.third) { let father = this.getParentTitle(this.dataList[k].key, treeData); let grandfather = this.getParentTitle(this.getParentKey(this.dataList[k].key, treeData), treeData); tmp.push( { key: this.dataList[k].key.toString(), type: this.dataList[k].title + ' (' + grandfather + ' -> ' + father + ')', father: father, grandfather: grandfather } ) tmpList.push( this.dataList[k].key.toString() ) } } } let maxLimited = tmpList.length if(maxLimited > 50){ Modal.info({ title: '请注意', content: <div> 最多可选50个类目 </div> }) } else{ dispatch(action.checkedType(tmpList)) dispatch(action.delTableItem(tmp,tableData)) } console.log('check',checkedList) // tableData = tmp // this.setState({ // expandedKeys: checkedList // }); } render() { const t = this const {data} = t.props const {treeData,checkedList} = data if(treeData){ this.dataList = []; this.generateList(treeData); } const tree_state = { checkable: true, multiple: true, showLine: true, showIcon: false } const { searchValue, expandedKeys, autoExpandParent } = this.state; const loop = data => data.map((item) => { const index = item.title.indexOf(searchValue); // const index = -2; // let title = '' // if(index > -1) // { // const beforeStr = item.title.substr(0, index); // const afterStr = item.title.substr(index + searchValue.length); // title = index > -1 // ?(<span>{beforeStr} // <span style={{color: '#f50'}}>{searchValue}</span> // {afterStr}</span>) // :<span>{item.title}</span>; // } // else { // title = <span>{item.title}</span>; // // } let title = [] if(index > -1){ const beforeStr = item.title.substr(0, index); const afterStr = item.title.substr(index + searchValue.length); title = (<span>{beforeStr}<span style={{color: '#f50'}}>{searchValue}</span>{afterStr}</span>) } else{ title = <span>{item.title}</span> } // const title = index > -1 // ?(<span>{beforeStr} // <span style={{color: '#f50'}}>{searchValue}</span> // {afterStr}</span>) // :<span>{item.title}</span>; // const title = <span>{item.title}</span>; if (item.child) { return ( <TreeNode key={item.key} title={title}> {loop(item.child)} </TreeNode> ); } return <TreeNode key={item.key} title={title} third/>; }); return ( <div> <Search style={{marginBottom: 8}} placeholder="三级类目名称" onSearch={this.onSearch}/> {treeData ? <Tree {...tree_state} onExpand={this.onExpand} expandedKeys={expandedKeys} autoExpandParent={autoExpandParent} onCheck={this.onCheck} checkedKeys={checkedList} > {loop(treeData)} </Tree> : null } </div> ) } } export default TreeList <file_sep>/union-entrance/src/views/nav/util/login.js import getEnv from './getEnv' import ajax from './ajax' import cookie from './cookie' const env = getEnv() import modal from '../modal' import tool from './tool' const pathname = tool.getPathKey() const APP_KEY = 200800 const goToLogin = function() { const url = { local: 'http://localhost:8070/page/index.html', dev: `http://tt.2dfire.net/${pathname}/entrance/page/index.html`, daily: 'http://d.2dfire-daily.com/entrance/page/index.html', pre: 'https://biz.2dfire-pre.com', publish: 'https://biz.2dfire.com' }[env] window.location.href = url + '?flag=timeout' } const logout = function() { const url = { local: `http://gateway.2dfire-daily.com/?app_key=${APP_KEY}&method=`, dev: `http://gateway.2dfire-daily.com/?app_key=${APP_KEY}&method=`, daily: `http://gateway.2dfire-daily.com/?app_key=${APP_KEY} &method=`, pre: `https://gateway.2dfire-pre.com/?app_key=${APP_KEY}&method=`, publish: `https://gateway.2dfire.com/?app_key=${APP_KEY}&method=` }[env] ajax({ url: url + 'com.dfire.boss.center.pc.ILoginBossPcService.logout', type: 'POST', data: {}, dataType: 'json', success: function(response) { // 此处放成功后执行的代码 let data = JSON.parse(response) if ( (data.code === 1 && data.data.data) || (data.code === 0 && data.errorCode === 'ERR_PUB200002') ) { sessionStorage.clear() cookie.clearCookies() modal.message('退出成功') setTimeout(function() { goToLogin() }, 0) } }, fail: function() { modal.message('退出失败') } }) } //跳转到切换店铺页 const goToShiftShop = function() { window.location.href = { local: 'http://localhost:8070/page/change.html', dev: `http://tt.2dfire.net/${pathname}/entrance/page/change.html`, daily: 'http://d.2dfire-daily.com/entrance/page/change.html', pre: 'https://biz.2dfire-pre.com/page/change.html', publish: 'https://biz.2dfire.com/page/change.html' // publish: 'https://biz.2dfire.com/entrance/page/change.html' }[env] } export default { goToLogin, logout, goToShiftShop } <file_sep>/inside-boss/src/container/customBillStore/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import Main from '../../components/customBillStore/main' import InitData from './init' import * as action from '../../action' import * as bridge from '../../utils/bridge' import styles from './style.css' const mapStateToProps = state => ({ data: state.customBill }) const mapDispatchToProps = dispatch => ({ dispatch }) @connect( mapStateToProps, mapDispatchToProps ) export default class extends Component { componentWillMount() { const query = bridge.getInfoAsQuery() const { dispatch, params } = this.props const data = InitData(params.pageType, query) dispatch(action.initData(data)) } componentDidMount() {} render() { const { data, dispatch, params } = this.props if (!data.importData) { return false } else { return ( <div className={styles.wrapper}> <Main data={data} dispatch={dispatch} params={params} /> </div> ) } } } <file_sep>/inside-boss/src/components/goods/data.js export const recursionClass = data => { const flat = arr => [].concat(...arr) const item = arr => { return flat(arr.map(i => { if (i.subList) { return item(i.subList).map(j => { return {name: i.name + '-' + j.name, id: j.id} }) } else { return {name: i.name, id: i.id} } } )) } return item(data) } const option = { packingBox:'packingBoxNum', deductKind:'deduct', serviceFeeMode:'serviceFee' } export const getColumns = (data)=> { const newdata = [].concat(data) data.map(i=>{ if(option[i]){ newdata.push(option[i]) } }) const col = [ { title: '分类名称', dataIndex: 'kindMenuName', key: 'kindMenuName', width: 150, }, { title: '商品名称', dataIndex: 'name', key: 'name', width: 120, }, { title: '商品编码', dataIndex: 'code', key: 'code', width: 120, }, { title: '商品ID', dataIndex: 'id', key: 'id', width: 120, }, { title: '双语名称', dataIndex: 'multiLangMenuName', key: 'multiLangMenuName', width: 120, }, { title: '单价(元)', dataIndex: 'price', key: 'price', width: 120, }, { title: '会员价(元)', dataIndex: 'memberPrice', key: 'memberPrice', width: 120, }, { title: '结账单位', dataIndex: 'account', key: 'account', width: 120, }, { title: '点菜单位', dataIndex: 'buyAccount', key: 'buyAccount', width: 120, }, { title: '外卖可点', dataIndex: 'isTakeout', key: 'isTakeout', width: 120, render: (text, record) => { return text == 1?"是":"否"; }, }, { title: '餐盒规格', dataIndex: 'packingBox', key: 'packingBox', width: 120, }, { title: '餐盒数量', dataIndex: 'packingBoxNum', key: 'packingBoxNum', width: 120, }, { title: '堂食可点', dataIndex: 'isReserve', key: 'isReserve', width: 120, render: (text, record) => { return text == 1?"是":"否"; }, }, { title: '商品上下架', dataIndex: 'state', key: 'state', width: 120, render: (text,record)=>{ return text == 1 ? '上架':'下架' } }, { title: '规格', dataIndex: 'hasSpec', key: 'hasSpec', width: 120, }, { title: '做法', dataIndex: 'hasMake', key: 'hasMake', width: 120, }, { title: '辣椒指数', dataIndex: 'acridLevelString', key: 'acridLevelString', width: 120, render: (text,record)=>{ let mes = '' if (record.label && record.label.acrid && record.label.acrid.acridLevelString){ mes = record.label.acrid.acridLevelString } return mes } }, { title: '特色标签', dataIndex: 'specialTagString', key: 'specialTagString', width: 120, render: (text,record)=>{ let mes = '' if (record.label && record.label.specialTag && record.label.specialTag.specialTagString){ mes = record.label.specialTag.specialTagString } return mes } }, { title: '推荐指数', dataIndex: 'recommendLevelString', key: 'recommendLevelString', width: 120, render: (text,record)=>{ let mes = '' if (record.label && record.label.recommend && record.label.recommend.recommendLevelString){ mes = record.label.recommend.recommendLevelString } return mes } }, { title: '允许商品金额计入优惠门槛', dataIndex: 'discountInclude', key: 'discountInclude', width: 120, render: (text, record) => { return record.discountInclude==1?"允许":"不允许"; }, }, { title: '允许收银员在收银时打折', dataIndex: 'isRatio', key: 'isRatio', width: 120, render: (text, record) => { return record.isRatio==1?"允许":"不允许"; }, }, { title: '允许收银员在收银时修改价格', dataIndex: 'isChangePrice', key: 'isChangePrice', width: 120, render: (text, record) => { return record.isChangePrice==1?"允许":"不允许"; }, }, { title: '退菜时需要权限验证', dataIndex: 'isBackAuth', key: 'isBackAuth', width: 120, render: (text, record) => { return record.isBackAuth==1?"是":"否"; }, }, { title: '可作为赠菜', dataIndex: 'isGive', key: 'isGive', width: 120, render: (text, record) => { return record.isGive==1?"是":"否"; }, }, { title: '此商品仅在套餐里显示', dataIndex: 'mealOnly', key: 'mealOnly', width: 120, render: (text, record) => { return record.mealOnly==1?"是":"否"; }, }, { title: '加工耗时(分钟)', dataIndex: 'consume', key: 'consume', width: 120, }, { title: '起点份数', dataIndex: 'startNum', key: 'startNum', width: 120, }, { title: '最小累加单位', dataIndex: 'stepLength', key: 'stepLength', width: 120, }, { title: '商品介绍', dataIndex: 'memo', key: 'memo', width: 500, }, { title: '销售提成', dataIndex: 'deductKind', key: 'deductKind', width: 120, render: (text,record)=>{ if(text == '1'){ return '不提成' }else if(text == '2'){ return '按比例' }else if(text == '3'){ return '按固定金额' }else{ return '不提成' } } }, { title: '提成额度或百分比', dataIndex: 'deduct', key: 'deduct', width: 120, }, { title: '服务费', dataIndex: 'serviceFeeMode', key: 'serviceFeeMode', width: 120, render: (text,record)=>{ if(text == '0'){ return '不收取' }else if(text == '1'){ return '固定费用' }else if(text == '2'){ return '商品价格百分比' }else{ return '不收取' } } }, { title: '服务费金额或百分比', dataIndex: 'serviceFee', key: 'serviceFee', width: 120, }, { title: '商品库存', dataIndex: 'stock', key: 'stock', width: 120, }, { title: '菜肴份量', dataIndex: 'weight', key: 'weight', width: 120, render: (text,record)=>{ if(text == 0){ return '极小份' }else if(text == 1){ return '标准菜量' }else if(text > 1){ return '特大量' }else{ return '' } } }, ] return col.filter(item=>{ return newdata.indexOf(item.key) != -1 }) } <file_sep>/inside-boss/src/container/visualConfig/开发说明.md # 概念定义 ``` sence 一个场景,场景下定义一系列可装修的页面,部分场景还可由用户建立自定义页面。例如零售单店装修是一个场景;联盟装修是另一个场景。 page 一个可装修的页面(如主页、商品列表页、店铺导航装修)。 designComponent 页面由一个个“装修组件”组成。每个组件有自己的业务逻辑和可配置项。注意这是一个业务上的概念,不是指 Vue 或 React 的组件。 appConfig 每个页面的装修数据会以 JSON 形式存储在后端。每份 JSON 数据称之为一份 appConfig。每份 appConfig 由各组件的 config 合并而成。。 configName appConfig 名字,同一场景内不能重复 designComponentConfigs appConfig 的数据格式不适合在装修过程中使用。 装修时使用的是整理过、补充了额外信息的 designConfigs 数据。具体格式见 'store/design.js' 里的定义。 ``` # 文件结构 ``` utils/ 工具函数 components/ 公共组件 views/ PC后台各页面内容 design/ 装修页面 pages/ 页面管理 backups/ 备份管理 templates/ 模板列表 store/ 业务逻辑代码,封装成 redux store sences/ 定义场景及其下页面 senceName/ 格式见 `sence definition` somePage.js 格式见 `page definition` designComponents/ 定义装修组件及其代码实现 someComponent/ definition.js 格式见 `component definition` component.js 组件代码,详见 `组件规范` index.js `export default { definition, component }` ``` # 数据格式定义 ## appConfig name 约定 - `page:xxx` xxx系统页面 - `page:custom:xxx` xxx自定义页面,xxx由后端生成 - `theme` 或其他名称,不属于某个页面的 appConfig。例如全局导航栏的配置。 ## sence definition ```js { // 必填。场景名称,不能重复。 name: '', // 必填。场景下各页面的定义,页面顺序决定了它们在“装修页面选择”功能里的排序。 pages: [ pageDefinition, ... ], // 用户手动创建的页面的定义(所有自定义页面统一使用此定义) // 没有此定义,说明当前场景不支持创建自定义页面 customPage: customPageDefinition || null, } ``` ### page definition ```js { name: '', // 必填。页面名称,显示在页面列表里。如:店铺首页 configName: '', // 必填。此页面的 appConfig name。如:page:home link: null, // null || () => url 推广链接,为 null 则不支持推广 manageable: true, // 是否出现在“页面管理”里。若为 false,则只在装修页面里可选择 components: [ // 必填。此页面可使用哪些组件(choosable 和非 choosable 组件都要列出来) 'component1', 'component2', { 'origName': 'customName' }, // 可通过对象指定别名(对象里只能有一个键值对) // 例如组件原名叫 'retailGoodsList',在零售场景下就简化为 'retail' // 此简化会体现在 appConfig 中,appConfig 里组件 type 值会是简化后的名称。 ], defaults: { // 初始的 appConfig 内容(未装修过此页面时,默认使用此内容) ... }, } // custom page 只需定义 `components` 和 `defaults`,其他信息通过接口获得。 ``` ## component definition ```js // 未标注“必填”的字段可省略,此时会使用冒号后的默认值 { name, // 必填。组件名,也是其在 appConfig 里的标识,不能重复。 userName, // 必填。显示给用户的组件名。 description, // 更详细的组件说明,显示在组件编辑面板 choosable: true, // 组件能否由用户手动添加、移除;若为 false,则此组件会固定出现在页面中。 // ----- choosable=true 时的专属选项 ----- max: null, // 组件最多往页面里添加几次,为 null 则不限制。 group: '其他类', // 组件分类名,不指定则会被分入“其他类”。 // 装修页面的“组件列表”处,会按照这个字段给组件分组。 // -------------------------------------- position: null, // 组件放置的位置 // null: 自然排序 'top': 页首 'bottom': 页尾 'fixed': 组件自己定位(等同 CSS 的 position: fixed) // 多个 position=top/bottom 的组件之间,按照在页面定义里出现的顺序排序。 // 设置了 position 的组件,max 属性会被固定为 1,不能修改。 bare: false, // 指定组件 config 是直接合并进 appConfig 还是放入 appConfig 里的 components 数组。 // - bare=true 则直接合并,此时会用组件名作为 key; // - bare=false 则放入 components 数组,此时会往组件 config 里额外加一个字段:type,其值是组件名。 // (后面有例子) // 只有 choosable=false 的组件可设置此属性,choosable 组件固定为 false。 // 设置了 bare=true 的组件,必须指定 position(不能为 null),默认为 top。 config: {}, // 此组件的 config definition。 // 用于在页面上使用组件时生成初始值,和对加载进来的组件 config 进行格式化。 // (例如一个组件“商品列表”,刚上线时没有“mode”字段,现在增加了,那么加载线上没有此字段的 config 时,就要通过这个定义把默认值补充进来) validator: null // (config) => null || { field: xxx, message: xxx } // 验证 component config 值是否合法。若合法,返回 null;否则指出哪个字段不合法,并给出错误信息。 // field 的值可以是组件 editor 能识别的任意值。 // 不指定 validator 则视为组件值始终合法。 } ``` ### component config definition ```js // 此对象是 config definition,根据它对组件的 config data 进行格式化 { key: defaultValue, // value 是 plain object 时会深入匹配。object 里还可以嵌套 object key2: { subKey: defaultValue, ... }, // value 是数组,且里面只有一个 plain object 时,会遍历 config data 的此项,分别与此 object 匹配。 key3: [ { key: defaultValue, ... } ], // value 是数组但里面不是 plain object 时,会把数组整体作为 default value key4: ['a', 'b'] } // config definition 例子,此为一个商品列表组件 { mode: '大图', orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, showFields: ['名称', '价格', '下单按钮'], goodsList: [ { linkType: 'goods', linkGoodsId: '', linkPage: '', } ] } ``` ### 组件 config 如何合并成 appConfig ```js { // bare=true 的组件,直接合并进 appConfig comName: { ...comConfig }, comName2: { ...comConfig }, // bare=false 的组件放在 components 数组下 components: [ { id, type: comName, ...comConfig }, { id, type: comName, ...comConfig }, ] } ``` ### 现有各组件的 appConfig 设计 <https://api.l.whereask.com/doc/isv/theme/retail-app-config.html#name-theme> # 组件规范 组件会接收到以下 props: - PreviewWrapper:用此容器包裹组件的 preview 部分 - EditorWrapper:用此容器包裹组件的 editor 部分 - editing:是否正在编辑此组件 - config:组件当前的 config 正常情况下,组件处在编辑状态时,渲染 EditorWrapper;处在非编辑状态时,不渲染 EditorWrapper。 部分组件可能希望未编辑时,也在编辑区域显示一个“占位符”,那么可以在非编辑状态下,也渲染 EditorWrapper 并带上占位符内容。 # 代码规范 - 业务逻辑代码尽可能放到 `store/` 中;`views/` 只包含界面、交互处理,以及调用业务操作的代码。 - 不要从父级向下传递不必要的数据。能直接从 store 里拿的,就让子级直接通过 store 去拿。 这样排查一个组件的数据是否有问题时,就不用一直向上排查数据来源。 # 开发流程 ## 如何定义业务操作 要新增一项业务操作,应走如下流程: 1. 在 `store/actionTypes.js` 里定义相关操作类型,及执行操作应传过来的参数格式 2. 在 `store/reducers/` 里写处理以上操作类型、更新 state 的代码 3. 在 `store/actions/` 里写触发这些操作的函数 即: - 操作的业务逻辑、要执行的行为(如请求接口)写在 `actions` 里 - 根据操作结果更新 state 的代码写在 `reducer` 里 ## 如何新增一个组件 1. 在 `designComponents/` 下定义并实现一个组件 2. 在 `sences/` 里,把此组件添加到能使用它的页面的 `components` 和 `defaults` 里 <file_sep>/inside-boss/src/utils/env.js const env = __ENV__; // eslint-disable-line const urlPrefix = { LOCAL: "http://merchant-api.2dfire-daily.com/merchant-api/", // 项目环境http://merchant-api.2dfire-daily.com/ DEV: "http://merchant-api.2dfire-daily.com/merchant-api/", // 项目环境http://merchant-api.2dfire-daily.com/ DAILY: "http://merchant-api.2dfire-daily.com/", PRE: "http://merchant-api.2dfire-pre.com/", PUBLISH: "https://merchant-api.2dfire.com/", }; const urlNetwork = { LOCAL: 'http://gateway.2dfire-daily.com', // 项目环境 DEV: 'http://gateway.2dfire-daily.com', // 项目环境 DAILY: 'http://gateway.2dfire-daily.com', PRE: 'http://gateway.2dfire-pre.com', PUBLISH: 'https://gateway.2dfire.com' } // 商品图片域名 const imgUrl = { LOCAL: "https://ifiletest.2dfire.com/", DEV: "https://ifiletest.2dfire.com/", DAILY: "https://ifiletest.2dfire.com/", PRE: "https://ifile.2dfire.com/", PUBLISH: "https://ifile.2dfire.com/", } // 商品图片上传projectName const imgProjectName = { LOCAL: "OssTest", DEV: "OssTest", DAILY: "OssTest", PRE: "OssDfire", PUBLISH: "OssDfire", } // webCocket const webCocketUrl = { LOCAL: "http://10.1.6.218:9003/notify?scanId=html-socket", DEV: "http://10.1.6.218:9003/notify?scanId=html-socket", DAILY: "http://10.1.6.218:9003/notify?scanId=html-socket", PRE: "https://websocket.2dfire-pre.com/notify?scanId=html-socket", PUBLISH: "https://websocket.2dfire.com/notify?scanId=html-socket", } const upload = { LOCAL: "https://upload.2dfire-daily.com", DEV: "https://upload.2dfire-daily.com", DAILY: "https://upload.2dfire-daily.com", PRE: "https://upload.2dfire-pre.com", PUBLISH: "https://upload.2dfire.com", } const urlUploadRul = { LOCAL: "https://upload.2dfire-daily.com", // 项目环境 DEV: "https://upload.2dfire-daily.com", // 项目环境 DAILY: "https://upload.2dfire-daily.com", PRE: "https://upload.2dfire-pre.com", PUBLISH: "https://upload.2dfire.com" }; const FHYurl = { LOCAL: "http://tt.2dfire.net/presellAdmin_league_shop_manager/page/index.html#", //项目环境 DEV: "../presell-admin/page/index.html#", DAILY: "../presell-admin/page/index.html#", PRE: "http://biz.2dfire-pre.com/presell-admin/page/index.html#", //预发环境 PUBLISH: "https://biz.2dfire.com/presell-admin/page/index.html#" //正式环境 } const weixinMealProjectName = 'visual_config' const urlWeixinMeal = { LOCAL: `http://api.l.whereask.com/${weixinMealProjectName}/api`, DEV: `http://api.l.whereask.com/${weixinMealProjectName}/api`, DAILY: 'http://api.l.whereask.com/daily/api', PRE: 'https://meal.2dfire-pre.com', PUBLISH: 'https://meal.2dfire.com', } // 获取当前运行时环境变量 export const currentEnvString = env || "DEV"; // eslint-disable-line // 运行时 API 前缀 export const currentAPIUrlPrefix = urlPrefix[currentEnvString]; export const currentAPIUrlNetwork = urlNetwork[currentEnvString]; export const currentUrlUploadRul = urlUploadRul[currentEnvString]; export const currentIMGProject = imgProjectName[currentEnvString] export const currentIMGUrl = imgUrl[currentEnvString] export const currentExLink = FHYurl[currentEnvString] export const currentWeixinMealUrl = urlWeixinMeal[currentEnvString] export const currentwebCocketUrl = webCocketUrl[currentEnvString] //针对于获取侧边栏信息的接口 export const UPLOAD_BASE_URL = upload[currentEnvString] //针对于获取侧边栏信息的接口 export const merApiPrefix = { LOCAL: "http://merchant-api.2dfire-daily.com/", DEV: "http://merchant-api.2dfire-daily.com/", DAILY: "http://merchant-api.2dfire-daily.com/", // http://merchant-api.2dfire-daily.com/ PRE: "http://merchant-api.2dfire-pre.com/", PUBLISH: "https://merchant-api.2dfire.com/" } [currentEnvString]; <file_sep>/inside-boss/src/container/visualConfig/views/pages_manage/page/index.js import React, { Component } from 'react' import { hashHistory } from 'react-router' import { connect } from 'react-redux' import cx from 'classnames' import { Table, Popconfirm, Modal, Button, message } from 'antd' import QRCode from 'qrcode.react' import * as actions from '@src/container/visualConfig/store/actions' import { getPages } from '@src/container/visualConfig/store/selectors' import checkShopStatus from '@src/container/visualConfig/components/checkShopStatus' import { Layout, Header, Content } from '@src/container/visualConfig/components/pageParts' import ImgUpload from '@src/container/visualConfig/views/design/common/imgUpload' import s from './index.css' function add0(m) { return m < 10 ? '0' + m : m } @checkShopStatus @connect(state => ({ loadingStatus: state.visualConfig.customPages.loadingStatus, pages: getPages(state), })) class Pages extends Component { state = { visible: false, defaultImg:'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png', isShowImgUpload: false, inputLength: 0, textareaLeng: 0, inputVal: '', textareaVal: '', img: '', qrcodeVisible: false, qrcodeLink: null, editingPageCode: null, }; componentWillMount() { actions.loadCustomPages() } get pages() { return this.props.pages.filter(p => p.manageable) } // ==================================== render() { const { loadingStatus } = this.props const { isShowImgUpload } = this.state let content if (loadingStatus === null) content = this.statusLoading() else if (loadingStatus === false) content = this.statusLoadFailed() else content = this.pagesTable() return <Layout> <Header title="页面管理" /> <Content className={s.content}> {content} </Content> {this.modalPriew()} {this.qrcodePriew()} <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> </Layout> } onChangeBtn = () => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, }) } _getImg = (data) => { // 获取图片 this.setState({ img: data }) console.log('data====', data) } close = () => { this.setState({ isShowImgUpload: false, }) } statusLoading() { return <div className={s.loading}>载入中...</div> } statusLoadFailed() { return <div className={s.loadFailed}> 页面列表加载失败,<a onClick={actions.loadCustomPages}>点此重试</a> </div> } format = (createTime) => { // 时间戳转换 if(!createTime) return false var time = new Date(createTime); var y = time.getFullYear(); var m = time.getMonth()+1; var d = time.getDate(); var h = time.getHours(); var mm = time.getMinutes(); var s = time.getSeconds(); return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s); } onChangeInput = (e, str) => { // 输入框 const num = str == 'input' ? 10 : 30 const type = str == 'input' ? 'inputVal' : 'textareaVal' const len = str == 'input' ? 'inputLength' : 'textareaLeng' const val = e.target.value.trim() if(val.length > num) { return } this.setState({ [type]: val, [len]: val.length }) } modalPriew = () => { const {visible, defaultImg, inputVal, textareaVal, inputLength, textareaLeng, img, editingPageCode } = this.state return( <Modal title={editingPageCode ? '编辑微页面' : '新建微页面'} width ={800} visible={visible} onOk={this.handleOk} onCancel={this.handleCancel} > <div className={s.modalContent}> <div className={s.tab}> <div className={s.tabname}>页面名称:</div> <div className={s.priewInput}> <input className={s.input} placeholder='请输入内容' value={inputVal} type="text" onChange={(e) => this.onChangeInput(e, 'input')} /> <p className={s.wordNumber}>{inputLength}/10</p> </div> </div> <div className={cx(s.tab+ ' ' + s.tabMargin)}> <div className={s.tabname}>分享描述:</div> <div className={s.priewTxtarea}> <textarea className={s.textarea} placeholder='请输入内容' value={textareaVal} type="text" onChange={(e) => this.onChangeInput(e, 'textarea')} /> <p className={s.wordNumber}>{textareaLeng}/30</p> <p className={s.text}>展示在分享信息中</p> </div> </div> <div className={cx(s.tab+ ' ' + s.tabMargin)}> <div className={s.tabname}>分享图片:</div> <div className={s.imgLoad}> <img className={s.imgBtn} src={img? img: defaultImg} onClick={this.onChangeBtn} /> <p className={s.text}>建议尺寸5:4,仅支持gif、jpg、jpeg、png格式图片,图片大小不超过2M</p> </div> </div> </div> </Modal> ) } showModal = () => { this.setState({ visible: true, inputLength: 0, textareaLeng: 0, }); }; handleOk = () => { const { editingPageCode, inputVal, textareaVal, img } = this.state if (!inputVal || !inputVal.trim()) return message.error('页面名称不能为空') if (!textareaVal || !textareaVal.trim()) return message.error('分享描述不能为空') if (!img) return message.error('必须上传分享图片') if (!editingPageCode) { actions.addCustomPage({ pageName: inputVal, shareImage: img, shareText: textareaVal, }).then(res => { if (!res.result) message.error(res.message) actions.loadCustomPages() }) } else { actions.updateCustomPage(editingPageCode, { pageName: inputVal, shareImage: img, shareText: textareaVal, }).then(res => { if (!res.result) message.error(res.message) actions.loadCustomPages() }) } this.setState({ visible: false, qrcodeVisible: false, inputVal: '', textareaVal: '', editingPageCode: null, img: '', }); }; handleCancel = () => { this.setState({ visible: false, editingPageCode: null, qrcodeVisible: false, inputVal: '', textareaVal: '', img: '', }); }; handleDelete = data => { actions.removeCustomPage(data.pageCode).then(res => { if (!res.result) { message.error(res.message) } actions.loadCustomPages() }) }; changeEdit = (e, str) =>{ console.log('str===', str) // 编辑 actions.initDesign(str) hashHistory.push('/visual_config_design') } changePromotion = (e, link) =>{ console.log('link===', link) // 推广 this.setState({ qrcodeVisible: true, qrcodeLink: link() }) } editShare = (record) => { this.setState({ inputLength: record.name.length, textareaLeng: record.shareText.length, visible: true, editingPageCode: record.pageCode, inputVal: record.name, textareaVal: record.shareText, img: record.shareImage, }) } qrcodePriew = () => { const { qrcodeVisible, qrcodeLink } = this.state return( <Modal title="推广二维码" visible={qrcodeVisible} onCancel={this.handleCancel} footer={null} width ={800} > <div className={s.qrcodeModal}> <p className={s.text}>用户通过扫描该二维码将直达该页面,满足不同场景的定制化展示需求。</p> <QRCode value={qrcodeLink} className={s.img} id='qrCode' /> <a download="二维码.jpg" id="downloadLink"></a> <Button type="primary" className={s.download} onClick={() => this.downLoad()}>下载</Button> </div> </Modal> ) } downLoad = () => { // 二维码下载 const canvas = document.getElementById('qrCode') const url = canvas.toDataURL('image/jpeg'); const downloadLink = document.getElementById('downloadLink') downloadLink.setAttribute('href', url) downloadLink.click(); } pagesTable() { const { pages } = this const columns = [ { title: '页面名称', dataIndex: 'name', }, { title: '页面类型', dataIndex: 'isSystem', render: isSystem => <span>{isSystem ? '系统页面' : '活动页面'}</span> }, { title: '创建时间', dataIndex: 'createTime', render: createTime => <span>{this.format(Number(createTime))}</span> }, { title: '浏览量', dataIndex: 'viewCount', }, { title: '操作', render: (text, record) => ( <span> <a className={s.btn} onClick={(e) =>this.changeEdit(e, record.configName) } href="javascript:;">编辑</a> {text.link == null ? null : <a onClick={(e) =>this.changePromotion(e, record.link) } className={s.btn} href="javascript:;">推广</a>} {!text.isSystem && <a className={s.btn} href="javascript:;" onClick={() => this.editShare(record)}>分享信息</a>} {!text.isSystem && <Popconfirm title="确定删除吗?" onConfirm={() => this.handleDelete(record)}> <a className={cx(s.closeBtn, s.btn)} href="javascript:;">删除</a> </Popconfirm>} </span> ), }, ]; return ( <div className={s.pageManage}> <Button className={s.addPage} type="primary" onClick={this.showModal}>新建微页面</Button> <Table columns={columns} dataSource={pages} /> </div> )} } export default Pages <file_sep>/union-entrance/src/views/manage/columns.js export default self => [ { title:'门店名称', key:'name', }, { title:'品牌', key:'plateName', }, { title:'店铺编码', key:'code', }, { title:'操作', render: (h, params) => { return h('span',{ style: { cursor: 'pointer', color: '#5599FF' }, on: { click: () => { self.goInfo(params.row) } } },'进入店铺') } }, ]<file_sep>/inside-chain/src/store/modules/distCenter/getters.js const getters = { publishTaskList: (state) => { return state.publishTaskList }, taskInfo: (state) => { return state.taskInfo }, brandList: (state) => { return state.brandList }, publishTimeType(state) { return state.publishTimeType }, } export default getters <file_sep>/union-entrance/build/webpack.dev.conf.js var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var HtmlWebpackPlugin = require('html-webpack-plugin') var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') var path = require('path'); var glob = require("glob"); // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) var getPlugin = function () { var plugin = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', title: '跳转页', chunks: [], inject: true }), new FriendlyErrorsPlugin() ]; var pages = glob.sync("./page/*.html"); pages.forEach(function (name) { var chunk = name.slice(7, name.length - 5); var page = name.slice(7, name.length); var file = name.slice(2, name.length); var temp = path.join(config.dev.page, page); if(chunk!="nav"){ if(chunk=="index"){ plugin.push( new HtmlWebpackPlugin({ filename: file, template: temp, inject: true, chunks: [chunk] }) ); }else{ plugin.push( new HtmlWebpackPlugin({ filename: file, template: temp, inject: true, chunks: [chunk,"nav"] }) ); } } }); return plugin; }; module.exports = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // cheap-module-eval-source-map is faster for development devtool: '#cheap-module-eval-source-map', plugins: getPlugin() }) <file_sep>/static-hercules/src/staff-management/store/actions.js /** * Created by huaixi on 2019/5/6. */ import * as types from './mutation-types' // 权限 export const modifyPermission = ({commit}, params) => { // commit(types.MODIFY_PERMISSION, params) commit('setState', {name: 'permissionList', value: params}) } //底部弹出选择 export const pickerChange = ({ commit }, params) => { commit(types.PICKER_CHANGE, params) } // 修改是否展示top-header的保存按钮 export const modifyShowSaveButton = ({ commit }, params) => { commit(types.SHOW_SAVE_BUTTON, params) } export const changeInfo = ({ commit }, params) => { commit('setState', { name: params.type, value: params.value }) } //修改职级相关信息 export const changeRankInfo = ({ commit }, params) => { commit(types.CHANGE_RANK_INFO, params) } export const assignRankInfo = ({ commit }, params) => { commit(types.ASSIGN_RANK_INFO, params) } export const changeTotalRankActionCount = ({ commit }, params) => { commit(types.CHANGE_TOTAL_RANK_ACTION_COUNT, params) } export const changeStaffInfo = ({ // 修改员工信息 commit }, params) => { commit(types.CHANGE_STAFF_INFO, params) } export const changeExtraAction = ({ // 修改设置项 commit }, params) => { commit(types.CHANGE_EXTRA_ACTION_INFO, params) } <file_sep>/static-hercules/src/fm-bank-chain/router.js import Vue from 'vue' import Router from 'vue-router' import Index from './views/index' import Record from './views/record' import RecordDetail from './views/record-detail' import AccountBook from './views/account-book' import AccountSelect from './views/account-select' import WithdrawDeposit from './views/withdraw-deposit' Vue.use(Router) export default new Router({ routes: [ { path: '*', redirect: '/index' }, { path: '/index', name: 'index', component: Index, meta: { title: '资金管理' } }, { path: '/record', name: 'record', component: Record, meta: { title: '提现操作记录' } }, { path: '/record-detail', name: 'recordDetail', component: RecordDetail, meta: { title: '提现操作详情' } }, { path: '/account-book', name: 'accountBook', component: AccountBook, meta: { title: '门店账户余额' } }, { path: '/account-select', name: 'accountSelect', component: AccountSelect, meta: { title: '发起提现' } }, { path: '/withdraw-deposit', name: 'withdrawDeposit', component: WithdrawDeposit, meta: { title: '提现' } }, ] }) <file_sep>/inside-chain/src/const/emu-shopNav.js const shopNavList = [ { id: 'shopNav_1', name: '经营概况', url: '/shop_manage_view', }, { id: 'shopNav_2', name: '店铺资料', url: '/shop_manage_info', }, { id: 'shopNav_3', name: '商品与套餐', url: '/shop_manage_library_goods_manage', }, { id: 'shopNav_4', name: '传菜', url: '/store_pass', }, { id: 'shopNav_5', name: '收银设置', url: '/shop_pay_kind_manage', }, { id: 'shopNav_6', name: '桌位设置', url: '/shop_table_manage', }, ] export default shopNavList <file_sep>/inside-boss/src/components/customBillStore/main.js import React, {Component} from 'react' import {Select, Switch, Button, Modal} from 'antd' const Option = Select.Option import styles from './css/main.css' import cls from 'classnames' import SelectStore from './content' import {message} from 'antd/lib/index' import * as bridge from '../../utils/bridge' import apiNetwork from '../../api/networkApi' import * as action from '../../action' import {errorHandler} from '../../action' import {hashHistory, Link} from 'react-router' export default class Main extends Component { constructor(props) { super(props) console.log(props) this.state = { isSwitch: true, shopActiveIndex: null } } componentDidMount() { const t = this const {dispatch, params, data} = t.props const {importData, entityType} = data apiNetwork.getUseStoreList({ tmplId: params.id, entityId: importData.entityId }).then( res => { console.log(res) this.setState({ shopActiveIndex: res.data.applyShopList, isSwitch: res.data.applyAll }) dispatch(action.setBillActiveShop(res.data.applyShopList)) }, err => dispatch(errorHandler(err)) ) .then() } switchChange(e) { this.setState({ isSwitch: e }) } //门店选择 storeListEdit(e) { const type = e.target.dataset.type if (type === 'chooseShop') { const index = Number(e.target.dataset.index) if (this.state.shopActiveIndex === index) { this.setState({ shopActiveIndex: '' }) } else { this.setState({ shopActiveIndex: index }) } } else if (type === 'closeBtn') { const index = Number(e.target.dataset.index) this.delShop(index) } } /** * 删除门店 * @param index 删除门店的index值 */ delShop(index) { const {data, dispatch, params} = this.props const {activeShopList} = data let shopList = activeShopList.concat() shopList.splice(index, 1) dispatch(action.setBillActiveShop(shopList)) this.setState({ shopActiveIndex: null }) } //选择门店 chooseStore() { const {dispatch} = this.props dispatch(action.billStoreModelSet({visible: true})) dispatch(action.getAllShopList()) dispatch(action.getBranch()) dispatch(action.getAllProvince()) } //清空 storeDelAll() { const {dispatch} = this.props dispatch(action.setBillActiveShop([])) this.setState({ shopActiveIndex: null }) } //保存 saveBill() { const {data, dispatch, params} = this.props let {importData} = data let entityList = [] if(data.activeShopList && data.activeShopList.length > 0) { entityList= data.activeShopList.map(val => val.entityId) } if (this.state.isSwitch) { apiNetwork .saveUseStore({ applyTmplBo: JSON.stringify({ tmplId: params.id, applyAll: this.state.isSwitch, entityId: importData.entityId, applyEntityIdList: entityList }) }) .then( res => { if (res.data) { message.success('保存成功') hashHistory.push(`/CUSTOM_BILL/main`); } }, err => dispatch(errorHandler(err)) ) .then() }else{ // if (!data.activeShopList || data.activeShopList.length <= 0) { // if (!data.activeShopList) { // message.error('请选择需要下发的门店') // return false // } else { apiNetwork .saveUseStore({ applyTmplBo: JSON.stringify({ tmplId: params.id, applyAll: this.state.isSwitch, entityId: importData.entityId, applyEntityIdList: entityList }) }) .then( res => { if (res.data) { message.success('保存成功') hashHistory.push(`/CUSTOM_BILL/main`); } }, err => dispatch(errorHandler(err)) ) .then() // } } } // ================================render render() { const {data, dispatch, params} = this.props const {activeShopList} = data return ( <div className={styles.main_wrapper}> <div className={styles.content_wrapper}> <div className={styles.switch_wrapper}> 全部门店使用此模板 <Switch checked={this.state.isSwitch} onChange={this.switchChange.bind(this)} className={styles.switch} /> </div> {!this.state.isSwitch && ( <div className={styles.store_wrapper}> <div className={styles.title}> <span className={styles.btn_add_store} onClick={this.chooseStore.bind(this)} > 选择门店 </span> 已选择下列门店:共{activeShopList ? activeShopList.length : 0}家 <span className={styles.btn_clear_store} onClick={this.storeDelAll.bind(this)} > 清空 </span> </div> <ul className={styles.store_list} onClick={this.storeListEdit.bind(this)} > {activeShopList && activeShopList.length > 0 && activeShopList.map((val, index) => { return ( <li key={val.entityId} className={cls( this.state.shopActiveIndex === index ? styles.store_list_active : '' )} > <span data-type="chooseShop" data-index={index}>{val.name}</span> <i data-type="closeBtn" data-index={index}/> </li> ) })} </ul> </div> )} </div> <div className={styles.btn_wrapper}> <Link to="/CUSTOM_BILL/main"> <Button className={styles.btn_back}>返回</Button> </Link> <Button className={styles.btn_save} type="primary" onClick={this.saveBill.bind(this)}> 保存 </Button> </div> <SelectStore data={data} dispatch={dispatch}/> </div> ) } } <file_sep>/inside-boss/src/components/goodsPicture/handle.js /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import {Button, message, Modal, Progress, Icon, Popover, Input, Alert} from 'antd' import AddPictureBtn from './addPictureBtn' import styles from './style.css' import * as action from '../../action' class Handle extends Component { constructor(props) { super(props); this.state = { previewText: '请上传图片', importLock: false, exportLock: false, visible: false, importPic: 0, importProgress: 0, imgUrl: 'https://assets.2dfire.com/frontend/9cc7696eb06429081f8036c5cac31c8a.png', show: false }; const {dispatch, data} = this.props; this.addImgData = data } clearFn(e, dispatch) { (e !== undefined) && e.preventDefault() window.location.reload() } searchName(name) { const t = this const {dispatch} = t.props const { data : { brandId, } } = this.props; dispatch(action.backPictureList()) dispatch(action.setSearchName(name)) dispatch(action.getPictureList(1, name, brandId)) } handleExample = ()=>{ this.setState(()=>({show:true})) } render() { const t = this // const {dispatch} = t.props // const showBtn = (t.state.previewText === '请上传图片') ? false : true const content = ( <div style={{width: '500px', color: '#999', padding: '10px 0px'}}> <p>图片格式:png,jpeg,jpg,gif;建议使用png格式图片</p> <p>图片尺寸:建议比例为5:4(如750*600px)</p> <p>图片大小:不可超过10M,至多可添加5张</p> <p>注意:系统会在主图中截取正方形区域作为菜单缩略图,以手机实际预览效果为准<span onClick={this.handleExample} className={styles.example} >示例</span></p> </div> ); const {data, dispatch, detail} = this.props return ( <div> <div className={styles.handleBox}> <div className={styles.t2}> <AddPictureBtn data={data} dispatch={dispatch} imgType="3" loadType="1"/> <AddPictureBtn data={data} dispatch={dispatch} imgType="1" loadType="1"/> <p className={styles.submit}>图片格式要求 <Popover content={content} placement="bottom"> <Icon type="question-circle-o" style={{fontSize: '16px', marginLeft: '5px', color: '#d52632'}}/> </Popover> </p> <Input.Search size="large" placeholder="请输入文件夹全称" onSearch={value => t.searchName(value)} className={styles.searchInput}/> </div> { (() => { if (this.state.visible) { return ( <div className={styles.progressBox} style={{left: (document.body.clientWidth - 200) / 2}}> <p className={styles.progressTitle}>文件正在导入中</p> <div style={{margin: '20px 50px'}}> <Progress type="circle" percent={this.state.importProgress} width={100}/> </div> <p style={{ width: '100%', textAlign: 'center' }}>已成功导入图片{this.state.importPic}张</p> </div> ) } else { return null } })() } </div> <Alert style={{margin: '20px 0'}} message="注意" description="1、商品主图和商品详情图请分开导入。批量导入的图片名称请跟商品名称保持一致,如果是多张图片请在每张图片后加上@+数字,例如:红烧肉@1,红烧肉@2,红烧肉@3。每个商品主图最多上传5张,超过5张则上传无效。每个商品详情图最多上传24张,超过24张则上传失败。列表页(小图)默认展示商品主图中的第一张。2、列表中商品名称置灰代表头图为空,文件框置灰代表详情图为空。" type="warning" closable showIcon /> <Modal footer={null} visible={this.state.show} width="600px" zIndex="1050" onCancel={()=>this.setState(()=>({show:false}))} > <div> <img style={{width:'520px',display:'block',margin:'0 auto'}} src={this.state.imgUrl} alt=""/> </div> </Modal> </div> ) } } export default Handle <file_sep>/inside-chain/src/store/modules/payKind/state.js export default { // 付款方式列表 payKindList: { total: 0, list: [] }, // 下拉列表用选择 selectPayKind: [], selectPayKindSingle: [], // 付款方式详情 payKindInfo: { // 支付方式名称 payKindName: '', // 支付类型 payKind: '', // 是否计入实收 isInclude: true, // 是否自动打开钱箱 isAutoOpen: false, // 代金券列表 couponList: [] }, // 所有付款方式列表 下发用 allPayKindList: [], // 付款方式列表 payKindListSingle: { total: 0, list: [] }, // 付款方式详情 payKindInfoSingle: { // 支付方式名称 payKindName: '', // 支付类型 payKind: '', // 是否计入实收 isInclude: true, // 是否自动打开钱箱 isAutoOpen: false, // 代金券列表 couponList: [] }, // 是否是支付宝直连店 isAlipay: { // 享受优惠开关 alipayIsEnjoyPreferential: true, // false: 是直连 true: 不是 alipayIsOurAccount: true } } <file_sep>/union-entrance/src/views/manage/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import GATEWAY_ENV from '../../config/env.js' //import { Icon, Row, Col } from 'iview' import { Input, Icon, Table, Button, Page, Message } from 'iview' // import 'iview/dist/styles/iview.css' // 使用 CSS Vue.component('Icon', Icon) // Vue.use('Row', Row) // Vue.use('Col', Col) Vue.component('Input', Input) Vue.component('Table', Table) Vue.component('Button', Button) Vue.component('Page', Page) Vue.prototype.$Message = Message Vue.config.productionTip = false // token放在header,网关接口需要令牌 Vue.http.headers.common['env'] = GATEWAY_ENV // console.log(Vue.http); // Vue.http.options.xhr = { withCredentials: true }; // Vue.http.headers.common['_k'] = localStorage.getItem("token"); new Vue({ el: '#app', // router, template: '<App/>', components: { App } }) <file_sep>/inside-chain/src/store/modules/components/left-nav.js // import Res from "@/base/requester"; import API from '@/config/api'; import emuNav from "@/const/emu-nav.js"; import router from "@/router"; import Session from "@2dfire/utils/sessionStorage"; import Cookie from '@2dfire/utils/cookie' import Requester from '@/base/requester'; import catchError from '@/base/catchError'; import API from '@/config/api'; import Obj from '@2dfire/utils/object'; import iView from "iview"; import shopNavList from "@/const/emu-shopNav" let Message = iView.Message; const leftNav = { namespaced: true, state: { shopNav: false, shop: { name: '', logo: '' }, select: "", list: [ { name: "", //导航展示名 id: 1, select: false, //是否被选中 list: [], // 二级菜单 show: false, //显示二级菜单 } ], shopNavList: [] }, mutations: { _updateNav(state, list) { state.list = list; }, _updateShopNav(state, list) { state.shopNavList = list; }, _setShop(state, shop) { state.shop.name = shop.name; state.shop.logo = shop.logo; }, _setSelect(state, id) { state.select = id; }, _showShopNav(state, show) { state.shopNav = show; } }, actions: { showShopNav(context, show) { context.commit('_showShopNav',show) let selected_nav = 'shopNav_' + show; let tmp_list = shopNavList; tmp_list.map(t_item =>{ if(t_item.id === selected_nav){ t_item.active = true }else{ t_item.active = false } }) context.commit('_updateShopNav',shopNavList) }, // 一级导航跳转 firstNavClick(context, item) { if (item.list) { item.show = !item.show; } let newlist = context .state .list .concat(); newlist.map(v => { if (v.id == item.id) { v.select = true; } else { v.select = false; v.show = false; } }) context.commit("_updateNav", newlist); if (item.url != "") { newlist.map(v => { if (v.id != item.id) { if (v.list) { v .list .map(v1 => { v1.select = false; }) } } }) context.commit("_updateNav", newlist); router.push({path: item.url}); } }, // 二级导航点击 secondNavClick(context, item) { if (item.url != "") { router.push({path: item.url}); } else { Message.info('正在开发中,敬请期待。如有需要,请在二维火掌柜APP进行操作'); } }, // 店铺内左导航跳转 shopNavClick(context, item) { let tmp_list = context.state.list.concat(); tmp_list.map(t_item =>{ if(t_item.id === item.id){ t_item.active = true }else{ t_item.active = false } }) context.commit('_updateNav', tmp_list) if (item.url != "") { router.push( { path: item.url, query: item.query } ); } else { Message.info('正在开发中,敬请期待。如有需要,请在二维火掌柜APP进行操作'); } }, // 导航列表 getNavFromApi() { let params = { // menuVersion: 10 menuVersion: 12 } Requester .get(API.GET_LEFT_NAV, {params: params}) .then(data => { // 数据处理 ... 提交mutation console.log(data.data) this.dispatch("leftNav/formateNav", data.data); // context.commit('_getShopsList', data); }) .catch(e => { catchError(e); }); }, // 格式化导航栏 formateNav(context, data) { let list = []; if (Obj.isEmpty(data)) { // sessionStorage.removeItem("leftNav"); context.commit("_updateNav", list); } else { data.map(v => { let o = {} o.name = v.menuName || ""; o.id = v.menuId || ""; o.select = false; o.list = []; o.show = false; o.url = emuNav[v.menuId] ? emuNav[v.menuId].url : ""; o.icon = emuNav[v.menuId] ? emuNav[v.menuId].icon : ""; if (!Obj.isEmpty(v.children)) { v .children .map(v0 => { let o1 = {} o1.name = v0.menuName || ""; o1.id = v0.menuId || ""; o1.select = false; o1.show = false; o1.url = emuNav[v0.menuId] ? emuNav[v0.menuId].url : ""; o .list .push(o1); }); } list.push(o); }); // sessionStorage.setItem("leftNav", JSON.stringify(list)); context.commit("_updateNav", list); this.dispatch("leftNav/setNavSelect"); } }, // 设置导航入口 setNav(context, id) { context.commit("_setSelect", id); // 显示连锁左侧栏 context.commit("_showShopNav", false); // let nav = Session.getItem("leftNav"); //阻止请求 for test // return // if (nav) { // let list = JSON.parse(nav); // context.commit("_updateNav", list); // this.dispatch("leftNav/setNavSelect", id); // } else { // store中存在侧边栏的数据时,直接选中某个项,而不是从接口获取,减少接口请求 let nav = context.state.list.concat(); if(nav && nav.length > 1){ this.dispatch("leftNav/setNavSelect", id); }else{ this.dispatch("leftNav/getNavFromApi"); } // } }, // 设置导航选中 setNavSelect(context) { let id = context.state.select; let nid = ""; for (let i in emuNav) { if (emuNav[i].id == id) { nid = i; } } let newlist = context .state .list .concat(); newlist.map(v => { if (v.id == nid) { v.select = true; v.show = true; } else { v.select = false; v.show = false; } if (v.list) { v .list .map(v1 => { if (v1.id == nid) { v1.select = true; v.select = true; v.show = true; } else { v1.select = false; } }) } }); context.commit("_updateNav", newlist); }, // 获取cookie中的店铺信息 setShop(context) { let shop = { name: '', logo: '' } let shopInfo = ''; if(Cookie.getItem('entrance') != undefined){ shopInfo = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).shopInfo } if (shopInfo) { shop.name = shopInfo.entityName; shop.logo = shopInfo.logo; } context.commit('_setShop', shop); }, }, getters: { data(state) { return state; }, shopNav(state) { return state.shopNav }, shopNavList(state) { return state.shopNavList } } } export default leftNav; <file_sep>/static-hercules/src/base/config/publish.js module.exports = { API_BASE_URL: 'https://meal.2dfire.com', NEW_API_BASE_URL: 'http://activity.zm1717.com', BOSS_API_URL: 'https://boss-api.2dfire.com', DD_API_URL: 'http://yardcontent.2dfire.com', APP_ID: 'dingoa49flkdpwskqhw4hh', SHARE_BASE_URL: 'http://live.zm1717.com', IMAGE_BASE_URL: '//ifile.2dfire.com/', API_WEB_SOCKET: 'https://websocket.2dfire.com/web_socket', // 网关 GATEWAY_BASE_URL: 'https://gateway.2dfire.com', // 供应链 SUPPLY_CHAIN_API: 'https://newapi.2dfire.com/supplychain-api', ENV: 'publish', APP_KEY: '200800', REPORT_URL: 'https://d.2dfire.com/pandora/#/', WEBSOCKET_URL: 'https://websocket.2dfire.com', // 接入易观方舟数据埋点系统相关 ANALYSYS_APPKEY: '27e0923002b01e08', ANALYSYS_DEBUG_MODE: 0, ANALYSYS_UPLOAD_URL: 'https://ark.2dfire.com' }; <file_sep>/static-hercules/src/staff-management/store/mutations.js /** * Created by huaixi on 2019/5/7. */ import Vue from 'vue' import * as types from './mutation-types' export default { // 修改权限 [types.MODIFY_PERMISSION](state, payload) { Vue.set(state.permissionList, payload.type, payload.value) }, setState(state, payload) { state[payload.name] = payload.value }, //底部弹出选择 [types.PICKER_CHANGE](state, payload) { state.picker = { ...state.picker, ...payload } }, //修改是否展示top-header的保存按钮 [types.SHOW_SAVE_BUTTON](state, payload) { state.isShowSaveButton=payload }, [types.CHANGE_RANK_INFO](state, payload) { Vue.set(state.rank, payload.type, payload.value) }, [types.ASSIGN_RANK_INFO](state, payload) { state.rank = payload }, [types.CHANGE_TOTAL_RANK_ACTION_COUNT](state, payload) { state.totalRankActionCount = payload }, // 修改员工信息 [types.CHANGE_STAFF_INFO](state, payload) { Vue.set(state.staffInfo, payload.type, payload.value) }, // 修改设置项 [types.CHANGE_EXTRA_ACTION_INFO](state, payload) { Vue.set(state.extraActionInfo, payload.type, payload.value) }, }<file_sep>/union-entrance/src/base/config/dev.js module.exports = { NEW_API_BASE_URL:'../../api', API_BASE_URL: 'http://gateway.2dfire-daily.com/?app_key=200800&method=', SHARE_BASE_URL: 'http://api.l.whereask.com', IMAGE_BASE_URL: 'http://ifiletest.2dfire.com/', API_WEB_SOCKET: 'http://10.1.5.114:9003/web_socket', WEB_SOCKET_URL: 'http://10.1.5.114:9003', MOCK_BASE_URL: 'http://mock.2dfire-daily.com/mockjsdata/7', }; <file_sep>/static-hercules/src/ele-account/constants/index.js const array2Map = (arr = []) => { let result = {} arr.map(val => { result[val.code] = val.name }) return result } const payTypes = [{ code: 1, name: '微信支付' }, { code: 2, name: '支付宝支付' }, { code: 4, name: '二维火支付' }, { code: 5, name: 'QQ钱包支付' }, { code: 6, name: '火通卡支付' }, { code: 15, name: '云闪付支付' }] const tradeTypes = [{ code: 1, name: '消费' }, { code: 2, name: '充值' }] const payStatus = [{ code: 0, name: '预付' }, { code: 1, name: '支付' }, { code: 11, name: '退款' }] const channelTypes = [{ code: 0, name: '未知' }, { code: 1, name: '直连' }, { code: 2, name: '间连' }] const payStatusSymbol = [{ code: 0, name: '' }, { code: 1, name: '+' }, { code: 11, name: '-' }] const symbolColor = [{ code: '+', name: 'c-ff0033' }, { code: '-', name: 'c-00cc33' }] module.exports = { payTypes, tradeTypes, payMap: array2Map(payTypes), tradeMap: array2Map(tradeTypes), payStatusMap: array2Map(payStatus), payStatusSymbolMap: array2Map(payStatusSymbol), symbolColorMap: array2Map(symbolColor) }<file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/ad/AdEditor.js import React from 'react'; import { Radio, Button, Icon } from 'antd'; import cx from 'classnames' import visualApi from '@src/api/visualConfigApi' import ImgUpload from '../../common/imgUpload' import GoogsSelect from '../../common/googsSelect' import Dropdown from '../../common/dropdown' import { DesignEditor, ControlGroup } from '../../editor/DesignEditor'; import style from './AdEditor.css' const RadioGroup = Radio.Group; export default class AdEditor extends DesignEditor { state = { size: 'large', isShowImgUpload: false, isShowGoods: false, goodIndex: -1, goodsNames: [], defaultImg: 'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png' }; componentDidMount() { const { config } = this.props.value; const { items } = config const arrId = [] for(let i = 0; i < items.length; i++) { if(items[i].linkGoodsId.length) arrId.push(items[i].linkGoodsId) } if(arrId) { this.getSpecifyRetailGoodsList(arrId) } } getSpecifyRetailGoodsList(arrId) { // 通用接口,通过ID来查询信息接口 visualApi.getSpecifyRetailGoodsList({ idList: arrId }).then( res=>{ this.setState({ goodsNames: res.data }) }, err=>{ console.log('err', err) } ) } onChange = (str, e) => { const { value, onChange } = this.props; const {config} = value onChange(value, {config: { ...config, [str]: e.target.value }}) } onChangeBtn = (index) => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, goodIndex: index }) } close = () => { this.setState({ isShowImgUpload: false, isShowGoods: false, }) } _selectType = (index, e) => { // 样式选择 this.setState({ goodIndex: index }) const { value, onChange } = this.props; const {config} = value let items = [...config.items] items[index].linkType = e.target.value onChange(value,{ config: { ...config, items }}) } closeItem = (index) => { // 删除编辑组件 const { value, onChange } = this.props; const { config } = value let items = [...config.items] items.splice(index, 1) onChange(value,{ config: { ...config, items }}) } getlinkGoodsName = (item, index) => { const { goodsNames } = this.state let name goodsNames.find((c) => { if(item.linkGoodsId == c.itemId) { name = c.itemName } }) return <div onClick={(e) => this._onChangGoods(index, e)} className={style.picturlink}> {name ? name : '选择商品的链接'} <Icon type="down" /></div> } relationPriew = () => { // 导航编辑组件 const { config } = this.props.value; const { items } = config const {defaultImg} = this.state return( items.map((item, index) => <div className={style.picturEdit}> <img className={style.closeBtn} src="https://assets.2dfire.com/frontend/73a3ec09ff1b5814aea734d1e7e226cb.png" onClick={() => this.closeItem(index)} /> <img onClick={(e) =>this.onChangeBtn(index, e)} className={style.uploadBtn} src={item.picture ? item.picture: defaultImg}></img> <div className={style.EditInfo}> <div className={style.picturEditor}> <div className={style.text}>关联:</div> <RadioGroup value={item.linkType} className={style.picturRelation} onChange={(e) => this._selectType(index, e)}> <Radio name="linkType" value='goods' className={style.radio}>商品</Radio> <Radio name="linkType" value='page' className={style.radio}>页面</Radio> </RadioGroup> </div> <div className={cx(style.picturEditor, style.picturLink)}> <div className={style.text}>链接:</div> {item.linkType == 'goods' ? this.getlinkGoodsName(item, index) : <Dropdown selectLink={this._selectLink} current={item.linkPage} />} </div> </div> </div> ) ) } _selectLink = (data) => { // 页面链接选择 const { value, onChange } = this.props; const {config} = value const {goodIndex} = this.state let items = [...config.items] items[goodIndex].linkPage = data onChange(value,{ config: { ...config, items }}) } _onChangGoods = (index) => { this.setState({ isShowGoods: true, goodIndex: index }) } _getImg = (data) => { // 获取图片 const { value, onChange } = this.props; const { config } = value const { goodIndex } = this.state let items = [...config.items] if(items.length == 0){ items.push({ picture: '', // 图片 URL,必填 linkType: 'goods', // 图片链接到哪里。可选值:goods(商品)、page(页面) linkGoodsId: '', // 链接到的商品 id,在 linkType 为 goods 时有效且必填 linkPage: '', // 链接到的页面路径,在 linkType 为 page 时有效且必填 }) } if(config.mode == '单图'){ items[0].picture = data } else { items[goodIndex].picture = data } onChange(value,{ config: { ...config, items }}) } addImg = () => { // 轮播图添加图片按钮 const { value, onChange } = this.props; const { config } = value let items = [...config.items] if(config.mode == '单图'){ this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, }) return } items.push({ picture: '', // 图片 URL,必填 linkType: 'goods', // 图片链接到哪里。可选值:goods(商品)、page(页面) linkGoodsId: '', // 链接到的商品 id,在 linkType 为 goods 时有效且必填 linkPage: '', // 链接到的页面路径,在 linkType 为 page 时有效且必填 }) onChange(value,{ config: { ...config, items }}) } getGoodsItem = (data) => { // 商品选择 const { value, onChange } = this.props; const { config } = value const {goodIndex} = this.state let items = [...config.items] items[goodIndex].linkGoodsId = data[0].itemId const arrgoodsNames = [...this.state.goodsNames] if(!arrgoodsNames.some(c => {return c.itemId == data[0].itemId})){ arrgoodsNames.push(data[0]) this.setState({ goodsNames:arrgoodsNames }) } onChange(value,{ config: { ...config, items }}) } render(){ const { value, prefix, validation } = this.props; const { config } = value; const size = this.state.size; const { isShowImgUpload, isShowGoods }= this.state; let isShowCompont = false if(config.items.length == 0){ isShowCompont = false } if(config.items.length > 0) { if(config.items[0].picture == ''){ isShowCompont = false } else { isShowCompont = true } if(config.mode =='轮播图'){ isShowCompont = true } } return ( <div className={`${prefix}-design-component-config-editor`}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <GoogsSelect radio getGoodsItem={this.getGoodsItem} isShowGoods={isShowGoods} close={this.close} /> <div className={style.componentConfigEditor}> <ControlGroup label="选择模板:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <Radio.Group value={config.mode} buttonStyle="solid" className={style.controlGroupControl} onChange={(e) => this.onChange('mode', e)}> <Radio.Button value="单图" name='mode' className={style.imgType}> <img src={value.config.mode == '单图' ? 'https://assets.2dfire.com/frontend/d777e5330a31b209352eff0db2fe568e.png':'https://assets.2dfire.com/frontend/3bc532d72c77bcabc0bc8602d9a26249.png'} /> </Radio.Button> <Radio.Button value="轮播图" name='mode' className={style.imgType}> <img src={config.mode == '轮播图' ? 'https://assets.2dfire.com/frontend/e25c6ce74c7a13e93c801e6b5e5cdde7.png':'https://assets.2dfire.com/frontend/e036d229a2c1f0d260b7dd6229d000b7.png'} /> </Radio.Button> {/* <Radio.Button value="c" name='hasPadding' className={style.imgType}> <img src={value.hasPadding == 'c' ? 'https://assets.2dfire.com/frontend/36cbfa04856035395fe5a388b9ff0bf9.png':'https://assets.2dfire.com/frontend/e926936b709902682c4c6265babb0735.png'} /> </Radio.Button> */} </Radio.Group> </div> <div className={style.componentConfigEditor}> <ControlGroup label="图片添加:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.adBut}> {isShowCompont && this.relationPriew()} {config.items.length <= 4 && <Button onClick={this.addImg} className={style.adAntBtn} type="primary" shape="round" icon="plus" size={size}>添加图片</Button>} <p className={style.tipAdBut}>建议宽度为750px</p> </div> </div> </div> ) } static designType = 'pictureAds'; static designTemplateType = '基础类'; static designDescription = '图片广告'; static getInitialValue() { return { config: { type: 'pictureAds', mode: '单图', // 模板类型;可选值:单图、轮播图、横向滑动 // 图片项列表。最多添加 5 项。mode 为 "单图" 时,只使用列表里的第一项 items: [ { picture: '', // 图片 URL,必填 linkType: 'goods', // 图片链接到哪里。可选值:goods(商品)、page(页面) linkGoodsId: "", // 链接到的商品 id,在 linkType 为 goods 时有效且必填 linkPage: '', // 链接到的页面路径,在 linkType 为 page 时有效且必填 }, ] } }; } } <file_sep>/inside-chain/src/utils/wxApp/array.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * 数组去重 * @param {Array} arr * @return {Array} 去重后数组 */ function arrayUnique(arr) { return Array.from(new Set(arr)); } /** * 数组find,数组中满足提供的测试函数的第一个元素的值 * @see also https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find * @param {Array} arr 数组 * @param {Function} predicate 在数组每一项上执行的函数 * @return {Any} 满足提供的测试函数的第一个元素的值,否则返回 undefined */ function arrayFind(arr, predicate) { if (arr === null) { throw new TypeError('arrayFind called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(arr); var length = list.length >>> 0; var thisArg = arguments[2]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; } /** * 数组find,返回数组中满足提供的测试函数的第一个元素的索引 * @see also https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex * @param {Array} arr 数组 * @param {Function} predicate 在数组每一项上执行的函数 * @return {Number} 满足提供的测试函数的第一个元素的索引。否则返回-1 */ function arrayFindIndex(arr, predicate) { if (arr === null) { throw new TypeError('arrayFind called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(arr); var length = list.length >>> 0; var thisArg = arguments[2]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; } exports.arrayUnique = arrayUnique; exports.arrayFind = arrayFind; exports.arrayFindIndex = arrayFindIndex; exports.default = { arrayUnique: arrayUnique, arrayFind: arrayFind, arrayFindIndex: arrayFindIndex };<file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionMemberCard/definition.js export default { name: 'unionMemberCard', userName: '营销会员卡', group: '互动营销类', max: 1, config: { type: 'memberCard' }, } <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionPage/definition.js export default { name: 'unionPage', userName: '页面基本信息配置', max: 1, config: { title: null, // 页面标题。不指定则使用商家名称 backgroundType: 'color', // 页面背景使用背景色还是背景图。可选值:color、image backgroundColor: 'transparent', backgroundImage: null, // 可选值:null、"URL" }, bare: true, choosable: false, } <file_sep>/union-entrance/src/base/catchError.js import {Modal} from "iview"; let ERR_INFO = { "400": "操作失败", "401": "服务器异常,请联系技术!", "701": "无法修改其他商户信息", "702": "查询不到对应用户", "703": "参数为空", "704": "邮箱和账号不匹配", // "705": "参数格式错误", "705": "url格式错误,需以http://开头", "706": "邮箱已被注册", "707": "账户已被注册", "708": "手机已被注册", "709": "开发者已被注册,无需重新注册", "711": "开发者账号不能用商户编码,请重新填写。", "712": "没有找到对应开发者...", "900": "验证码错误", "901": "账号或密码错误!", "902": "请输入开发者账号!", "903": "邮箱为必填项", "904": "应用授权二维码编码错误", "905": "应用授权二维码编码已失效", "906": "不能使用连锁店铺进行授权", "907": "获取权限失败!", "908": "获取权限组失败!", } function catchError(e) { console.log('error!!!', e); if (e.result) { let errorCode = e.result.resultCode; let errorMsg = e.result.message; // 授权 未登录 或 登录过期 resultCode 为 -2 if (errorCode == -2) { let appId = e.appId || ''; Modal.warning({ title: '请注意', content: errorMsg, onOk: function () { window.location.href= "../page/auth.html#/login?appId=" + appId } }); } if(errorCode == 'SYSTEM_DEFAULT_ERROR'){ Modal.warning({ title: '请注意', content: errorMsg, }); }; // todo 根据错误码,替换文案或者不显示 if (errorCode && ERR_INFO[errorCode]) { // if (errorCode == "SYSTEM_DEFAULT_ERROR" || errorCode == "" || errorCode == "") { // Modal.warning({ // title: '请注意', // content: errorMsg, // }); // } else { // Modal.warning({ // title: '请注意', // content: ERR_INFO[errorCode], // }); // } Modal.warning({ title: '请注意', content: ERR_INFO[errorCode], }); } } } export default catchError <file_sep>/inside-chain/src/store/modules/distCenter/mutations.js export default{ // 获取品牌列表 _getPublishTaskList(state, obj){ state.publishTaskList = obj }, _getTaskInfo(state, obj){ state.taskInfo = obj }, _getAllBrands(state, list){ state.brandList = list }, _setTaskName(state, res){ state.taskInfo.name = res }, _setTimeType(state, res){ state.taskInfo.timeType = res }, // 获取下发时间类型 _getPublishTimeType(state, res) { state.publishTimeType = res }, } <file_sep>/union-entrance/src/views/nav/modal/index.js /** * created by zipai at 2018-01-25 * * 通用 modal框 提示框 * 不依赖其他js,各种框架通用 * ------------------------ * */ const _body = document.getElementsByTagName('body')[0] let _modalMask let _modalWrap let _title let _content let _sure let _cancel let _messageMask let _text let lastTime = 0 function createModal() { if (!document.getElementById('modalMask')) { const modalMask = document.createElement('div') modalMask.setAttribute('class', 'modal-mask') modalMask.setAttribute('id', 'modalMask') modalMask.innerHTML = ` <div class="modal-wrap" id="modalWrap"> <div class="modal-top"> <span class="modal-title" id="title"></span> </div> <div class="modal-content"> <span class="modal-text" id="content"></span> </div> <div class="modal-bottom"> <button class="modal-btn" id="cancel">取消</button> <button class="modal-btn" id="sure">确定</button> </div> </div>` const messageMask = document.createElement('div') messageMask.setAttribute('class', 'message-mask animated fadeInDown') messageMask.setAttribute('id', 'messageMask') messageMask.innerHTML = `<div class="message-wrap"><span id="text"></span></div>` _body.appendChild(modalMask) _body.appendChild(messageMask) _modalMask = document.getElementById('modalMask') _modalWrap = document.getElementById('modalWrap') _title = document.getElementById('title') _content = document.getElementById('content') _sure = document.getElementById('sure') _cancel = document.getElementById('cancel') _messageMask = document.getElementById('messageMask') _text = document.getElementById('text') } } export default { notic(e) { createModal() if (e) { _body.style.overflow = 'hidden' _modalMask.style.display = 'block' _modalWrap.style.display = 'block' _title.innerText = e.title _content.innerText = e.content _sure.onclick = function() { _modalMask.style.display = 'none' _modalWrap.style.display = 'none' if (e.onOk && typeof e.onOk === 'function') { e.onOk() } _body.style.overflow = 'auto' } _cancel.onclick = function() { _modalMask.style.display = 'none' _modalWrap.style.display = 'none' _body.style.overflow = 'auto' } } }, message(e) { createModal() const currentTime = new Date() if (e && currentTime - lastTime >= 300) { _messageMask.style.display = 'block' _messageMask.style.top = (e.top || 100) + 'px' if (typeof e === 'string') { _text.innerText = e } else { _text.innerText = e.content } const duration = e.duration || 1500 setTimeout(function() { _messageMask.style.display = 'none' _messageMask.style.top = -100 + 'px' lastTime = new Date() }, duration) } } } <file_sep>/union-entrance/src/views/change/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import GATEWAY_ENV from '../../config/env.js' import { Icon, Row, Col, Message } from 'iview' Vue.component('Icon', Icon) Vue.component('Row', Row) Vue.component('Col', Col) Vue.prototype.$Message = Message // import Cookie from "@2dfire/utils/cookie"; Vue.config.productionTip = false // token放在header,网关接口需要令牌 Vue.http.headers.common['env'] = GATEWAY_ENV // console.log(Vue.http); // Vue.http.options.xhr = { withCredentials: true }; // Vue.http.headers.common['_k'] = localStorage.getItem("token"); new Vue({ el: '#app', // router, template: '<App/>', components: { App } }) <file_sep>/inside-chain/src/views/pass/scheme/list/columns.js import Divider from '../../common/divider' export default self => [ { title: '传菜方案名称', key: 'name' }, { title: 'IP地址', key: 'printerIp' }, { title: '商品', key: 'menuCount', render: (h, { row: { producePlanId, name, menuCount } }) => { return ( <router-link style="color:#3e76f6" to={{ path: '/pass/scheme/goodsManage', query: { id: producePlanId, title: name, ...self.$route.query } }} > {menuCount || '未设置'} </router-link> ) } }, { title: '操作', render: (h, { row }) => { return ( <div class="pass-scheme-columns-action"> <span onClick={self.editAddSchemeModal(row)}>编辑</span> <Divider /> <span onClick={self.delScheme(row)}>删除</span> </div> ) } } ] <file_sep>/inside-boss/src/components/updown/select.js import React, { Component } from 'react' import { Dropdown, Menu, Button, Icon, Popconfirm } from 'antd' import * as action from '../../action' import styles from './select.css' import cx from 'classnames' const MySelect = ({ content, onClickLeft, onClickRight }) => ( <div style={{ overflow: 'hidden', height: '100%' }}> <div onClick={onClickLeft} className={styles.options_left}> {content} </div> <Popconfirm title="是否确认删除该文件?" onConfirm={onClickRight}> <div className={styles.options_right}> <Icon type="close" /> </div> </Popconfirm> </div> ) class BatchSelector extends Component { onClick() { const buttonLock = sessionStorage.getItem('dropDownButtonLock') if (buttonLock === 'loading') { return false } const { dispatch } = this.props dispatch(action.fetchBatchList) } handleClickDropdownItem(position, index) { const { dispatch } = this.props const { batchList } = this.props.data const { id } = batchList[index] const rechargeBatchId = id const startTime = 0 const endTime = 0 const rechargeStatusList = '' const pageSize = 50 const pageIndex = 1 if (position === 'left') { const tag = 'fromBatchSelector' dispatch( action.fetchRechargeList({ rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, tag }) ) } else if (position === 'right') { dispatch(action.deleteBatch(id)) } } render() { const t = this const { batchList, name } = this.props.data const menu = ( <Menu className={cx(styles.dropdown_wrapper)}> {batchList.map((e, i) => { return ( <Menu.Item key={i} className={cx(styles.dropdown_item)}> <MySelect content={e.name} onClickLeft={t.handleClickDropdownItem.bind( t, 'left', i )} onClickRight={t.handleClickDropdownItem.bind( t, 'right', i )} /> </Menu.Item> ) })} </Menu> ) return ( <Dropdown overlay={menu} trigger={['click']}> <Button className={cx(styles.select_btn)} onClick={t.onClick.bind(t)} > <span className={styles.sel_text}> {name ? name : '选择已上传的文件'} </span> <Icon type="down" className={cx(styles.icon)} /> </Button> </Dropdown> ) } } export default BatchSelector <file_sep>/static-hercules/src/alipay-agent/store/state.js /** * Created by zipai on 2019/5/20. */ export default { //提交的所有字段信息 merchantInfo: { entityId: '', //entityId alipayAccount: '', //支护宝账号 linkman: '', //联系人姓名 mobile: '', //联系人手机号 email: '', //常用邮箱 industryType: '', //经营类目 licensePhoto: '', //营业执照 // licensePhoto: // 'https://assets.2dfire.com/frontend/9c881aebd52e43ac1b2dfe9baf3637a6.png', //营业执照 licenseNo: '', //营业执照号码 isLongValid: false, //营业执照是否长期有效 startTime: '', //起始时间 endTime: '', //到期时间 // shopPhoto: // 'https://assets.2dfire.com/frontend/cb3a941bfcdbb74f9bad8e8697a85c66.jpg' shopPhoto: '' //店铺门头照 }, isEnable: false, //是否启用 //底部选择弹出 picker: { showPicker: false, pickerName: '', //当前选择的字段 pickerSlots: [ { defaultIndex: 0 } //默认选中第一个 ], pickerTitle: '', other: '' //其他需要设置的值,省份需要设置id的值 }, //底部日期选择弹出 dateNewPicker: { showPicker: false, pickerName: '', //当前选择的字段 pickerTitle: '', //当前标题 pickerValue: '' //当前选中日期值 }, //底部地址选择器 addressPicker: { showPicker: false, pickerName: '', pickerTitle: { province: {}, city: {} }, topTitle: '选择地址' }, //switch开关 switchControl: { switchName: '', switchValue: false }, //图片展示 examplePhoto: { img: '', isShow: false }, /** * 显示状态 * detail: 查看详情,不可修改; * edit: 编辑修改,已提交之后,申请通过,并为可修改状态; * */ viewState: 'edit', //状态,number类型,当为31时代表进件成功报名失败,只可修改部分数据 merchantInfoString: '', // 保存表单初始的参数内容 ispopShow: false // 是否展示底部弹框 } <file_sep>/inside-boss/src/container/visualConfig/views/new_design/editing/PreviewWrapper.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { Popconfirm } from 'antd' import c from 'classnames' import cookie from '@2dfire/utils/cookie' import * as actions from '@src/container/visualConfig/store/actions' import s from './PreviewWrapper.css' class PreviewWrapper extends Component { static contextTypes = { designId: PropTypes.string.isRequired, designEditing: PropTypes.bool.isRequired, designDefinition: PropTypes.object.isRequired, } get removeable() { return this.context.designDefinition.choosable } get editing() { return this.context.designEditing } get id() { return this.context.designId } isUnionShop = () => { const data = JSON.parse(cookie.getItem('entrance')).shopInfo const { entityTypeId, isInLeague } = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (entityTypeId == '3' && !!isInLeague){ // 联盟或者是联盟下的店铺 return false } return true } edit = e => { if(this.isUnionShop()) { if (e.target.dataset.removeBtn) return actions.designEditComponent(this.id) } } remove = () => actions.designRemoveComponent(this.id) render() { return <div className={c(s.previewWrapper, this.editing && s.editing)} onClick={this.edit}> {this.props.children} {this.isUnionShop() && this.removeable && this.removeBtn()} </div> } removeBtn() { return <Popconfirm title="确定删除?" wrapperClassName={s.actionBtnDelete} trigger="click" onConfirm={this.remove} > <img data-remove-btn="1" className={s.removeBtn} src="https://assets.2dfire.com/frontend/73a3ec09ff1b5814aea734d1e7e226cb.png" /> </Popconfirm> } } export default PreviewWrapper <file_sep>/static-hercules/src/borrow-money/utils/catchError.js import Vue from 'vue' let ERR_INFO = { '0001': '网络暂时开小差了,请稍后重试' /*系统错误*/, '0002': '网络暂时开小差了,请稍后重试' /*数据库异常*/, '0003': '网络暂时开小差了,请稍后重试' /*空数据*/, '0004': '网络暂时开小差了,请稍后重试' /*贷款平台异常*/, '0005': '网络暂时开小差了,请稍后重试' /*缺少参数*/, DEFAULT_ERROR_CODE: '' } function catchError(err) { let message = ERR_INFO[err.errorCode] /*ERR_PUB 统一认为来自于网关的报错*/ if (err.errorCode.indexOf('ERR_PUB') >= 0) { Vue.prototype.$toast('网络暂时开小差了,请稍后重试') return } if (message) { Vue.prototype.$toast(message) } else { Vue.prototype.$toast(err.message) } } export default catchError <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/pictureTextNav/TmpPreview.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames' // debugger import style from './TmpPreview.css' export default class pictureTextPreview extends PureComponent { static propTypes = { value: PropTypes.object, }; state= { defaultImg: 'https://img.yzcdn.cn/public_files/2018/03/08/837f3d12e14b299778ae5fea5c05a3a3.png' } render() { const { config } = this.props.value const { mode, items } = config const { defaultImg} = this.state return ( <div className="zent-design-component-pictureText-preview"> <div className={style.pictureTextList}> {items.map((item) => mode == '文字导航'? <div style={createStyle(config)} className={style.listText}>{item.text}</div>: <div className={style.pictureTextInfo} style={createStyle(config)}> <div className={cx(style.pictureTextLi, 'desigeCove')} style={{backgroundImage:`url(${item.picture ? item.picture : defaultImg})`}}></div> {mode == '图文导航' && <p className={style.pictureTextName}>{ item.text }</p>} </div> )} </div> </div> ); } } function createStyle(config) { const { items, textColor } = config const pictureWidth = 375 const pictureLiWidth = (pictureWidth / items.length) - (3 * (items.length - 1)) return { width: items.length ==1 ? `${pictureWidth}px` : `${pictureLiWidth}px`, color: textColor, } } <file_sep>/inside-chain/src/tools/gw-params/README.md ## 提供调用网关api的必要参数 因网关方面要求,现请求时网关接口时需要多传递9个和业务无关的参数。为了调用网关接口更加方便,api配置更加简洁,减少重复劳动而写了这个js。 功能:取浏览器UA中浏览器及其版本号、操作系统及其版本号,api版本等`网关要求`的请求必须参数,并返回一个字符串,包含所有与业务无关的参数键值对。 具体使用方法见文档,另附赠前端API网关调用文档。 git: [http://git.2dfire-inc.com/zeqi/2dfire-gw-params](http://git.2dfire-inc.com/zeqi/2dfire-gw-params) ### Installation $ npm i @2dfire/gw-params --save-dev ### Usage import { GW } from '@2dfire/gw-params' ### Intro 该js会返回网关请求所需要的相关参数,是必须参数。 为方便其他同事调用API,免去重复劳动之苦,特增加该文件,以备不时之需。 GW的可能值示例 GW = s_os=Mac%20OS&s_osv=10.12.6&s_ep=Chrome&s_epv=65.0.3325.181&s_sc=1280*324&timestamp=1523176879447&s_web=1&v=1.0&format=json ### 返回的参数释义 | 名称 | 类型 |是否必须|参数来源| 描述 | |---|---|---|---|---| |s_web| string| Y| GET |web端参数开关,1为开启| |s_os |string|Y|GET |系统名称 mac / windows /| |s_osv|string|Y|GET |系统版本 10.1| |s_epv |string|Y|GET |浏览器版本| |s_ep |string|Y|GET| 浏览器型号: chrome| |s_sc| string|Y|GET |屏幕尺寸(800x600)| |format|string|Y|GET|返回格式,目前只支持json| |v |String| Y |GET |API协议版本,可选值:1.0| |timestamp| String| Y| GET |时间戳| --- ## API网关调用文档 ### api网关调用规范 原有的公共参数 | 名称 | 类型 |是否必须|参数来源| 描述 | |---|---|---|---|---| |app_key|string|Y|GET|api分配给每个应用的key,新应用需要申请| | method |string|Y|GET|api接口名称,需要请求的接口| |env|string|Y|HEAD|环境,放在header中(daily、pre、publish、变更中有单独生成)| |token|string|N|HEAD|登陆后获得,除登陆外接口需要带上这个参数| |lang|string|Y|HEAD|国际化需要,语言(en_US 英文/zh_CN中文(简体)/zh_TW中文(繁體))| |s_web| string| Y| GET |PC参数开关,1为开启| |s_os |string|Y|GET |系统名称 mac / windows /| |s_osv|string|Y|GET |系统版本 10.1| |s_epv |string|Y|GET |浏览器版本| |s_ep |string|Y|GET| 浏览器型号:chrome| |s_sc| string|Y|GET |屏幕尺寸(800x600)| |format|string|Y|GET|返回格式,目前只支持json| |v |String| Y |GET |API协议版本,可选值:1.0| |timestamp| String| Y| GET |时间戳| **注意:env/token/lang参数必须放入`Header`中,其余参数(例如:app_key)不要放入`Header`中,否则会导致请求失败,不能通过option请求。 更多参数要求及说明,请点击访问:[API网关规范](http://k.2dfire.net/pages/viewpage.action?pageId=233374194),第二部分-PC端参数 #### api调用地址 api调用时使用的地址: 日常环境:http://gateway.2dfire-daily.com 预发环境:http://gateway.2dfire-pre.com/ 线上环境:https://gateway.2dfire.com #### 配置后台(登录账号密码同yoyo) 登录后台后可以看到接口的出入参数或测试接口。 日常环境:http://console.gateway.2dfire-daily.com 预发环境:http://console.gateway.pre.2dfire.net 线上环境:http://console.gateway.2dfire.net #### 调用示例 示例为一个简单的ajax请求,注意`url`参数,此请求为`日常环境`的请求。 建议请求url组成: http://gateway.2dfire-daily.com? + (请求网关地址,域名应依环境改变) 'method=xxx' + (请求方法,每一个请求都不同) '& appkey=xxx' + (应用密钥) '&' + GW (网关请求必要参数) --- ``` JavaScript import {GW} from '@2dfire/gw-params' $.getJSON({ url: 'http://gateway.2dfire-daily.com?method=com.dfire.simple.getInfo&app_key=200006' + GW, dataType: "json", data: { id: id }, type: "get", beforeSend: function (request) { request.setRequestHeader("env","dev"); request.setRequestHeader("token","token"); }, success: function (res) { // 成功 }, error: function (data) { // 失败 } }) ``` #### 返回格式 ResultMsp 请求错误返回 { "code":0, "errorCode":"1000", "message":"您输入的用户名或密码有误" } 请求正确返回 { "code":1, "data":[{"sendTimeStr":"2015-01-22 16:59:16","_id":82}] } 或 { "code":1, "data":{total:100,list:[{name:'Tom'}]} } `常见的成功返回`——实际项目开发中,业务soa处理完后,通过网关返回数据,前端获取到的数据,经常会包裹一层data返回: { "code":1, "data":{ "data":{ // 实际返回的数据 } } } ### 常见的错误 #### 配置的错误 网关接口可以跨域调用, #### 常见错误码 以下是web端请求网关接口时,比较常见的错误码: ERR_PUB 开头的错误码,都是网关报错。 |编码|中文|错误释义| |---|---|---| |ERR_PUB200001|访问令牌为空|请求头中没有找到token| |ERR_PUB200002|无效的访问令牌|常在当前用户被登出或token编码错误时出现| |ERR_PUB200003|访问令牌已过期|token过期| |ERR_PUB200004|接口未授权|网关接口需要授权,请向对接的后端同事请求帮助| |ERR_PUB300021|缺少环境参数env|日常环境请求网关接口时,需要在请求头中添加env参数,在预发和正式环境不需要env| | ERR_PUB300022 |缺少系统请求参数|网关未过滤接口,需要在请求时传多个不需要的参数| 遇到错误时,请大胆的寻求后端同事、网关同事的帮助,可以快速解决问题。 其它错误码请点击:[所有网关错误码](http://k.2dfire.net/pages/viewpage.action?pageId=280002723) ### 参考文档 以下为本文档书写时的参考文档: api网关规范: http://k.2dfire.net/pages/viewpage.action?pageId=233374194 网关错误码: http://k.2dfire.net/pages/viewpage.action?pageId=280002723 ### 备注 此文档将会日渐丰富完善,或跟随网关的更新而更新,如有错误或过时的内容,还请钉钉联系@泽漆,谢谢。 <file_sep>/static-hercules/src/base/utils/unit.js module.exports = { initGiftsFormat: function(gifts, otherData, callback){ var tempData = {}; var giftWithId = this.checkGiftsWithId(); // 为gifts数组转变成对象属性 for(var i = 0; i < gifts.length; i++){ // gifts[i].unitPrice = gifts[i].unitPrice !== undefined ? gifts[i].unitPrice/100 : 0; if (gifts[i].giftId == giftWithId.lollies) { tempData.lollies = gifts[i]; } else if (gifts[i].giftId == giftWithId.chocoolate) { tempData.chocoolate = gifts[i]; } else if (gifts[i].giftId == giftWithId.flower) { tempData.flower = gifts[i]; } } // 将其他属性合并进gifts对象 // return Object.assign(otherData, tempData); return this.combineobject(otherData, tempData); }, // 礼物对应的giftId checkGiftsWithId: function(){ return { lollies: '777de2bb56fe490cb2aadbaa9c36e0e7', chocoolate: '2ea898e0feef4628917e26ec7d722dda', flower: 'a705affe2f7c4fc094bb93cc16141d78' } }, // 合并对象(Object.assign 通过外引入的方式在android上不兼容) combineobject: function(oriObject, newObject){ for (var item in newObject) { oriObject[item] = newObject[item]; } return oriObject; }, // 截取url参数,可用this.$route.query代替 getRequest: function(){ var url = location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]); } } return theRequest; }, // 提示弹出框 showDialog: function(text){ var alertdialog = document.getElementById('alertdialog') if ( alertdialog !== undefined && alertdialog !== null ) { document.getElementById('alertdialog').style.display = 'block'; document.getElementById('alertdialogtext').innerHTML = text; } else { alertdialog = document.createElement("div"); alertdialog.innerHTML = '<div id="alertdialog" styles="display:block" class="alertdialog"><div class="box"><div id="alertdialogtext">' + text + '</div></div></div>' alertdialog.addEventListener('click', function(){ document.getElementById('alertdialog').style.display = 'none'; }) document.body.appendChild(alertdialog); } }, // cookie操作 Cookie: { set: function(name,value,expHour,domain,path){ /*把cookie的domain设置到根域名下*/ var strDomain = document.domain; var aryDomain = strDomain.split("."); var strRootDomain = strDomain; var domainLen = aryDomain.length; //域名数组求和,判断是否为ip地址
 var ipSum = aryDomain.reduce(function (preValue, curValue) { return preValue + curValue }); //如果是localhost或者ip地址访问,则不修改domain
 if (strDomain != "localhost" && isNaN(ipSum)) { strRootDomain = "." + aryDomain[domainLen - 2] + "." + aryDomain[domainLen - 1]; } // 如果没有主动设置domain,则修改为根域名
 if (typeof domain == "undefined") { domain = strRootDomain; } //如果是localhost或者ip地址访问,则不修改domain
 if (strDomain != "localhost" && isNaN(ipSum)) { strRootDomain = "." + aryDomain[domainLen - 2] + "." + aryDomain[domainLen - 1]; } document.cookie = name+"="+encodeURIComponent(value==undefined?"":value)+(expHour?"; expires="+new Date(new Date().getTime()+(expHour-0)*3600000).toUTCString():"")+"; domain="+(domain?domain:document.domain)+"; path="+(path?path:"/"); }, get: function(name){ return document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))==null ? null : decodeURIComponent(RegExp.$2); }, remove: function(name){ if(this.get(name) != null) this.set(name,null,-1); } }, // 设置Token setToken: function( token ){ var Cookie = this.Cookie; Cookie.set('token', token ); }, // 获取Token getToken: function(){ var Cookie = this.Cookie; if (Cookie.get('token')) { return Cookie.get('token'); }else{ return null } }, // 获取用户名 getNickName: function(){ var Cookie = this.Cookie; if (Cookie.get('nickname')) { var nickname = Cookie.get('nickname'); return nickname.replace(/\"/g, ""); } }, // 另一种实现方法 getCookie: function(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(/.*\s/, ""); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }, // 防止滚动穿透 fixedBody: function(){ var scrollTop = document.body.scrollTop || document.documentElement.scrollTop document.body.style.cssText += 'position:fixed;top:-' + scrollTop + 'px' }, // 恢复 looseBody: function() { var body = document.body body.style.position = '' var top = body.style.top document.body.scrollTop = document.documentElement.scrollTop = - parseInt(top) body.style.top = '' } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/coupons/definition.js export default { name: 'coupons', userName: '优惠券', group: '互动营销类', max: 3, config: { source: 'manualAdd', items: [], fetchLength: 3, backgroundColor: '#4c85e8', }, } <file_sep>/inside-boss/src/container/importHistory/index.js import React, { Component }from 'react' import { connect } from 'react-redux' import Main from '../../components/importHistory/main' import InitData from './init' import * as action from '../../action' import * as bridge from '../../utils/bridge' import styles from './style.css' class commContainer extends Component { componentWillMount () { const query = bridge.getInfoAsQuery() const {dispatch,params} = this.props console.log('output',params.pageType, query); const data = InitData(params.pageType, query) dispatch(action.initDataImportHostory(data)); dispatch(action.getImportHistoryList({ pageNum:1 })); } render () { const {data, dispatch} = this.props return ( <div className={styles.wrapper}> <Main data={data} dispatch={dispatch}/> </div> ) } } const mapStateToProps = (state) => ({ data: state.importHistory }) const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(commContainer) <file_sep>/static-hercules/src/ocean-zl/config/api.js import axios from './interception.js' /** * 查询审核结果-直连 * @returns * @constructor */ export const getApplyStatus = params => axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.queryAlipayBlueSea', params: params }) /** * 提交支付宝直连蓝海审核资料 * @returns * @constructor */ export const saveAlipayBlueSea = data => axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.saveAlipayBlueSea', data }) /** * 查询通联进件审核结果 * @returns * AUTH_SUCCESS 到蓝海申请页 * AUTH_FAIL 到激活失败页 * AUDITING 激活中 * NO_AUTH 未进件 * @constructor */ export const checkIfAuthByBizType = params => axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.IMerchantAccountService.checkIfAuthByBizType', params }) /** * 提交通联蓝海审核资料 * @returns * @constructor */ export const saveAllinBlueSea = data => axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.saveAllinBlueSea', data }) /** * 获取中国行政区 * @param sub_area_type 行政区域划分(province, city, town, street) * @param id 上级行政区域id */ export const getRegion = (sub_area_type, id) => axios({ method: 'GET', url: 'com.dfire.soa.boss.center.base.service.ISystemService.getAreaInfo', params: { sub_area_type, id, need_sub_area: true } }) /** * 根据entityId和BizType查询审核信息 * @returns * @constructor */ export const queryAlipayBlueSea = data => axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.queryAlipayBlueSea', data }) /** * 判断是否是超级管理员 * @returns * @constructor */ export const judgeSuper = params => axios({ method: 'get', url: 'com.dfire.boss.center.soa.user.service.IUserClientService.isSuper', params }) <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionNav/TmpEditor.js // 商品分类 编辑组件 import React from 'react' import { Radio } from 'antd' import ImgUpload from '@src/container/visualConfig/views/design/common/imgUpload' import { DesignEditor } from '@src/container/visualConfig/views/design/editor/DesignEditor'; import style from './TmpEditor.css' import cx from 'classnames' export default class CateEditor extends DesignEditor { constructor(props) { super(props) this.state = { orderIcons: [ '堂食点餐', '预售', '外卖', '排队', ], infoIcons: [ '商品列表' ], isShowImgUpload: false, typeName:null, obj: null } } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } _getImg = (data) => { // 获取图片 const { value } = this.props; const { config } = value const {typeName, obj} = this.state if(obj == 'mealIcons') { let mealIcons = Object.assign({}, config.mealIcons) mealIcons[typeName] = data this.configChang({mealIcons}) }else { let retailIcons = Object.assign({}, config.retailIcons) retailIcons[typeName] = data this.configChang({retailIcons}) } } close = () => { this.setState({ isShowImgUpload: false, }) } onChangeBtn = (item, str) => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, typeName: item, obj: str }) } render() { const { value } = this.props const { orderIcons, infoIcons } = this.state const { config } = value const { mealIcons, retailIcons} = config const { isShowImgUpload }= this.state; return ( <div className={style.member_editor_container}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <p className={style.member_upload_tips}>icon配置(请上传60*52px大小的icon)</p> <div className={style.member_icons_box}> <p className={style.member_p}>餐饮店铺相关icon配置:</p> { orderIcons.map( (item, i) => { return ( <div className={style.member_flex_icon} key={i}> <div className={style.member_upload} onClick={() => this.onChangeBtn(item, 'mealIcons')}> <img className={style.orderImg} src={mealIcons[item]} alt=""/> <div className={style.member_title}>{ item }</div> </div> </div> ) }) } </div> {/* <div className={style.member_icons_box}> <p className={style.member_p}>零售店铺相关icon配置:</p> { infoIcons.map( (item, i) => { return ( <div className={style.member_flex_icon} key={i}> <div className={style.member_upload} onClick={() => this.onChangeBtn(item, 'retailIcons')}> <img className={style.orderImg} src={retailIcons[item]} alt=""/> <div className={style.member_title}>{ item }</div> </div> </div> ) }) } </div> */} </div> ) } } <file_sep>/inside-boss/src/components/goodsPicture/templateList/goodsDetailTemplate.js import React, {Component} from 'react' import styles from '../style.css' import {Modal} from 'antd' import * as action from "../../../action"; import Preview from "./preview"; class GoodsDetailTemplate extends Component { constructor(props) { super(props) this.state = { destory:true, previewCover:"" } } // 预览 preview = (url)=>{ this.setState({ destory: false, previewCover: url }) } // 关闭预览弹窗 closePreview =()=>{ this.setState({ destory: true, }) } // 使用 userTemplate =(type,id)=>{ const { dispatch ,detail,data} = this.props; let itemId = detail.pictureFileId; if (type == 2) { // 新模板跳转到编辑模板页 dispatch(action.detailChange({detail:false,pictureFileId:itemId})) dispatch(action.editTemplate({edit:true,templateId:id})) }else{//默认、老模板直接改变使用状态 let entityId = data.importData.entityId; let ItemDetailVO = { entityId: entityId, itemDetailJson: "", itemId: itemId, templateId: id || "" }; dispatch(action.saveTemplate(ItemDetailVO, 1, itemId,entityId)) } } render() { let {data} =this.props; let templateList = data.goodsDetailTemplate; return ( <div> <div className={styles.pictureDetailListTitle} style={{background: '#fff'}}> <p className={styles.chooseNum}>商品详情页模板</p> </div> <ul className={styles.pictureListUl} style={{marginLeft: '-40px'}}> { templateList&&templateList.length>0&& templateList.map((item,index)=>{ return ( <li className={styles.goodsItemStyle} key={index}> <p className={styles.goodsTitle}>{item.templateName || "默认"}</p> <div className={styles.goodsPictureBox}> <img className={styles.goodsPicture} src={item.templateImage || require("../images/default.png")} alt={item.templateName}/> { !!item.useTemplate && <div className={styles.userLabel}></div> } </div> <div className={styles.btnBox}> { !!item.oldTemplate && <a onClick={()=>this.preview(item.templatePreview)}>预览</a> } { (item.oldTemplate == 2 || (item.oldTemplate == 1 && item.useTemplate == 0)) && <span>|</span> } { !item.useTemplate && <a onClick={()=>this.userTemplate(item.oldTemplate,item.templateId)}>使用</a> } { (item.oldTemplate == 2 && item.useTemplate == 1) && <a onClick={()=>this.userTemplate(item.oldTemplate,item.templateId)}>编辑</a> } </div> </li> ) }) } </ul> <Preview logo={this.state.previewCover} destory={this.state.destory} closePreview={this.closePreview}/> </div> ) } } export default GoodsDetailTemplate <file_sep>/inside-boss/src/container/visualConfig/components/pageParts/Layout.js import React, { Component } from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import c from 'classnames' import s from './index.css' /* inside-boss 对页面样式的控制不够灵活 1. 无法对 header 部分进行自定义,例如增加一些控件、按钮 2. 不能让内容区域自动填满整个可视空间,也不能自定义内容区域的 padding 此组件通过把内容渲染到更上一级,来绕过限制,可以自定义实现 header,且组件直接填满了整个空间 参考:https://www.cnblogs.com/rubylouvre/p/7016685.html */ export default class Layout extends Component { static propTypes = { className: PropTypes.string, } componentDidMount() { this.mountParent() this.renderContent() } componentDidUpdate() { this.renderContent() } componentWillUnmount() { this.unmountParent() } // ================================= mountParent() { this.parent = document.createElement('div') this.parent.className = c(s.layout, this.props.className) this.baseElm.parentNode.parentNode.appendChild(this.parent) } unmountParent() { this.parent.parentNode.removeChild(this.parent) } renderContent() { ReactDOM.unstable_renderSubtreeIntoContainer( this, <div>{this.props.children}</div>, this.parent, ) } // ================================= render() { return <div ref={baseElm => this.baseElm = baseElm} /> } } <file_sep>/static-hercules/src/bindPhone/config/index.js module.exports = { APP_KEY: '200102' }<file_sep>/static-hercules/src/ele-account/config/api.js import axios from './interception' import {API_BASE_URL, APP_KEY} from "apiConfig"; const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, /*首页-收款明细*/ getHomeBill() { return axios({ method: 'GET', url: 'com.dfire.acs.service.IHomeService.getHomeBillCountByEntityId' }) }, /*首页-折线图*/ getWeeklyTotal() { return axios({ method: 'GET', url: 'com.dfire.acs.service.IHomeService.getLastSevenDayTotalFlowsByEntityId' }) }, /*费率表*/ getFeeData() { return axios({ method: 'GET', url: 'com.dfire.acs.service.IPaySceneRateService.getPaymentSceneListByEntityId' }) }, /*当日收款明细-分页 receipt-info*/ getTodayFlowList(data) { return axios({ method: 'POST', url: 'com.dfire.acs.service.IFlowService.queryTodayFlowListByCondition', data: data }) }, /*当日收款明细总额 receipt-info*/ getTodayTotalAmount(params) { return axios({ method: 'GET', url: 'com.dfire.acs.service.IFlowService.queryTodayTotalAmountByCondition', params: params }) }, /*结算明细列表-分页 bill-info*/ getTotalBillList(data) { return axios({ method: 'POST', url: 'com.dfire.acs.service.IBillService.queryTotalSettleBillListByCondition', data: data }) }, /*结算渠道明细 bill-day-info*/ getChannelList(params) { return axios({ method: 'GET', url: 'com.dfire.acs.service.IBillService.queryChannelSettleDetailsByEntityIdAndDate', params: params }) }, /*结算流水明细列表 分页 bill-day-info*/ getOneDayFlowList(data) { return axios({ method: 'POST', url: 'com.dfire.acs.service.IFlowService.querySettleFlowListByCondition', data: data }) }, /*首页-最近一次结算数据*/ getLastDayTotalSettle(params) { return axios({ method: 'GET', url: 'com.dfire.acs.service.IHomeService.getLastDayTotalSettleByEntityId', params: params }) }, /*首页-折线图-近7天结算*/ getWeeklySettle(params) { return axios({ method: 'GET', url: 'com.dfire.acs.service.IHomeService.getLastSevenDayTotalSettleByEntityId', params: params }) }, /*结算明细-金额汇总*/ getTotalSettleBill(data) { return axios({ method: 'POST', url: 'com.dfire.acs.service.IBillService.queryTotalSettleBillByEntityIdAndDate', data: data }) } } export default API; <file_sep>/static-hercules/src/secured-account/components/toast/index.js /** * * @param res * @author * */ import Toast from './index.vue' let toast = {} toast.install = (Vue)=>{ let constructor = Vue.extend(Toast)//实例化一个Toast let instance = new constructor({ el: document.createElement('div') }); document.body.appendChild(instance.$el); Vue.prototype.$toast = (options)=>{ if (typeof options === 'string') { instance.text = options } else if (typeof options === 'object') { Object.assign(instance, options) } instance.show = true instance.start() } } export default toast; <file_sep>/static-hercules/src/secured-account/constants/index.js const array2Map = (arr = []) => { let result = {} arr.map(val => { result[val.code] = val.name }) return result } const withdrawStatus = [ { code: 1, name: '提现中' }, { code: 2, // name: '提现成功', name: '' }, { code: 3, name: '提现失败' }, { code: 4, name: '提现退票' } ] const withdrawStatusColor = [ { code: 1, name: 'c-ff9900' }, { code: 2, name: 'c-00cc33' }, { code: 3, name: 'c-ff0033' }, { code: 4, name: 'c-ff0033' } ] const inOutTypes = [ { code: 0, name: '收入' }, { code: 1, name: '支出' } ] module.exports = { inOutTypes, withdrawStatusMap: array2Map(withdrawStatus), withdrawStatusColorMap: array2Map(withdrawStatusColor), payMap: array2Map(inOutTypes) } <file_sep>/inside-boss/src/components/goodsPicture/pictureDetailList.js /** * Created by air on 2017/8/4. */ /** * Created by air on 2017/7/11. */ import React, {Component} from 'react' import {Icon, message, Checkbox, Button, Modal} from 'antd' import styles from './style.css' import * as action from '../../action' import api from '../../api' import AddPictureBtn from './addPictureBtn' import HaveDropPic from './picDetailListBox' import GoodsDetailTemplate from './templateList/goodsDetailTemplate.js' import getUserInfo from '../../utils/getUserInfo' // import DustbinCopyOrMove from "./haveDropPic"; class PictureDetailList extends Component { constructor(props) { super(props) this.state = { plainOptions: [], checkedList: [], indeterminate: false, checkAll: false, page: 1 } } componentDidMount() { const t = this const {dispatch, detail,data} = t.props let entityId = data.importData.entityId; dispatch(action.getPictureDetailList(detail.pictureFileId)) if(data.isInclude==1)return; dispatch(action.getTemplateList(entityId, detail.pictureFileId)); } //返回按钮 backPictureList() { const t = this const {dispatch} = t.props dispatch(action.detailChange({detail: false})) } goodsDetailPriew = (data, dispatch, detail) => { // industry:3是零售店铺,不展示 const { shopInfo } = getUserInfo(); const { industry } = shopInfo || {}; if(industry == 3) return false return !data.isInclude && <GoodsDetailTemplate data={data} dispatch={dispatch} detail={detail} /> } render() { const t = this const { dispatch, detail} = t.props let {data}= t.props data.importData.memberId=detail.pictureFileId const total = data.pictureDetailListTotal return ( <div className={styles.pictureDetailListBox}> <div className={styles.pictureListBody}> <div className={styles.pictureListTitle}> <div className={styles.turnBtn} onClick={this.backPictureList.bind(this)}> <Icon className={styles.pictureIcon} type="left-circle-o"/> {/*<p className={styles.pictureTitleWord}>返回</p>*/} </div> <span className={styles.chooseNum}>{data.pictureName}</span> </div> {/*3为主图,1为详情图*/} <HaveDropPic data={data} type={'3'} dispatch={dispatch} detail={detail}/> <HaveDropPic data={data} type={'1'} dispatch={dispatch} detail={detail}/> {/* 商品详情模板*/} { this.goodsDetailPriew(data, dispatch, detail) } </div> </div> ) } } export default PictureDetailList <file_sep>/inside-boss/src/container/visualConfig/sences/retail/index.js import home from './home' import nav from './nav' import goodsList from './goodsList' import mine from './mine' import customPage from './custom' export default { pages: [ home, nav, goodsList, mine, ], customPage, } <file_sep>/inside-chain/src/store/modules/menu/state.js export default{ // 品牌列表 allMenuList: { total: 0, menus: [] }, reuseMenuList: [], goodsList: [], noSearchItems: true, unSubmitGoods: [], resultBackup: [], // 进入某菜单后,记录菜单的信息 // 如不存在,则从cookie中获取 menuInfo: { menuName: '' }, filterParams: { type: '', keyword: '' }, goodsKinds: [], goodsKindsSingle: [], typeList: [ ], goodsOfMenu: [], goodsOfMenuTotal: 0, goodsOfMenuSimple: [], goodsOfMenuSimpleTotal: 0, // 商品价格 goodsPrice: { useDefaultPriceSwitch: false, priceSwitch: false, price: 0, memberPrice: 0, defaultPrice: 0, defaultMemberPrice: 0, specPrices: [ // { // defaultPrice: 0, // price: 0, // specDetailId: '', // specDetailName: '' // } ] }, // 商品价格备份 priceBackup: { }, kindMenuTree: [], allSimpleItem: [], publishType: [], publishTimeType: [], publishMenus: [] } <file_sep>/inside-chain/src/utils/wxApp/ajax.js "use strict"; var ajax = function ajax(params) { if (!params || !params.url) { return; } function success(resp) { params.success && params.success.call(this, resp.data); } function error(resp) { params.error && params.error.call(this, resp.data); } var paramsFormat = { url: params.url, method: (params.type || "GET").toUpperCase(), data: params.data || "", header: { 'content-type': params.contentType || 'application/json', 'platform': 'wxapp' }, success: success, fail: error, complete: params.complete }; wx.request(paramsFormat); }; module.exports = ajax;<file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/cateList/definition.js export default { name: 'cateList', userName: '分类商品', description: '分类商品(分类商品排序规则由掌柜端设置决定)', choosable: false, position: 'bottom', config: { seeLevel: 2, showFields: ['商品名称', '商品价格', '下单按钮'], orderButton: { mode: '加入购物车', orderStyle: '1', cartStyle: '1', }, }, } <file_sep>/static-hercules/src/base/components/dialogs/apis/sendMobileVerificationCode.js const requester = require('base/requester'); const { API_BASE_URL } = require('apiConfig'); const API_URL = API_BASE_URL + '/bind/v1/get_code'; module.exports = function sendMobilePhoneVerificationCode ({ mobile, areaCode = '+86' }) { const params = { mobile, areaCode }; return requester.post(API_URL, { params }); }; <file_sep>/static-hercules/src/ocean-zl/utils/rules.js // 字符串长度2~10 const twoToTen = /^\w{2,10}$/ // 字符串长度1~15 const oneToFifteen = /^\w{1,15}$/ // 字符串1~40 const oneToForty = /^\w{1,40}$/ // 验证手机 const checkTel = /^[1][0-9]{10}$/ export const ruleList = { shopName: { isRequired: true, types: 'text', name: '店铺名称' }, alipayAccount: { isRequired: true, types: 'text', name: '支付宝账号' }, detailAddress: { isRequired: true, types: 'text', name: '店铺地址' }, businessLicensePhoto: { isRequired: true, types: 'img', name: '营业执照' }, shopPhoto: { isRequired: true, types: 'img', name: '店铺门头照' }, shopCashierPhoto: { isRequired: true, types: 'img', name: '收银台照片' }, indoorPhoto: { isRequired: true, types: 'img', name: '店内环境' }, otherPlatformPhoto: { isRequired: true, types: 'img', name: '其他平台' } } export const ruleListTl = { shopName: { isRequired: true, types: 'text', name: '店铺名称' }, businessLicenseName: { isRequired: true, types: 'text', name: '营业执照名称' }, provinceName: { isRequired: true, types: 'text', name: '省份' }, cityName: { isRequired: true, types: 'text', name: '城市' }, townName: { isRequired: true, types: 'text', name: '区' }, detailAddress: { isRequired: true, types: 'text', name: '详细地址' }, businessLicensePhoto: { isRequired: true, types: 'img', name: '营业执照' }, shopPhoto: { isRequired: true, types: 'img', name: '店铺门头照' }, shopCashierPhoto: { isRequired: true, types: 'img', name: '收银台照片' }, indoorPhoto: { isRequired: true, types: 'img', name: '店内环境' }, otherPlatformPhoto: { isRequired: true, types: 'img', name: '其他平台' } } /** * 表单验证 * @param val 用户输入的值 * @param dataVal ruleList对应的key * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ export const inputIsOk = function(val, dataVal, source) { let data = {} if (source === 'tl') { data = ruleListTl[dataVal] } else { data = ruleList[dataVal] } //如果不存在,或者isRequired=false,则说明是不需要验证的字段 if (!data || !data.isRequired) { return { data: true } } if (data.types === 'boolean') { if (typeof val !== 'boolean') { return { data: false, message: data.name + '不能为空' } } } else { if (!val) { return { data: false, message: data.name + '不能为空' } } } //类型判断 let returnData switch (data.types) { case 'number': //验证数字 returnData = getMatchResult(/^[0-9]*$/, val, data.name) break case 'mobile': //验证手机号码 returnData = getMatchResult(/^[1][0-9]{10}$/, val, data.name) break case 'tel': //验证电话 returnData = getMatchResult(/^[0-9]{5,15}$/, val, data.name) break case 'email': returnData = getMatchResult( /(^([a-zA-Z0-9_-]{2,})+@([a-zA-Z0-9_-]{2,})+(.[a-zA-Z0-9_-]{2,})+)|(^$)/, val, data.name ) break case 'img': returnData = getMatchResult(/^[http|https]/, val, data.name) break default: returnData = { data: true } } return returnData } /** * 返回正则效验结果 * @param reg 正则效验规则 * @param val 值 * @param name 效验字段名字 * @return object { * data: false, 验证是否通过 * message: data.name + '不能为空' false的时候需要message值 * } * */ const getMatchResult = (reg, val, name) => { let r r = val.match(reg) if (r == null) { return { data: false, message: '请上传正确的' + name } } else { return { data: true } } } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/seach/SeachPreview.js import React, { PureComponent } from 'react'; import cx from 'classnames' import { Icon } from 'antd'; import style from'./SeachPreview.css' export default class SeachPreview extends PureComponent { render() { const { config } = this.props.value; const { shape, backgroundColor } = config return ( <div className="zent-design-component-title-preview"> <div className={style.seachPreview} style={{backgroundColor: backgroundColor}} > <div style={createStyle(config)} className = {cx(style.seachinput +' '+ style[`seach${shape}`])}><Icon type="search" />&nbsp;&nbsp;搜索内容</div> </div> </div> ); } } function createStyle(value) { const { textColor, textAlign } = value; return { color: textColor, textAlign: textAlign, }; } <file_sep>/inside-boss/src/container/visualConfig/store/register.js import { injectAsyncReducer } from '@src/utils/asyncInjector' import store from '@src/store' import visualConfigReducer from './reducers' injectAsyncReducer(store, 'visualConfig', visualConfigReducer) <file_sep>/inside-chain/src/const/emu-distType.js const distType = { 1: '单个模块', 2: '综合模块', } export default distType; <file_sep>/union-entrance/src/views/nav/util/getEnv.js let env = null /** * 判断环境 */ export default function getEnv() { if (env) { return env } const hostname = window.location.hostname const devHostList = ['tt.2dfire.net'] const dailyHostList = ['d.2dfire-daily.com', 'biz.2dfire-daily.com'] const preHostList = [ 'd.2dfire-pre.com', 'biz.2dfire-pre.com', 'shoppingmall.2dfire-pre.com' ] const publishHostList = ['biz.2dfire.com', 'd.2dfire.com'] if (devHostList.includes(hostname)) { env = 'dev' } else if (dailyHostList.includes(hostname)) { env = 'daily' } else if (preHostList.includes(hostname)) { env = 'pre' } else if (publishHostList.includes(hostname)) { env = 'publish' } else { env = 'local' } return env } <file_sep>/inside-chain/config/prod.env.js module.exports = { NODE_ENV: process.env.NODE_ENV || '"prod"' } <file_sep>/static-hercules/src/oasis/router/index.js import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '*', redirect: '/entrance' }, { path: '/entrance', name: 'entrance', meta: { title: '支付优惠费率' }, component: resolve => require(['../views/entrance/ApplyEntrance.vue'], resolve) }, { path: '/second-entrance', name: 'second-entrance', component: resolve => require(['../views/entrance/entrance.vue'], resolve) }, { path: '/introduce', name: 'introduce', component: resolve => require(['../views/entrance/introduce.vue'], resolve) }, { path: '/input', name: 'input', component: resolve => require(['../views/inputshopinfo/InputShopInfo.vue'], resolve) }, { path: '/view', name: 'view', component: resolve => require(['../views/viewshopinfo/ViewShopInfo.vue'], resolve) }, { path: '/unbind', name: 'unbind', component: resolve => require(['../views/inactive/result.vue'], resolve) }, { path: '/inactive', name: 'inactive', component: resolve => require(['../views/inactive/index.vue'], resolve) }, { path: '/result', name: 'result', component: resolve => require(['../views/result/ApplyResult.vue'], resolve) }, { path: '/natural', name: 'natural', component: resolve => require(['../views/naturalPerson/index.vue'], resolve) } ] }) <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionGroupActivity/TmpPreview.js import React, { PureComponent } from 'react' import style from './TmpPreview.css' export default class BannerPreview extends PureComponent { render() { return ( <div className={style.configPreview} > <img src='https://assets.2dfire.com/frontend/59879ca26bc53a7500aa339ce57d5d5e.png'/> </div> ) } } <file_sep>/inside-chain/src/views/shop/store-manage/pass/utils/index.js import API from '@/config/api_pass' import cookie from '@2dfire/utils/cookie' //获取当前门店entityId,isChain:是否是总部的entityId(cookie中的) export function getEntityId(self, isChain = true) { return isChain ? JSON.parse(cookie.getItem('entrance')).shopInfo.entityId : self.$route.query.entityId } //获取所有商品类别 export async function getGoodTypes(params) { const { data } = await API.getAllGoodsType(params || {}) const res = (data || []).map(({ name, kindId }) => ({ label: name, value: kindId })) res.unshift({ label: '全部', value: '-' }) return res } //获取所有的区域 export async function getAllAreas(params = { sale_out_flag: true },isAllArea) { const { data } = await API.getAllArea(params) return (data || []).map(item => { return { _checked: isAllArea===1||item.isCheck === 1, ...item } }) } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/goodsList/definition.js export default { name: 'goodsList', userName: '商品', group: '基础类', max: 5, config: { mode: '大图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '新品', image: null, }, }, } <file_sep>/static-hercules/src/wechat-direct-con/lang/zh.js export default { // top-header 里面设置title,key为路由的名字 pageTitle: { '/index': '微信支付特约商户', '/input/first/first': '小微商户', '/input/second/second': '小微商户', '/input/third/third': '小微商户', '/input/fourth/fourth': '小微商户', '/merchants/first/first': '升级普通商户', '/merchants/second/second': '升级普通商户', '/merchants/third/third': '升级普通商户', '/merchants/fourth/fourth': '升级普通商户', '/merchantinfo': '查看商户信息', '/merchantupgradeinfo': '查看商户信息', '/editbankcard': '修改收款银行卡', '/edituserinfo': '修改商户信息', } } <file_sep>/static-hercules/src/alipay-agent/store/getters.js /** * Created by zipai on 2019/5/20. */ // 商户基本信息 export const merchantInfo = state => { return state.merchantInfo } export const merchantInfoKeys = state => { return [ 'entityId', 'alipayAccount', 'linkman', 'mobile', 'email', 'industryType', 'licensePhoto', 'licenseNo', 'isLongValid', 'startTime', 'endTime', 'shopPhoto' ] } export const merchantOrgInfo = state => { return ['orgPhoto', 'orgNo', 'orgStartTime', 'orgEndTime'] } export const merchantBusinessAccountInfo = state => { return [ 'businessAccountName', 'businessAccountBank', 'businessAccountBankCode', 'businessAccountNumber', 'businessAccountAddressProvince', 'businessAccountAddressCity', 'businessAccountSubBank' ] } // 小微部分 export const XwMerchantInfoStepFirst = state => { return [ 'shopName', 'detailAddress', 'shopLicensePic', 'shopEnvironmentPic', 'serviceTel', 'serviceType', 'idCardFront', 'idCardReverse', 'idCardName', 'idCardNumber', 'startDate', 'endDate', 'userSimpleName', 'accountName', 'accountBank', 'accountNumber', 'accountAddressProvince', 'accountAddressCity', 'accountSubBank', 'userTelNumber', 'userEmailNumber' ] } <file_sep>/inside-boss/src/api/index_old.js import nattyFetch from 'natty-fetch' import * as bridge from '../utils/bridge' import {callParent} from '../utils/bridge' import {currentAPIUrlPrefix, merApiPrefix} from '../utils/env' import getUserInfo from '../utils/getUserInfo' import cookie from "@2dfire/utils/cookie"; // import cookie from "@2dfire/utils/cookie"; // import {currentEnvString} from "./networkApi"; const apiContext = nattyFetch.context({ mock: false, urlPrefix: currentAPIUrlPrefix, // eslint-disable-line mockUrlPrefix: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/', withCredentials: false, postDataFormat: 'JSON', willFetch: (vars, config) => { if (!config.mock) { // let token = cookie.getItem("new-token"); // const url = config.url; // if ( // url.indexOf("get_boss_function") !== -1 || // url.indexOf("get_railway_functions") !== -1 // ) { // token = getUserInfo().token; // } config.header['X-Token'] = getUserInfo().token; config.header['token'] = undefined; config.header['lang'] = undefined; config.header['env'] =undefined; // config.header['Accept'] = 'application/vnd.ms-excel;charset=UTF-8'; } }, fit: res => { if (res.code === 0 && res.errorCode === '401') { return callParent('logout') } return { success: res.code && res.code === 1, content: res.data, error: {message: res.message, errorCode: res.errorCode} } } }) // 全局 AppKey const APP_AUTH = '?app_key=200800&s_os=pc_merchant_back' apiContext.create({ // 搜索条件 getSearchFormArgs: { url: 'report/queryArgs.json' + APP_AUTH, mockUrl: '127/report/queryArgs.json', method: 'POST' }, // 报表 chart 结构 getChartDetails: { url: 'report/details.json' + APP_AUTH, mockUrl: '127/report/details.json', method: 'POST' }, // 报表 chart 数据 getChartData: { url: 'report/data.json' + APP_AUTH, mockUrl: '127/report/data.json', method: 'POST' }, // "导出 Excel " getExcel: { url: 'report/exportXls.do' + APP_AUTH, mockUrl: '127/report/exportXls.do', method: 'POST' }, // 联动下拉框时,异步取数据 getUnionSelect: { url: 'report/lovValues.json' + APP_AUTH, mockUrl: '127/report/lovValues.json', method: 'POST' }, //获取充值批次列表 fetchBatchList: { mock: false, url: 'merchant/batch/v1/get_batch_list' + APP_AUTH, mockUrl: '123/getFilesSuccess', method: 'GET' }, //删除批次 deleteBatch: { mock: false, url: 'merchant/batch/v1/delete_batch' + APP_AUTH, mockUrl: '123/deleteBatchSuccess', method: 'GET' }, //查询表格数据 fetchRechargeList: { mock: false, url: 'merchant/batch/v1/get_batch_details_list_by_query' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_batch_details_list', method: 'GET' }, //查询导入日志信息 getCommTypes: { mock: false, url: 'merchant/batch/v1/getCommTypes' + APP_AUTH, mockUrl: '123/merchant/batch/v1/getCommTypes', method: 'GET' }, //查询导入日志信息 getImportLog: { mock: false, url: 'merchant/import/v1/query_import_operate_Log' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET' }, //查询日志详情 getImportLogDetail: { mock: false, url: 'merchant/import/v1/query_import_operate_detail_Log' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET' }, //获取商家可选择的类目列表 getCategory: { mock: false, url: 'merchant/import/v1/query_category' + APP_AUTH, mockUrl: '123/merchant/batch/v1/get_import_log', method: 'GET' }, //下载商品模板 downloadTemplate: { mock: false, url: 'merchant/import/v1/create_import_template' + APP_AUTH, mockUrl: '123/merchant/import/v1/create_import_template', method: 'GET', header: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' } }, //商品库列表 getGoodsList: { mock: false, url: 'merchant/menu/v1/menu_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'POST' }, //商品库列表(新) getGoodsListNew: { mock: false, url: 'merchant/menu/v2/menu_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'POST' }, //获取数据订正状态 getIsShowBrand: { mock: false, url: 'merchant/plate/fixstatus' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjs/532/merchant/plate/fixstatus', method: 'GET' }, //获取品牌列表 getBrandList: { mock: false, url: 'merchant/plate/get_plate_list' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/532/merchant/plate/get_plate_list', method: 'GET' }, // 交路信息库列表 getRouteList: { mock: false, url: 'railway/v1/queryTrains' + APP_AUTH, mockUrl: '', method: 'POST' }, // 车次时刻信息库列表 getTrainList: { mock: false, url: 'railway/v1/queryTrainStations' + APP_AUTH, mockUrl: '', method: 'POST' }, //充值信息编辑 rechargeModify: { mock: false, url: 'merchant/batch/v1/modify_batch_details' + APP_AUTH, mockUrl: '', method: 'POST' }, //批量删除充值信息 deleteMultiple: { mock: false, url: 'merchant/batch/v1/delete_batch_details_list' + APP_AUTH, mockUrl: '', method: 'POST' }, //批量充值 rechargeMultiple: { mock: false, url: 'merchant/batch/v1/batch_recharge' + APP_AUTH, mockUrl: '', method: 'POST' }, //批量红冲 refund: { mock: false, url: 'merchant/batch/v1/cancel_charge_card' + APP_AUTH, mockUrl: '', method: 'POST' }, //删除单个 deleteSingle: { mock: false, url: 'merchant/batch/v1/delete_batch_details' + APP_AUTH, mockUrl: '', method: 'POST' }, modifyInfo: { mock: false, url: 'merchant/batch/v1/modify_batch_details' + APP_AUTH, mockUrl: '', method: 'POST' }, // 视频列表 videoList: { mock: false, url: 'shadow_deer/list_video_library' + APP_AUTH, mockUrl: '', method: 'POST' }, // 名字检验是否重复 is_name_repeat: { mock: false, url: 'shadow_deer/is_name_repeat' + APP_AUTH, mockUrl: '', method: 'POST' }, pictureList: { mock: false, url: 'merchant/menu/v1/get_menu_page' + APP_AUTH, mockUrl: '281/pictureList', method: 'POST' }, pictureDetailList: { mock: false, url: 'merchant/menu/v2/get_menu_image' + APP_AUTH, mockUrl: '281/pictureDetailList', method: 'POST' }, //商品排序 changeListSort: { mock: false, url: 'merchant/menu/v1/sort_image' + APP_AUTH, mockUrl: '496/sort_image', method: 'POST' }, //删除图片 deletePicture: { mock: false, url: 'merchant/menu/v2/remove_menu_image' + APP_AUTH, mockUrl: '281/pageChange', method: 'POST' }, //订单存照列表 orderList: { mock: false, url: 'cashlog/orderHistoryList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/427/orderList', method: 'POST' }, //是否展示会员导出按钮 isShowMemberExportBtn: { mock: false, url: 'merchant/export/v1/init_page' + APP_AUTH, mockUrl: '', method: 'GET' }, //发放优惠券 getCouponType: { mock: false, url: 'coupon/back/v1/getCouponType' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/getCouponType', method: 'GET' }, importFileList: { mock: false, url: 'coupon/back/v1/importFileList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/importFileList', method: 'GET' }, rechargeList: { mock: false, url: 'coupon/back/v1/rechargeList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/rechargeList', method: 'POST' }, reupload: { mock: false, url: 'coupon/back/v1/reupload' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/reupload', method: 'POST' }, deleteBatch_: { mock: false, url: 'coupon/back/v1/deleteBatch' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/deleteBatch', method: 'POST' }, pushProgress: { mock: false, url: 'coupon/back/v1/pushProgress' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, //获取掌柜侧边栏 getBossMenuList: { url: merApiPrefix + 'merchant/function/v1/get_boss_functions' + APP_AUTH + '&' + getUserInfo(true), method: 'POST' }, //获取高铁侧边栏 getRailwayMenuList: { url: merApiPrefix + 'merchant/function/v1/get_railway_functions' + APP_AUTH + '&' + getUserInfo(true), method: 'POST' }, // 获取不记名优惠券下拉框内容 getNoOwnerCoupon: { mock: false, url: 'coupon/offline/v1/init' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // 不记名优惠券批量激活 noOwnerCouponActive: { mock: false, url: ' coupon/offline/v1/batchActivate' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // 不记名优惠券批量停用 noOwnerCouponStop: { mock: false, url: 'coupon/offline/v1/batchStop' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // 不记名优惠券批量激活 noOwnerCouponSearch: { mock: false, url: 'coupon/offline/v1/report' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' }, // // 不记名优惠券查询 // noOwnerSetList: { // mock: false, // url: 'coupon/offline/v1/report' + APP_AUTH, // mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', // method: 'POST' // }, // 不记名优惠券获取优惠券 noOwnerGetCoupon: { mock: false, url: 'coupon/offline/v1/couponList' + APP_AUTH, mockUrl: 'http://mock.2dfire-daily.com/mock-serverapi/mockjsdata/481/pushProgress', method: 'POST' } }) export default apiContext.api <file_sep>/inside-chain/src/base/tools.js import Requester from "@/base/requester"; import API from "@/config/api"; import catchError from "@/base/catchError"; let tools = { /** * 格式化数字 * @param s:带格式化数据 * @param n:保留小数点后几位(默认2位) */ formateNumber(s, n) { n = n >= 0 && n <= 20 ? n : 2; s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; let l = s.split(".")[0].split("").reverse(), r = s.split(".")[1]; let t = ""; for (let i = 0; i < l.length; i++) { t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); } if (n == 0) return t.split("").reverse().join(""); return t.split("").reverse().join("") + "." + r; }, /** * 格式化金额 * @param s:带格式化数据 * @param n:保留小数点后几位(默认2位) */ formateMoney(s, n) { n = n >= 0 && n <= 20 ? n : 2; return s.toFixed(n); }, /* * 日期格式化 * @param date:日期 * @param fmt:数据格式 */ dateFormate(date, fmt) { var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }, /** * formdate参数转化 * @param o:需要转化的对象 * return string: key=value&key=value */ formDate(o) { let p = ""; for (let i in o) { p += i + "=" + o[i] + "&"; } p = p.substring(0, p.length - 1); return p; }, /** * formatDateByStamp 时间戳转时间(yyyy-MM-dd) * @param stamp:需要转化的时间戳(单位ms) * return string: yyyy-MM-dd */ formatDateByStamp(stamp) { let time = new Date(stamp); let y = time.getFullYear(); let m = time.getMonth() + 1; if (m < 10) { m = '0' + m; } let d = time.getDate(); if (d < 10) { d = '0' + d; } return y + '-' + m + '-' + d }, /** * scrollTo 滚动至某位置 * @param id || class 需要跳转到的元素位置绑定的id或class * demo * <div id='t'>...</div> * <div class='t'>...</div> 会跳转到文档流中第一个匹配的class * scrollTo('t') */ scrollTo(t) { let tmp_id = '#' + t; let tmp_class = '.' + t; let tmp_target = ''; if (document.querySelector(tmp_id)) { tmp_target = document.querySelector(tmp_id) } else { tmp_target = document.querySelector(tmp_class) } let targetTop = tmp_target.offsetTop || 0; window.scrollTo(0, targetTop); }, /** * 文件下载 * @param list:需要下载的文件路径 */ fileDownload(list) { Requester.post(API.DOWNLOAD_INVOICE, {urlList: list}, {emulateJSON: true}).then((data) => { window.location = data; }).catch((e) => { catchError(e) }); }, /** * 套餐/商品分类递归 * @param data */ recursion(data) { const flat = arr => [].concat(...arr) const item = arr => { return flat(arr.map(i => { if (i.subList) { return item(i.subList).map(j => { return {name: i.name + '-' + j.name, id: j.id} }) } else { return {name: i.name, id: i.id} } } )) } return item(data) }, /** * 套餐/商品分类递归-最后一级和自己不可选 * @param data */ recursionClass(data) { let tmp_list = []; const loop = (arr,father) => { arr.map(item => { if(father){ tmp_list.push({ name: father.name + '-' + item.name, id: item.id, disabled: item.disabled }) }else{ tmp_list.push({ name: item.name, id: item.id, disabled: item.disabled }) } if (item.subList) { loop(item.subList, item) } }) return tmp_list } return loop(data) }, /** * 套餐/商品分类递归 只取叶子节点的名称 * @param data */ recursionLeaf(data) { const flat = arr => [].concat(...arr) const item = arr => { return flat(arr.map(i => { if (i.subList) { return item(i.subList).map(j => { return {name: j.name, id: j.id} }) } else { return {name: i.name, id: i.id} } } )) } return item(data) }, /** * 给有children的添加disabled */ addDisableWithChildren(data) { const item = arr => { return arr.map(i => { if (!!i.children && i.children.length) { i.disabled = true item(i.children) return i } else { i.disabled = false return i } }) } return item(data) }, addDisableWidthOutChoosed(data, id) { const item = arr => { return arr.map(i => { i.disabled = i.id !== id !!i.children && i.children.length && item(i.children) return i }) } return item(data) } } export default tools; <file_sep>/static-hercules/src/ocean/store/state.js /** * Created by zyj on 2018/4/3. */ export default { //提交的所有字段信息 applyInfo: { // // 审核状态 // auditStatus: "", // // 实体id // entityId: "", // // id // id: "", // // 快递单号 // expressNo: "", //==================================step1 // 店铺名称 shopName: "", // 店铺简称 shopSimpleName: "", // 营业模式 shopKind: "", // 营业模式名称 shopKindName: "", // 商户类型:02:个体工商户;03:企业商户 merchantType: "", // 店铺电话 shopPhone: "", // 省id provinceId: "", // 省名称 provinceName: "", // 城市id cityId: "", // 城市名称 cityName: "", // 区id townId: "", // 区名称 townName: "", // 街道id streetId: "", // 街道名称 streetName: "", // 详细地址 detailAddress: "", // 联系人 contactName: "", // 联系人手机号 contactMobile: "", // 联系人邮箱 contactEmail: "", //===========================step2 // 法人姓名 corporationName: "", // 法人联系电话 corporationLinkTel: "", // 法人证件类型:01:身份证,只能选择身份证 certificateType: "01", // 法人证件号码 certificateNum: "", // 法人证件图片正面 certificateFrontPic: "", // 法人证件图片反面 certificateBackPic: "", // 统一社会信用代码 creditCode: "", // 营业执照名称 businessLicenseName: "", // 营业执照照片 businessLicensePic: "", // 其他证明 otherCertificationPic: '', // 开户许可证照片(企业商户显示,个体工商户不显示) businessCert: "", // ==========================step3 // 帐户类型 accountType: "",//01:个人帐户,02:对公帐户 ,不可选择,如果商户类型选择个人,就是个人帐户,如果商户类型选择企业,那就是对公帐户; // 开户人名称 accountName: "", // 开户银行 bankName: "", // 银行代码 bankCode: "", // 开户省份 bankProvince: "", // 开户省份id bankProvinceId: "", // 开户城市 bankCity: "", // 开户城市id bankCityId: "", // 开户支行 bankSubName: "", // 开户人证件类型 idType: "01", // 开户人证件号码 idNumber: "", // 开户人证件图片正面 idCardFrontPic: "", // 开户人证件图片反面 idCardBackPic: "", // 支行代码 bankSubCode: "", // 收款银行账号预留手机 accountMobile: "", // 收款银行账号 accountNumber: "", // =================================================step4 // 是否需要支付宝台牌物料 // needMaterial: true, // 门头照 doorPic: "", // 收银台照片 checkoutCounterPic: "", // 店内环境照 shopEvnPic: "", // 其他平台照片 otherPlatformPic: "", // 验证码 smsCode: "" }, // 保存的id saveId:'', //底部选择弹出 picker: { showPicker: false, pickerName: '',//当前选择的字段 pickerSlots: [ {defaultIndex: 0},//默认选中第一个 ], pickerTitle: '', other: '',//其他需要设置的值,省份需要设置id的值 }, //图片展示 examplePhoto:{ img:'', isShow:false }, /** * 显示状态 * detail: 查看详情,不可修改; * edit: 编辑修改,已提交之后,申请通过,并未可修改状态; * first: 第一次提交 * */ viewState: 'first' , //状态,number类型,当为31时代表进件成功报名失败,只可修改部分数据 subStatus:0 }<file_sep>/inside-chain/src/store/modules/payKind/mutations.js export default{ // 获取付款方式列表 _getPayKindList(state, obj){ state.payKindList = obj }, //获取付款方式详情 _getPayKindInfo(state, obj){ state.payKindInfo = obj }, _getAllPayKindList(state, list){ state.allPayKindList = list }, // 获取付款方式列表 _getPayKindListSingle(state, obj){ state.payKindListSingle = obj }, //获取付款方式详情 _getPayKindInfoSingle(state, obj){ state.payKindInfoSingle = obj }, _getAllPayKindListSingle(state, list){ state.allPayKindListSingle = list }, _getPayKindListForSelect(state, list){ state.selectPayKind = list }, _getPayKindListForSelectSingle(state, list){ state.selectPayKindSingle = list }, _setIsAlipay(state, obj){ state.isAlipay = obj } } <file_sep>/static-hercules/src/loan/main.js import Vue from 'vue' import vueResource from 'vue-resource' import App from './App.vue' import Router from 'vue-router' import openApp from '@2dfire/vue-OpenApp' Vue.use(openApp) Vue.use(Router) Vue.use(vueResource) Vue.http.options.credentials = true; var router = new Router({ routes: [ { path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "活动首页", component: require("./views/loanapply/LoanApply.vue") } ] }); router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: '<App/>', components: { App } }) <file_sep>/inside-chain/src/const/emu-tableType.js //1:散座,2:包厢,3:卡座 const tableType = { 1: '散座', 2: '包厢', 3: '卡座', } export default tableType; <file_sep>/inside-boss/src/container/visualConfig/views/new_design/header/DesignHeader.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Button, message, Modal, Popover } from 'antd' import QRCode from 'qrcode.react' import * as actions from '@src/container/visualConfig/store/actions' import { pick } from '@src/container/visualConfig/utils' import { Header } from '@src/container/visualConfig/components/pageParts' import Loading from '@src/container/visualConfig/components/Loading' import ChoosePage from '@src/container/visualConfig/components/ChoosePage' import cookie from '@2dfire/utils/cookie' import s from './DesignHeader.css' @connect(state => pick(state.visualConfig.design, 'configName', 'componentConfigs', 'previewUrl')) class DesignHeader extends Component { constructor(props) { super(props) this.state = { loadingTip: null, } } // ===== getters ===== get disabled() { // config 载入中时不允许执行操作 return this.props.componentConfigs === null } // ===== 公共函数 ===== loading(tip, promise) { this.setState({ loadingTip: tip }) promise.then( () => this.setState({ loadingTip: null }), () => this.setState({ loadingTip: null }), ) return promise } // ==== 业务函数 ===== switchConfig = (configName) => { actions.initDesign(configName) } publish = () => { // TODO: 表单校验 const promise = this.loading('上架中...', actions.designPublish()) promise.then(res => { if (res.result) { message.success('上架成功') } else { message.error(res.message) } }) } switchPreviewQRCode = (shouldVisible) => { if (shouldVisible) { this.preview() } else { actions.designLeavePreview() } } preview = () => { // TODO: 表单校验 const promise = this.loading('保存中...', actions.designPreview()) promise.then(res => { if (!res.result) message.error(res.message) }) } backup = () => { this.loading('备份中...', this.executeBackup()) } executeBackup = async (force = false) => { const ret = await actions.designBackup(force) if (ret.result) { message.success('备份成功') } else if (ret.forceable) { return new Promise(resolve => { Modal.confirm({ title: ret.message, onOk: () => { this.executeBackup(true).then( () => resolve(), () => resolve(), ) }, onCancel: () => resolve() }) }) } else { message.error(`备份失败:${ret.message}`) } return null } isUnionShop = () => { const data = JSON.parse(cookie.getItem('entrance')).shopInfo const { entityTypeId, isInLeague } = data // entityTypeId: 3是店铺,10是联盟;isInLeague:1,店铺是属于联盟下的店铺 if (entityTypeId == '3' && !!isInLeague){ // 联盟或者是联盟下的店铺 return false } return true } // =========================================== render() { const { configName, previewUrl } = this.props const disabled = this.disabled const { loadingTip } = this.state // const title = <span>自定义装修(拖拽相应的组件至页面期望位置即可)</span> const title = <span>自定义装修</span> return <Header title={title}> <div className={s.chooseWrap}> <ChoosePage current={configName} onChange={this.switchConfig} disabled={disabled} /> </div> <div className={s.actions}> {this.isUnionShop() && <Button type="primary" size="large" disabled={disabled} onClick={this.publish}>上架</Button>} {this.isUnionShop() && <Button size="large" disabled={disabled} onClick={this.backup}>备份</Button>} <Popover content={<PreviewQRCode url={previewUrl} />} placement="bottom" trigger="click" visible={!!previewUrl} onVisibleChange={this.switchPreviewQRCode} > <Button size="large" disabled={disabled}>预览</Button> </Popover> </div> {loadingTip && <Loading tip={loadingTip} />} </Header> } } /** * qrcode 是放在 Popover 里显示的,Popover 收起时会有一段过场动画。 * 若 url 为空时立刻不再渲染 qrcode 内容,那么 Popover 收起时会有一瞬间处于无内容、缩小的状态,不好看。 * 因此这里处理成 url 为空时依然渲染上一次的 url 内容。 */ class PreviewQRCode extends Component { static propTypes = { url: PropTypes.string, } constructor(props) { super(props) this.state = { cachedUrl: props.url, } } componentWillReceiveProps(nextProps) { // nextProps.url 为空时,不更新 state.cachedUrl const { url } = nextProps if (url) this.setState({ cachedUrl: url }) } render() { const { cachedUrl } = this.state if (!cachedUrl) return null return <QRCode value={cachedUrl} /> } } export default DesignHeader <file_sep>/inside-chain/src/store/modules/organ/mutations.js export default { _setOrganHead(state, name) { state.organ.name = name; }, _getOrganMap(state, organ) { state.organ = organ }, _searchOrgan(state, organs) { state.organ.organs = organs }, _getOrganInfo(state, organ_info) { state.organ_info = organ_info }, _expandOrgan(state, organs) { state.tmp_organs = organs }, _setOrganFlow(state, flow) { state.organ_flow = flow }, _setOrganTmpFlow(state, flow) { state.tmp_flow = flow }, _clearTmpFlow(state) { state.tmp_flow = [] }, _selectOrgan(state, organs) { state.shop_filter.organs_show = organs }, _setOrgan(state, organ) { state.shop_filter.selected_organ = organ }, _setOrganChecked(state, organs_checked) { console.log('organs_checked', organs_checked) state.shop_filter.organs_checked = organs_checked }, _clearOrgan(state) { state.organ.organs = [] } } <file_sep>/static-hercules/build/webpack.dev.conf.js var config = require('../config'); var webpack = require('webpack'); var merge = require('webpack-merge'); var path = require('path'); var utils = require('./utils'); var baseWebpackConfig = require('./webpack.base.conf'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var glob = require("glob"); // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function(name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]); }); var getPlugin = function() { var plugin = [ // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', title: '跳转页', chunks: [], inject: true }), ]; if (config.dev.partialPackage) { var current = baseWebpackConfig.current; current.forEach(function(item) { console.log("打包item:" + item); plugin.push(new HtmlWebpackPlugin({ filename: 'page/' + item + '.html', template: path.join(config.dev.page, item + '.html'), chunks: [item], inject: true })); }); } else { var pages = glob.sync("./page/*.html"); pages.forEach(function(name) { var chunk = name.slice(7, name.length - 5); var page = name.slice(7, name.length); var file = name.slice(2, name.length); var temp = path.join(config.dev.page, page); // console.log("chunk:" + chunk) // console.log("page:" + page) // console.log("file:" + file) // console.log("temp:" + temp) plugin.push( new HtmlWebpackPlugin({ filename: file, template: temp, inject: true, chunks: [chunk] }) ); }); } return plugin; }; module.exports = merge(baseWebpackConfig, { module: { loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // eval-source-map is faster for development devtool: '#eval-source-map', plugins: getPlugin() // [ // // https://github.com/glenjamin/webpack-hot-middleware#installation--usage // new webpack.optimize.OccurenceOrderPlugin(), // new webpack.HotModuleReplacementPlugin(), // new webpack.NoErrorsPlugin(), // // https://github.com/ampedandwired/html-webpack-plugin // new HtmlWebpackPlugin({ // filename: 'page/example.html', // template: path.join(config.dev.page, 'example.html'), // chunks: ['example'], // inject: true // }), // new HtmlWebpackPlugin({ // filename: 'page/eatlive.html', // template: path.join(config.dev.page, 'eatlive.html'), // chunks: ['eatlive'], // inject: true // }), // new HtmlWebpackPlugin({ // filename: 'page/lottery.html', // template: path.join(config.dev.page, 'lottery.html'), // chunks: ['lottery'], // inject: true // }), // new HtmlWebpackPlugin({ // filename: 'page/managerReword.html', // template: path.join(config.dev.page, 'managerReword.html'), // chunks: ['managerReword'], // inject: true // }), // new HtmlWebpackPlugin({ // filename: 'page/meetgame.html', // template: path.join(config.dev.page, 'meetgame.html'), // chunks: ['meetgame'], // inject: true // }), // new HtmlWebpackPlugin({ // filename: 'index.html', // template: 'index.html', // title: '跳转页', // chunks: [], // inject: true // }) // ] });<file_sep>/static-hercules/src/reportCenter/components/confirm/index.js import Confirm from './index.vue' const defaults = { type: 'alert', title: '提示', content: '请确定当前操作', confirmText: '确定', cancelText: '取消', confirm: null, cancel: null } let confirm = {} confirm.install = (Vue) => { let constructor = Vue.extend(Confirm) let instance = new constructor({ el: document.createElement('div') }); document.body.appendChild(instance.$el); Vue.prototype.$confirm = (options) => { if (typeof options === 'string') { options = { content: options } } Object.assign(instance, defaults, options) instance.type = 'confirm'; instance.visible = true } Vue.prototype.$alert = (options) => { if (typeof options === 'string') { options = { content: options } } Object.assign(instance, defaults, options) instance.type = 'alert'; instance.visible = true } } export default confirm <file_sep>/inside-boss/src/container/priceTag/reducers.js import { SET_PRICE_TAG_MODULE } from '../../constants' const priceTagReducer = (state = {}, action) => { switch (action.type) { case SET_PRICE_TAG_MODULE: return Object.assign({}, state, { priceTagModuleList: action.data }) default: return state } } export default priceTagReducer <file_sep>/inside-boss/src/container/visualConfig/store/reducers/index.js import shopInfoReducer from './shopInfo' import customPagesReducer from './customPages' import backupsReducer from './backups' import templatesReducer from './templates' import designReducer from './design' export default function visualConfigReducer(state, action) { if (!state) state = {} return { shopInfo: shopInfoReducer(state.shopInfo, action), customPages: customPagesReducer(state.customPages, action), backups: backupsReducer(state.backups, action, state), templates: templatesReducer(state.templates, action), design: designReducer(state.design, action), } } <file_sep>/inside-boss/src/container/priceTagEdit/reducers.js import { SET_GOOD_TAG_IMAGE, SET_MODULE_DETAIL,SET_UPDATE_MODULE_RESULT } from '../../constants' const priceTagEditReducer = (state = {}, action) => { switch (action.type) { case SET_GOOD_TAG_IMAGE: return Object.assign({}, state, { upLoadGoodTagImage: action.data }) case SET_MODULE_DETAIL: return Object.assign({}, state, { moduleDetail: action.data }) case SET_UPDATE_MODULE_RESULT: return Object.assign({}, state, { updateModuleResult: action.data }) default: return state } } export default priceTagEditReducer <file_sep>/inside-chain/src/router/storePass/index.js //门店传菜路由 import storePassRoot from '../../views/shop/store-manage/pass' import scheme from '../../views/shop/store-manage/pass/scheme' import schemeList from '../../views/shop/store-manage/pass/scheme/list/index' import schemeGoodsManage from '../../views/shop/store-manage/pass/scheme/goodsManage' import areaPrint from '../../views/shop/store-manage/pass/areaPrint' import notIssue from '../../views/shop/store-manage/pass/notIssue' import printer from '../../views/shop/store-manage/pass/printer' import printSetting from '../../views/shop/store-manage/pass/printSetting' import schemeCheck from '../../views/shop/store-manage/pass/schemeCheck' export default [ { path: '/store_pass', name: 'storePass', title: '门店传菜', component: storePassRoot, redirect: '/store_pass/scheme', children: [ { path: 'scheme', name: 'storePassScheme', title: '门店传菜方案', component: scheme, redirect: '/store_pass/scheme/list', children: [ { path: 'list', name: 'storePassList', title: '门店传菜方案列表', component: schemeList }, { path: 'goodsManage', name: 'shopGoodsManage', title: '门店传菜方案商品管理', component: schemeGoodsManage } ] }, { path: 'printer', name: 'printer', title: '门店传菜备用打印机', component: printer }, { path: 'notIssue', name: 'notIssue', title: '门店传菜不出单商品', component: notIssue }, { path: 'areaPrint', name: 'areaPrint', title: '门店传菜区域打印', component: areaPrint }, { path: 'printSetting', name: 'printSetting', title: '门店传菜打印设置', component: printSetting }, { path: 'schemeCheck', name: 'schemeCheck', title: '门店传菜检查', component: schemeCheck } ] } ] <file_sep>/inside-boss/src/container/visualConfig/views/pages_manage/recommendedGood/index.js import React, { Component } from 'react' import { Table, Button, message, Icon, } from 'antd' import Cookie from '@2dfire/utils/cookie' import visualApi from '@src/api/visualConfigApi' import * as actions from '@src/container/visualConfig/store/actions' import GoogsSelect from '@src/container/visualConfig/views/design/common/googsSelect' import { Layout, Header, Content } from '@src/container/visualConfig/components/pageParts' import s from './index.css' const entityId = JSON.parse(Cookie.getItem('entrance')).shopInfo.entityId class Pages extends Component { state = { materials: [], isShowGoods: false, }; componentWillMount() { this.getMaterials() } getMaterials = () => { // 获取列表 visualApi.getMaterials({ entityId, pageIndex: 1, pageSize: 20, type: 3, }).then( res=>{ const { materials } = res.data this.setState({ materials: materials, }) }, err=>{ console.log('err', err) } ) } swapEntityMaterialSort = (firstId, secondId) => { // 交换素材顺序 visualApi.swapEntityMaterialSort({ entityId, firstMaterialId:firstId, secondMaterialId:secondId }).then( res=>{ if(res.data) { this.getMaterials() }else { message.error(res.message) } }, err=>{ console.log('err', err) } ) } render() { const { loadingStatus } = this.props const { isShowGoods }= this.state; let content if (loadingStatus === null) content = this.statusLoading() else if (loadingStatus === false) content = this.statusLoadFailed() else content = this.pagesTable() return <Layout> <Header title="页面管理" /> <Content className={s.content}> {this.pagesTable()} </Content> <GoogsSelect radio getGoodsItem={this.addEntityMaterial} isShowGoods={isShowGoods} close={this.close} /> </Layout> } addEntityMaterial = (data) => { // 添加图文广告 const meta = JSON.stringify({ linkType: 'goods', linkGoodsId: data[0].itemId, linkPage: '', }) visualApi.addMaterial({ type: 3, meta, name:data[0].itemName, }).then( res=>{ if(res.data) { this.getMaterials() this.setState({ isShowGoods: false }) } }, err=>{ console.log('err', err) } ) } deleteEntityMaterial = (e, id) => { // 删除推荐商品 visualApi.deleteEntityMaterial({ entityId, materialId: id, }).then( res=>{ if(res.data) { this.getMaterials() } }, err=>{ console.log('err', err) } ) } statusLoading() { return <div className={s.loading}>载入中...</div> } statusLoadFailed() { return <div className={s.loadFailed}> 页面列表加载失败,<a onClick={actions.loadCustomPages}>点此重试</a> </div> } close = () => { this.setState({ isShowGoods: false, }) } showGoodsItem = () => { this.setState({ isShowGoods: true, }) } pagesTable() { const { materials } = this.state const columns = [ { title: '名称', dataIndex: 'name', }, { title: '操作', render: (text, record, index) => { return ( <span> <a className={s.btn} onClick={(e) =>this.deleteEntityMaterial(e, record.materialId) } href="javascript:;">删除</a> { index != 0 && <a className={s.btn} onClick={() => this.swapEntityMaterialSort(record.materialId, materials[index - 1].materialId )} href="javascript:;">上移</a>} { (index != materials.length-1) && <a onClick={() => this.swapEntityMaterialSort(materials[index + 1].materialId, record.materialId)} className={s.btn} href="javascript:;">下移</a>} </span> ) }, }, ]; return ( <div className={s.pageManage}> <Button className={s.addPage} icon="plus" type="primary" onClick={this.showGoodsItem}>添加推荐商品</Button> <Table columns={columns} rowKey={record => record.materialId} dataSource={materials} /> </div> )} } export default Pages <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/announce/AnnounceEditor.js import React, {Component} from 'react' import { Radio, Button, Input } from 'antd'; import { SketchPicker } from 'react-color'; import style from './AnnounceEditor.css' import { DesignEditor, ControlGroup } from '../../editor/DesignEditor'; const RadioGroup = Radio.Group; export default class AnnounceEditor extends DesignEditor { constructor(props) { super(props); this.state= { isSketchPicker: false, isSketchPickerbg: false, } } onChange = (str, val) => { const { value, onChange } = this.props; const { config } = value onChange(value,{ config: { ...config, [str]: val.target.value }}) } showSkentPick = (str) => { this.setState({ [str]: !this.state[str] }) } handleChangeComplete = (str, color) => { // 拾色器的回调 const { value, onChange } = this.props; const { config } = value onChange(value,{ config: { ...config, [str]: color.hex }}) } onChangeInput = (e) => { const { value, onChange } = this.props; const { config } = value const val = e.target.value.trim() if(val.length > 20) { return } value.announWordLeng = val.length config.text = val onChange(value, {config}) } render() { const { value, prefix, validation } = this.props; const { config } = value const { text } = config const { isSketchPicker, isSketchPickerbg } = this.state return ( <div className={`${prefix}-design-component-Announce-editor`}> <div className={style.componentAnnounceEditor}> <ControlGroup label="标题内容:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.AnnouncInput}> <input className={style.input} placeholder='请输入公告内容' value={text} type="text" onChange={(e) => this.onChangeInput(e)} /> <p className={style.wordNumber}>{value.announWordLeng}/20</p> </div> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="框体样式:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.mode} className={style.controlGroupControl} onChange={(e) => this.onChange('mode', e)}> <Radio name="shape" value='1'>样式一</Radio> {/* <Radio name="shape" value='round'>圆角</Radio> */} </RadioGroup> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="背景颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{backgroundColor: value.config.backgroundColor}} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPickerbg')} type="primary" /> {isSketchPickerbg && <SketchPicker color={value.config.backgroundColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('backgroundColor', e)} />} </div> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="文本位置:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.textAlign} className={style.controlGroupControl} onChange={(e) => this.onChange('textAlign', e)}> <Radio name="textAlign" value='left'>居左</Radio> <Radio name="textAlign" value='center'>居中</Radio> </RadioGroup> </div> <div className={style.componentAnnounceEditor}> <ControlGroup label="文本颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{backgroundColor: value.config.textColor}} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPicker')} type="primary" /> {isSketchPicker && <SketchPicker color={value.config.textColor} className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('textColor', e)} />} </div> </div> </div> ) } static designType = 'announce'; static designDescription = '公告信息'; static designTemplateType = '其他类'; static getInitialValue() { return { announWordLeng: 0, config: { type: 'announce', text: '', // 公告内容。必填。1 ~ 20个字 mode: '1', // 公告样式。可选值:'1'(暂时只支持这一个值) backgroundColor: '#ffedca', // 背景色 textAlign: 'left', // 文字位置。可选值:left、center textColor: '#f86e21', // 文字颜色 } } } }<file_sep>/static-hercules/src/loan/config/api.js /** * Created by zyj on 2017/12/20. */ const { API_BASE_URL } = require('apiConfig'); module.exports = { // 获取掌柜端app的最新版本 QUERY_CARD_STATUS: API_BASE_URL + '/enterprise/card/apply/query_card_status', // 获取最新安卓版的二维火APP下载链接 NEWEST_ANDROID_URL: API_BASE_URL + '/sales/stack_base/app_latest_version' }<file_sep>/inside-chain/src/store/modules/shop/getters.js const getters = { // 数据 data(state) { return state; }, shop_filter(state) { return state.shop_filter }, shops(state) { return state.shops }, brands(state) { return state.brands }, shop_info(state) { return state.shop_info }, brand_info(state) { return state.brand_info }, view_date(state) { return state.view_date }, shop_view(state) { return state.shop_view }, categoryList(state){ return state.category }, isCatch(state){ return state.catchFilter.status } } export default getters <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionGroupActivity/definition.js export default { name: 'unionGroupActivity', userName: '拼团活动', group: '互动营销类', max: 1, config: { type: 'groupActivity' }, } <file_sep>/inside-boss/src/container/visualConfig/components/pageParts/Content.js import React from 'react' import PropTypes from 'prop-types' import c from 'classnames' import s from './index.css' // 页面内容容器 export default function Content(props) { return <div className={c(s.content, props.className)}> {props.children} </div> } Content.propTypes = { className: PropTypes.string, // 向内容容器指定额外的 class } <file_sep>/static-hercules/src/sweep-face/utils/imgTool.js export function chooseImage(config) { const { success, fail } = config || {} wx.chooseImage({ count: 1, // 默认9 success(res) { const localId = res.localIds[0] wx.getLocalImgData({ localId, success(res) { let localData = res.localData if (localData.indexOf('data:image') !== 0) { //判断是否有这样的头部 localData = 'data:image/jpeg;base64,' + localData } const base64 = localData .replace(/\r|\n/g, '') .replace('data:image/jgp', 'data:image/jpeg') success && success(base64) }, fail(e) { fail && fail(e, 'getLocalImgData') } }) }, fail(e) { fail && fail(e, 'chooseImage') } }) } //base64转换为file文件 export function base64ToFile(dataurl, filename = 'file') { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let suffix = mime.split('/')[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], `${filename}.${suffix}`, { type: mime }) } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/navigation/NavigationEditor.js import React from 'react'; import { Radio, Button } from 'antd'; import { SketchPicker } from 'react-color'; import { DesignEditor, ControlGroup } from '../../editor/DesignEditor'; import ImgUpload from '../../common/imgUpload' import Dropdown from '../../common/dropdown' import style from './NavigationEditor.css' const RadioGroup = Radio.Group; export default class NavEditor extends DesignEditor { state = { size: 'large', defaultImg:'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png', navIndex: -1, isShowImgUpload: false, imgType: '默认', isShowColorPicker: false, }; onChange = (str, e) => { const { value, onChange } = this.props; const { config } = value config.nav[str] = e.target.value onChange(value, {config}) } getItems = () => { const config = this.props.value.config return config.nav.mode === '经典展开式' ? config.nav.expandItems : config.nav.appItems } closeItem = (index) => { // 删除组件 const { value, onChange } = this.props; const { config } = value this.getItems().splice(index, 1) onChange(value, {config}) } addItem = () => { // 添加编辑组件 const { value, onChange } = this.props; const { config } = value const item = config.mode === '经典展开式' ? { icon: null, linkPage: null } : { defaultIcon: null, // 默认状态下的 icon URL。必填 highlightIcon: null, // 高亮状态下的 icon URL。必填 linkPage: null, // 链接到哪个页面。必填 } this.getItems().push(item) onChange(value, {config}) } _selectLink = (data) => { // 页面链接选择 const { value, onChange } = this.props; const { config } = value const { navIndex } = this.state this.getItems()[navIndex].linkPage = data onChange(value,{config}) } onChangnavIndex = (index) => { this.setState({ navIndex: index }) } _getImg = (data) => { // 获取图片 const { value, onChange } = this.props; const { config } = value const { navIndex, imgType } = this.state if(config.nav.mode == '经典展开式') { config.nav.expandItems[navIndex].icon = data } else { if(imgType == '默认') { config.nav.appItems[navIndex].defaultIcon = data } else{ config.nav.appItems[navIndex].highlightIcon = data } } onChange(value, {config}) } close = () => { this.setState({ isShowImgUpload: false, }) } onChangeBtn = (index) => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload, navIndex: index }) } imgTypeChange = (str) => { this.setState({ imgType: str, }) } showColorPicker() { this.setState({ isShowColorPicker: !this.state.isShowColorPicker }) } choosedColor(e) { const { value, onChange } = this.props; value.config.nav.backgroundColor = e.hex onChange(value) this.setState({ isShowColorPicker: false }) } render(){ const { value, prefix, validation } = this.props; const { config } = value const { defaultImg, size, isShowImgUpload, isShowColorPicker } = this.state const appItems = config.nav.mode == '经典展开式' ? config.nav.expandItems : config.nav.appItems const maxLen = config.nav.mode == '经典展开式' ? 10 : 4 return ( <div className={`${prefix}-design-component-config-editor`}> {config.nav.mode === 'app式' && <div className={style.row}> <ControlGroup label="背景颜色:" error={validation.hasPadding} className={style.groupLabel} ></ControlGroup> <div className={style.navPickColor}> <Button style={{backgroundColor: config.nav.backgroundColor}} className={style.pickColorBtn} onClick={() => this.showColorPicker()} type="primary" /> {isShowColorPicker && <SketchPicker className={style.navSketchPicker} onChangeComplete={(e) => this.choosedColor(e)} />} </div> </div>} <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <div className={style.componentConfigEditor}> <ControlGroup label="选择模板:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.right}> <RadioGroup value={config.nav.mode} className={style.controlGroupControl} onChange={(e) => this.onChange('mode', e)}> <Radio name="mode" value='经典展开式'>经典展开式</Radio> <Radio name="mode" value='app式'>app式</Radio> </RadioGroup> {appItems.map((item, index) => <div className={style.upload}> <div className={style.uplodInfo} onClick={() => this.imgTypeChange('默认')}> <p>默认</p> <img onClick={(e) => this.onChangeBtn(index, e)} src={(item.defaultIcon || item.icon) ? (item.defaultIcon || item.icon) : defaultImg}></img> </div> {config.nav.mode == 'app式' && <div className={style.uplodInfo} onClick={() => this.imgTypeChange('高亮')}> <p>高亮</p> <img onClick={(e) => this.onChangeBtn(index, e)} src={item.highlightIcon ? item.highlightIcon : defaultImg}></img> </div> } <p className={style.uploadTip}>图片尺寸要求(支持png格式)图片尺寸要求(支持png格式)60x60px</p> <div className={style.navEditor} onClick={() => this.onChangnavIndex(index)}> <div className={style.text}>链接:</div> <Dropdown selectLink={this._selectLink} current={item.linkPage} /> </div> <img className={style.closeBtn} src="https://assets.2dfire.com/frontend/73a3ec09ff1b5814aea734d1e7e226cb.png" onClick={() => this.closeItem(index)} /> </div> )} { appItems.length < maxLen && <Button onClick={this.addItem} className={style.adAntBtn} type="primary" shape="round" icon="plus" size={size}>添加导航项</Button> } </div> </div> </div> ) } static designType = 'navigation'; static designDescription = '导航'; // static designTemplateType = '基础类'; } <file_sep>/static-hercules/src/wechat-direct-con/libs/tools.js import sessionStorage from '@2dfire/utils/sessionStorage' import { bankList } from '../constant/address-config' export default { // 将对象转换为接口需要的参数对象 xwMerchantInfoToParam(merchantInfo,paymentWxXwAuthInfo) { paymentWxXwAuthInfo.entityId = sessionStorage.getItem('entityId') paymentWxXwAuthInfo.shopName = merchantInfo.shopName paymentWxXwAuthInfo.shopProvince = merchantInfo.shopAddress.province.name paymentWxXwAuthInfo.shopCity = merchantInfo.shopAddress.city.name paymentWxXwAuthInfo.detailAddress = merchantInfo.detailAddress paymentWxXwAuthInfo.shopPhoto = merchantInfo.shopLicensePic paymentWxXwAuthInfo.indoorPhoto = merchantInfo.shopEnvironmentPic paymentWxXwAuthInfo.servicePhone = merchantInfo.serviceTel if (merchantInfo.serviceType === '餐饮') { paymentWxXwAuthInfo.industryType = 'FOOD' } else if(merchantInfo.serviceType === '零售' || merchantInfo.serviceType === '线下零售') { paymentWxXwAuthInfo.industryType = 'RETAIL' } paymentWxXwAuthInfo.certFront = merchantInfo.idCardFront paymentWxXwAuthInfo.certBack = merchantInfo.idCardReverse paymentWxXwAuthInfo.certName = merchantInfo.idCardName paymentWxXwAuthInfo.certNo = merchantInfo.idCardNumber paymentWxXwAuthInfo.certValidStartTime = merchantInfo.startDate if (merchantInfo.idCardEffLongTime === true) { paymentWxXwAuthInfo.certValidEndTime = '长期' } else { paymentWxXwAuthInfo.certValidEndTime = merchantInfo.endDate } paymentWxXwAuthInfo.wxXwBankInfo.accountName = merchantInfo.accountName paymentWxXwAuthInfo.wxXwBankInfo.accountBank = merchantInfo.accountBank paymentWxXwAuthInfo.wxXwBankInfo.accountNo = merchantInfo.accountNumber paymentWxXwAuthInfo.wxXwBankInfo.accountProvince = merchantInfo.accountAddressProvince paymentWxXwAuthInfo.wxXwBankInfo.accountCity = merchantInfo.accountAddressCity paymentWxXwAuthInfo.wxXwBankInfo.accountSubBank = merchantInfo.accountSubBank paymentWxXwAuthInfo.wxXwContactInfo.contactPhone = merchantInfo.userTelNumber paymentWxXwAuthInfo.wxXwContactInfo.email = merchantInfo.userEmailNumber paymentWxXwAuthInfo.wxXwContactInfo.merchantShortName = merchantInfo.userSimpleName return paymentWxXwAuthInfo }, // 将接口返回的对象参数转换为merchantInfo对象 paramToXwMerchantInfo(paymentWxXwAuthInfo, merchantInfo) { merchantInfo.shopName = paymentWxXwAuthInfo.shopName merchantInfo.detailAddress = paymentWxXwAuthInfo.detailAddress merchantInfo.shopLicensePic = paymentWxXwAuthInfo.shopPhoto merchantInfo.shopEnvironmentPic = paymentWxXwAuthInfo.indoorPhoto merchantInfo.serviceTel = paymentWxXwAuthInfo.servicePhone if (paymentWxXwAuthInfo.industryType === 'FOOD') { merchantInfo.serviceType = '餐饮' } else if ((paymentWxXwAuthInfo.industryType === 'RETAIL')) { merchantInfo.serviceType = '线下零售' } merchantInfo.idCardFront = paymentWxXwAuthInfo.certFront merchantInfo.idCardReverse = paymentWxXwAuthInfo.certBack merchantInfo.idCardName = paymentWxXwAuthInfo.certName merchantInfo.idCardNumber = paymentWxXwAuthInfo.certNo merchantInfo.startDate = paymentWxXwAuthInfo.certValidStartTime if (paymentWxXwAuthInfo.certValidEndTime === '长期') { // 身份证是否长久有效 merchantInfo.idCardEffLongTime = true merchantInfo.endDate = '' } else { merchantInfo.idCardEffLongTime = false merchantInfo.endDate = paymentWxXwAuthInfo.certValidEndTime } merchantInfo.shopAddress = { "province": {"name": paymentWxXwAuthInfo.shopProvince}, "city": {"name": paymentWxXwAuthInfo.shopCity} } merchantInfo.accountAddressProvince = paymentWxXwAuthInfo.wxXwBankInfo.accountProvince merchantInfo.accountAddressCity = paymentWxXwAuthInfo.wxXwBankInfo.accountCity merchantInfo.accountSubBank = paymentWxXwAuthInfo.wxXwBankInfo.accountSubBank merchantInfo.accountAddressProCode = '' merchantInfo.accountAddressCityCode = '' merchantInfo.accountName = paymentWxXwAuthInfo.wxXwBankInfo.accountName merchantInfo.accountBank = paymentWxXwAuthInfo.wxXwBankInfo.accountBank merchantInfo.accountBankCode = this.getBankCode(paymentWxXwAuthInfo.wxXwBankInfo.accountBank) merchantInfo.accountNumber = paymentWxXwAuthInfo.wxXwBankInfo.accountNo merchantInfo.userTelNumber = paymentWxXwAuthInfo.wxXwContactInfo.contactPhone merchantInfo.userEmailNumber = paymentWxXwAuthInfo.wxXwContactInfo.email merchantInfo.userSimpleName = paymentWxXwAuthInfo.wxXwContactInfo.merchantShortName return merchantInfo }, // 将接口返回的升级信息的对象参数转换为merchantInfo对象 paramToWxXwUpgradeInfo(paymentWxXwUpgradeInfo, merchantInfo) { merchantInfo.businessLicensePic = paymentWxXwUpgradeInfo.businessLicensePhoto merchantInfo.registerAddress = { "province": {"name": paymentWxXwUpgradeInfo.address}, "city": {"name": ''} } merchantInfo.corporationName = paymentWxXwUpgradeInfo.legalPerson if (paymentWxXwUpgradeInfo.licenseEndTime == '长期') { merchantInfo.businessDeadLine = false merchantInfo.businessEndTime = paymentWxXwUpgradeInfo.licenseEndTime } else { merchantInfo.businessDeadLine = true merchantInfo.businessEndTime = paymentWxXwUpgradeInfo.licenseEndTime } merchantInfo.businessStartTime = paymentWxXwUpgradeInfo.licenseStartTime merchantInfo.businessLicenseNum = paymentWxXwUpgradeInfo.businessLicenseNo merchantInfo.merchantName = paymentWxXwUpgradeInfo.merchantName merchantInfo.orgPhoto = paymentWxXwUpgradeInfo.orgPhoto merchantInfo.orgNo = paymentWxXwUpgradeInfo.orgNo merchantInfo.orgStartTime = paymentWxXwUpgradeInfo.orgStartTime merchantInfo.orgEndTime = paymentWxXwUpgradeInfo.orgEndTime if(paymentWxXwUpgradeInfo.isIntegrade == true) { merchantInfo.businessLicenseType = '已三证合一' } else { merchantInfo.businessLicenseType = '未三证合一' } if (paymentWxXwUpgradeInfo.merchantType == 'INDIVIDUAL') { merchantInfo.merchantType = '个体工商户' } else if(paymentWxXwUpgradeInfo.merchantType == 'ENTERPRISE') { merchantInfo.merchantType = '企业商户' } merchantInfo.businessAccountName = paymentWxXwUpgradeInfo.wxXwBankInfo.accountName merchantInfo.businessAccountBank = paymentWxXwUpgradeInfo.wxXwBankInfo.accountBank merchantInfo.businessAccountBankCode = this.getBankCode(paymentWxXwUpgradeInfo.wxXwBankInfo.accountBank) merchantInfo.businessAccountNumber = paymentWxXwUpgradeInfo.wxXwBankInfo.accountNo merchantInfo.businessAccountAddressProvince = paymentWxXwUpgradeInfo.wxXwBankInfo.accountProvince merchantInfo.businessAccountAddressCity = paymentWxXwUpgradeInfo.wxXwBankInfo.accountCity merchantInfo.businessAccountSubBank = paymentWxXwUpgradeInfo.wxXwBankInfo.accountSubBank merchantInfo.businessAccountAddressProCode = '' merchantInfo.businessAccountAddressCityCode = '' merchantInfo.qualification.splice(0, merchantInfo.qualification.length) if(paymentWxXwUpgradeInfo.qualification1 != null && paymentWxXwUpgradeInfo.qualification1 != '') { merchantInfo.qualification.push(paymentWxXwUpgradeInfo.qualification1) } if(paymentWxXwUpgradeInfo.qualification2 != null && paymentWxXwUpgradeInfo.qualification2!= '') { merchantInfo.qualification.push(paymentWxXwUpgradeInfo.qualification2) } if(paymentWxXwUpgradeInfo.qualification3 != null && paymentWxXwUpgradeInfo.qualification3 != '') { merchantInfo.qualification.push(paymentWxXwUpgradeInfo.qualification3) } if(paymentWxXwUpgradeInfo.qualification4 != null && paymentWxXwUpgradeInfo.qualification4 != '') { merchantInfo.qualification.push(paymentWxXwUpgradeInfo.qualification4) } if(paymentWxXwUpgradeInfo.qualification5 != null && paymentWxXwUpgradeInfo.qualification5 != '') { merchantInfo.qualification.push(paymentWxXwUpgradeInfo.qualification5) } return merchantInfo }, // 将接口返回的小微及升级部分信息的对象参数转换为merchantInfo对象 paramToWxAllInfo(paymentWxXwAuthInfo, paymentWxXwUpgradeInfo, merchantInfo) { let authInfo = this.paramToXwMerchantInfo(paymentWxXwAuthInfo, merchantInfo) let upgradeInfo = this.paramToWxXwUpgradeInfo(paymentWxXwUpgradeInfo, authInfo) return upgradeInfo }, // 根据银行name获取银行的code getBankCode(accountBank) { var aa = (accountBank !== '' && accountBank !== 'undefined') if (accountBank !== '' && accountBank !== 'undefined') { var length = bankList.length for (var i = 0; i < length; i++) { if (bankList[i].bankDisplayName === accountBank) { return bankList[i].bankName } } } return '' }, // 封装成修改收款银行卡接口需要的数据 modifyWxXwBankInfoParam(merchantInfo, wxXwBankInfo) { wxXwBankInfo.accountName = merchantInfo.accountName wxXwBankInfo.accountBank = merchantInfo.accountBank wxXwBankInfo.accountNo = merchantInfo.accountNumber wxXwBankInfo.accountProvince = merchantInfo.accountAddressProvince wxXwBankInfo.accountCity = merchantInfo.accountAddressCity wxXwBankInfo.accountSubBank = merchantInfo.accountSubBank return wxXwBankInfo }, // 封装成修改收款银行卡接口需要的数据--企业商户 modifyWxXwBankInfoParamFromUpgrade(merchantInfo, wxXwBankInfo) { wxXwBankInfo.accountName = merchantInfo.businessAccountName wxXwBankInfo.accountBank = merchantInfo.businessAccountBank wxXwBankInfo.accountNo = merchantInfo.businessAccountNumber wxXwBankInfo.accountProvince = merchantInfo.businessAccountAddressProvince wxXwBankInfo.accountCity = merchantInfo.businessAccountAddressCity wxXwBankInfo.accountSubBank = merchantInfo.businessAccountSubBank return wxXwBankInfo }, // 封装成修改收联系信息接口需要的数据 modifyWxXwContactInfoParam(merchantInfo, wxXwContactInfo) { wxXwContactInfo.merchantShortName = merchantInfo.userSimpleName wxXwContactInfo.contactPhone = merchantInfo.userTelNumber wxXwContactInfo.email = merchantInfo.userEmailNumber return wxXwContactInfo }, // 小微升级请求入参组装 xwUpgradeInfoParam(merchantInfo, paymentWxXwUpgradeInfo) { paymentWxXwUpgradeInfo.entityId = sessionStorage.getItem('entityId') paymentWxXwUpgradeInfo.merchantType = merchantInfo.merchantType if (merchantInfo.merchantType == '个体工商户') { paymentWxXwUpgradeInfo.merchantType = 'INDIVIDUAL' } else if(merchantInfo.merchantType == '企业商户' ) { paymentWxXwUpgradeInfo.merchantType = 'ENTERPRISE' } paymentWxXwUpgradeInfo.businessLicensePhoto = merchantInfo.businessLicensePic paymentWxXwUpgradeInfo.businessLicenseNo = merchantInfo.businessLicenseNum paymentWxXwUpgradeInfo.address = merchantInfo.registerAddress.province.name+merchantInfo.registerAddress.city.name paymentWxXwUpgradeInfo.merchantName = merchantInfo.merchantName paymentWxXwUpgradeInfo.legalPerson = merchantInfo.corporationName paymentWxXwUpgradeInfo.licenseStartTime = merchantInfo.businessStartTime if(merchantInfo.businessLicenseType == '已三证合一') { paymentWxXwUpgradeInfo.isIntegrade = true } else if(merchantInfo.businessLicenseType == '未三证合一') { paymentWxXwUpgradeInfo.isIntegrade = false } if (merchantInfo.businessDeadLine == false) { paymentWxXwUpgradeInfo.licenseEndTime = '长期' } else { paymentWxXwUpgradeInfo.licenseEndTime = merchantInfo.businessEndTime } if(merchantInfo.businessLicenseType == '未三证合一') { paymentWxXwUpgradeInfo.orgPhoto = merchantInfo.orgPhoto paymentWxXwUpgradeInfo.orgNo = merchantInfo.orgNo paymentWxXwUpgradeInfo.orgStartTime = merchantInfo.orgStartTime paymentWxXwUpgradeInfo.orgEndTime = merchantInfo.orgEndTime } paymentWxXwUpgradeInfo.qualification1 = merchantInfo.qualification[0] paymentWxXwUpgradeInfo.qualification2 = merchantInfo.qualification[1] paymentWxXwUpgradeInfo.qualification3 = merchantInfo.qualification[2] paymentWxXwUpgradeInfo.qualification4 = merchantInfo.qualification[3] paymentWxXwUpgradeInfo.qualification5 = merchantInfo.qualification[4] if(merchantInfo.merchantType === '企业商户' ) { paymentWxXwUpgradeInfo.wxXwBankInfo.accountName = merchantInfo.businessAccountName paymentWxXwUpgradeInfo.wxXwBankInfo.accountBank = merchantInfo.businessAccountBank paymentWxXwUpgradeInfo.wxXwBankInfo.accountNo = merchantInfo.businessAccountNumber paymentWxXwUpgradeInfo.wxXwBankInfo.accountProvince = merchantInfo.businessAccountAddressProvince paymentWxXwUpgradeInfo.wxXwBankInfo.accountCity = merchantInfo.businessAccountAddressCity paymentWxXwUpgradeInfo.wxXwBankInfo.accountSubBank = merchantInfo.businessAccountSubBank } // console.log('paymentWxXwUpgradeInfo:'+paymentWxXwUpgradeInfo) return paymentWxXwUpgradeInfo }, // 打款信息 xwUpgradePayParam(merchantInfo, accountVerifyInfo) { merchantInfo.accountName = accountVerifyInfo.accountName merchantInfo.payAmount = accountVerifyInfo.payAmount merchantInfo.destinationAccountNumber = accountVerifyInfo.destinationAccountNumber merchantInfo.destinationAccountName = accountVerifyInfo.destinationAccountName merchantInfo.destinationAccountBank = accountVerifyInfo.destinationAccountBank merchantInfo.city = accountVerifyInfo.city merchantInfo.remark = accountVerifyInfo.remark merchantInfo.deadlineTime = accountVerifyInfo.deadlineTime return merchantInfo } }<file_sep>/inside-chain/src/base/config/dev.js module.exports = { NEW_API_BASE_URL:'../../api', API_BASE_URL: 'http://gateway.2dfire-daily.com/?app_key=200800&method=', SHARE_BASE_URL: 'http://api.l.whereask.com', IMAGE_BASE_URL: 'http://ifiletest.2dfire.com/', API_WEB_SOCKET: 'http://10.1.5.114:9003/web_socket', MOCK_BASE_URL: 'http://mock.2dfire-daily.com/mockjsdata/7', ENTRANCE_LOGIN: 'http://localhost:8070/page/index.html', ENV: 'bedb3e48c8a1422eb514dd6460135a5d', UPLOAD_PATH: 'https://ifiletest.2dfire.com/', UPLOAD_OSS: 'https://upload.2dfire-daily.com/api/uploadfile', DATA_URL: 'http://data.2dfire-pre.com/report-home.html' }; <file_sep>/static-hercules/src/oasis/store/mutations.js /** * Created by zyj on 2018/4/3. */ import Vue from 'vue' import * as types from './mutation-types' export default{ // 从接口获取到表单的所有信息 [types.GET_APPLY_MATERIALS](state, payload){ state.shopInfo = payload }, // 修改店铺信息 [types.MODIFY_SHOPINFO](state, payload){ Vue.set(state.shopInfo, payload.type, payload.value) }, // 修改picker里面的内容 [types.MODIFY_PICKER_SLOT](state, payload){ state.pickerSlots = payload }, // 保存省列表 [types.SAVE_PROVINCE_LIST](state, payload){ state.provinceList = payload }, // 修改 MODIFY_PICKER_CHANGE_VALUE 里面的值 [types.MODIFY_PICKER_CHANGE_VALUE](state, payload){ Vue.set(state.pickerChangeValue, payload.type, payload.value) }, // hide 区县 [types.HIDE_TOWN](state, payload){ state.isHideDistrict = payload }, //修改示例图片显示状态 [types.CHANGE_EXAMPLE_PHOTO](state, payload) { state.examplePhoto = {...state.examplePhoto, ...payload} }, }<file_sep>/inside-boss/src/container/mallBannerManager/reducers.js import ActionTypes from '../../action/type' import { formatBannerList } from '../../format/mall' export default (state = {}, action) => { switch (action.type) { case ActionTypes.FETCH_BANNER_LIST_SUCCESS: const list = formatBannerList(action.data) return Object.assign({}, state, { bannerList: list }) default: return state } } <file_sep>/static-hercules/src/give-key/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; import qs from 'qs' const API = { /*获取session信息*/ getSessionMap() { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: { appKey: APP_KEY } }) }, /*获取店铺试用状态*/ getShopVoByEntityId(params) { return axios({ method: 'GET', url: 'com.dfire.soa.cloudcash.getShopVoByEntityId', params: params }) }, /**获取签到信息 */ getSingInInfo(params) { return axios({ method: 'GET', url: 'com.dfire.soa.cloudcash.getSignInInfoByEntityId', params: params }) }, /**签到 */ signIn(params) { return axios({ method: 'GET', url: 'com.dfire.soa.cloudcash.keepSignIn', params: params }) }, } export default API; <file_sep>/inside-boss/src/components/couponPush/main.js /** * Created by air on 2017/7/10. */ import React, { Component } from 'react' import styles from './style.css' import Handle from './handle' import RechargeList from './rechargeList' import { Spin } from 'antd' class Main extends Component { render () { const {data, dispatch ,params} = this.props const {total,showSpin} = data // console.log(data) return ( <div className={styles.wraperBox}> <div className={styles.viewBox}> <Handle data={data} dispatch={dispatch} params={params}/> { (() => { if (total > 0) { return ( <RechargeList data={data} dispatch={dispatch}/> ) } else { return null } })() } </div> { showSpin && showSpin.bool ? ( <div className={styles.cover}> <Spin tip={showSpin.content} style={{marginTop: 160, marginLeft: -160}} size="large"></Spin> </div> ) : null } </div> ) } } export default Main <file_sep>/inside-boss/src/container/visualConfig/views/design/common/defaultConfig.js const pageHome = { backgroundImage: null, components: [ { type: 'banner', mode: '2', backgroundImage: null, }, { type: 'whitespace', height: 25, }, { type: 'goodsList', mode: '大图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '新品', image: null, }, }, { type: 'goodsList', mode: '详细列表', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'goodsList', mode: '双列小图', goodsList: [], showFields: ['名称', '价格', '下单按钮'], orderButton: { mode: '立即下单', orderStyle: '1', cartStyle: '1', }, subscript: { type: 'text', text: '热卖', image: null, }, }, { type: 'whitespace', height: 35, }, { type: 'title', text: '更多商品', size: 'medium', textAlign: 'center', textColor: '#000000', backgroundColor: '#fff', linkType: 'page', linkGoodsId: '', linkPage: '商品分类', }, { type: 'whitespace', height: 25, }, ], } const theme = { nav: { mode: '经典展开式', // 导航样式。可选值:"经典展开式", "app式", "微信公众号式" backgroundColor: '#000000', // 背景颜色。仅在 mode="app式" 时有效 // 经典展开模式的导航项;最少一项,最多10项 expandItems: [ { icon: 'https://assets.2dfire.com/frontend/8c3d71df65796bcd1f376fa123960fbe.png', linkPage: '店铺主页', }, { icon: 'https://assets.2dfire.com/frontend/a62f80820be80156ed78632697edfefd.png', linkPage: '购物车', }, { icon: 'https://assets.2dfire.com/frontend/0c9ca727a8c263b557708dab237d10c6.png', linkPage: '商品分类', }, { icon: 'https://assets.2dfire.com/frontend/472cf3d8154da74168cd073f9983b08e.png', linkPage: '我的', }, ], // app 模式的导航项;最少一项,最多4项 appItems: [ { defaultIcon: null, // 默认状态下的 icon URL。必填 highlightIcon: null, // 高亮状态下的 icon URL。必填 linkPage: null, // 链接到哪个页面。必填 }, { defaultIcon: null, // 默认状态下的 icon URL。必填 highlightIcon: null, // 高亮状态下的 icon URL。必填 linkPage: null, // 链接到哪个页面。必填 }, { defaultIcon: null, // 默认状态下的 icon URL。必填 highlightIcon: null, // 高亮状态下的 icon URL。必填 linkPage: null, // 链接到哪个页面。必填 }, { defaultIcon: null, // 默认状态下的 icon URL。必填 highlightIcon: null, // 高亮状态下的 icon URL。必填 linkPage: null, // 链接到哪个页面。必填 } ], } } const pageCate = { backgroundColor: '#eeeeee', components: [ { type: 'cateList', }, ], } const mine = { backgroundColor: '#eeeeee', components: [ { type: 'mine', }, ], } export default { 'page:home': JSON.stringify(pageHome), 'theme': JSON.stringify(theme), 'page:cate': JSON.stringify(pageCate), 'page:mine': JSON.stringify(mine), } <file_sep>/inside-chain/src/store/modules/pass/state.js export default { // 传菜下发模块信息 下发用 passPublishModule: { name: '', remarkRight: '' }, } <file_sep>/inside-boss/src/components/orderPhotos/title.js /** * Created by air on 2017/7/10. */ import React, { Component } from 'react' import { Menu } from 'antd' import styles from './style.css' class Title extends Component { state = { current: 'video', } handleClick = (e) => { console.log('click ', e); this.setState({ current: e.key, }); } render () { return ( <Menu onClick={this.handleClick} selectedKeys={[this.state.current]} mode="horizontal" > <Menu.Item key="video" className={styles.select}>视频导入</Menu.Item> </Menu> ) } } export default Title <file_sep>/inside-boss/src/container/visualConfig/designComponents/union/unionPictureAds/TmpPreview.js import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { Carousel } from 'antd' import style from './TmpPreview.css' export default class AdPreview extends PureComponent { static propTypes = { value: PropTypes.object, }; state = { img: 'https://assets.2dfire.com/frontend/2d64253f7654e785d1ab5b24802fce9b.png' } render() { const { config } = this.props.value const { img } = this.state return ( <div className={style.adPreview}> {config.mode == '单图' ? <img src={img} /> : <Carousel> <div> <img src={img} /> </div> <div> <img src={img} /> </div> <div> <img src={img} /> </div> </Carousel> } </div> ) } } <file_sep>/inside-chain/src/router/pass/index.js //总部传菜路由 import pass from '../../views/pass' import passScheme from '../../views/pass/scheme' import passNotIssue from '../../views/pass/notIssue' import passPrint from '../../views/pass/print' import passSchemeList from '../../views/pass/scheme/list' import passSchemeGoodsManage from '../../views/pass/scheme/goodsManage' // import passsSendManage from '../../views/pass/scheme/sendManage' export default [ { path: '/pass', name: 'pass', title: '传菜', component: pass, redirect: '/pass/scheme', children: [ { path: 'scheme', name: 'passScheme', title: '传菜方案', component: passScheme, redirect: '/pass/scheme/list', children: [ { path: 'list', name: 'schemeList', title: '传菜方案列表', component: passSchemeList }, { path: 'goodsManage', name: 'passGoodsManage', title: '传菜方案商品管理', component: passSchemeGoodsManage } // { // path: 'sendManage', // name: 'sendManage', // title: '传菜下发', // component: passsSendManage // } ] }, { path: 'notIssue', name: 'passNotIssue', title: '不出单商品', component: passNotIssue }, { path: 'print', name: 'passPrint', title: '套餐中商品分类打印设置', component: passPrint } ] } ] <file_sep>/static-hercules/src/secured-account/store/actions.js import * as types from './mutation-types' //底部弹出选择 export const pickerChange = ({commit}, params) => { commit(types.PICKER_CHANGE, params) } //底部弹出日期选择 export const openDatePicker = ({commit}, params) => { commit(types.DATE_PICKER_CHANGE, params) } //底部弹出地址选择器 export const openAddressPicker = ({commit}, params) => { commit(types.ADDRESS_PICKER_CHANGE, params) } // 修改商户信息 export const modifyInputInfo = ({commit}, params) => { commit(types.MODIFY_MERCHANT, params) } // 修改示例图片显示状态 export const changeExamplePhoto = ({commit}, params) => { commit(types.CHANGE_EXAMPLE_PHOTO, params) } // 修改当前编辑状态 export const changeViewState = ({commit}, params) => { commit(types.CHANGE_VIEWSTATE, params) }<file_sep>/inside-chain/src/config/api_batch.js import {API_BASE_URL} from "apiConfig"; import Requester from '@/base/requester' import {GW} from '@2dfire/gw-params'; const AND = '&' + GW; const API = { //批量删除修改 batchUpdate(params){ return Requester.post( API_BASE_URL + "com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.batchModifyItem" + AND, params, {emulateJSON: true} ) }, //批量移除 batchChainShopUpdate(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.boss.center.item.facade.service.IItemFacadeService.batchRemoveChainShopItem" + AND, params, {emulateJSON: true} ) }, //获取批量删除结果 getBatchRemoveChainShopItemResult(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.boss.center.item.facade.service.IItemFacadeService.getBatchRemoveChainShopItemResult" + AND, params, {emulateJSON: true} ) }, //获取分类信息 getCategory(){ return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.entity.service.IChainShopGroupService.getCategory" + AND ) }, // 增加修改分类 insertOrUpdateCategory(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.entity.service.IChainShopGroupService.insertOrUpdateCategory" + AND, params, {emulateJSON: true} ) }, //获取分组信息 getBaseGroup(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.entity.service.IChainShopGroupService.getBaseGroup" + AND, params, {emulateJSON: true} ) }, //分组查询 getGroupDetail(params){ return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.entity.service.IChainShopGroupService.getGroupDetail" + AND, { params: { groupId: params.id, } } ) }, //增删改分组 insertOrUpdateGroup(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.entity.service.IChainShopGroupService.insertOrUpdateGroup" + AND, params, {emulateJSON: true} ) }, //获取连锁门店分组下门店的信息 getShopInGroup(){ return Requester.get( API_BASE_URL + "com.dfire.boss.center.soa.IChainShopGroupService.getShopInGroup" + AND, { params: { groupId: params.groupId, } } ) }, //收银台监控信息获取 getCashDeviceInfo(params){ return Requester.post( API_BASE_URL + "com.dfire.soa.cashplatform.device.getCashDeviceInfo" + AND, params, {emulateJSON: true} ) }, //获取连锁下所有店铺 getAllShops(){ return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IShopBossPcService.queryAllShopList" + AND, ) } } export default API <file_sep>/inside-boss/src/components/goods/format.js const menuList = { name:'商品名称', kindMenuName:'分类名称', code:'商品编码', price:'单价(元)', memberPrice:'会员价(元)', account:'结账单位', buyAccount:'点菜单位', multiLangMenuName:'双语名称', isReserve:'堂食可点', isTakeout:'外卖可点', packingBox:'规格与数量', packingBoxNum:'餐盒数量', acridLevelString:'辣椒指数', specialTagString:'特色标签', recommendLevelString:'推荐指数', discountInclude:'允许商品金额计入优惠门槛', isRatio:'允许收银员在收银时打折', isChangePrice:'允许收银员在收银时修改价格', isBackAuth:'退菜时需要权限验证', isGive:'可作为赠菜', mealOnly:'此商品仅在套餐里显示', deductKind:'销售提成', deduct:'提成额度或百分比', serviceFeeMode:'服务费', serviceFee:'服务费金额或百分比', consume:'加工耗时(分钟)', weight:'菜肴份量', startNum:'起点份数', stepLength:'最小累加单位', memo:'商品介绍', stock:'商品库存', state:'商品上下架', hasMake:'做法', hasSpec:'规格', } const reversal = (obj = {})=>{ const data = {} Object.keys( obj ).map(key=>{ data[obj[key]] = key }) return data } const formatCheck = (h,plateEntityId)=>{ if((h.gridFieldDisplayName == '双语名称' || h.gridFieldDisplayName == '商品上下架') && plateEntityId ){ return true } return false } const promptMes = (h)=>{ let message = '' if(h.gridFieldDisplayName == '分类名称' || h.gridFieldDisplayName == '商品名称' || h.gridFieldDisplayName == '单价(元)' ){ message = '必填' } return message } export default { /** * @param data 接口返回数据, * @param {Boolean} MenuLanguage 双语设置 default false * @param {Boolean} custom 是否自定义表头 default false * @param {String} plateEntityId 品牌id */ formatTableHeader : (data,MenuLanguage=false,custom=false,plateEntityId) =>{ let newDate = [] newDate = data.map(i=>{ const info = { groupCaption: i.groupCaption || '', groupDisplayOrder: i.groupDisplayOrder || '', groupName: i.groupName || '', layout: i.layout || '', parentGroupCaption: i.parentGroupCaption || '', parentGroupName: i.parentGroupName || '' } if(i.children){ info.children = i.children.map(j=>{ let childrenInfo = { groupCaption: j.groupCaption, groupDisplayOrder: j.groupDisplayOrder, groupName: j.groupName, layout: j.layout, parentGroupCaption: j.parentGroupCaption, parentGroupName: j.parentGroupName } if(j.fields){ childrenInfo.fields = j.fields.map(h=>({ gridFieldDisplayName: h.gridFieldDisplayName, gridFieldDisplayOrder: h.gridFieldDisplayOrder, gridFieldId: custom ? reversal(menuList)[h.gridFieldDisplayName] || '' : h.gridFieldId, customId: h.gridFieldId, gridName: h.gridName, isChecked: h.isChecked, isDisabled: formatCheck(h,plateEntityId) ? true : h.gridFieldDisplayName == '双语名称'? !MenuLanguage : h.isDisabled , isSelected: h.isSelected, relGridFieldId: h.relGridFieldId, relType: h.relType, parentFieldId: (h.relGridFieldId != '0' && h.relType == '11') ? h.relGridFieldId : '0', childrenFidldId: (h.relGridFieldId != '0' && h.relType == '0') ? h.relGridFieldId : '0', twinsFiledId: (h.relGridFieldId != '0' && h.relType == '22') ? h.relGridFieldId : '0', custom: custom, promptMes: custom ? '' : promptMes(h), visibleHide: formatCheck(h,plateEntityId) })) } return childrenInfo }) } if(i.fields){ info.fields = i.fields.map(h=>({ gridFieldDisplayName: h.gridFieldDisplayName, gridFieldDisplayOrder: h.gridFieldDisplayOrder, gridFieldId: custom ? reversal(menuList)[h.gridFieldDisplayName] || '' : h.gridFieldId, customId: h.gridFieldId, gridName: h.gridName, isChecked: h.isChecked, isDisabled: formatCheck(h,plateEntityId) ? true : h.gridFieldDisplayName == '双语名称'? !MenuLanguage : h.isDisabled , isSelected: h.isSelected, relGridFieldId: h.relGridFieldId, relType: h.relType, parentFieldId: custom ? '0' : (h.relGridFieldId != '0' && h.relType == '11') ? h.relGridFieldId : '0', childrenFidldId: custom ? '0' : (h.relGridFieldId != '0' && h.relType == '0') ? h.relGridFieldId : '0', twinsFiledId: custom ? '0' : (h.relGridFieldId != '0' && h.relType == '22') ? h.relGridFieldId : '0', custom: custom, promptMes: custom ? '' : promptMes(h), visibleHide: formatCheck(h,plateEntityId) })) } return info }) return newDate }, formatTableMain: data=>{ const newData = { records:[], totalRecord: 0 } const itemList = data.itemList ? data.itemList : [] newData.totalRecord = data.total ? data.total : 0 itemList.map( records => { newData.records.push({ key: records.id, code: records.code, consume: records.consume, deduct: records.deduct, deductKind: records.deductKind, discountInclude: records.discountInclude, id: records.id, isBackAuth: records.isBackAuth, isChangePrice: records.isChangePrice, isGive: records.isGive, isRatio: records.isRatio, isReserve: records.isReserve, isTakeout: records.isTakeout, isTwoAccount: records.isTwoAccount, kindId: records.kindId, kindMenuName: records.kindName, mealOnly: records.mealOnly, memberPrice: records.memberPrice, name: records.name, price: records.price, serviceFee: records.serviceFee, serviceFeeMode: records.serviceFeeMode, showTop: records.showTop, startNum: records.startNum, state: records.state, stepLength: records.stepLength, account: records.account, accountId: records.accountId, buyAccount: records.buyAccount, buyAccountId: records.buyAccountId, memo: records.memo, multiLangMenuName: records.multiLangMenuName, packingBox: records.packingBoxName, packingBoxNum: records.packingBoxNum, acridLevelString: records.acridLevelString, specialTagString: records.specialTagString, recommendLevelString: records.recommendLevelString, weight: records.weight, stock: records.stock, hasMake: records.hasMake, hasSpec: records.hasSpec, label: records.label }) }) return newData } } <file_sep>/inside-boss/src/utils/image.js export function getRectImageUrl(url = '', opt = {}) { const { w, h } = opt if (url && w && h) { return `${url}?x-oss-process=image/resize,m_lfit,w_${w},h_${h}` } } <file_sep>/inside-boss/src/components/goodsPicture/picDetailListBox.js import React, {Component} from 'react' import {DragSource, DropTarget, DragDropContext} from 'react-dnd' import HTML5Backend from 'react-dnd-html5-backend' import update from 'immutability-helper' // import PropTypes from 'prop-types' // import {findDOMNode} from 'react-dom' import styles from './style.css' import Card from './haveDropPic' import {Icon, message, Checkbox, Button, Modal} from 'antd' import AddPictureBtn from './addPictureBtn' import api from "../../api"; import * as action from "../../action"; // import HaveDropPic from './picDetailListBox' const ItemTypes = { CARD: 'card', } @DragDropContext(HTML5Backend) class HaveDropPic extends Component { constructor(props) { super(props) this.moveCard = this.moveCard.bind(this) this.state = { type: this.props.type,//3为头图,1为详情图 title: this.props.type === '1' ? '商品详情图' : '商品主图', cards: this.props.type === "1" ? this.props.data.pictureDetailList : this.props.data.pictureHeaderList,//数据内容 isDrop: false,//当前是否在可拖动排序状态 } } componentWillReceiveProps(nextProps) { console.log(nextProps) let cards = nextProps.type === "1" ? nextProps.data.pictureDetailList : nextProps.data.pictureHeaderList;//数据内容 this.setState({ cards: cards }) } //点击全选按钮 onCheckAllChange(e) { if (this.state.isDrop) { message.info('处于排序状态,暂不支持全选'); return false } const t = this const picList = t.state.cards const plainOptions = [] for (let i = 0; i < picList.length; i++) { plainOptions.push(picList[i].id) } this.setState({ checkedList: e.target.checked ? plainOptions : [], indeterminate: false, checkAll: e.target.checked, }); } //图片checkbox发生变化 onChange(checkedList) { const t = this const {data} = t.props const {pictureDetailListLength} = data const pictureDetailList = data.pictureDetailList const plainOptions = [] for (let i = 0; i < pictureDetailListLength; i++) { plainOptions.push(pictureDetailList[i].id) } this.setState({ checkedList, indeterminate: !!checkedList.length && (checkedList.length < plainOptions.length), checkAll: checkedList.length === plainOptions.length, }); } //点击删除按钮 pictureDetailDelete() { if (this.state.isDrop) { message.info('处于排序状态,暂不支持删除'); return false } const t = this const {dispatch, detail} = t.props const {pictureFileId} = detail const liArr = document.getElementsByClassName("ant-checkbox-checked") const idArr = []; for (let i = 0; i < liArr.length; i++) { const id = liArr[i].parentNode.parentNode.getAttribute('data-index') if (id) { idArr.push(id); } } if (idArr.length > 0) { const idSting = idArr.join(','); Modal.confirm({ title: '确定要删除所选图片?', onOk() { api.deletePicture({ menuId: pictureFileId, imageIds: idSting, img_type: t.state.type }).then( res => { if (res === null) { message.success('图片删除成功'); dispatch(action.getPictureDetailList(detail.pictureFileId)) } else { message.error('图片删除失败'); dispatch(action.getPictureDetailList(detail.pictureFileId)) } }, err => { dispatch(action.errorHandler(err)) } ) }, onCancel() { }, }); } else { message.error('请先选择商品图片再删除。'); } } returnAddPicture(resp, type) { const {detail, dispatch} = this.props; dispatch(action.getPictureDetailList(detail.pictureFileId)) console.log(resp); console.log(type) } moveCard(dragIndex, hoverIndex) { const {cards} = this.state const dragCard = cards[dragIndex] this.setState( update(this.state, { cards: { $splice: [[dragIndex, 1], [hoverIndex, 0, dragCard]], }, }), ) } //转化为排序 toSort() { if (this.state.cards.length < 2) { message.info('当前图片少于2张,暂不支持排序') return false } this.setState({ isDrop: true }) } //排序完成 finishSort() { const picture = this.state.cards this.setState({ isDrop: false }) const oldPic = this.props.type === "1" ? this.props.data.pictureDetailList : this.props.data.pictureHeaderList; if (picture === oldPic) { message.success('排序完成,图片顺序未修改') return false } let changePic = JSON.stringify(picture.map((item, index, arr) => { return { id: item.id, sortCode: index + 1 } })); const {dispatch, detail} = this.props dispatch(action.changeListSort(changePic, function (res) { if (res) { message.success('图片排序成功'); } else { message.success('图片排序失败'); } dispatch(action.getPictureDetailList(detail.pictureFileId)) })) } render() { const pictureList = this.state.cards const {data, dispatch} = this.props return ( <div> <div className={styles.pictureDetailListTitle} style={{background: '#fff'}}> <p className={styles.chooseNum}>{this.state.title}</p> <p className={styles.chooseNum}>已选{this.state.checkedList ? this.state.checkedList.length : '0'}条</p> <Checkbox indeterminate={this.state.indeterminate} onChange={this.onCheckAllChange.bind(this)} checked={this.state.checkAll} className={styles.checkall}> 全选 </Checkbox> {(() => { if (this.state.isDrop) { return ( <span className={styles.hint}>请拖动商品图片对图片重新排序,排序结束后点击完成进行保存。</span> ) } })()} <Button className={styles.deleteBtn} onClick={this.pictureDetailDelete.bind(this)}>删除</Button> <Button onClick={this.state.isDrop ? this.finishSort.bind(this) : this.toSort.bind(this)} className={styles.deleteBtn}>{this.state.isDrop ? '完成' : '排序'}</Button> </div> {(() => { if (!this.state.isDrop) { return ( <ul className={styles.pictureListUl} style={{marginLeft: '-40px'}}> <Checkbox.Group onChange={this.onChange.bind(this)} value={this.state.checkedList}> {(pictureList && pictureList.length > 0) ? pictureList.map((picture, index) => { let url; if (picture.server === 'zmfile.2dfire-daily.com' || picture.server === 'rest3.zm1717.com' || picture.server === 'assets.2dfire.com') { url = 'http://' + picture.server + '/upload_files/' + picture.path } else { url = 'http://' + picture.server + '/' + picture.path } return ( <li className={styles.pictureDetailListcard} key={index} data-index={picture.id}> <img className={styles.picturnDetailImg} src={url} alt={picture.name}/> <Checkbox className={styles.picturnDetailName} value={picture.id}> {picture.sortCode} </Checkbox> </li> ) }) : ''} </Checkbox.Group> {(() => { if ((this.state.type === '3' && pictureList && pictureList.length < 5) || (this.state.type === '1' && pictureList && pictureList.length < 24)) { return ( <AddPictureBtn data={data} dispatch={dispatch} imgType={this.state.type} loadType="2" returnAddPicture={this.returnAddPicture.bind(this)} /> ) } })()} {/*<AddPictureBtn data={data}*/} {/*dispatch={dispatch}*/} {/*imgType={this.state.type}*/} {/*loadType="2"*/} {/*returnAddPicture={this.returnAddPicture.bind(this)}*/} {/*/>*/} </ul>) } else { return ( <ul className={styles.pictureListUl} style={{marginLeft: '-40px'}}> <Checkbox.Group onChange={this.onChange.bind(this)} value={this.state.checkedList}> {pictureList ? pictureList.map((card, i) => { let url; if (card.server === 'zmfile.2dfire-daily.com' || card.server === 'rest3.zm1717.com' || card.server === 'assets.2dfire.com') { url = 'http://' + card.server + '/upload_files/' + card.path } else { url = 'http://' + card.server + '/' + card.path } return (<Card key={card.id} index={i} id={card.id} path={url} moveCard={this.moveCard} />) }) : ''} </Checkbox.Group> </ul> ) } } )()} </div> ) } } export default HaveDropPic <file_sep>/union-entrance/src/const/storeType.js /** * 切店页门店类型 图标映射 */ /** * 0单店, 1连锁, 2连锁店铺, 3分公司 */ module.exports = { 0: '//assets.2dfire.com/frontend/5ce922b9847995ed3ceae3d873d0238b.png', 1: '//assets.2dfire.com/frontend/ce8c587010627af97dca42eba4a88b59.png', 2: '//assets.2dfire.com/frontend/5ce922b9847995ed3ceae3d873d0238b.png', 3: '//assets.2dfire.com/frontend/f1627063bfc1a8c269eb7e666e9e93fa.png', 4: '//assets.2dfire.com/frontend/5a7b67303d76252980ef4bd5996837f7.png', 6: '//assets.2dfire.com/frontend/562738d118cffee9f851d50ff51e6928.png' } <file_sep>/inside-boss/src/components/customBillStore/content.js import React, { Component } from 'react' import { Select, Switch, Button, Modal, Input, Checkbox } from 'antd' const Search = Input.Search const CheckboxGroup = Checkbox.Group import { message } from 'antd/lib/index' const Option = Select.Option import styles from './css/content.css' import cls from 'classnames' import * as action from '../../action' const defaultCheckedList = [] export default class SelectStore extends Component { constructor(props) { super(props) this.state = { confirmLoading: false, checkedList: defaultCheckedList,//店铺选中内容 classifyIsShow: false,//是否不显示类型选择 indeterminate: true, checkAll: false,//是否全选 keyword: '', //搜索内容 typeActive: '-1',//类型当前选中 //地区选中 provinceActive: [ { index: 0, name: '全部', isEnd: false, id: 0 } ], //机构选中 branchActive: [ { index: 0, branchName: '全部', isEnd: false, id: 0 } ], joinModes: [ { name: '全部', entityId: '-1' }, { name: '加盟', entityId: 0 }, { name: '直营', entityId: 1 }, { name: '合作', entityId: 2 }, { name: '合营', entityId: 3 } ] } } //关键词搜索 search(e) { this.setState( { keyword: e }, () => { this.getShopList() } ) } //单选 onChange = checkedList => { const { shopList } = this.props.data this.setState({ checkedList, indeterminate: !!checkedList.length && checkedList.length < shopList.length, checkAll: checkedList.length === shopList.length }) } //全选 onCheckAllChange = e => { const { shopList } = this.props.data this.setState({ checkedList: e.target.checked ? shopList.map(val => val.name) : [], indeterminate: false, checkAll: e.target.checked }) } // 查询 getShopList() { const { dispatch } = this.props dispatch( action.getAllShopList({ keyword: this.state.keyword, joinMode: this.state.typeActive, branchEntityId: this.state.branchActive[this.state.branchActive.length - 1].id || '', provinceId: this.state.provinceActive[1] ? this.state.provinceActive[1].id : '', cityId: this.state.provinceActive[2] ? this.state.provinceActive[2].id : '', townId: this.state.provinceActive[3] ? this.state.provinceActive[3].id : '' }) ) } //类型选择 typeChange(entityId) { this.setState( { typeActive: entityId }, () => { this.getShopList() } ) } /** * 选择类型点击事件 * @param i 当前属于第几次 * @param id 当前选中值再当前层出的index值 * @param name 名字 * @param type 类型,值为province、branch * @param isEnd 当前选中是否为最后层,值为true、false * @param value 搜索时所需要的值 * */ menuChange(i, id, name, type, isEnd, value) { let menuActive = type + 'Active', menuName = type === 'province' ? 'name' : 'branchName' let menuActiveList = this.state[menuActive].concat() //如果没有返回名字 if (!name) { menuActiveList.splice(i + 1, menuActiveList.length) } //如果是最后一层 else if (menuActiveList[menuActiveList.length - 1].isEnd) { menuActiveList.splice(i - 2, 1, { index: id, [menuName]: name, isEnd: isEnd, id: value }) } else { menuActiveList.push({ index: id, [menuName]: name, isEnd: isEnd, id: value }) } this.setState( { [menuActive]: menuActiveList }, () => { this.getShopList() } ) } /** * 获取类型选择html * @param type province地址选择、branch机构选择 * */ getMenuHtml(type) { const { data } = this.props const { branch, province } = data let menu = type === 'province' ? province : branch, menuActive = type + 'Active', menuName = type === 'province' ? 'name' : 'branchName', menuChild = type === 'province' ? 'subList' : 'children', menuValue = type === 'province' ? 'id' : 'entityId' let i = 1, itemList = menu && menu.concat() if (!itemList) return while (i <= this.state[menuActive].length) { itemList = i > 1 && this.state[menuActive][i - 1].isEnd === false ? itemList[this.state[menuActive][i - 1].index][menuChild] : itemList i++ } return ( itemList && itemList.map((val, index) => { return ( <span className={cls( styles.search_span, val[menuValue] === this.state[menuActive][this.state[menuActive].length - 1].id ? styles.search_active : '' )} key={index} onClick={this.menuChange.bind( this, i, index, val[menuName], type, !val[menuChild], val[menuValue] )} > {val[menuName]} </span> ) }) ) } //筛选按钮,是否隐藏筛选条件 classifyBtnChange() { this.setState({ classifyIsShow: !this.state.classifyIsShow }) } //确定事件 handleOk = () => { const { data,dispatch } = this.props const { shopList,activeShopList } = data let checkedList=shopList.filter(val=>{ if(this.state.checkedList.indexOf(val.name)>-1){ return val } } ) // 合并已选和新选的门店 let allList = activeShopList?activeShopList.concat(checkedList):checkedList.concat(); // 选择门店去重 *** let hash = {}; let new_list = allList.reduce(function (item, next) { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []); let allCount=checkedList?checkedList.length:0 let repeatCount=(allList?allList.length:0)-new_list.length // 判断三种情况 全部重复、部分重复、无重复 if (repeatCount === allCount) { message.info("您添加了" + allCount + "个门店,其中重复" + repeatCount + "个,已自动为您合并。") } else if (repeatCount > 0 && repeatCount !== allCount) { message.info("您添加了" + allCount + "个门店,其中重复" + repeatCount + "个,已自动为您合并。") } dispatch(action.setBillActiveShop(new_list)) // 确定事件 this.setState({ confirmLoading: true }) setTimeout(() => { dispatch(action.billStoreModelSet({ visible: false })) this.setState({ confirmLoading: false }) // this.init() }, 500) } //取消事件 handleCancel = () => { const { dispatch } = this.props dispatch(action.billStoreModelSet({ visible: false })) // this.init() } //选中或者取消后的初始化 init(){ this.setState({ checkedList: [], classifyIsShow: false, indeterminate: true, checkAll: false, keyword: '', //搜索内容 typeActive: '-1', provinceActive: [ { index: 0, name: '全部', isEnd: false, id: 0 } ], //机构选中 branchActive: [ { index: 0, branchName: '全部', isEnd: false, id: 0 } ] }) } render() { const { data } = this.props const { shopList } = data return ( <div> <Modal title="选择门店" visible={data && data.visible} onOk={this.handleOk} okText="保存" confirmLoading={this.state.confirmLoading} onCancel={this.handleCancel} className={styles.modal_wrapper} afterClose={this.init.bind(this)} bodyStyle={{ height:'640px', overflowY:'auto' }} > <div className={styles.search_wrapper}> <Search placeholder="门店名称" onSearch={this.search.bind(this)} style={{ width: 200 }} /> <Button className={cls(styles.btn_filtrate)} onClick={this.classifyBtnChange.bind(this)} > 筛选 <span className={cls( this.state.classifyIsShow ? styles.arrow_bottom : styles.arrow_top )} /> </Button> </div> <content className={cls(styles.arrow)} style={this.state.classifyIsShow?{display:'none'}:{}}> <ul className={styles.search_classify}> <li className={styles.search_list}> <span className={styles.search_name}>类型:</span> <span> {this.state.joinModes.map(val => { return ( <span className={cls( styles.search_span, this.state.typeActive === val.entityId && styles.search_active )} onClick={this.typeChange.bind(this, val.entityId)} key={val.name} > {val.name} </span> ) })} </span> </li> {/*=============地区&&机构=====================*/} {[ { type: 'province', item: this.state.provinceActive }, { type: 'branch', item: this.state.branchActive } ].map(val => { let title = val.type === 'province' ? '地区:' : '机构:' let menuName = val.type === 'province' ? 'name' : 'branchName' return ( <li className={styles.search_list} key={val.type}> <span className={styles.search_name}>{title}</span> <span className={styles.search_active_list}> {val.item && val.item.map((item, index, arr) => { return item.isEnd === false ? ( <span key={index}> {index === 0 ? '' : '>'} <span className={cls( styles.search_menu, index + 2 > arr.length && styles.search_active )} onClick={this.menuChange.bind( this, index, null, null, val.type )} > {item[menuName]} </span> </span> ) : ( '' ) })} </span> <span>{this.getMenuHtml(val.type)}</span> </li> ) })} </ul> </content> {/*==================================*/} <div className={styles.search_total}> 当前符合条件门店总数: {shopList && shopList.length} </div> {/*================门店选择==================*/} <div className={styles.result_wrapper}> <div className={styles.result_all}> <Checkbox indeterminate={this.state.indeterminate} onChange={this.onCheckAllChange} checked={this.state.checkAll} > 全选 </Checkbox> </div> <CheckboxGroup options={ shopList && shopList.map(val => { return val.name }) } value={this.state.checkedList} className={styles.result_checkbox_wrapper} onChange={this.onChange} /> </div> </Modal> </div> ) } } <file_sep>/inside-boss/src/components/goodsPicture/templateDetail/editGoodsTemplate.js import React, {Component} from 'react' import styles from '../style.css' import {message,Input} from 'antd' import * as action from "../../../action"; import PreviewTemplate from "./previewTemplate.js"; import ChoicePicture from "./choicePicture.js"; import ButtonList from "./buttonList.js"; import imgURL from '../images/add.png'; import add1 from '../images/add1.png'; import add2 from '../images/add2.png'; import forbid from '../images/forbid.png'; const imgArr=[add1,add2,forbid]; const { TextArea } = Input; class editGoodsTemplate extends Component{ constructor(props) { super(props) this.state={ goodsName:"", goodsImageText:[{ image:"", text:"" }], combineGoods:[{ images:["","","",""], text:"" }], visible:false,//预览图片弹窗 flag:false,//选择图片弹窗 curType: 1, //1商品头图2商品详情图 curIndex: 0, //索引 childIndex:0,//组合图下面的索引 } } componentDidMount() { const {dispatch,detail,data} = this.props let entityId = data.importData.entityId; dispatch(action.getTemplateDetail(detail.templateId, detail.pictureFileId, entityId)) } componentWillReceiveProps(newProps) { let l1 = newProps.data.templateDetail.trace; let l2 = newProps.data.templateDetail.cook; let result = [],arr=[],g1,g2; if(l2.length>0){ if(!l2[0].images){//老格式数据兼容 for (let i = 0; i < l2.length; i++) { result.push(l2.slice(i, (i + 1))) } for (let i = 0; i < result.length; i++) { let item = {}; let images = [result[i][0].image, "", "", ""]; let text = result[i][0].text; item.images = images; item.text = text; arr.push(item); } l2 = [...arr]; } } g1=l1.length>0?l1:this.state.goodsImageText; g2=l2.length>0?l2:this.state.combineGoods; this.setState({ goodsName: newProps.data.templateDetail.title[0].text || newProps.data.pictureName, goodsImageText: g1, combineGoods: g2 }) } // 控制输入的长度 controlLength =(e,len)=>{ if(len&&e.target.value.length<=len){ this.setState({ [e.target.name]: e.target.value }) } } // 计数器 handleChange = (e, index, len) => { let length = e.target.value.length if (len && length <= len) { let obj = JSON.parse(JSON.stringify(this.state[e.target.name])); obj.map((item,i)=>{ if(i==index){ item.text=e.target.value; } }) this.setState({ [e.target.name]: obj, }) } } // 删除模板 delTemplate=(index,target)=>{ let obj = JSON.parse(JSON.stringify(this.state[target])); obj.splice(index,1); this.setState({ [target]: obj }) } // 添加模板 addTemplate = (target,type) => { if(this.state[target].length>=8){ message.info('图文最多不能超过8组。'); return; } let obj = JSON.parse(JSON.stringify(this.state[target])); let item={}; if(type==1){ item={ image: "", text: "" } }else{ item={ images: ["", "", "", ""], text: "" } } obj.push(item); let curIndex=obj.length-1; this.setState({ [target]: obj, flag:true, curIndex: curIndex, curType:type, childIndex:0 }) } // 取消模板 handleCancel =()=>{ let {dispatch,detail} =this.props dispatch(action.detailChange({detail:true,pictureFileId:detail.pictureFileId})) dispatch(action.editTemplate({edit:false})) } // 预览模板 handlePreview =()=>{ this.setState({ visible: true }) } // 保存模板 saveTemplate =()=>{ let {dispatch,data,detail} =this.props; let entityId = data.importData.entityId; let traceTemp = JSON.parse(JSON.stringify(this.state.goodsImageText)); let cookTemp = JSON.parse(JSON.stringify(this.state.combineGoods)); let trace=[],cook=[]; traceTemp.map((item,index)=>{ if(item.image==''&&item.text=='')return; else trace.push(item); }) cookTemp.map((item,index)=>{ let arr=item.images; if(arr[0]==''&&arr[1]==''&&arr[2]==''&&arr[3]==''&&item.text=='')return; else cook.push(item) }) let itemDetailJson={ version: 1, modules: { title: [{ image:null, text: this.state.goodsName }], trace: trace, cook: cook } } let itemId = detail.pictureFileId; let templateId = detail.templateId; let ItemDetailVO={ entityId: entityId, itemDetailJson: JSON.stringify(itemDetailJson), itemId: itemId, templateId: templateId }; dispatch(action.saveTemplate(ItemDetailVO, 2, itemId, entityId)) } // 选择图片 choicePicture=(type,index,childIndex)=>{ if (type == 1) { this.setState({ flag: true, curType: type, curIndex: index }) }else{ let flag; let arr = this.state.combineGoods[index].images; if(childIndex==0){ flag=true; } for(let i=1;i<arr.length;i++){ if(childIndex==i){ if(arr[i-1]=="")flag=false; else flag=true; break; } } this.setState({ flag: flag, curType: type, curIndex: index, childIndex: childIndex }) } } // 关闭弹窗 closePopup=(url)=>{ if(url){ if(this.state.curType==1){ let list = JSON.parse(JSON.stringify(this.state.goodsImageText)); list[this.state.curIndex].image=url; this.setState({ goodsImageText:list }) }else{ let list2 = JSON.parse(JSON.stringify(this.state.combineGoods)); list2[this.state.curIndex].images[this.state.childIndex]=url; this.setState({ combineGoods: list2 }) } } this.setState({ flag: false, visible: false }) } forbidFlag=(list)=>{ list.map(item=>{ let arr=item.images; if(arr[0]==""){ arr[0]=imgArr[0] arr[1]=arr[2]=arr[3]=imgArr[2]; } if(arr[0]!==""&&arr[1]==""){ arr[1]=imgArr[1] arr[2] = arr[3] = imgArr[2]; } if(arr[1]!==""&&arr[2]==""){ arr[2] = imgArr[1]; arr[3] = imgArr[2]; } if(arr[2]!==""&&arr[3]==""){ arr[3] = imgArr[1]; } if(item.text=="null" || item.text==null){ item.text=""; } }) return list; } render(){ let {data} =this.props; let list = JSON.parse(JSON.stringify(this.state.goodsImageText)); let list2 = JSON.parse(JSON.stringify(this.state.combineGoods)); list.map(item=>{ if (item.image == "" || item.image=="null") { item.image = imgURL; } if(item.text=="null" || item.text==null){ item.text=""; } }) this.forbidFlag(list2); return ( <div> <div className={styles.editTemplateBox}> <div className={styles.goodsNameBox}> <span className={styles.goodsName}>商品名称</span> <Input className={styles.inputStyle} name="goodsName" value={this.state.goodsName} onChange={(e)=>this.controlLength(e,21)}/> </div> <div className={styles.goodsNameBox}> <span className={styles.goodsName}>商品图文</span> <div className={styles.imageTextBox}> <ul> { list&& list.map((item,index)=>{ return ( <li key={index} className={styles.itemStyle}> <img className={styles.goodsPicture} src={item.image} onClick={()=>this.choicePicture(1,index)}/> <div className={styles.goodsTextBox}> <TextArea autosize={false} className={styles.textAreaStyle} name="goodsImageText" value={item.text} placeholder="请输入文本描述,不填写则不展示文字" onChange={(e)=>this.handleChange(e,index,60)}/> <span className={styles.inputNumber}>{item.text?item.text.length:0}/60</span> <a className={styles.delTemplate} onClick={() => this.delTemplate(index, "goodsImageText")}>删除</a> </div> </li> ) }) } </ul> <div className={styles.addGoods} onClick={()=>this.addTemplate("goodsImageText",1)}><span>+</span>添加</div> </div> </div> <div className={styles.goodsNameBox}> <span className={styles.goodsName}>组合商品图</span> <div className={styles.imageTextBox}> <ul> { list2&& list2.map((item,index)=>{ return ( <li key={index} className={styles.itemStyle}> <div className={styles.combineImageBox}> <img src={item.images[0]} className={styles.combineTop} onClick={()=>this.choicePicture(2,index,0)}/> <img src={item.images[1]} className={styles.combineBottom} onClick={()=>this.choicePicture(2,index,1)}/> <img src={item.images[2]} className={styles.combineLeft} onClick={()=>this.choicePicture(2,index,2)} /> <img src={item.images[3]} className={styles.combineRight} onClick={()=>this.choicePicture(2,index,3)}/> </div> <div className={styles.goodsTextBox}> <TextArea autosize={false} className={styles.textAreaStyle} name="combineGoods" value={item.text} placeholder="请输入文本描述,不填写则不展示文字" onChange={(e)=>this.handleChange(e,index,60)}/> <span className={styles.inputNumber}>{item.text?item.text.length:0}/60</span> <a className={styles.delTemplate} onClick={() => this.delTemplate(index, "combineGoods")}>删除</a> </div> </li> ) }) } </ul> <div className={styles.addGoods} onClick={()=>this.addTemplate("combineGoods",2)}><span>+</span>添加</div> </div> </div> </div> <ButtonList handlePreview={this.handlePreview} saveTemplate={this.saveTemplate} handleCancel={this.handleCancel}/> <PreviewTemplate goodsName={this.state.goodsName} goodsImageText={this.state.goodsImageText} combineGoods={this.state.combineGoods} visible={this.state.visible} closePopup={this.closePopup}/> <ChoicePicture data={data} flag={this.state.flag} closePopup={this.closePopup}/> </div> ) } } export default editGoodsTemplate <file_sep>/inside-boss/src/container/customBill/reducers.js import { INIT_DATA_BILL, SET_ALL_TMPL_TYPE, SET_ENTITY_TYPE, SET_TYPE_TMPL_LIST, SET_TYPE_TMPL_TITLE, } from '../../constants' const updownReducer = (state = {}, action) => { switch (action.type) { case INIT_DATA_BILL: return action.data case SET_ALL_TMPL_TYPE: return Object.assign({}, state, {allTmplType: action.data}) case SET_ENTITY_TYPE: console.log('eeeee output {entityType: action.data}',state,{entityType: action.data}); return Object.assign({}, state, {entityType: action.data}) case SET_TYPE_TMPL_LIST: return Object.assign({}, state, {typeTmplList: action.data}) case SET_TYPE_TMPL_TITLE: return Object.assign({}, state, {billTitle: action.data}) default: return state } } export default updownReducer <file_sep>/inside-chain/src/base/config/publish.js module.exports = { API_BASE_URL: 'https://gateway.2dfire.com/?app_key=200800&method=', NEW_API_BASE_URL: 'https://gateway.2dfire.com/?app_key=200800&method=', SHARE_BASE_URL: 'http://live.zm1717.com', IMAGE_BASE_URL: '//ifile.2dfire.com/', API_WEB_SOCKET: 'https://websocket.2dfire.com/web_socket', ENTRANCE_LOGIN: 'https://biz.2dfire.com/', ENV: 'publish', UPLOAD_PATH: 'https://ifile.2dfire.com/', UPLOAD_OSS: 'https://upload.2dfire.com/api/uploadfile', DATA_URL: 'https://data.2dfire.com/report-home.html' }; <file_sep>/static-hercules/src/approval/config/interception.js import {GATEWAY_BASE_URL, ENV, APP_KEY} from "apiConfig"; import axios from 'axios' import {GW} from '@2dfire/gw-params' import qs from 'qs' import {getCookie} from '../../base/utils/AppUtil' import router from "@2dfire/utils/router"; import handleError from '../utils/catchError' const GWObject = qs.parse(GW) const ENTITY_ID = router.route.query['entity_id'] || "" const API_PARAMS = `?app_key=${APP_KEY}&s_eid=${ENTITY_ID}&method=`; // 超时时间 axios.defaults.timeout = 30000 axios.defaults.headers.common['env'] = ENV; // http请求拦截器 axios .interceptors .request .use(config => { let token = encodeURIComponent(getCookie("token")); config.headers.common['token'] = token || ""; config.url = GATEWAY_BASE_URL + API_PARAMS + config.url config.params = Object.assign({}, config.params, GWObject) return config }, error => { return Promise.reject(error) }) // http响应拦截器 axios .interceptors .response .use(res => { // 响应成功关闭loading let data = res.data if (data.code === 1) { return data.data.data } else { handleError(data) return Promise.reject(res) } }, error => { handleError(error.data) return Promise.reject(error) }) export default axios <file_sep>/static-hercules/build/webpack.prod.conf.js var path = require('path'); var config = require('../config'); var utils = require('./utils'); var webpack = require('webpack'); var merge = require('webpack-merge'); var baseWebpackConfig = require('./webpack.base.conf'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var glob = require("glob"); var options = process.argv; for (var i = options.length - 1; i >= 0; i--) { if (options[i] && options[i].indexOf('NODE_ENV') > -1) { process.env.NODE_ENV = options[i].split('=')[1]; } } var getPlugin = function() { var plugin = [ // new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false // } // }), new webpack.optimize.OccurenceOrderPlugin(), // extract css into its own file new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', title: '跳转页', chunks: [], inject: true }), ]; if (config.dev.partialPackage) { var current = baseWebpackConfig.current; current.forEach(function(item) { plugin.push(new HtmlWebpackPlugin({ filename: 'page/' + item + '.html', template: path.join(config.dev.page, item + '.html'), chunks: [item], inject: true, minify: false, })); }); } else { var pages = glob.sync("./page/*.html"); pages.forEach(function(name) { var chunk = name.slice(7, name.length - 5); var page = name.slice(7, name.length); var file = name.slice(2, name.length); var temp = path.join(config.dev.page, page); plugin.push( new HtmlWebpackPlugin({ filename: file, template: temp, inject: true, chunks: [chunk], minify: { removeComments: false, collapseWhitespace: false, removeAttributeQuotes: false }, }) ); }); } return plugin; }; var webpackConfig = merge(baseWebpackConfig, { module: { loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, vue: { loaders: utils.cssLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, plugins: getPlugin() }); if (config.build.productionGzip) { var CompressionWebpackPlugin = require('compression-webpack-plugin'); webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ); } module.exports = webpackConfig;<file_sep>/static-hercules/src/staff-management/router.js var Router = require("vue-router"); export var router = new Router({ routes: [{ path: "*", redirect: "/staffmanage" }, { path: "/staffmanage", name: "staffmanage", title: "员工管理", component: require("./views/staff/StaffManage.vue") }, { path: "/permissions", name: "permissions", title: "权限设置", component: require("./views/permissions/permission.vue") }, { path: "/rank/rankmanagelist", name: "rankmanagelist", title: "职级管理", component: require("./views/rank/RankManageList.vue") }, { path: "/rank/rankmanagedetail", name: "rankmanagedetail", title: "职级管理", component: require("./views/rank/RankManageDetail.vue") }, { path: "/help", name: "help", title: "帮助", component: require("./views/help/help.vue") }, { path: "/addstaff", name: "addstaff", title: "添加员工", component: require("./views/staff/AddStaff.vue") }, { path: "/staffinfo", name: "staffinfo", title: "员工", component: require("./views/staff/StaffInfo.vue") }] }); router.beforeEach((to, from, next) => { // console.log(to,from,next); // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) <file_sep>/inside-chain/src/tools/eslint-config-2dfire-base/globals.js const globals = { sessionInfo: true, Http_dFireHttp: true, DFAnalytics: true, queryFromURL: true, argsFromQuery: true, format_number: true, localInfo: true, AppUtil: true, orderParamsInfo: true, globalBasePage: true, LocationRedirect: true, wx: true, shareInfoStr: true, WXUtil: true, WeixinJSBridge: true, mqq: true, fireTrack: true, SkinUtil: true, ENV_BASE_URL: true }; module.exports = globals; <file_sep>/static-hercules/src/staff-management/store/state.js /** * Created by huaixi on 2019/5/6. */ export default { permissionList: [], //底部选择弹出 picker: { showPicker: false, pickerName: '', //当前选择的字段 pickerSlots: [{ defaultIndex: 0 }, //默认选中第一个 ], pickerTitle: '', other: '', //其他需要设置的值,省份需要设置id的值 pickerToolbarTitle: '', // 展示的toobar title showBottom: false, // 是否展示底部bottom }, isShowSaveButton: false, // 是否展示top-header的保存按钮 staffInfoTitle: '员工', addStaffTitle: '添加员工', clickedSaveButton: false, // 是否点击保存按钮 pageTitle: { '/staffmanage': '员工管理', '/permissions': '权限设置', '/rank/rankmanagelist': '职级管理', '/rank/rankmanagedetail': '职级管理', '/help': '帮助', '/addstaff': '添加员工', '/staffinfo': '员工', }, totalRankActionCount: '0', //云收银权限总数 rank: { id: '', name: '', actionCount: '0', }, // 员工信息 staffInfo: { userName: "", mobile: "", roleName: "", roleId: "", isSupper: 0, // 是否是超级管理员,服务端用的此字段,为了保持一致 }, // 员工设置信息 extraActionInfo: { allowDiscount: false, allowDiscountValue: "100", noAllowDiscount: false, // 关闭 noAllowDiscountValue: "100", limitSubZero: true, maxLimitSubZero: "10", }, }<file_sep>/union-entrance/src/views/nav/util/ajax.js import cookie from "./cookie"; //格式化参数 function formatParams(data) { const arr = []; for (const name in data) { arr.push( encodeURIComponent(name) + "=" + encodeURIComponent(data[name]) ); } arr.push(("v=" + Math.random()).replace(".", "")); return arr.join("&"); } export default function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; const params = formatParams(options.data); //创建 - 第一步 const xhr = new XMLHttpRequest(); //接收 - 第三步 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { const status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } }; //连接 和 发送 - 第二步 if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); const token = cookie.getCookie("entrance").token; // console.log(getCookies('entrance'),111) // console.log(token,222) // const tokenCookie = Cookie.getItem('token'); // if (tokenCookie) { // const token = tokenCookie // } //设置表单提交时的内容类型 xhr.setRequestHeader("token", token); xhr.setRequestHeader("env", "85da200fc40b467b9e20aca6b39833af"); // xhr.setRequestHeader("env", "3c46b0f369e64415a167b5d6af060545"); xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" ); xhr.send(params); } } <file_sep>/inside-chain/src/views/shop/store-manage/pass/printer/columns.js import Divider from '@/components/divider' export default self => [ { title: '原打印机IP', key: 'originIp' }, { title: '备用打印机IP', key: 'backupIp' }, { title: '操作', render: (h, { row }) => { return ( <div class="pass-scheme-columns-action"> <span onClick={self.editPrinterModal(row)}>编辑</span> <Divider /> <span onClick={self.delPrinter(row)}>删除</span> </div> ) } } ] <file_sep>/static-hercules/src/base/components/trace/events.js const Vue = require('vue'); const bindLevels = ['debug', 'log', 'warn', 'error', 'info']; const bus = new Vue({ data () { return { traceStatus: 0 }; }, methods: { }, created () { const re = window.location.href.match(/trace=(\d)/); const traceStatus = re ? +re[1] : (+window.localStorage.getItem('traceStatus') || 0); if (traceStatus === 1) { bindLevels.forEach(level => { const consoleBak = console[level]; console[level] = (...args) => { consoleBak(...args); bus.$emit('log', level, args); }; }); } window.localStorage.setItem('traceStatus', traceStatus); this.traceStatus = traceStatus; setTimeout(() => { bus.$emit('setTraceStatus', traceStatus); }, 1000); } }); module.exports = bus; <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/announce/AnnouncePreview.js import React, { PureComponent } from 'react'; import cx from 'classnames' import { Icon } from 'antd'; import style from'./AnnouncePreview.css' export default class AnnouncePreview extends PureComponent { render() { const { config } = this.props.value; const { text } = config console.log('text', text) return ( <div className="zent-design-component-Announce-preview"> <div className={style.AnnouncePreview} style={createStyle(config)} > <img className={style.Icon} src="https://assets.2dfire.com/frontend/6729d47fd2ada8dbf6b49478726eb79f.png" />{text ? text : '公告内容过长时会滚动展示'} </div> </div> ); } } function createStyle(value) { const { textColor, textAlign, backgroundColor } = value; return { color: textColor, textAlign: textAlign, backgroundColor: backgroundColor }; } <file_sep>/static-hercules/src/cashier/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, /** 获取banner*/ getBanner(params) { return axios({ method: 'POST', url: 'com.dfire.soa.boss.mg.service.IOptimizeBannerService.getBanner', params: params }) }, getInfo(params) { return axios({ method: 'GET', url: 'com.dfire.soa.cloudcash.client.service.IOnlinePurchaseClientService.getShopInfo', params: params }) }, getProduct(params) { return axios({ method: 'GET', url: 'com.dfire.soa.cloudcash.client.service.IOnlinePurchaseClientService.getProductList', params: params }) } } export default API;<file_sep>/static-hercules/src/base/interception.js import axios from 'axios' import { GW } from '@2dfire/gw-params' import catchError from './catchError' const { getCookie } = require("./utils/AppUtil") const { warning: warningDialog } = require("./components/dialogs/events") const Promise = require("promise") import { API_BASE_URL, ENV, GATEWAY_BASE_URL } from "apiConfig" /** * 创建一个地址附带查询参数 * @param {String} baseUrl 基础地址 * @param {Object} params key-value 对象,选填 * @return {void} */ function createUrlWithToken(baseUrl, token) { let subStr = ""; // 没有问号 if (baseUrl.lastIndexOf("?") === -1) { subStr = "?"; } else { // 最后一个字符 const lastChar = baseUrl.slice(-1); // 如果最后接在最后一个字符不是是?并且是&加上一个& if (lastChar !== "&" && lastChar === "?") { subStr = "&"; } } return baseUrl + subStr + "xtoken=" + token; } // 超时时间 axios.defaults.timeout = 30000 /** * @config isToken 是否需要token 默认为true * @config isGw 是否走网关 默认为false * @config isUrl 是否拼接url 默认为false * @config isCatch 是否catchError 默认为false 接口异常不影响主流程 * @config method 请求方式(POST/GET/DELETE/PUT/HEAD/PATCH)默认为GET * @config url 请求接口路径 * @config data 请求方式为'PUT', 'POST', 和 'PATCH'时发送的参数 * @config params 请求方式为'GET', 'DELETE', 和 'HEAD'时发送的参数 */ // http请求拦截器 axios .interceptors .request .use((config) => { let token = getCookie("token") || ''; let yToken = getCookie('ytoken') || ''; if (yToken === 'undefined' || yToken === 'null') { yToken = ''; } if (token === '' || token === undefined || token === null || token === 'undefined' || token === 'null') { token = yToken; } let needToken = true; // 此写法只为了兼容老项目,其他工程则需要将报错处理配置在axios的配置上 if (typeof (config.isToken) == "boolean") { needToken = config.isToken; } // 是否走网关 if (config.isGw) { config.headers.common['env'] = ENV; config.url = `${GATEWAY_BASE_URL}?${GW}&${config.url}`; return config } // 是否需要token else if (needToken) { if (!token) { warningDialog.showError("授权失败,请重新扫码", { canClose: false }); console.warn("没有token"); return Promise.reject("没有token"); } config.url = createUrlWithToken(config.url, token); } else if (config.isUrl) { return config } config.url = API_BASE_URL + config.url; return config }, error => { return Promise.reject(error) }) // http响应拦截器 axios .interceptors .response .use(res => { console.log(res) let data = res.data; let baseConfig = res.config; const handleError = baseConfig.handleError || catchError if (data.code === 1) { // 网关 if (baseConfig.isGw) { return data.data.data } return data.data } else { baseConfig.isCatch?'': handleError(data); return Promise.reject(data) } }, error => { if (!error.status) { return warningDialog.showError("网络请求失败", { canClose: false }); } return Promise.reject(error) }) /* demo // 默认配置项 axios.defaults.isToken = false axios.defaults.isGw = true // 客户列表 customerList(data) { return axios({ method: 'POST', url: '/crm/v1/customer/getCustomerList.bsh', data: qs.stringify(data), withCredentials:true, isGw:false }) }, // 网关 gwParams(groupId, pageIndex = 1, pageSize = 10, isOrderByNew = false){ return axios({ method:'POST', url:'app_key=200006&method=com.dfire.boss.center.business.service.ICourseClientService.getSimpleCourseVoByQuery', data:{ groupId, pageIndex, pageSize, isOrderByNew }, }) }, getGwParams(){ API.gwParams() .then(data=>{ }) } */ export default axios <file_sep>/inside-boss/src/container/visualConfig/.eslintrc.js // https://eslint.org/docs/user-guide/configuring const path = require('path') module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaFeatures: { jsx: true } }, env: { browser: true, }, extends: [ 'airbnb-base', 'plugin:react/recommended' ], plugins: [ 'react', ], settings: { 'import/resolver': { webpack: { config: path.resolve(__dirname, './eslint_webpack_resolve.js') } }, react: { version: "detect", }, }, rules: { // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'max-len': [1, { 'code': 120 }], 'indent': ['warn', 4, { 'SwitchCase': 1 }], 'semi': [1, 'never'], 'comma-dangle': [1], // 对象 逗号 'padded-blocks': [1], // 闭包 空行 'no-unused-vars': [1], // var 'no-trailing-spaces': [1], // 末尾空格 'no-multiple-empty-lines': [1], // 空行 'no-multi-spaces': 0, // 行内注释前的额外空格有助于保持代码整齐美观 'no-underscore-dangle': [0, 'never'], 'no-restricted-syntax': 0, 'no-return-await': 0, // 有时需要通过 return 提前退出函数,会有 return await xxx 的情况 'no-use-before-define': 0, // 自行判断一个函数能否调用成功 'no-else-return': 0, // 有时多余的 else 是为了明晰代码结构,有必要保留 'prefer-template': 0, // 有时候使用 string template 反倒影响可读性 'no-param-reassign': 0, 'arrow-parens': 0, 'prefer-destructuring': 0, 'no-continue': 0, 'no-await-in-loop': 0, 'import/no-dynamic-require': 0, 'import/order': 0, 'no-loop-func': 0, // 此规则是针对以前的 var 的,循环中 var 值会变,函数取到的不一定是预期的值;但 const 没有此问题 'no-undef-init': 0, // 有时就是想明确地把一个变量的初始值设为 undefined 'no-multi-assign': 0, 'import/prefer-default-export': 0, 'prefer-const': 0, 'react/prop-types': 0, 'no-return-assign': 0, // 无意义的规则 'lines-between-class-members': 0, 'class-methods-use-this': 0, 'object-curly-newline': 0, 'import/newline-after-import': 0, 'no-multiple-empty-lines': 0, } } <file_sep>/inside-boss/src/container/goods/index.js /** * Created by air on 2017/7/31. */ import React, { Component }from 'react' import { connect } from 'react-redux' import Main from '../../components/goods/main' import RetailMain from '../../components/retailManage/main' import InitData from './init' import * as action from '../../action' import * as bridge from '../../utils/bridge' import styles from './style.css' class goodsContainer extends Component { componentWillMount () { const query = bridge.getInfoAsQuery() const { dispatch, params } = this.props const data = InitData(params.pageType, query) dispatch(action.initData(data)) dispatch(action.checkWhiteList()) } componentDidMount () { sessionStorage.setItem('oldBatchId', '') sessionStorage.setItem('rechargeStatusList', '') sessionStorage.setItem('pageSize', 50) sessionStorage.setItem('startTime', 0) sessionStorage.setItem('endTime', 0) sessionStorage.setItem('pageIndex', 1) sessionStorage.setItem('selectedList', '[]') sessionStorage.setItem('dropDownButtonLock', '') sessionStorage.setItem('currentItem', '{}') } render () { const { data, dispatch,location={} } = this.props const { query } = location const { routeSource = '' } = query const { industry, inWhite } = data return ( <div className={styles.wrapper}> { industry === 3 && !!inWhite ? <RetailMain data={data} source={routeSource} dispatch={dispatch}></RetailMain> : <Main data={data} dispatch={dispatch}/>} </div> ) } } const mapStateToProps = (state) => ({ data: state.goods }) const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(goodsContainer) <file_sep>/inside-boss/src/container/rootContainer/index.js import React, { Component } from 'react' import styles from './style.css' import SideMenu from './SideMenu' import Header from './Header' import getUserInfo from '../../utils/getUserInfo' import { goToChangePage } from '../../utils/jump' export default class extends Component { constructor(p) { super(p) const { shopInfo } = getUserInfo() const { entityId } = shopInfo || {} //没有选择任何店铺,就跳转到选择店铺页面 if (!entityId) { goToChangePage() } } shouldComponentUpdate(nextProps) { const { location: { pathname } } = this.props if(pathname.split('/')[1] === 'EXTERNAL_LINK' ) return true return nextProps.location.pathname !== pathname } render() { const { location: { pathname }, children } = this.props return ( <div className={styles.main}> <SideMenu pathname={pathname.substring(1)} /> <div className={styles.container}> <Header /> <div className={styles.content}>{children}</div> </div> </div> ) } } <file_sep>/inside-boss/src/container/externalLink/index.js import React from "react"; import { currentExLink as baseUrl } from '../../utils/env' import styles from "./style.css"; import options from './init' const externalLink = (props) => { const pageType = props.params.pageType const suffixUrl = options(pageType) const currentFHYUrl = suffixUrl ? `${baseUrl}${suffixUrl}?${Date.now()}` : '' return ( <div className={styles.wrapper}> <iframe frameBorder="0" width="100%" height="100%" src={currentFHYUrl} ></iframe> </div> ); }; export default externalLink; <file_sep>/static-hercules/src/share/config/api.js const { SUPPLY_CHAIN_API} = require("apiConfig"); module.exports = { SUPPLY_CHAIN_API };<file_sep>/static-hercules/src/staff-management/store/getters.js /** * Created by huaixi on 2019/5/7. */ export const permissionMap = state => { const map = {} state.permissionList.forEach(item => { map[item.code] = item.name }) return map } export const grantedActionIdList = state => { var array = [] state.permissionList.forEach(item => { let actionList = item.actionVOList actionList.forEach(listItem => { if (listItem.selected) { array.push(listItem.id) } }) }) return array.sort() } export const rankName = state => { return state.rank.name } export const StaffInfoFirst = state => { return [ 'userName', 'mobile', 'roleName', ] } export const extraActionsInfoFirst = state => { return [ 'maxLimitSubZero', ] } <file_sep>/inside-boss/src/container/goodsPicture/reducers.js import { combineReducers } from 'redux' import { INIT_PICTURE_DATA, DETAIL_CHANGE, SET_PICTURE_LIST, LIST_DUPLICATED_ITEMS, BACK_TO_PICTURE_LIST, GET_DUPLICATED_ITEMS, SET_PICTURE_DETAIL_LIST, SET_PAGE_NUMBER, SET_SEARCH_NAME, SET_IS_SHOW_BRAND, SET_BRAND_LIST, SET_BRAND_ID, EDIT_TEMPLATE, TEMPLATE_DETAIL_DATA, TEMPLATE_LIST } from '../../constants' const pictureReducers = (state = {pageNumber:1}, action) => { const { data } = action; switch (action.type) { case INIT_PICTURE_DATA: return Object.assign({}, state, action.data) case BACK_TO_PICTURE_LIST: return { ...state, duplicated: false, } case LIST_DUPLICATED_ITEMS: return { ...state, pictureList: state.duplicatedItems, duplicated: true, } case GET_DUPLICATED_ITEMS: return { ...state, duplicatedItems: data, hasDuplicatedItems: data && (data.length > 0), } case SET_PICTURE_LIST: const {records={},totalRecord}=action.data||{} return Object.assign({}, state, { pictureList: records, pictureListTotal : totalRecord, pictureListLength : records.length, }) case SET_PICTURE_DETAIL_LIST: return Object.assign({}, state, { pictureDetailList: action.data.detailPicList, pictureDetailListLength : action.data.detailPicList.length, pictureHeaderList: action.data.headPicList, pictureHeaderListLength : action.data.headPicList.length, }) case SET_PAGE_NUMBER: return Object.assign({}, state, { pageNumber:action.data }) case SET_SEARCH_NAME: return Object.assign({}, state, { searchName:action.data }) case SET_IS_SHOW_BRAND: return Object.assign({},state,{isShowBrand:action.data}) case SET_BRAND_ID: return Object.assign({},state,{brandId:action.data}) case SET_BRAND_LIST: return Object.assign({},state,{brandList:action.data}) case TEMPLATE_DETAIL_DATA: return Object.assign({},state,{ templateDetail: JSON.parse(action.data.data.itemDetailJson).modules || [] }) case TEMPLATE_LIST: return Object.assign({}, state, { goodsDetailTemplate: action.data.data }) default: return state } } const pictureDetailReducers =(state = {}, action) => { switch (action.type) { case DETAIL_CHANGE: return Object.assign({}, state, { detail : action.data.detail, pictureFileId : action.data.pictureFileId, }) case EDIT_TEMPLATE: return Object.assign({}, state, { edit: action.data.edit, templateId: action.data.templateId, }) default: return state } } const reducer = combineReducers({ pictureReducers, pictureDetailReducers }) export default reducer <file_sep>/inside-boss/src/action/type.js var keyMirror = require('keymirror') module.exports = keyMirror({ FETCH_BANNER_LIST_SUCCESS: null, FETCH_BANNER_LIST_FAILURE: null, EDIT_BANNER_INDEX_SUCCESS: null, EDIT_BANNER_INDEX_FAILURE: null, EDIT_BANNER_ITEM_SUCCESS: null, EDIT_BANNER_ITEM_FAILURE: null, FETCH_ACTIVITY_LIST_SUCCESS: null, FETCH_ACTIVITY_LIST_FAILURE: null, EDIT_ACTIVITY_ITEM_SUCCESS: null, EDIT_ACTIVITY_ITEM_FAILURE: null, }) <file_sep>/static-hercules/src/wechat-direct-con/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; const API = { /*获取TOKEN信息*/ getToken(params) { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) }, /** * 获取session信息(用于埋点) * */ getSessionInfo(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: params }) }, /** 获取address*/ getAddress(params) { return axios({ method: 'GET', url: 'com.dfire.loan.platform.activate.IActivateService.getRegion', params: params }) }, /** * 判断是否是超级管理员 */ judgeSuper(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.user.service.IUserClientService.isSuper', params: params }) }, /** * 查看申请状态 */ getPaymentStatus(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.getPaymentStatus', params: params }) }, /** * 获取开户银行 */ getBanks(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.pay.service.IBankService.getBanks', params: params }) }, /** * 获取开户省 */ getBankProvince(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.pay.service.IBankService.getProvince', params: params }) }, /** * 获取开户市 */ getBankCity(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.pay.service.IBankService.getCities', params: params }) }, /** * 获取开户支行 */ getSubBanks(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.pay.service.IBankService.getSubBanks', params: params }) }, /** * 小微申请 */ authWxXw(params) { return axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.authWxXw', params: params }) }, /** * 查看小微进件及升级资料 */ getWxXwAuthInfoAndUpgradeInfo(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.getWxXwAuthInfoAndXwUpgradeInfo', params: params }) }, /** * 查询签约是否已完成 */ querySignFinished(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.querySignFinished', params: params }) }, /** * 启用小微 */ enableWxXw(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.enableWxXw', params: params }) }, /** * 修改银行卡信息 */ modifyWxXwBankInfo(params) { return axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.modifyWxXwBankInfo', params: params }) }, /** * 修改联系信息 */ modifyWxXwContactInfo(params) { return axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.modifyWxXwContactInfo', params: params }) }, /** * 小微升级资料 */ upgradeWxWx(params) { return axios({ method: 'POST', url: 'com.dfire.fin.thirdpart.merchant.service.upgradeWxXw', params: params }) }, /** * 查询打款信息 */ getAccountVerifyInfo(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.getAccountVerifyInfo', params: params }) }, /** * 查询是否已完成打款验证 */ queryVerifyAccountFinished(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.queryVerifyAccountFinished', params: params }) }, /** * 使用OCR */ ocrNetImage(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.ocr.service.IOcrApiClientService', params: params }) }, /** * 是否展示升级模块 */ getUpgradeIsShow(params) { return axios({ method: 'GET', url: 'com.dfire.fin.thirdpart.merchant.service.IPaymentAuthApplyService.upgradeIsShow', params: params }) } } export default API;<file_sep>/inside-boss/src/container/orderPhotos/init.js /** * Created by air on 2018/2/28. */ import { currentAPIUrlPrefix, currentEnvString } from '../../utils/env' const protocol = (currentEnvString === 'PUBLISH' ? 'https://' : 'http://') const templateDomainPrefix = (currentEnvString === 'PUBLISH' || currentEnvString === 'PRE' ? 'ifile' : 'ifiletest') const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query) => { const {entityId, memberId, userId} = query; var options = { 'order': { exportUrl: currentAPIUrlPrefix + 'merchant/export/exportCashLog', exportData: { ...APP_AUTH, entityId: entityId, memberId: memberId, userId: userId, }, pageNumber:1, exportBtnText: 'Export', showSpin: { boole: false, content: '' } } } return options[key] }; <file_sep>/union-entrance/src/views/index/js/interval.js /** * 二维码刷新定时器 * */ export default class Timer { constructor() { this.timer = null; this.time = 5 * 1000 * 60; } init(callback) { let that = this; if (!this.timer) { callback(); this.timer = setInterval(function () { callback(true) }, this.time) } else { this.clear(function () { that.init(callback) }) } } clear(callback) { clearInterval(this.timer); this.timer = null; callback ? callback() : ''; } };<file_sep>/inside-boss/src/container/combinedGoodsEdit/index.js /** * Created by shantaohua on 2018/02/15. * 组合商品编辑 */ import React, { Component } from 'react' import { connect } from 'react-redux' import Main from '../../components/goodCombinedEdit/main' import * as action from '../../action' import * as bridge from '../../utils/bridge' import styles from './style.css' import InitData from './init' class combinedGoodsEdit extends Component { constructor(props) { super(props) } componentWillMount() { const { dispatch, location } = this.props const { query } = location const { id='' } = query if(id){ dispatch(action.getCombinedGoodDetail(id)) }else{ dispatch(action.setCombinedGoodDetail([])) dispatch(action.setSelectCombinedGoodsList([])) dispatch(action.setHeadPicture([])) } dispatch(action.getGoodUnitList(3)) dispatch(action.getGoodCategory()) dispatch(action.getItemList(1)) dispatch(action.getFreightTemplate()) } render() { const { data, dispatch, location } = this.props const { query } = location const { id } = query return ( <div> <Main data={data} menuId={id} dispatch={dispatch} /> </div> ) } } const mapStateToProps = state => ({ data: state.combinedGoodsEdit }) const mapDispatchToProps = dispatch => ({ dispatch }) export default connect( mapStateToProps, mapDispatchToProps )(combinedGoodsEdit) <file_sep>/inside-chain/src/store/modules/menu/mutations.js export default{ // 获取品牌列表 _getAllMenus(state, params){ state.allMenuList = params }, _getReuseMenus(state, params){ state.reuseMenuList = params }, _setMenuInfo(state, menuInfo) { state.menuInfo = menuInfo }, _getGoodsByMenuId(state, res) { state.goodsOfMenu = res.goods || [] state.goodsOfMenuTotal = res.total }, _getGoodsByMenuIdSimple(state, res) { state.goodsOfMenuSimple = res.goods || [] state.goodsOfMenuSimpleTotal = res.total }, _getGoodsKindsByMenuId(state, list) { state.goodsKinds = list }, _getGoodsKindsByMenuIdSingle(state, list) { state.goodsKindsSingle = list }, _setMenuInfo(state, menuInfo) { state.menuInfo = menuInfo }, _setGoodsOfMenu(state, goods) { state.goodsOfMenu = goods }, _setGoodsByMenuIdSimple(state, goods) { state.goodsOfMenuSimple = goods }, _getGoodsPrice(state, res) { state.goodsPrice = res }, _priceBackup(state, res) { state.priceBackup = res }, // 商品导入 mutations // 获取所有商品/套餐 _listAllSimpleItem(state, res) { state.allSimpleItem = res }, _kindMenuTree(state, res){ state.typeList = res }, // 设置结果区列表 _setUnSubmitList(state, list) { state.unSubmitGoods = list }, // 设置结果区备份 _setResultBackup(state, list) { state.resultBackup = list }, // 存储筛选数据 _setFilterParams(state, res) { state.filterParams = res }, // 获取下发类型 _getPublishType(state, res) { state.publishType = res }, // 获取下发时间类型 _getPublishTimeType(state, res) { state.publishTimeType = res }, _getAllPublishMenus(state, res) { state.publishMenus = res }, _setNoSearchItems(state, res) { state.noSearchItems = res }, } <file_sep>/inside-chain/src/base/unit.js // 防止滚动穿透 export const fixedBody = function () { let scrollTop = document.body.scrollTop || document.documentElement.scrollTop document.body.style.cssText += 'position:fixed;top:-' + scrollTop + 'px' } // 恢复滚动 export const looseBody = function () { let body = document.body body.style.position = '' let top = body.style.top document.body.scrollTop = document.documentElement.scrollTop = - parseInt(top) body.style.top = '' } <file_sep>/inside-boss/src/container/visualConfig/store/formatters/definition.js /** * 数据定义 formatter * 2019/05/02 @fengtang */ export function formatSenceDefinition(raw) { const definition = { name: null, pages: [], customPage: null, ...raw, } if (definition.pages.length) { definition.pages = definition.pages.map(formatPageDefinition) } if (definition.customPage) { definition.customPage = formatCustomPageCommonDefinition(definition.customPage) } return definition } function formatPageDefinition(raw) { return { name: null, configName: null, link: null, manageable: true, components: [], defaults: {}, ...raw, } } function formatCustomPageCommonDefinition(raw) { return { components: [], defaults: {}, ...raw, } } export function formatDesignComponent(com) { return { definition: formatComponentDefinition(com.definition), component: com.component, } } function formatComponentDefinition(raw) { const defaultGroup = '其他类' const definition = { name: null, userName: null, description: null, choosable: true, max: null, group: defaultGroup, position: null, bare: false, config: {}, ...raw, } // 修正无效值 if (!definition.description) { definition.description = definition.userName } if (definition.choosable) { definition.bare = false } if (!definition.choosable) { definition.max = null definition.group = defaultGroup } if (definition.bare && !definition.position) { definition.position = 'top' } if (definition.choosable && definition.position) { definition.max = 1 } return definition } <file_sep>/inside-boss/src/container/visualConfig/views/design/preview/DesignPreview.js import React, { PureComponent } from 'react'; import find from 'lodash/find'; import DesignPreviewItem from './DesignPreviewItem' import DesignEditorItem from '../editor/DesignEditorItem'; import DesignPreviewController from './DesignPreviewController' import DesignEditorAddComponent from '../editor/DesignEditorAddComponent'; import BackgroundPreview from '../compoents/background'; import { isExpectedDesginType } from '../utils/design-type'; import style from './DesignPreview.css' export default class DesignPreview extends PureComponent { static defaultProps = { background: '#f9f9f9', disabled: false, appendableComponents: [], prefix: 'zent', }; imgHeight = (url) => { var img = new Image() img.src = url img.onload =() => { return `${img.height}px` } } render() { const { components, prefix, value, showAddComponentOverlay, onAddComponent, settings, getUUIDFromValue, selectedUUID, onSelect, onComponentValueChange, validations, handleClickBySortUp, handleClickBySortDown, onDelete, onCloseEditor, backgroundChang, backgroundImage, designMode } = this.props return ( <div className={style.Designpreview}> <div className={style.DesignEditorItem} > <DesignEditorAddComponent prefix={prefix} fromSelected designMode={designMode} components={components} onAddComponent={onAddComponent} /> </div> <div className={style.previewMain}> <p className={style.previewTitle}>{designMode}</p> <div className={style.arrPreviewItem}> <img className={style.previewItemHeadImg} src="https://assets.2dfire.com/frontend/204a5c5b98152b85c9350640d0865e2c.png"></img> <div className={style.arrPreviewBg} style={{backgroundImage: 'url('+backgroundImage+')', height: this.imgHeight(backgroundImage)}}> {value.map((v, index) => { const valueType = v.type; const comp = find(components, c=> isExpectedDesginType(c, valueType) ) const PreviewItem = comp.previewItem || DesignPreviewItem; const EditorItem = comp.editorItem || DesignEditorItem; const id = getUUIDFromValue(v); const selected = id === selectedUUID; return ( <PreviewItem key={id}> <DesignPreviewController value={v} prefix={prefix} selected = {selected} onSelect = {onSelect} component = {comp.preview} canDelete = {v.canDelete} onDelete = {onDelete} index = {index} designMode={designMode} /> {selected && !showAddComponentOverlay && ( <EditorItem move prefix={prefix} compName = {v.title} handleClickBySortUp = {handleClickBySortUp} handleClickBySortDown = {handleClickBySortDown} index = {index} value={v} onCloseEditor = {onCloseEditor} > <comp.editor value={v} settings={settings} prefix={prefix} onChange={onComponentValueChange} validation={validations[id] || {}} /> </EditorItem> )} </PreviewItem> ) })} </div> </div> {designMode == '微店铺首页' && <BackgroundPreview backgroundChang={backgroundChang} />} </div> </div> ); } } <file_sep>/inside-chain/src/const/emu-goodsDefaultValue.js export const goodsDefaultValue = { opEntityId: '', plateEntityId: '', id: '', kindId: '', label: { labelInfo: '', acridLevel: 0, recommendLevel: 0, specialTagId: '', tagSource: 1, mainIngredient: [], typeId: 0 }, name: '', price: 0, memberPrice: 0, buyAccount: '份', buyAccountId: '991801476208c1e8016209fab06267fa', account: '份', accountId: '991801476208c1e8016209fab06267fa', isTwoAccount: 0, code: '', headPicList: [], specDetailList: [], makeList: [], weight: 1, specWeightList: [], isRatio: 1, isChangePrice: 0, isBackAuth: 1, isGive: 0, consume: 0, serviceFeeMode: 0, serviceFee: 0, deductKind: 0, deduct: 0, startNum: 1, mealOnly: 0, stepLength: 1, isReserve: 1, isTakeout: 1, packingBoxId: '', packingBoxNum: 0, memo: '', showTop: 0, detailPicList: [], state: 1, discountInclude: 1 } <file_sep>/inside-boss/src/container/goodsPicture/index.js /** * Created by air on 2017/7/10. */ import React, { Component }from 'react' import Main from '../../components/goodsPicture/main' import { connect } from 'react-redux' import InitData from './init' import * as action from '../../action' import * as bridge from '../../utils/bridge' class GoodsPictureContainer extends Component { componentWillMount () { const query = bridge.getInfoAsQuery() const {dispatch, params} = this.props const data = InitData(params.pageType, query) dispatch(action.initPictureData(data)) dispatch(action.detailChange({detail:false})) dispatch(action.getIsShowBrand(1)) dispatch(action.editTemplate({edit:false,templateId:""})) } render () { const { data , dispatch ,detail} = this.props return ( <div> <Main data={data} dispatch={dispatch} detail={detail}/> </div> ) } } const mapStateToProps = (state) => { return { data: state.goodsPicture.pictureReducers, detail : state.goodsPicture.pictureDetailReducers } } const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(GoodsPictureContainer) <file_sep>/static-hercules/src/borrow-money/config/api.js /** * C端借款超市模块API */ import axios from './interception' import { APP_KEY } from 'apiConfig' export const getToken = params => axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { appKey: APP_KEY, ...params } }) /* * 掌柜或者云收银查询贷款用户信息 */ export const queryUserInfoByMemberId = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.queryUserInfoByMemberId', params: params }) /* * 贷款产品列表 */ export const getList = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.getPersonalLoanPrdList', params }) /** * 根据二维火会员ID获取用户是否绑定 * @param params * @property {string} consumerId 从火拼拼进来 * @returns {AxiosPromise} */ export const checkUserInfoByConsumerId = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.checkUserInfoByConsumerId', params }) /** * 根据thirdId检查用户是否绑定 * @param params * @property {string} thirdId 从公众号进来 * @returns {AxiosPromise} */ export const checkIsBindByThirdId = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.checkIsBindByThirdId', params }) /** * 获取session信息(用于埋点) * */ export const getSessionMapFromToken = params => axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: params }) /** * 验证用户短信验证码发送 * @param params * @property {string} mobile 手机号 * @property {string} thirdId 第三方id * @returns {AxiosPromise} */ export const sendMobileValidCode = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.sendMobileValidCode', params }) /** * 用户验证提交 * @data data * @property {object} loanUserInfoRequest * @returns {AxiosPromise} */ export const userInfoCheckApply = data => axios({ method: 'POST', url: 'com.dfire.fin.loan.userInfoCheckApply', data }) /** * 获取验证码错误次数 * @param params * @property {string} thirdId 第三方id * @returns {AxiosPromise} */ export const getValidCodeErrorTimes = params => axios({ method: 'GET', url: 'com.dfire.fin.loan.getValidCodeErrorTimes', params }) <file_sep>/inside-chain/src/utils/wxApp/localStorage.js 'use strict'; var _createStorage = require('./createStorage'); var _createStorage2 = _interopRequireDefault(_createStorage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = (0, _createStorage2.default)({ clear: function clear() { wx.clearStorage(); }, setItem: function setItem(name, value) { wx.setStorageSync(name, value); }, getItem: function getItem(name) { var value = wx.getStorageSync(name); return value === '' ? null : value; }, removeItem: function removeItem(name) { wx.removeStorageSync(name); } }); module.default = module.exports;<file_sep>/static-hercules/src/ocean-zl/store/mutation-types.js /** * Created by zipai on 2019/7/11. */ // 在input页面修改店铺信息 export const MODIFY_SHOPINFO = 'MODIFY_SHOPINFO' //底部弹出选择 export const PICKER_CHANGE = 'PICKER_CHANGE' //查询并更新直连已填写的数据 export const UPDATA_SHOPINFO = 'UPDATA_SHOPINFO' //查询并更新通联已填写的数据 export const UPDATA_SHOPINFO_TL = 'UPDATA_SHOPINFO_TL' //修改当前编辑状态 export const CHANGE_VIEWSTATE = 'CHANGE_VIEWSTATE' //修改示例图片图片显示 export const CHANGE_EXAMPLE_PHOTO = 'CHANGE_EXAMPLE_PHOTO' //修改编辑状态 export const CHANGE_SUB_STATUS = 'CHANGE_SUB_STATUS' <file_sep>/static-hercules/src/final-statement/config/interception.js import {GATEWAY_BASE_URL, ENV,APP_KEY} from "apiConfig"; import axios from 'axios' import {GW} from '@2dfire/gw-params' import qs from 'qs' import sessionStorage from "@2dfire/utils/sessionStorage"; import Vue from 'vue' const GWObject = qs.parse(GW) const API_PARAMS = `?app_key=${APP_KEY}&method=`; // 超时时间 axios.defaults.timeout = 30000 axios.defaults.headers.common['env'] = '56660396ae55428694921a3d18949fec'; // axios.defaults.headers.common['excludefilter'] = 'UserAuthFilter' let ERR_INFO = { } function catchError(err) { let message = ERR_INFO[err.errorCode] /*ERR_PUB 统一认为来自于网关的报错*/ if (err.errorCode.indexOf('ERR_PUB') >= 0) { Vue.prototype.$toast("网络暂时开小差了,请稍后重试") return } if (message) { Vue.prototype.$toast(message) } else { console.log(err.message) Vue.prototype.$toast(err.message) } } // http请求拦截器 axios .interceptors .request .use(config => { let token = sessionStorage.getItem("token"); config.headers.common['token'] = token || ""; config.url = GATEWAY_BASE_URL + API_PARAMS + config.url config.params = Object.assign({}, config.params, GWObject) return config }, error => { return Promise.reject(error) }) // http响应拦截器 axios .interceptors .response .use(res => { // 响应成功关闭loading let data = res.data if (data.code === 1) { return data.data.data } else { catchError(data) return Promise.reject(res) } }, error => { catchError(error.data) return Promise.reject(error) }) export default axios <file_sep>/static-hercules/src/dishesStatistics/main.js var Vue = require("vue"); var Router = require("vue-router"); var vueResource = require("vue-resource"); var App = require('./App.vue'); Vue.use(Router); Vue.use(vueResource); Vue.http.options.credentials = true; var router = new Router({ routes: [{ path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "活动首页", component: require("./views/index/index.vue") }] }); router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: "<App/>", components: { App }, });<file_sep>/inside-boss/src/container/visualConfig/views/design/common/couponSelect.js import React, { PureComponent } from 'react'; import { Modal, Table, Input, Icon, Button } from 'antd'; import {formatNumber} from '../utils/index' import visualApi from '@src/api/visualConfigApi' const { Column } = Table; const couponType ={ 'CASH': '全场现金券', 'DISCOUNT': '全场折扣券', 'SINGLE_CASH': '单品现金', 'SINGLE_DISCOUNT': '单品折扣', 'SALE': '特价券', 'EXCHANGE': '兑换券' } function add0(m) { return m < 10 ? '0' + m : m } export default class CouponSelectPreview extends PureComponent { state = { shopInput:'', data: [], selectedRows: [], selectedRowKeys: [] } componentDidMount() { this.getRetailCouponList() } componentWillReceiveProps(nextProps) { // 每次重新打开子组件的时候重新请求数据 if(nextProps.isShowCoupon) { this.getRetailCouponList() } } getRetailCouponList = () =>{ // 获取优惠券列表 visualApi.getRetailCoupons().then( res=>{ this.setState({ data: res.data }) }, err=>{ console.log('err', err) } ) } handleOk = () => { const {close, getCoupons} = this.props const {selectedRows} = this.state if(selectedRows.length > 0) { getCoupons(selectedRows) } close() this.deleKeys() } handleCancel = () => { const {close} = this.props close() this.deleKeys() } deleKeys = () => { // 选中重置 this.setState({ selectedRows: [], selectedRowKeys: [] }); } onChangeShopInput = (e) => { this.setState({ shopInput: e.target.value }); } format = (createTime) => { // 时间戳转换 if(!createTime) return false var time = new Date(createTime); var y = time.getFullYear(); var m = time.getMonth()+1; var d = time.getDate(); var h = time.getHours(); var mm = time.getMinutes(); var s = time.getSeconds(); return y+'-'+add0(m)+'-'+add0(d); } render() { const { shopInput, data, selectedRowKeys } = this.state for(var i = 0; i< data.length; i++ ){ data[i].key = i data[i].couponType = couponType[data[i].promoCouponBaseInfoList[0].type] let price; if(data[i].couponType == '全场现金券') { price = `${formatNumber(data[i].promoCouponBaseInfoList[0].worthValue, true)}元` } else if(data[i].couponType == '全场折扣券') { price = `${data[i].promoCouponBaseInfoList[0].rate / 10}折` } data[i].price = price } const rowSelection = { selectedRowKeys, type: 'radio', onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys, selectedRows }) } }; return ( <div className='zent-couponSelect-preview'> <Modal title="优惠券选择" visible={this.props.isShowCoupon} onOk={this.handleOk} onCancel={this.handleCancel} width ={800} > <Table dataSource={data} rowSelection={rowSelection} pagination={{ pageSize: 5 }} > <Column title="券标题" dataIndex="name" key="name" /> <Column title="券类型" dataIndex="couponType" key="couponType" /> <Column title="价值" dataIndex="price" key="price" /> <Column title="可领取时间" dataIndex="promoCouponBaseInfoList" key="promoCouponBaseInfoList" render={(promoCouponBaseInfoList) => ( <span> <span>{this.format(Number(promoCouponBaseInfoList[0].ruleInfo.activeDeliverTime.startTime))} ~ {this.format(Number(promoCouponBaseInfoList[0].ruleInfo.activeDeliverTime.endTime))}</span> </span> )} /> <Column title="剩余张数" dataIndex="remainNum" key="remainNum" /> </Table> </Modal> </div> ); } } function creatStyle() { return{ width: '150px', height: '32px', margin: '0 0 20px', } } <file_sep>/static-hercules/src/staff-management/config/api.js import axios from './interception' import { API_BASE_URL, APP_KEY } from "apiConfig"; import qs from 'qs' const API = { /*获取session信息*/ getSessionMap() { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: { appKey: APP_KEY } }) }, /*获取员工列表信息*/ listAllShopUsers() { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.listAllShopUsers', }) }, /*获取员工简要信息和权限数量*/ getEmployeeBriefInfo(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.getEmployeeBriefInfo', params: params }) }, /**删除员工信息 */ deleteEmployee(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.deleteEmployee', params: params }) }, /**创建员工 */ createEmployee(data) { return axios({ method: 'POST', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.createEmployee', data: qs.stringify(data), }) }, /**获取店铺职级列表 */ listShopRoles(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.listShopRoles', params: params }) }, /**获取职级可选和已选的权限列表 */ getRoleActionList(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.getRoleActionList', params: params }) }, /**删除职级 */ deleteRole(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.deleteRoleOfShop', params: params }) }, /**获取店铺权限总数 */ getShopActionTotal() { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.getShopActionTotal', }) }, /**创建店铺职级 */ createRole(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.createRole', params: params }) }, /**更新店铺职级名称 */ updateRole(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.updateRoleOfShop', params: params }) }, /**获取员工配置项 */ getExtraActionSettings(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.getExtraActionSettings', params: params }) }, /**给云收银店铺职级赋予权限 */ grantAction(data) { return axios({ method: 'POST', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.grantActionForRole', data: qs.stringify(data), }) }, /**获取职级的权限统计 */ getRoleActionCount(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.getRoleActionCount', params: params }) }, /**更新员工信息 */ updateEmployee(data) { return axios({ method: 'POST', url: 'com.dfire.boss.center.soa.employee.service.IEmployeeClientServiceV2.updateEmployee', data: qs.stringify(data), }) }, /**更新员工职级 */ updateEmployeeRole(params) { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.employee.service.updateEmployeeRole', params: params }) }, } export default API; <file_sep>/inside-boss/src/container/visualConfig/store/reducers/shopInfo.js import types from '../actionTypes' import { formatShopInfo } from '../formatters/api' const initialState = { // null: 加载中/待加载, true: 加载成功,false: 加载失败 loadingStatus: null, // ... shopInfo properties } export default function shopInfoReducer(state, action) { if (!state) state = initialState switch (action.type) { case types.SHOP_INFO_LOADED: return { ...initialState, loadingStatus: true, ...formatShopInfo(action.data), } case types.SHOP_INFO_LOAD_FAILED: return { ...initialState, loadingStatus: false } case types.SHOP_INFO_RESET: return initialState default: return state } } <file_sep>/inside-boss/src/components/goodsProperty/main.js // 商品属性 管理 模块 import React, { Component } from 'react' import styles from "./goodsProperty.css"; import * as action from "../../action"; import { Button, Modal } from "antd"; class GoodsProperty extends Component { constructor(props) { super(props) this.state = { isShowAddSpecPop: false, // 是否显示添加规格弹窗 isShowAddUnitPop: false, // 是否显示添加单位弹窗 specName: '', // 新增的规格名称 specModifyFlag: false, // 规格名称是否只读 specId: '', // 新增的规格Id unitName: '', // 新增的规格名称 isShowConfirmModal: false, // 是否显示确认弹框 propertyTabs: [{ name: '规格管理', active: true, }, { name: '单位管理', active: false, }], addSpecList: [{ key: '规格值1', value: '', }], currentDeleteUnit: {}, // 当前删除的单位 } } componentWillMount() { const { data, dispatch } = this.props const { industry } = data dispatch(action.getSpecList(industry)) dispatch(action.getUnitList(industry)) } /** * 切换商品属性的tab项 * @param item * @private */ _switchTab(data) { const { propertyTabs } = this.state propertyTabs.map(function(item){ item.active = false if(item.name === data.name) { item.active = true } }) this.setState({ propertyTabs }) } /** * 切换规格分类的展开状态 * @param item * @private */ _toggleFoldSpec(params) { const { data } = this.props const { specList=[] } = data const { id, isFold } = params specList.map(function(item) { if(item.id === id) { item.isFold = !isFold } }) this.setState({ specList }) } /** * 显示添加规格值 * @private */ _isShowAddSpecPop(flag, item={}) { if(!flag) { // 隐藏 this.setState({ specName: '', specModifyFlag: false, addSpecList: [{key: '规格值1', value: ''}] }) } else { const { name='', id } = item if(Object.keys(item).length === 0) { // 新增规格值 console.log('新增规格值') } else { // 新增规格项 this.setState({ specName: name, specId: id, specModifyFlag: true, }) } } this.setState({ isShowAddSpecPop: flag }) } /** * 编辑规格名称 * @param name * @private */ _handleSpecName(event) { this.setState({specName: event.target.value}) } /** * 编辑规格项 * @private */ _handleSpecItem(i, event) { const { addSpecList } = this.state addSpecList[i].value = event.target.value this.setState({ addSpecList, }) } /** * 添加规格项 * @private */ _addSpecItem() { const { addSpecList } = this.state if(addSpecList.length>0) { } addSpecList.push({ key: `规格值${addSpecList.length+1}`, value: '', }) this.setState({ addSpecList, }) } /** * 保存规格 * @private */ _saveSpec() { const { dispatch, data } = this.props const { industry } = data const { specName='', addSpecList, specId } = this.state if(specName.toString().trim().length === 0) { dispatch(action.errorHandler({message: '规格名称不能为空!'})) return } const list = addSpecList.map(item => { return item.value }) for(let i=0; i<addSpecList.length; i++) { const index = list.indexOf(addSpecList[i].value) if(i === index) continue if(index > -1 && addSpecList[i].value !== '') { dispatch(action.errorHandler({message: `规格值${index+1} 和 规格值${i+1} 存在重复, 添加失败!`})) return } } list.forEach( (item, i) => { // 删除数组中的空项 if(item.trim() === '') { list.splice(i, 1) } }) const args = { industry, specName, specId, addSpecList: list } dispatch(action.saveSpecName(args)) this._isShowAddSpecPop(false) } /** * 切换 规格值 启用或者 禁用状态 * @param item * @param mode name-切换名称 item-切换属性值 * @private */ _switchSpec(item, mode) { const { id, enable } = item const { dispatch, data } = this.props const { industry, specList } = data const args = { industry, id, flag: enable ? 0 : 1, specList } if(mode === 'item') { dispatch(action.switchSpecItemStatus(args)) } else if(mode === 'name') { dispatch(action.switchSpecNameStatus(args)) } } /** * 删除单位 * @param item * @private */ _deleteUnit(item) { if(item.unitType === 0) return this.setState({ isShowConfirmModal: true, currentDeleteUnit: item, }) } /** * 点击确认按钮 * @private */ _handleOk() { const { id } = this.state.currentDeleteUnit const { dispatch, data } = this.props const { industry } = data const args = { id, industry } dispatch(action.deleteUnit(args)) this._handleCancel() } /** * 点击取消按钮 * @private */ _handleCancel() { this.setState({ isShowConfirmModal: false, currentDeleteUnit: {}, }) } /** * 保存新的单位 * @private */ _saveUnit() { const { dispatch, data } = this.props const { unitName='' } = this.state if(unitName.toString().trim().length === 0) { dispatch(action.errorHandler({message: '单位名称不能为空!'})) return } const { industry } = data const args = { industry, unitName, } dispatch(action.addUnit(args)) this._isShowAddUnitPop(false) } /** * 显示单位弹窗 * @param flag * @private */ _isShowAddUnitPop(flag) { this.setState({ isShowAddUnitPop: flag, }) if(!flag) { this.setState({ unitName: '', }) } } /** * 更新单位名称 * @param e * @private */ _handleUnitName(e) { this.setState({ unitName: e.target.value, }) } render() { const { propertyTabs, isShowAddSpecPop, addSpecList, specName, unitName, isShowAddUnitPop, specModifyFlag, isShowConfirmModal, currentDeleteUnit } = this.state const { data } = this.props const { unitList=[], specList=[] } = data return ( <div className={styles.property_manage_body}> <div className={styles.property_tabs}> { propertyTabs.map((item, i) => { return ( <span key={i} onClick={() => this._switchTab(item)} className={item.active ? styles.active : ''} > {item.name} </span> ) }) } </div> { propertyTabs[0].active && <div className={styles.spec_manage_box}> <Button type="primary" className={styles.add_spec_absolute} onClick={() => this._isShowAddSpecPop(true)}> 添加规格 </Button> <div className={styles.spec_body_title}> <span>规格名称</span> <span>操作</span> </div> <ul className={styles.spec_list_box}> { specList.map( (item, i) => { return ( <li className={styles.spec_list} key={i*2}> <div className={styles.spec_title}> <div className={styles.table_title_name} onClick={()=> this._toggleFoldSpec(item)}> <span className={item.isFold ? styles.fold : styles.unfold}></span> <span>{item.name}</span> </div> <div className={styles.spec_opt}> <span className={styles.spec_add} onClick={() => {this._isShowAddSpecPop(true, item)}}>添加规格值</span> <span className={styles.spec_add} onClick={() => {this._switchSpec(item, 'name')}}>{item.enable ? '停用' : '启用'}</span> </div> </div> { item.isFold && <ul className={styles.spec_group}> { item.list && item.list.map((data, j) => { return ( <li className={styles.spec_item} key={j*3}> <div className={styles.spec_name}>{data.name}</div> <div className={styles.spec_item_opt} onClick={() => this._switchSpec(data, 'item')}>{data.enable ? '停用' : '启用'}</div> </li> ) }) } </ul> } </li> ) }) } </ul> </div> } { propertyTabs[1].active && <div className={styles.unit_manage_box}> <Button type="primary" className={styles.add_unit_absolute} onClick={() => this._isShowAddUnitPop(true)}> 添加单位 </Button> <div className={styles.unit_body_title}> <span>单位名称</span> <span>操作</span> </div> <ul className={styles.unit_list_box}> { unitList.map((item) => { return ( <li className={styles.unit_item} key={item.id}> <div className={styles.unit_name}> {item.name} {item.unitType===0 && <i>(系统默认)</i>} { item.chain && <i className={styles.chain_bg}>连锁</i> } </div> <div className={item.unitType === 0 ? styles.unit_group_disable : styles.unit_group} onClick={()=>this._deleteUnit(item)}>删除</div> </li> ) } ) } </ul> </div> } { isShowAddSpecPop && <div className={styles.add_spec_container}> <div className={styles.box_bg} onClick={() => this._isShowAddSpecPop(false)}></div> <div className={styles.add_spec_box}> <div className={styles.add_title}>添加规格</div> <div className={styles.spec_list}> <div className={styles.add_spec_name}> <span>*规格名称</span> <input type="text" maxLength="10" value={specName} readOnly={specModifyFlag} onChange={this._handleSpecName.bind(this)}/> </div> { addSpecList.map( (item, i) => { return ( <div className={styles.add_spec_value} key={i}> <span>{item.key}</span> <input type="text" maxLength="8" value={item.value} onChange={this._handleSpecItem.bind(this, i)}/> </div> ) }) } </div> { addSpecList.length <=14 && <div className={styles.add_spec_btn} onClick={() => this._addSpecItem()}> <span className={styles.icon_add}></span> <span className={styles.text}>添加规格值</span> </div> } <div className={styles.add_spec_bottom}> <div className={styles.btn_cancel} onClick={() => this._isShowAddSpecPop(false)}>取消</div> <div className={styles.btn_save} onClick={() => this._saveSpec()}>保存</div> </div> </div> </div> } { isShowAddUnitPop && <div className={styles.add_spec_container}> <div className={styles.box_bg} onClick={() => this._isShowAddUnitPop(false)}></div> <div className={styles.add_spec_box}> <div className={styles.add_title}>添加单位</div> <div className={styles.add_spec_name}> <span>单位名称</span> <input type="text" value={unitName} onChange={this._handleUnitName.bind(this)}/> </div> <div className={styles.add_spec_bottom}> <div className={styles.btn_cancel} onClick={() => this._isShowAddUnitPop(false)}>取消</div> <div className={styles.btn_save} onClick={() => this._saveUnit()}>保存</div> </div> </div> </div> } { <Modal title="确认弹窗" visible={isShowConfirmModal} onOk={() => this._handleOk()} onCancel={() => this._handleCancel()} > 确认要删除 [{currentDeleteUnit.name}] 吗? </Modal> } </div> ) } } export default GoodsProperty <file_sep>/inside-boss/src/api/networkApi.js import axios from './networkAxios' export default { getMonitorList(params) { return axios({ isWg: true, method: 'get', url: `com.dfire.thirdbind.not.Is.allow.train.number`, params: params }) }, getAllShopList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.pc.IShopBossPcService.queryAllShopList', mockUrl: '127/report/queryArgs.json', method: 'GET' }) }, //获取机构 getBranch(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.pc.IBranchBossPcService.getAllBranchTreeByBrandEntityId', mockUrl: '127/report/queryArgs.json', method: 'GET' }) }, // 获取省份 getAllProvince(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.pc.IAddressBossPcService.getAllProvince', mockUrl: '127/report/queryArgs.json', method: 'GET' }) }, // 获取店铺类型 getEntityType(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.getEntityType', mockUrl: '', method: 'GET', params }) }, // 获取所有的模板分类 getAllTmplType(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.getAllTmplType', mockUrl: '', method: 'GET', params }) }, // 根据模板类型获取模板列表 getTypeTmplList(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.getAllTmplByTmplCode', mockUrl: '', method: 'GET', params }) }, // 删除模板 delTmpl(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.delTmpl', mockUrl: '', method: 'GET', params }) }, // 使用模板 useTmpl(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.useTmpl', mockUrl: '', method: 'GET', params }) }, // 创建模板 createPrintTmpl(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.createPrintTmpl', mockUrl: '', method: 'GET', params }) }, // 编辑模板接口 getEditTmpl(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.editTmpl', mockUrl: '', method: 'GET', params, timeout: 5000 }) }, // 保存模板 editTmplName(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.updateTmplBasic', mockUrl: '', method: 'GET', params }) }, // 保存模板 saveTmpl(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.saveTmpl', mockUrl: '', method: 'POST', data: params, timeout: 5000 }) }, // 获取适用的门店 getUseStoreList(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.getApplyShopList', mockUrl: '', method: 'GET', params }) }, // 将模板适用给门店 saveUseStore(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.applyTmpl', mockUrl: '', method: 'GET', params }) }, // 上传图片 submitImg(params) { return axios({ isWg: true, url: 'com.dfire.cashconfig.applyTmpl', mockUrl: '', method: 'GET', type: 'addImg', params }) }, // 商品模板列表 getTemplateList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.IItemService.queryBItemTemplates', mockUrl: '', method: 'GET', params }) }, // 商品模板列表 checkWhiteList(params) { return axios({ isWg: true, url: 'com.dfire.soa.retail.platform.config.facade.ConfigFacade.checkWhiteList', mockUrl: '', method: 'GET', params }) }, // 获取模板详情 getTemplateDetail(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.IItemService.queryBItemDetail', mockUrl: '', method: 'GET', params }) }, // 保存模板 saveEditTemplate(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.IItemService.saveBItemDetail', mockUrl: '', method: 'GET', params }) }, // 获取banner列表 getMallBannerList(params) { return axios({ isWg: true, url: 'com.dfire.soa.mis.center.client.applets.IMallBannerService.listBannerList', mockUrl: '', method: 'GET', params }) }, postEditBannerIndex(params) { return axios({ isWg: true, url: 'com.dfire.soa.mis.center.client.applets.IMallBannerService.editBannerSequenceOrder', mockUrl: '', method: 'POST', params }) }, postEditBannerItem(params) { return axios({ isWg: true, url: 'com.dfire.soa.mis.center.client.applets.IMallBannerService.saveBanner', mockUrl: '', method: 'POST', params }) }, getMallActivityList(params) { return axios({ isWg: true, url: 'com.dfire.soa.mis.center.client.applets.IMallPromotionService.listPromotionList', mockUrl: '', method: 'GET', params }) }, postEditActivityItem(params) { return axios({ isWg: true, url: 'com.dfire.soa.mis.center.client.applets.IMallPromotionService.savePromotion', mockUrl: '', method: 'POST', params }) }, //设置规格 getShowSpecification(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.IItemService.saveBItemDetail', mockUrl: '', method: 'GET', params }) }, // 获取分类管理 getCateList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.listCategory', mockUrl: '', method: 'POST', params }) }, // 获取规格列表 getSpecList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.listSku', mockUrl: '', method: 'POST', params }) }, // 获取商品单位列表 getUnitList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.listUnit', mockUrl: '', method: 'POST', params }) }, // 保存规格 saveSpec(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.saveSkuPropertyAndValues', method: 'POST', params }) }, // 切换规格值的启用或停用状态 specItemSwitch(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.onOrOffSkuValue', mockUrl: '', method: 'POST', params }) }, // 切换规格名称的启用或停用状态 specNameSwitch(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.onOrOffSkuProperty', mockUrl: '', method: 'POST', params }) }, // 删除单位 deleteUnit(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.deleteUnit', mockUrl: '', method: 'POST', params }) }, // 新增分类信息 saveCate(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.addCategory', mockUrl: '', method: 'POST', params }) }, // 更新分类信息 updateCate(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.modifyCategory', mockUrl: '', method: 'POST', params }) }, // 删除分类 deleteCate(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.removeCategory', mockUrl: '', method: 'POST', params }) }, // 请求商品列表 getItemList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.tidyListItem', mockUrl: '', method: 'POST', params }) }, // 添加单位 addUnit(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.saveUnit', mockUrl: '', method: 'POST', params }) }, // 拉取商品详情 getGoodItemDetail(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.detailItem', mockUrl: '', method: 'GET', params }) }, // 拉取运费模版 getFreightTemplate(params) { return axios({ isWg: true, url: 'com.dfire.soa.lp.facade.LogisticsTemplateFacade.getLogisticsTemplateList', mockUrl: '', method: 'GET', params }) }, // 拉取运费模版 deleteItem(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.removeItem', mockUrl: '', method: 'POST', params }) }, // 获取店铺策略 getStrategy(params) { return axios({ isWg: true, url: 'com.dfire.retail.platform.strategy.facade.ShopStrategyFacade.queryShopStrategyByEntityIdAndType', mockUrl: '', method: 'POST', data: params, postType: 'formData' }) }, // 获取商品转自建策略 getFacadeService(params) { return axios({ isWg: true, url: 'com.dfire.soa.boss.center.strategy.service.IShopConfigFacadeService', mockUrl: '', method: 'POST', data: params, postType: 'formData' }) }, // 清除批量任务 clearBatch(params) { return axios({ isWg: true, url: 'com.dfire.batch.BatchFacade.clear', mockUrl: '', method: 'POST', data: params, postType: 'formData' }) }, // 保存商品 saveGoodItem(industry, data) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.modifyItem', mockUrl: '', method: 'POST', params: { industry }, data: { req: JSON.stringify(data) }, postType: 'formData' }) }, // 换分类 changeCategory(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.facade.service.IItemFacadeService.changeCategory', mockUrl: '', method: 'POST', params }) }, changeCombinedCategory(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.changeItemAssembleCategory', mockUrl: '', method: 'POST', params }) }, getChildGoodResult(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.deleteCheck', mockUrl: '', method: 'POST', params }) }, // 标价签获取所有模板 getPriceTagModule(params) { return axios({ isWg: true, url: 'com.dfire.soa.retail.platform.pricetag.facade.PriceTagTemplateFacade.queryAllPriceTagTemplate', mockUrl: '', method: 'POST', params }) }, // 复制模板 copyPriceTagModule(params) { return axios({ isWg: true, url: 'com.dfire.soa.retail.platform.pricetag.facade.PriceTagTemplateFacade.copyPriceTagTemplate', mockUrl: '', method: 'POST', params }) }, // 查询模板详情 getModuleDetail(params) { return axios({ isWg: true, url: 'com.dfire.soa.retail.platform.pricetag.facade.PriceTagTemplateFacade.queryPriceTagTemplateById', mockUrl: '', method: 'POST', params }) }, // 更改模板属性 updatePriceTagModule(params) { return axios({ isWg: true, url: 'com.dfire.soa.retail.platform.pricetag.facade.PriceTagTemplateFacade.updatePriceTagTemplate', mockUrl: '', method: 'POST', params }) }, // 修改组合商品 updateCombinedGood(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.modifyItemAssemble', mockUrl: '', method: 'POST', postType: 'formData', data: { req: JSON.stringify(params) } }) }, // 添加组合商品 addCombinedGood(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa..item.retail.service.IRetailItemService.addItemAssemble', mockUrl: '', method: 'POST', postType: 'formData', data: { req: JSON.stringify(params) } }) }, // 下发任务详情 distributeWorkDetail(params) { return axios({ isWg: true, url: 'bosscenter.IChainPublishPlatformClientService.saveTask', mockUrl: '', method: 'POST', params }) }, // 删除组合商品 deleteCombinedGoodDetail(params) { return axios({ isWg: true, postType: 'formData', url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.removeItemAssemble', mockUrl: '', method: 'POST', params }) }, //拉取组合商品列表 getCombinedGoodsList(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.listItemAssemble', mockUrl: '', method: 'POST', params }) }, // 获取组合商品详情 getCombinedGoodDetail(params) { return axios({ isWg: true, url: 'com.dfire.boss.center.soa.item.retail.service.IRetailItemService.getItemAssembleDetail', mockUrl: '', method: 'POST', params }) }, //导出excel表字段查询 queryUserGridFieldForDisplay(params={}){ return axios({ isWg: true, url:'com.dfire.soa.boss.gridfield.service.IUserGridFieldService.queryUserGridFieldForDisplay', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //重置表格字段 createResetForDisplay(params={gridType:1}){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.gridfield.service.IUserGridFieldService.createResetForDisplay', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //空白模板导出 downloadDefaultTemplate(params={ gridType: 1 }){ return axios({ isWg: true, url:'com.dfire.soa.boss.boss.excel.application.IMenuBatchImportService.downloadDefaultTemplate', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //商品导出模板 setupTemplate(params={gridType:1}){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.application.IMenuBatchImportService.setupTemplate', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //历史记录查询 getImportResultList(params={gridType:1}){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.application.IMenuBatchImportService.getImportResultList', mockUrl:'', method: 'POST', data:{ query: JSON.stringify(params) }, postType: 'formData', }) }, //单次导入结果查询 getImportResult(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchImportService.getImportResult', mockUrl:'', mockUrl: '', method: 'GET', params }) }, //导入进度查询 getImportProcess(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchImportService.getImportProcess', mockUrl:'', mockUrl: '', method: 'GET', params }) }, //检查是否使用双语 canSetupMenuLanguage(params={}){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.gridfield.service.IUserGridFieldService.canSetupMenuLanguage', mockUrl:'', mockUrl: '', method: 'GET', params }) }, //保存选择字段 batchCreatUserGridField(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.boss.gridfield.service.IUserGridFieldService.batchCreatUserGridField', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //获取菜单分类 kindMenuTreeSelect(params={}){ return axios({ isWg: true, url:'com.dfire.boss.center.pc.IKindMenuService.kindMenuTreeSelect', mockUrl:'', method: 'GET', params }) }, //商品导出 batchExportMenu(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchExportService.batchExportMenu', mockUrl: '', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //套餐导出 batchExportSuit(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchExportService.batchExportSuit', mockUrl:'', method: 'POST', data:{ request: JSON.stringify(params) }, postType: 'formData', }) }, //导入 batchImport({plateEntityId,fileName}){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchImportService.batchImport', mockUrl:'', method: 'POST', data:{ baseRequest: JSON.stringify({plateEntityId}), fileName }, postType: 'formData', }) }, //获取导出地址 getExportPath(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.com.dfire.soa.boss.excel.service.IMenuBatchExportService.getExportPath', mockUrl:'', method: 'GET', params }) }, //商品列表获取 listItemDetail(params){ return axios({ isWg: true, url:'com.dfire.boss.center.soa.com.dfire.soa.boss.centerpc.item.service.IItemService.listItemDetail', mockUrl:'', method: 'GET', params:{ listItemReq: JSON.stringify(params), }, }) }, //商品列表获取 listItem(params){ return axios({ isWg: true, url:'com.dfire.soa.boss.centerpc.item.service.IItemService.listItem', mockUrl:'', method: 'GET', params:{ listItemReq: JSON.stringify(params), }, }) }, } <file_sep>/static-hercules/src/ocean-zl/store/mutations.js /** * Created by zipai on 2019/7/11. */ import Vue from 'vue' import * as types from './mutation-types' export default { // 修改店铺信息 [types.MODIFY_SHOPINFO](state, payload) { if (payload.formId === 'tl') { Vue.set(state.applyInfoTl, payload.type, payload.value) } else { Vue.set(state.applyInfo, payload.type, payload.value) } }, //底部弹出选择 [types.PICKER_CHANGE](state, payload) { state.picker = { ...state.picker, ...payload } }, //查询并更新直连已填写的数据 [types.UPDATA_SHOPINFO](state, payload) { state.applyInfo = { ...state.applyInfo, ...payload } }, //查询并更新通联已填写的数据 [types.UPDATA_SHOPINFO_TL](state, payload) { state.applyInfoTl = { ...state.applyInfoTl, ...payload } }, //修改当前编辑状态 [types.CHANGE_VIEWSTATE](state, payload) { state.viewState = payload }, //修改当前编辑状态 [types.CHANGE_EXAMPLE_PHOTO](state, payload) { state.examplePhoto = { ...state.examplePhoto, ...payload } }, //修改编辑状态 [types.CHANGE_SUB_STATUS](state, payload) { state.subStatus = payload } } <file_sep>/inside-chain/src/utils/wxApp/location.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.navigateBack = exports.redirectTo = exports.navigateTo = exports.setCanJumpAlways = undefined; var _object = require('./object'); var _qs = require('./qs'); var _qs2 = _interopRequireDefault(_qs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var href = ''; var search = ''; var history = []; // 路由是否改变,用于判断是否需要从CurrentPages重新取url // let isChange = false; /** * 创建一个代理onLoad和onUnload的Page方法,应该在wx-component覆盖Page前执行 * (因为在wx-component的Page.onLoad中迟于Component.onLoad执行) * !!只有使用此方法产生的Page,获取search和href才是有效的 * * @param {Function} originalPage 原Page * @return {Function} 绑定历史的Page */ function createHistoryPage(originalPage) { return function historyPage(config) { var originalOnLoad = config.onLoad; var originalOnUnload = config.onUnload; originalPage((0, _object.objectAssign)(config, { onLoad: function historyPageHandleLoad() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var curPage = getCurrentPages()[getCurrentPages().length - 1] || {}; var route = curPage.route || curPage.__route__ || ''; if (route && route[0] !== '/') { route = '/' + route; } try { options = (0, _object.objectMap)(options, function (v) { return decodeURIComponent(v); }); } catch (e) { console.error(e); } search = _qs2.default.stringify(options); if (search) { search = '?' + search; } href = route + search; history.push({ // route, // options, search: search, href: href }); if (originalOnLoad) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } originalOnLoad.call.apply(originalOnLoad, [this, options].concat(args)); } }, onUnload: function historyPageHandleUnload(options) { if (originalOnUnload) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } originalOnUnload.call.apply(originalOnUnload, [this, options].concat(args)); } history.pop(); if (history.length > 0) { var route = history[history.length - 1]; search = route.search; href = route.href; } else { search = ''; href = ''; } } })); }; } var latestJumpTime = 0; var latestJumpUrl = ''; /** * Android微信存在多次点击带跳转动作的按钮会跳转多次, * 如果是navigateTo则打开多个Page,此处对跳转间隔限制,在700毫秒内的第二次跳转无效 * @return {Boolean} true 表示可以跳转,false表示不能 */ var canJumpNow = function canJumpNow(url) { var nowTime = Date.now(); if (nowTime - latestJumpTime < 700 && latestJumpUrl === url) { return false; } latestJumpUrl = url; latestJumpTime = nowTime; return true; }; /** * 设置可以一直跳 */ function setCanJumpAlways() { canJumpNow = function canJumpNow() { return true; }; } function navigateTo(url) { if (!canJumpNow(url)) { return; } wx.navigateTo({ url: url }); } function redirectTo(url) { if (!canJumpNow(url)) { return; } wx.redirectTo({ url: url }); } function navigateBack() { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; wx.navigateBack(n); } exports.setCanJumpAlways = setCanJumpAlways; exports.navigateTo = navigateTo; exports.redirectTo = redirectTo; exports.navigateBack = navigateBack; exports.default = { navigateTo: navigateTo, redirectTo: redirectTo, navigateBack: navigateBack, get search() { return search; }, // TODO 支持hash get hash() { return ''; }, get href() { return href; }, set href(href) { navigateTo(href); }, createHistoryPage: createHistoryPage };<file_sep>/static-hercules/src/static/js/analytics.js /** * Created by hupo. * on 17/4/24. * * !!! 加载位置: 在head标签最下面 !!! 目的是用于统计白屏时间和监听所有js报错 * * !!! 重要的事情说三遍(~加三个感叹号) !!! * !!! 为了减少日志数据量, 所有定义的key/value尽可能用了简写 !!! * !!! 后续编辑人员, 如果新增定义,必须在这里写明详细注释 !!! * !!! 防止日志别人看不懂 !!! * * * 错误类型配置表 (其他子配置见各处注释 直接在本文件中搜索) * T: 同 type 日志类型 EXAMPLE: "Er": 错误日志, "Wa": 警示日志, "Nm": 常规日志, "Cu": 自定义日志 * S: 同 subType 日志子类型 EXAMPLE: "js": js报错, "api": 接口请求, "zy": 资源错误, "pv": 访问量, "uv": 用户量, "st": 超时类错误, * U: 同 url 日志相关页面的url * M: 同 msg 日志信息详情 * A: 同 additionalMsg 附加的日志信息 * V: 同 randomString 每次请求的随机串, 防止浏览器缓存机制造成不发起请求 * */ (function () { var win = window; // 防止报错 if (typeof win != "undefined" && win.performance != "undefined" && win.performance.now != "undefined" && win.performance.timing != "undefined") { var per = win.performance; /*** * 主逻辑部分 * */ DFAnalytics = { type: "static", // 日志请求类型, 默认静态日志 IMG_URL: "https://trace.2dfire.com/0.gif", // 静态日志请求地址 API_URL: "https://trace.2dfire.com/0.gif", // api实时统计接口地址 useFirstPageTime: false, // 是否使用自定义首屏接口 isPvSend: false, // 是否已经发送过pv统计 times: { rdt: "", // 重定向完成时间 wst: "", // 白屏时间 fPt: "", // 首屏时间(包括异步加载完成时的耗时, 每个页面需要手动指定) tPt: "", // onload时间(同步加载完成的耗时, 没有异步加载时等同于首屏时间) dmt: "", // domready的时间 dit: "", // dom 解析耗时 tct: "" // tcp 耗时 }, res: [], // 所有资源耗时 usr: { // 用户和店铺相关信息 uid: "", // 用户id qrc: "", // qr_code eid: "", // 店铺 id stc: "" // 座位码 }, oth: { // 其他 ntw: "", // 网络类型 gps: "" // 经纬度坐标 }, /*** * 发送日志信息 * @param type 日志类型(具体见顶部注释) 必要 * @param msg 日志信息详情 必要 * @param sub_type 日志子类型(具体见顶部注释) * @param params 其他自定义参数 * @param track_type 发送日志的方式: 静态/api */ fire: function (type, msg, params, sub_type, track_type) { if (!params) { params = {}; } params.M = msg; params.U = encodeURIComponent(win.location.href); params.S = sub_type || ""; params.T = type || "Nm"; if (track_type && track_type == "api") { this.utils.fireAPI(this.API_URL, params); } else { this.utils.fireStatic(this.IMG_URL, params); } }, // 白屏时间 /*** * 记录首屏时间, 由每个页面自定义 */ markFirstPageTime: function () { this.useFirstPageTime = true; this.times.fPt = this.utils.timeFormat(per.now()); var networkType = this.utils.getSession("networkType"); if (networkType && !this.isPvSend && this.times.tPt) { this.sendPv() } else { var _this = this; setTimeout(function () { // 防止jsSdk初始化失败造成pv不发送的情况 if (!_this.isPvSend) { _this.sendPv() } }, 5000) } }, /*** * 自动发送pv统计 会保证 onload 和 自定义的 markFirstPageTime 完成后发送 */ autoSendPv: function () { var networkType = this.utils.getSession("networkType"); if (!this.isPvSend && networkType) { if (this.useFirstPageTime) { if (this.times.tPt && this.times.fPt) { this.sendPv() } } else { this.sendPv() } } }, /*** * pv */ sendPv: function () { this.oth.gps = this.utils.getLocalStorage("gps") || ""; this.oth.ntw = this.utils.getSession("networkType") || ""; var params = { rdt: this.times.rdt, wst: this.times.wst, fPt: this.times.fPt, tPt: this.times.tPt, dmt: this.times.dmt, dit: this.times.dit, tct: this.times.tct, uid: this.usr.uid, qrc: this.usr.qrc, eid: this.usr.eid, stc: this.usr.stc, gps: this.oth.gps, ntw: this.oth.ntw, res: this.res }; this.isPvSend = true; this.fire("Nm", "pv", params); }, /*** * utils 工具相关 * */ utils: { // 发送静态资源请求 用于日志 fireStatic: function (url, params) { //发送信息到http服务器 里面要追加信息标识 比如info error等 if (!params) { params = {}; } // 防止浏览器缓存 params.V = (new Date().getTime() + parseInt(1000 * Math.random(0, 1))).toString(36); var img = new Image(); img.onload = img.onerror = function (e) { // 请求完成后清除 img = null; }; img.src = url + this.formatParam(params); }, // 发送ajax请求 用户实时监控 fireAPI: function (url, arg1, arg2, arg3) { //发送信息到http服务器 里面要追加信息标识 比如info error等 var params, success, error; if (typeof(arg1) == "object") { params = arg1; success = arg2; error = arg3 } else { params = undefined; success = arg1; error = arg2 } var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { var resp = JSON.parse(xmlHttp.responseText); if (resp.code == 1 && success) { success(resp.data) } else if (error) { error(resp) } } else if (error) { error("error status: " + xmlHttp.status) } } }; xmlHttp.open("get", url + this.formatParam(params), true); xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.timeout = 15000; xmlHttp.ontimeout = function () { error("timeout") }; xmlHttp.send(); }, //格式化请求参数 formatParam: function (params) { if (params && Object.keys(params).length > 0) { var paramArray = []; for (var k in params) { if (params.hasOwnProperty(k)) { if (typeof params[k] === "object") { params[k] = JSON.stringify(params[k]) } paramArray.unshift(k + "=" + encodeURIComponent(params[k])); } } return "?" + paramArray.join("&"); } else { return "" } }, //格式化请求参数 timeFormat: function (time) { time = Math.round(time); if (time < 0) { time = 0 } return time }, getCookie: function (name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return win.unescape(arr[2]); } return ""; }, // 获取sessionStorage中的参数 getSession: function (name) { return sessionStorage.getItem(name); }, // 获取localStorage中的参数 getLocalStorage: function (name) { return localStorage.getItem(name); }, // 获取url中的参数 queryUrl: function (name) { var url = window.location.href; var values = url.match(new RegExp("[(\?)|(\&)]" + name + "\=[^\?\&\\\/\#]*", "g")); var value = ""; if (values) { var val = ""; if (values.length === 1) { val = values[0] || ""; value = val.split("=")[1] } else if (values.length > 1) { // 有多个值 就返回第二个 val = values[values.length - 1] || ""; value = val.split("=")[1] } } return value || "" } }, /*** * 自定义埋点 * todo hupo 待完成, 需要自己封装原生方法 */ // 时间打点 参考 performance user timing api mark 方法 mark: function (name) { if (typeof per.mark != "undefined") { per.mark(name) } }, // 时间打点 参考 performance user timing api measure 方法 measure: function (name, mark_1, mark_2) { if (typeof per.measure != "undefined") { per.measure(name, mark_1, mark_2); per.getEntriesByType && per.getEntriesByType('measure').forEach(function (ms) { if (ms.name == name) { var params = {}; params[name] = ms.duration; this.fire("Cu", "measure", params); per.clearMarks(mark_1); per.clearMarks(mark_2); per.clearMeasures(name); } }) } } }; /*** * 基础统计信息采集 * */ // js报错监控 win.onerror = function (message, url, line) { if (!url) { return } var params = { 'fn': url, 'li': line }; DFAnalytics.fire("Er", message || "", params, "js"); return false; }; // 获取基础数据 win.onload = function (event) { setTimeout(function () { if (typeof per.timing != "undefined" && typeof per.now != "undefined") { var t = per.timing || {}; DFAnalytics.times.tPt = DFAnalytics.utils.timeFormat(per.now()); // onload时间 DFAnalytics.times.dmt = DFAnalytics.utils.timeFormat(t.domContentLoadedEventEnd - t.navigationStart); // domready的时间 DFAnalytics.times.rdt = DFAnalytics.utils.timeFormat(t.redirectEnd - t.navigationStart); // 重定向完成时间 DFAnalytics.times.dit = DFAnalytics.utils.timeFormat(t.domComplete - t.domInteractive); // dom 解析耗时 DFAnalytics.times.tct = DFAnalytics.utils.timeFormat(t.connectEnd - t.connectStart); // tcp 耗时 var result = []; if (typeof per.getEntriesByType != "undefined") { var resource = per.getEntriesByType('resource') || []; resource.forEach(function (item) { var nameStr = item.name; var name = ""; // 排除无名/百度或百度统计相关/自己/ajax if (item.initiatorType != "xmlhttprequest" && nameStr && nameStr.search("baidu.com") < 0 && nameStr.search("0.gif") < 0) { var nameList = nameStr.split("/") || []; name = nameList[nameList.length - 2] + "/" + nameList[nameList.length - 1] || ""; result.push({ nam: name, // name 请求名(文件名) typ: item.initiatorType || "", // type 类型 stm: DFAnalytics.utils.timeFormat(item.startTime) || "", // startTime 请求延时(请求开始时间, 可能是队列等原因造成的延时)单位:ms dur: DFAnalytics.utils.timeFormat(item.duration) || "", // duration 请求耗时(请求开始时间, 可能是队列等原因)单位:ms tfs: DFAnalytics.utils.timeFormat(item.transferSize / 1024) || "" // transferSize 请求文件大小 单位:kb }); } }); DFAnalytics.res = result; } DFAnalytics.usr = { uid: DFAnalytics.utils.queryUrl('uid') || DFAnalytics.utils.getSession("user_id") || "", // 用户id qrc: DFAnalytics.utils.queryUrl('qr_code') || DFAnalytics.utils.getSession("qr_code") || "", // qr_code eid: DFAnalytics.utils.queryUrl('entity_id') || DFAnalytics.utils.getSession("shop_id") || DFAnalytics.utils.getSession("entity_id") || "", // 店铺 id stc: DFAnalytics.utils.queryUrl('seat_code') || DFAnalytics.utils.getSession("seat_code") || "", // 座位码 }; // 保证在gps和markFirstPageTime执行完成后发送 DFAnalytics.autoSendPv() } }, 0); }; win.DFAnalytics = DFAnalytics; DFAnalytics.times.wst = DFAnalytics.utils.timeFormat(per.now()); } else { // 防止报错 todo hupo 不支持此api的要发送一条统计 注明: 此浏览器不支持 win.DFAnalytics = { fire: function () { }, markFirstPageTime: function () { }, autoSendPv: function () { }, sendPv: function () { }, mark: function () { }, measure: function () { } }; } })(); <file_sep>/static-hercules/src/dishesStatistics/config/api.js const {API_BASE_URL} = require('apiConfig'); module.exports = { // 购买详情页 GET_DATA: API_BASE_URL + '/presell/v1/get_presell_menu_view', // GET_DATA:'http://api.l.whereask.com/presell_server/presell/v1/get_presell_menu_view' }<file_sep>/inside-boss/src/container/visualConfig/store/actionTypes.js import { mirror } from '@src/container/visualConfig/utils' const prefix = 'VISUAL_CONFIG/' /* 最终格式: { SHOP_INFO_LOADED: 'VISUAL_CONFIG/SHOP_INFO_LOADED', ... } */ export default mirror(prefix, [ // ===== SHOP INFO ===== 'SHOP_INFO_LOADED', // { data: shopInfoResp } 'SHOP_INFO_LOAD_FAILED', 'SHOP_INFO_RESET', // ===== CUSTOM PAGES ===== 'CUSTOM_PAGES_LOADED', // { data: customPagesResp } 'CUSTOM_PAGES_LOAD_FAILED', 'CUSTOM_PAGES_NOT_LOAD', // 判断不需要加载 custom pages(如当前店铺不支持装修)时触发此 action 'CUSTOM_PAGES_RESET', // ===== BACKUPS ===== 'BACKUPS_LOADED', // { data: backupsResp } 'BACKUPS_LOAD_FAILED', 'BACKUPS_RESET', // ===== TEMPLATES ===== 'TEMPLATES_LOADED', // { data: templatesResp } 'TEMPLATES_LOAD_FAILED', 'TEMPLATES_RESET', // ===== DESIGN CONFIG ACTION ===== // 切换要设计的 config,切换后当前 data 等数据会被重置,需要重新执行加载 // { name: configName } 'DESIGN_CONFIG_LOADING', // config data 加载完成 // { data: configDataObject } 'DESIGN_CONFIG_LOADED', // config data 加载失败 // { message: string } 'DESIGN_CONFIG_LOAD_FAILED', // 将 config data 标记为已保存过(即离开时不再提示是否要保存) 'DESIGN_SAVED', // 显示预览信息 // { url } 'DESIGN_PREVIEW', // 隐藏预览信息 'DESIGN_LEAVE_PREVIEW', // 重置 design 状态 'DESIGN_RESET', // ===== DESIGN COMPONENT ACTION ===== // 装修:在指定位置添加组件 // { name: componentName, index: number | null } // index 为组件放置位置,为 null 则放到最下面。对设置了 position 的组件无效。 'COMPONENT_ADD', // 装修:移除指定位置的组件 // { id } 'COMPONENT_REMOVE', // 装修:移动组件 // { id, toIndex } 'COMPONENT_MOVE', // 装修:更新指定组件的 config // { id, config } 'COMPONENT_UPDATED', // 装修:编辑指定的组件 // { id } 'COMPONENT_EDITING', // 装修:取消编辑当前组件 'COMPONENT_LEAVE', ]) <file_sep>/inside-chain/gulpfile.js /** * Create by duhuo@2dfire 2017/08/16 **/ var gulp = require('gulp'); var clean = require('gulp-clean'); var useref = require('gulp-useref'); var replace = require('gulp-replace'); var inject = require('gulp-inject'); var gulpif = require('gulp-if'); var rev = require('gulp-rev'); var revReplace = require('gulp-rev-replace'); var taskReplace = require('gulp-replace-task'); var stripDebug = require('gulp-strip-debug'); var cssmin = require('gulp-cssmin'); var htmlmin = require('gulp-htmlmin'); var uglify = require('gulp-uglify'); var PATH_ASSETS = './release/tmp'; var PATH_IMAGES = './images/**/*'; var PATH_JS = './js/**/*'; var PATH_CHECK_HEALTH = './check_health'; var PATH_PUBLIC = './public'; var PATH_TMP = './release/tmp'; var PATH_REV = './release/rev'; var PATH_MIN = './release/min'; var config = require('./config'); var path = require('path'); var env = process.env.NODE_ENV || 'dev'; var ASSETS_PATH = { html: './page/**/*.html', js: './js/**/*.js', css: './css/**/*.css', img: './img/**/*', images: './images/**/*', fonts: './fonts/**/*' }; // 清理目录 release gulp.task('clean', function () { return gulp.src(['./release'], { read: false }) .pipe(clean()); }); // 清理目录 rev gulp.task('clean-rev', ['min'], function () { return gulp.src(['./release/rev'], { read: false }) .pipe(clean()); }); // 文件 reb hash gulp.task('rev-hash', ['useref'], function () { var css = path.join(PATH_TMP, ASSETS_PATH.css); var js = path.join(PATH_TMP, ASSETS_PATH.js); var img = path.join(PATH_TMP, ASSETS_PATH.img); var files = [css, js, img]; console.log('rev:', files); return gulp.src(files, { base: PATH_TMP }) .pipe(rev()) .pipe(gulp.dest(PATH_REV)) .pipe(rev.manifest()) .pipe(gulp.dest(PATH_REV)) }); // 文件 rev replace gulp.task("rev-replace", ['rev-hash'], function () { var manifest = gulp.src(PATH_REV + "/rev-manifest.json"); var html = path.join(PATH_TMP, ASSETS_PATH.html); var js = path.join(PATH_REV, ASSETS_PATH.js); var css = path.join(PATH_REV, ASSETS_PATH.css); var files = [html, js, css]; return gulp.src(files, { base: PATH_TMP }) .pipe(revReplace({ manifest: manifest })) .pipe(gulp.dest(PATH_REV)); }); // 文件 copy public js gulp.task('copy-public', ['rev-replace'], function () { var css = path.join(PATH_PUBLIC, ASSETS_PATH.css); var js = path.join(PATH_PUBLIC, ASSETS_PATH.js); var files = [css, js]; console.log('copy-public:', files) return gulp.src(files, { base: './' }) .pipe(gulp.dest(PATH_TMP)) .pipe(gulp.dest(PATH_MIN)) }); // 文件 copy assets img gulp.task('copy-assets', ['rev-replace'], function () { var img = path.join(PATH_ASSETS, ASSETS_PATH.img); var files = [img]; console.log('copy-assets:', files) return gulp.src(files, { base: PATH_ASSETS }) .pipe(gulp.dest(PATH_TMP)) .pipe(gulp.dest(PATH_MIN)) }); // 文件 copy images gulp.task('copy-images', ['clean'], function () { var images = PATH_IMAGES; var files = [images]; console.log('copy-images:', files); return gulp.src(files, { base: "./" }) .pipe(gulp.dest(PATH_TMP)) }); // 文件 copy js gulp.task('copy-js', function () { var jsPath = PATH_JS; var files = [jsPath]; console.log('copy-js:', files); return gulp.src(files, { base: "./" }) .pipe(gulp.dest(PATH_TMP)) }); // 文件 copy check_health gulp.task('copy-check-health', function () { var check_health = PATH_CHECK_HEALTH; var files = [check_health]; console.log('copy-check-health:', files); return gulp.src(files, { base: "./" }) .pipe(gulp.dest(PATH_TMP)) .pipe(gulp.dest(PATH_MIN)) }); // 文件 copy html 合并 请求 gulp.task('useref', ['clean'], function () { var replace_assets = replace('/assets/', '../'); return gulp.src(ASSETS_PATH.html) .pipe(inject(gulp.src(['./node_modules/@2dfire/analytics-utils/*.html']), { starttag: '<!-- inject:{{path}} -->', transform: function (filePath, file) { return file.contents.toString('utf8') } })) .pipe(useref()) .pipe(gulpif('*.js', replace_assets)) .pipe(gulpif('*.css', replace_assets)) .pipe(gulp.dest(PATH_TMP + '/page')); }); // 文件 min gulp.task('min', function () { var css = path.join(PATH_ASSETS, ASSETS_PATH.css); var html = path.join(PATH_ASSETS, ASSETS_PATH.html); var js = path.join(PATH_ASSETS, ASSETS_PATH.js); var img = path.join(PATH_ASSETS, ASSETS_PATH.img); var image = path.join(PATH_ASSETS, ASSETS_PATH.images); var font = path.join(PATH_ASSETS, ASSETS_PATH.fonts); var files = [css, html, js, css, img, image, font]; console.log('min:', files); var patterns = config.patterns[env] || []; console.log(env); return gulp.src(files, { base: PATH_ASSETS }) // .pipe(gulpif('*.css' , cssmin())) // .pipe(gulpif('*.js' , uglify())) // uglify 在webpack 的时候做了。 .pipe(gulpif('*.html', htmlmin({ collapseWhitespace: true }))) .pipe(gulpif('*.js', taskReplace({ patterns: patterns }))) .pipe(gulpif('*.css', taskReplace({ patterns: patterns }))) .pipe(gulpif('*.html', taskReplace({ patterns: patterns }))) .pipe(gulp.dest(PATH_MIN)); }); gulp.task('strip', ['min'], function () { var js = path.join(PATH_MIN, "/js/*.js"); var isPublish = (env == "publish"); return gulp.src(js, { base: PATH_MIN }) .pipe(gulpif(isPublish, stripDebug())) .pipe(gulp.dest(PATH_MIN)); }); // 打包 // 拷贝 pub 目录 // // 拷贝 html // 拷贝 combo css js // // 文件 js eslint // 文件 js ugliy // // 文件 css prefix // 文件 css mini // // 文件 rev hash // 文件 rev replace // gulp.task('build', [ // 'clean', // 'copy-public', // 'copy-assets', // 'copy-images', // 'copy-js', 'copy-check-health', // 'useref', // 'rev-hash', // 'rev-replace', 'min', 'strip' // 'clean-rev' ]); // gulp.task('default', ['watch']); <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/goods/GoodsPreview.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import style from './GoodsPreview.css' import visualApi from '@src/api/visualConfigApi' import constants from '../../common/constants' const ItemArr = { '大图': [1], '详细列表': [1, 2, 3], '双列小图': [1, 2] } const ItemClass = { '大图': 'Big', '详细列表': 'Detailed', '双列小图': 'Double' } export default class GoodsPreview extends PureComponent { static propTypes = { value: PropTypes.object, // 用来和 Design 交互 design: PropTypes.object, }; state = { superscriptList : { '新品': 'https://assets.2dfire.com/frontend/d8bb4ca9cc57fbcd02173f9ae478c5da.png', '热卖': 'https://assets.2dfire.com/frontend/72ff61facf07a6dd4f622a25a30caa97.png', 'NEW': 'https://assets.2dfire.com/frontend/990bd6c197ca2da87bd561dd982b6b28.png', 'HOT': 'https://assets.2dfire.com/frontend/2a3c27f8b2cd467bc40f96f53edb19e6.png' }, data: [], ItemArr: [], } componentDidMount() { this.getRetailGoodsList() } getRetailGoodsList = ({ keyWord } = {}) => { // 零售商品列表 visualApi.getRetailGoodsList({ keyWord }).then( res=>{ this.setState({ data: res.data }) }, err=>{ console.log('err', err) } ) } shopButtonPreview = () => { const { config } = this.props.value; const { orderButton } = config if(orderButton.mode == '立即下单') { return <p className={style[`rankOrderBut${orderButton.orderStyle}`]}>{orderButton.mode}</p> } return <p className={style[`rankCartBut${orderButton.cartStyle}`]} /> } superscriptType = () => { const { value } = this.props; const { config } = value let superscriptType = 1 const text = config.subscript.text if(text == 'NEW' || text == 'HOT' || text == '自定义') { superscriptType =2 } return superscriptType } superscripIcon = () => { const { superscriptList } = this.state const { config } = this.props.value; if (config.subscript.text == '自定义') { return <img className={style.rankSuperscript2} src={config.subscript.image ? config.subscript.image : ''} /> } return <img className={style[`rankSuperscript${this.superscriptType()}`]} src={superscriptList[config.subscript.text]} /> } imgList = (data, newGoodsList) => { // 图片列表 const dataLen = data.length const goodLen = newGoodsList.length let imglist = [] // debugger for( var i = 0; i < goodLen; i++ ) { for(var j = 0; j < dataLen; j++ ) { if(newGoodsList[i] == data[j].itemId) { imglist.push(data[j].imagePath) } } } return imglist } previewType = () => { const { config } = this.props.value; const {data} = this.state let newGoodsList = Array.from(config.goodsList) let isShopName = config.showFields.indexOf('名称') > -1 // 是否显示商品名称 let isShopPrice = config.showFields.indexOf('价格') > -1 // 是否显示商品价格 let isShopButton = config.showFields.indexOf('下单按钮') > -1 // 是否显示商品按钮 let isShowSuperscript = config.showFields.indexOf('角标') > -1 // 角标是否显示 if(config.mode == '大图'){ if(newGoodsList.length > 6) { newGoodsList = newGoodsList.splice(0, 6) } } const imglist = this.imgList(data, newGoodsList) return ( imglist.length > 0 ? imglist.map((item, i) => <div className={style[`rank${ItemClass[config.mode]}Img`]} key={i}> <div className={style[`rank${ItemClass[config.mode]}List`]}> <div className={style.defultImg}> <img className={style.imgItem} src={item || constants.defaultGoodsImg} /> {isShowSuperscript && this.superscripIcon()} </div> <div className={style[`rank${ItemClass[config.mode]}Info`]}> <p className={style.rankShopName}>{isShopName &&'此处显示商品名称此'}</p> <div className={style.rankOrder}> <p className={style.rankPrice}>{isShopPrice &&'¥ 99.99'}</p> {isShopButton && this.shopButtonPreview()} </div> </div> </div> </div> ) : ItemArr[config.mode].map((item, i) => <div className={style[`rank${ItemClass[config.mode]}Img`]} key={i}> <div className={style[`rank${ItemClass[config.mode]}List`]}> <div className={style.defultImg}> <img className={style.logo} src="https://assets.2dfire.com/frontend/970fdb540e5b0f40621b14ba11e28601.png" /> {isShowSuperscript && this.superscripIcon()} </div> <div className={style[`rank${ItemClass[config.mode]}Info`]}> <p className={style.rankShopName}>{isShopName &&'此处显示商品名称此'}</p> <div className={style.rankOrder}> <p className={style.rankPrice}>{isShopPrice &&'¥ 99.99'}</p> {isShopButton && this.shopButtonPreview()} </div> </div> </div> </div> ) ) } render() { return ( <div className={style.rankingPreview}> <div className={style.rankImg}> {this.previewType()} </div> </div> ); } } <file_sep>/inside-boss/src/routes.js import { injectAsyncReducer } from './utils/asyncInjector' export default function createRoutes(store) { return [ { path: '/RECHARGE_BATCH/:pageType', name: 'updown', getComponent: (location, render) => { require.ensure( ['./container/updown/reducers', './container/updown'], require => { const container = require('./container/updown').default const reducer = require('./container/updown/reducers') .default injectAsyncReducer(store, 'updown', reducer) render(null, container) }, 'updown' ) } }, { path: '/ITEM_EXPORT/:pageType', name: 'goods', getComponent: (location, render) => { require.ensure( ['./container/goods/reducers', './container/goods'], require => { const container = require('./container/goods').default const reducer = require('./container/goods/reducers') .default injectAsyncReducer(store, 'goods', reducer) render(null, container) }, 'goods' ) } }, { path: "/ITEM_EDIT/:pageType", name: "goodEdit", getComponent: (location, render) => { require.ensure( ["./container/goodEdit/reducers", "./container/goodEdit"], require => { const container = require("./container/goodEdit").default; const reducer = require("./container/goodEdit/reducers") .default; injectAsyncReducer(store, "goodEdit", reducer); render(null, container); }, "goodEdit" ); } }, { path: "/COMBINED_GOODS_EDIT/:pageType", name: "combinedGoodsEdit", getComponent: (location, render) => { require.ensure( ["./container/combinedGoodsEdit/reducers", "./container/combinedGoodsEdit"], require => { const container = require("./container/combinedGoodsEdit").default; const reducer = require("./container/combinedGoodsEdit/reducers") .default; injectAsyncReducer(store, "combinedGoodsEdit", reducer); render(null, container); }, "combinedGoodsEdit" ); } }, { path: '/BOSS_MENU_IMG_IMPORT/:pageType', name: 'goodsPicture', getComponent: (location, render) => { require.ensure( ['./container/goodsPicture/reducers', './container/goodsPicture'], require => { const container = require('./container/goodsPicture').default const reducer = require('./container/goodsPicture/reducers').default injectAsyncReducer(store, 'goodsPicture', reducer) render(null, container) }, 'goodsPicture' ) } }, { path: '/MEMBER_EXPORT/:pageType', name: 'memberInformation', getComponent: (location, render) => { require.ensure( [ './container/memberInformation/reducers', './container/memberInformation' ], require => { const container = require('./container/memberInformation') .default const reducer = require('./container/memberInformation/reducers') .default injectAsyncReducer(store, 'memberInformation', reducer) render(null, container) }, 'memberInformation' ) } }, { path: '/PC_BRAND_ISSUE_COUPON/:pageType', name: 'couponPush', getComponent: (location, render) => { require.ensure( ['./container/couponPush/reducers', './container/couponPush'], require => { const container = require('./container/couponPush').default const reducer = require('./container/couponPush/reducers').default injectAsyncReducer(store, 'couponPush', reducer) render(null, container) }, 'couponPush' ) } }, { path: '/NO_OWNER_COUPON/:pageType', name: 'noOwnerCoupon', getComponent: (location, render) => { require.ensure( [ './container/noOwnerCoupon/reducers', './container/noOwnerCoupon' ], require => { const container = require('./container/noOwnerCoupon') .default const reducer = require('./container/noOwnerCoupon/reducers') .default injectAsyncReducer(store, 'noOwnerCoupon', reducer) render(null, container) }, 'noOwnerCoupon' ) } }, { path: '/BOSS_VIDEO_IMPORT/:pageType', name: 'videoImport', getComponent: (location, render) => { require.ensure( [ './container/videoImport/reducers', './container/videoImport' ], require => { const container = require('./container/videoImport') .default const reducer = require('./container/videoImport/reducers') .default injectAsyncReducer(store, 'videoImport', reducer) render(null, container) }, 'videoImport' ) } }, { path: '/ORDER_HISTORY_SNAPSHOT/:pageType', name: 'orderPhotos', getComponent: (location, render) => { require.ensure( [ './container/orderPhotos/reducers', './container/orderPhotos' ], require => { const container = require('./container/orderPhotos') .default const reducer = require('./container/orderPhotos/reducers') .default injectAsyncReducer(store, 'orderPhotos', reducer) render(null, container) }, 'orderPhotos' ) } }, { path: '/welcome', name: 'welcome', getComponent: (location, render) => { require.ensure( ['./container/welcome'], require => { const container = require('./container/welcome').default render(null, container) }, 'welcome' ) } }, { path: '/EXTERNAL_LINK/:pageType', name: 'externalLink', getComponent: (location, render) => { require.ensure( ['./container/externalLink'], require => { const container = require('./container/externalLink').default render(null, container) }, 'externalLink' ) } }, { path: '/old_design', name: 'visualConfigDesign', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/design'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/design').default; render(null, container); }, 'old_design' ); } }, { path: '/visual_config_design', name: 'visualConfigDesign', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/new_design'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/new_design').default; render(null, container); }, 'design' ); } }, { path: '/price_tag', name: 'priceTag', getComponent: (location, render) => { require.ensure([ './container/priceTag/reducers', './container/priceTag' ], (require) => { const container = require('./container/priceTag') .default const reducer = require('./container/priceTag/reducers').default injectAsyncReducer(store, 'priceTag', reducer) render(null, container) }, 'priceTag') } }, { path: '/PRICE_TAG_EDIT', name: 'priceTagEdit', getComponent: (location, render) => { require.ensure([ './container/priceTagEdit/reducers', './container/priceTagEdit' ], (require) => { const container = require('./container/priceTagEdit') .default const reducer = require('./container/priceTagEdit/reducers').default injectAsyncReducer(store, 'priceTagEdit', reducer) render(null, container) }, 'priceTagEdit') } }, { path: '/visual_config_union', name: 'visualConfigDesign', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/new_design'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/new_design').default; render(null, container); }, 'design' ); } }, { path: '/visual_config_pages', name: 'visualConfigPages', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/pages_manage/page'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/pages_manage/page').default; render(null, container); }, 'visualConfigPages' ); } }, { path: '/visual_config_adPage', name: 'visualConfigAdPage', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/pages_manage/adPage'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/pages_manage/adPage').default; render(null, container); }, 'visualConfigAdPage' ); } }, { path: '/visual_config_recommendedGood', name: 'visualConfigRecommendedGood', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/pages_manage/recommendedGood'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/pages_manage/recommendedGood').default; render(null, container); }, 'visualConfigRecommendedGood' ); } }, { path: '/visual_config_templates', name: 'visualConfigTemplates', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/templates'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/templates').default; render(null, container); }, 'visualConfigTemplates' ); } }, { path: '/visual_config_backups', name: 'visualConfigBackups', getComponent: (location, render) => { require.ensure( ['./container/visualConfig/views/backups'], require => { require('./container/visualConfig/store/register') const container = require('./container/visualConfig/views/backups').default; render(null, container); }, 'visualConfigBackups' ); } }, { path: '/UPLOAD_COMM_FILE/:pageType', name: 'uploadComm', getComponent: (location, render) => { require.ensure( [ './container/uploadComm/reducers', './container/uploadComm' ], require => { const container = require('./container/uploadComm') .default const reducer = require('./container/uploadComm/reducers') .default injectAsyncReducer(store, 'uploadComm', reducer) render(null, container) }, 'uploadComm' ) } }, { path: '/IMPORT_LOG/:pageType', name: 'importLog', getComponent: (location, render) => { require.ensure( ['./container/importLog/reducers', './container/importLog'], require => { const container = require('./container/importLog') .default const reducer = require('./container/importLog/reducers') .default injectAsyncReducer(store, 'importLog', reducer) render(null, container) }, 'importLog' ) } }, { path: '/DOWNLOAD_COMM_TMPL/:pageType', name: 'downComm', getComponent: (location, render) => { require.ensure( ['./container/downComm/reducers', './container/downComm'], require => { const container = require('./container/downComm') .default const reducer = require('./container/downComm/reducers') .default injectAsyncReducer(store, 'downComm', reducer) render(null, container) }, 'downComm' ) } }, { path: '/HIGH_ROUTE_IMPORT/:pageType', name: 'routeInfoImport', getComponent: (location, render) => { require.ensure( [ './container/routeInfoImport/reducers', './container/routeInfoImport' ], require => { const container = require('./container/routeInfoImport') .default const reducer = require('./container/routeInfoImport/reducers') .default injectAsyncReducer(store, 'routeInfoImport', reducer) render(null, container) }, 'routeInfoImport' ) } }, { path: '/HIGH_TRAIN_IMPORT/:pageType', name: 'trainInfoImport', getComponent: (location, render) => { require.ensure( [ './container/trainInfoImport/reducers', './container/trainInfoImport' ], require => { const container = require('./container/trainInfoImport') .default const reducer = require('./container/trainInfoImport/reducers') .default injectAsyncReducer(store, 'trainInfoImport', reducer) render(null, container) }, 'trainInfoImport' ) } }, { path: '/HIGH_DAILY_MONITOR/:pageType', name: 'highMonitor', getComponent: (location, render) => { require.ensure( [ './container/highMonitor/reducers', './container/highMonitor' ], require => { const container = require('./container/highMonitor') .default const reducer = require('./container/highMonitor/reducers') .default injectAsyncReducer(store, 'highMonitor', reducer) render(null, container) }, 'highMonitor' ) } }, { path: '/CUSTOM_BILL/:pageType', getComponent: (location, render) => { require.ensure( [ './container/customBill/reducers', './container/customBill' ], require => { const container = require('./container/customBill') .default const reducer = require('./container/customBill/reducers') .default injectAsyncReducer(store, 'customBill', reducer) render(null, container) }, 'customBill' ) } }, { path: '/CUSTOM_BILL/detail/:pageType(/:id)', name: 'customBillDetail', getComponent: (location, render) => { require.ensure( ['./container/customBillDetail'], require => { const container = require('./container/customBillDetail') .default const reducer = require('./container/customBillDetail/reducers') .default injectAsyncReducer(store, 'customBill', reducer) render(null, container) }, 'customBillDetail' ) } }, { path: '/MALL_BANNER_MANAGER/:pageType', name: 'mallBannerManager', getComponent: (location, render) => { require.ensure([ './container/mallBannerManager/reducers', './container/mallBannerManager' ], (require) => { const container = require('./container/mallBannerManager').default const reducer = require('./container/mallBannerManager/reducers').default injectAsyncReducer(store, 'mallBannerManager', reducer) render(null, container) }, 'mallBannerManager') } }, { path: '/MALL_PROMOTION_MANAGER/:pageType', name: 'mallActivityManager', getComponent: (location, render) => { require.ensure([ './container/mallActivityManager/reducers', './container/mallActivityManager' ], (require) => { const container = require('./container/mallActivityManager').default const reducer = require('./container/mallActivityManager/reducers').default injectAsyncReducer(store, 'mallActivityManager', reducer) render(null, container) }, 'mallActivityManager') } }, { path: "/IMPORT_HISTORY/:pageType", name: "importHistory", getComponent: (location, render) => { require.ensure( ["./container/importHistory/reducers", "./container/importHistory"], require => { const container = require("./container/importHistory").default; const reducer = require("./container/importHistory/reducers") .default; injectAsyncReducer(store, "importHistory", reducer); render(null, container); }, "importHistory" ); } }, { path: '/CUSTOM_BILL/store/:pageType(/:id)', getComponent: (location, render) => { require.ensure( [ './container/customBillStore/reducers', './container/customBillStore' ], require => { const container = require('./container/customBillStore') .default const reducer = require('./container/customBillStore/reducers') .default injectAsyncReducer(store, 'customBill', reducer) render(null, container) }, 'customBillStore' ) } }, { path: '/ITEM_IMPORT/:pageType', name: 'goodsImport', getComponent: (location, render) => { require.ensure([ './container/goodsImport/reducers', './container/goodsImport' ], (require) => { const container = require('./container/goodsImport').default const reducer = require('./container/goodsImport/reducers').default injectAsyncReducer(store, 'goodsImport', reducer) render(null, container) }, 'goodsImport') } }, { path: '/', onEnter(n, r) { r('/welcome') } }, { path: '*', component: null } ] } <file_sep>/inside-boss/src/container/visualConfig/views/new_design/editing/EditItem.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import * as actions from '@src/container/visualConfig/store/actions' import { getComponentEditing } from '@src/container/visualConfig/store/selectors' import PreviewWrapper from './PreviewWrapper' import EditorWrapper from './EditorWrapper' import EditPlaceholderWrapper from './EditPlaceholderWrapper' import s from './EditItem.css' @connect((state, props) => ({ editing: getComponentEditing(state, props.id), })) class EditItem extends Component { static propTypes = { id: PropTypes.string.isRequired, config: PropTypes.any, // 因为值有可能为 null,不能标记为 required designComponent: PropTypes.object.isRequired, } static childContextTypes = { designId: PropTypes.string.isRequired, designEditing: PropTypes.bool.isRequired, designDefinition: PropTypes.object.isRequired, } getChildContext() { return { designId: this.props.id, designEditing: this.props.editing, designDefinition: this.props.designComponent.definition, } } updateConfig = (config) => { actions.designUpdateComponentConfig( this.props.id, config, ) } render() { const { config, editing } = this.props const DesignComponent = this.props.designComponent.component return <div className={s.editItem}> <DesignComponent PreviewWrapper={PreviewWrapper} EditorWrapper={EditorWrapper} EditPlaceholderWrapper={EditPlaceholderWrapper} editing={editing} config={config} onUpdate={this.updateConfig} /> </div> } } export default EditItem <file_sep>/inside-boss/src/components/noOwnerCoupon/list.js /** * Created by air on 2018/3/14. */ /** * Created by air on 2017/7/10. */ import React, {Component} from 'react' import {Table} from 'antd' import styles from './style.css' import * as action from "../../action"; const columns = [ { title: '序列号', dataIndex: 'numId', key: 'numId' }, { title: '券号', dataIndex: 'couponId', key: 'couponId', }, { title: '优惠券名称', dataIndex: 'couponName', key: 'couponName', }, { title: '状态', dataIndex: 'status', key: 'status', }, { title: '面值/折扣', dataIndex: 'worth', key: 'worth', }, { title: '券有效期', dataIndex: 'indata', key: 'indata', }, { title: '核销门店', dataIndex: 'store', key: 'store', }, { title: '核销时间', dataIndex: 'time', key: 'time', }, { title: '导出时间', dataIndex: 'exportTime', key: 'exportTime', }, ]; class List extends Component { constructor(props) { super(props); } componentDidMount() { } changePage(page, pageSize) { const {data, dispatch} = this.props const {search} = data dispatch(action.noOwnerCouponSearch({...search, pageNumber: page})) } componentWillReceiveProps(nextProps) { } render() { const {data} = this.props const pagination = { current: data.pageNumber, defaultPageSize: 10, pageSize: 20, total: data.listLeg, showTotal: (total) => `当前检索共有${total}条数据`, onChange: this.changePage.bind(this) }; return ( <div> <div className={styles.handleBox2}> <Table columns={columns} dataSource={data.list} bordered pagination={pagination} rowKey={(record) => `${record.numId}_${record.couponId}`} /></div> </div> ) } } export default List <file_sep>/static-hercules/src/example/apis/getMenuList.js /** * Created by hupo * on 16/10/11. * * 获取菜单列表 * @param options */ // 基础 URL 地址, 在webpack配置中, 根据打包的环境变量加载不同的URL配置文件 默认加载 ../base/config/dev const { API_BASE_URL } = require('apiConfig'); var Fetch = require('../../base/utils/Fetch').dFireFetch; var AppUtil = require('../../base/utils/AppUtil'); var API_URL_MENUS = API_BASE_URL + '/menus/v1/list'; var getMenuList = function (options) { options.url = API_URL_MENUS; options.params = { entity_id: AppUtil.getCookie('entity_id') }; return Fetch(options); }; module.exports = getMenuList; <file_sep>/inside-boss/src/components/goodEdit/uploadImage.js import { currentUrlUploadRul, currentIMGProject } from '../../utils/env' import Cookie from '@2dfire/utils/cookie' // 'mis/temp/' || 'mis/permanent/' export default function () { const entityId = JSON.parse(Cookie.getItem('entrance')).shopInfo.entityId const bindData = { name: 'file', multiple: true, action: `${currentUrlUploadRul}/api/uploadfile`, data: { projectName: currentIMGProject, path: `${entityId}/menu` }, headers: { 'app-id': '200800', 'session-id': encodeURIComponent(JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).token), 'X-Requested-With': null, }, } return bindData }<file_sep>/inside-boss/src/components/goodsPicture/haveDropPic.js import React, {Component} from 'react' import PropTypes from 'prop-types' import {DragSource, DropTarget, DragDropContext} from 'react-dnd' import styles from './style.css' const ItemTypes = { CARD: 'card', } const cardSource = { beginDrag(props) { return { id: props.id, index: props.index, } }, } const cardTarget = { hover(props, monitor, component) { const dragIndex = monitor.getItem().index const hoverIndex = props.index // Don't replace items with themselves if (dragIndex === hoverIndex) { return } // Time to actually perform the action props.moveCard(dragIndex, hoverIndex) // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex }, } @DropTarget(ItemTypes.CARD, cardTarget, connect => ({ connectDropTarget: connect.dropTarget(), })) @DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), })) class Card extends Component { static propTypes = { connectDragSource: PropTypes.func.isRequired, connectDropTarget: PropTypes.func.isRequired, index: PropTypes.number.isRequired, isDragging: PropTypes.bool.isRequired, id: PropTypes.any.isRequired, path: PropTypes.string.isRequired, moveCard: PropTypes.func.isRequired, } render() { const { path, isDragging, connectDragSource, connectDropTarget, id } = this.props const opacity = isDragging ? 0 : 1 return connectDragSource( connectDropTarget( <li className={styles.pictureDetailListcard} style={{opacity, cursor: 'move'}}> <img src={path} className={styles.picturnDetailImg}/> </li>), ) } } export default Card <file_sep>/static-hercules/src/marketPlan/config/api.js import axios from './interception' import qs from 'qs' const API = { // 营销方案列表 getMarketList(params) { return axios({ method: 'GET', url: '/integral-api/market_scheme/v1/scheme_list', params: params }) }, // 营销方案详情 getMarketDetail(params) { return axios({ method: 'get', url: '/integral-api/market_scheme/v1/get_market_detail', params: params }) }, // 是否开通 marketIsOpen(params) { return axios({ method: 'POST', url: '/integral-api/market_scheme/v1/plans_open', data: qs.stringify(params) }) }, // 营销方案列表顶部通知栏信息 topNotificyData(params) { return axios({ method: 'GET', url: '/integral-api/market_scheme/v1/top_notification', params: params }) }, // 预览信息 previewData(params) { return axios({ method: 'GET', url: '/integral-api/market_scheme/v1/get_preview_data', params: params }) }, // 免费模板 freeUseTemplate(params){ return axios({ method: 'POST', url: '/integral-api/market_scheme/v1/open_by_present', data: qs.stringify(params) }) }, // 营销方案详情顶部通知栏信息 topNotificyMarket(params){ return axios({ method: 'GET', url: '/integral-api/market_scheme/v1/get_rule_member_count', params: params }) } } export default API;<file_sep>/inside-chain/src/tools/feed-back-auto/toast.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.hide = exports.loading = exports.warn = exports.warning = exports.success = exports.error = exports.info = undefined; var _utils = require('./utils'); var type = 'toast'; var info = (0, _utils.createShowWithLevel)(type, 'info'); var warning = (0, _utils.createShowWithLevel)(type, 'warning'); var warn = warning; var error = (0, _utils.createShowWithLevel)(type, 'error'); var success = (0, _utils.createShowWithLevel)(type, 'success'); var loading = (0, _utils.createShowWithLevel)(type, 'loading'); var hide = (0, _utils.createHide)(type); exports.info = info; exports.error = error; exports.success = success; exports.warning = warning; exports.warn = warn; exports.loading = loading; exports.hide = hide; exports.default = { info: info, error: error, success: success, warning: warning, warn: warn, loading: loading, hide: hide };<file_sep>/inside-chain/src/tools/eslint-config-2dfire-base/README.md - easy 变量检查+常用globals - index 变量检查+常用globals+es6+import+node - strict <file_sep>/inside-boss/src/container/priceTagEdit/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import * as action from '../../action' import Main from '../../components/goodTagEdit/main' class priceTagEditContainer extends Component { componentWillMount() { const { dispatch, location } = this.props const { query } = location const { id, entityId } = query dispatch(action.getModuleDetail(({param: { id: id, entityId: entityId}}))) } render() { const { data, dispatch } = this.props return <Main data={data} dispatch={dispatch} /> } } const mapStateToProps = state => ({ data: state.priceTagEdit, }) const mapDispatchToProps = dispatch => ({ dispatch }) export default connect( mapStateToProps, mapDispatchToProps )(priceTagEditContainer) <file_sep>/inside-chain/src/const/emu-joinMode.js const joinMode = { 0: '加盟', 1: '直营', 2: '合作', 3: '合营', } export default joinMode; <file_sep>/static-hercules/src/base/components/dialogs/apis/checkMobileReg.js const requester = require('base/requester'); const { API_BASE_URL } = require('apiConfig'); const API_URL = API_BASE_URL + '/users/v1/is_mobile_reg'; module.exports = function checkMobileReg ({ mobile, area_code = '+86' }) { const params = {mobile, area_code} return requester.get(API_URL, { params }); }; <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/nav/TmpPreview.js import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { Carousel } from 'antd' // debugger import style from './TmpPreview.css' export default class NavPreview extends PureComponent { static propTypes = { value: PropTypes.object, }; classicPriew = () => <img className={style.classic} src="https://assets.2dfire.com/frontend/e7806b3785ff1c78c6924f7bd581ac05.png" /> appPriew = () => { const { value } = this.props const { config } = value return ( <ul className={style.navList} > {config.nav.appItems.map((item) => <li className={style.navLi} style={createStyle(config)}> {item.defaultIcon ? <img src={item.defaultIcon} /> : <p className={style.light}></p> } </li>,)} </ul> ) } render() { const { config } = this.props.value return ( <div className={style.NavPreview}> {config.nav.mode == '经典展开式' ? this.classicPriew() : this.appPriew()} </div> ) } } function createStyle(config) { const { nav } = config const navWidth = 375 const navLiWidth = (navWidth / nav.appItems.length) - (3 * (nav.appItems.length - 1)) return { width: nav.appItems.length == 1 ? `${navWidth}px` : `${navLiWidth}px`, } } <file_sep>/inside-chain/src/const/emu-batch-select-lib.js export default { list:[ { id: '1', name: '允许' }, { id: '0', name: '不允许' } ], selfList:[ { id: '1', name: '上架' }, { id: '0', name: '下架' } ], backAuthList:[ { id: '1', name: '需要' }, { id: '0', name: '不需要' } ], mealOnlyList:[ { id: '1', name: '是' }, { id: '0', name: '否' } ], statusSelect:[ {id:'-1',name:'全部'},{id:'在线',name:'在线'},{id:'离线',name:'离线'} ], versionSelect:[ {id:'-1',name:'全部'},{id:'是',name:'是'},{id:'否',name:'否'} ], }<file_sep>/inside-boss/src/components/routeInfoImport/routeList.js import React, { Component } from 'react' import { Table, Pagination } from 'antd' import styles from './style.css' import * as action from '../../action' const columns = [ { title: '车底号', dataIndex: 'trainNo', key: 'trainNo', }, { title: '发车日期', dataIndex: 'currDate', key: 'currDate', }, { title: '车次号', dataIndex: 'trainNumber', key: 'trainNumber', }, { title: '始发站', dataIndex: 'startStation', key: 'startStation', }, { title: '始发日期', dataIndex: 'startDay', key: 'startDay', }, { title: '始发时间', dataIndex: 'startTime', key: 'startTime', }, { title: '终点站', dataIndex: 'endStation', key: 'endStation', }, { title: '到站日期', dataIndex: 'endDay', key: 'endDay', }, { title: '到站时间', dataIndex: 'endTime', key: 'endTime', }, { title: '是否过夜', dataIndex: 'stayOver', key: 'stayOver', render: (text, record) => { return record.stayOver=="1"?"是":"否"; }, } ] class RouteList extends Component{ constructor (props) { super(props) } paginationChange(pageNumber){ const t =this const { dispatch ,data} = t.props this.setState({ current: pageNumber, }); dispatch(action.setCurIndex(pageNumber)) dispatch(action.getRouteList(pageNumber)) } render(){ const t = this const { data } = t.props const total = data.routeListTotal const routelist = data.routeList const pageNumber = data.pageNumber return ( <div className={styles.wrap}> <p className={styles.headTip}>交路信息库</p> <Table dataSource={routelist} columns={columns} pagination={false} rowKey={routelist => routelist.id} bordered/> <div className={styles.paginationBox}> <Pagination className={styles.paginationHtml} showQuickJumper current={pageNumber} total={total} defaultPageSize={10} pageSize={10} onChange={this.paginationChange.bind(this)} /> <p>共{total}条记录</p> </div> </div> ) } } export default RouteList <file_sep>/inside-chain/src/views/shop/store-manage/pass/scheme/list/columns.js import Divider from '@/components/divider' import MyTag from '../../common/Tag' export default self => [ { title: '传菜方案名称', key: 'name', render( h, { row: { name, chain } } ) { return ( <div> <span style="margin-right:4px">{name}</span> {chain ? <MyTag>连锁</MyTag> : null} </div> ) } }, { title: 'IP地址', key: 'printerIp' }, { title: '商品', key: 'menuCount', render: (h, { row: { producePlanId, name, menuCount } }) => { return ( <router-link style="color:#3e76f6" to={{ path: '/store_pass/scheme/goodsManage', query: { id: producePlanId, title: name, ...self.$route.query } }} > {menuCount || '未设置'} </router-link> ) } }, { title: '区域', key: 'areaCount', render(h, { row }) { let text = '未设置' let areaVOS = row.areaVOS || [] if (row.isAllArea === 1) { text = '全部' } else if (areaVOS.length) { areaVOS = areaVOS.map(({ name }) => name) text = areaVOS.length > 2 ? areaVOS.slice(0, 2).join('、') + ` 等${areaVOS.length}个` : areaVOS.join('、') } return ( <span class="pass-scheme-columns-action"> <span onClick={self.showAreaModal(row)}>{text}</span> </span> ) } }, { title: '操作', render: (h, { row }) => { return ( <div class="pass-scheme-columns-action"> <span onClick={self.editAddSchemeModal(row)}>编辑</span> <Divider /> <span onClick={self.delScheme(row)}>删除</span> </div> ) } } ] <file_sep>/inside-chain/src/store/modules/pass/getters.js const getters = { passPublishModule: (state) => { return state.passPublishModule } } export default getters <file_sep>/inside-boss/src/container/importHistory/reducers.js import { INIT_DATA_IMPORT_HISTORY, SET_IMPORT_HISTORY_LIST, SET_IMPORT_PAGE_NUM, } from '../../constants' const importReducer = (state = {}, action) => { console.log(action) switch (action.type) { case INIT_DATA_IMPORT_HISTORY: return action.data case SET_IMPORT_HISTORY_LIST: return Object.assign({},state, {records:action.data.records, totalRecord:action.data.totalRecord}) case SET_IMPORT_PAGE_NUM: return Object.assign({},state,{pageNum:action.data}) default: return state } } export default importReducer <file_sep>/static-hercules/src/example/apis/getMenuList2.js /** * Created by hupo * on 16/10/11. * * 获取菜单列表 * @param options */ const { API_BASE_URL } = require('apiConfig'); var Fetch = require('../../base/utils/Fetch').dFireFetch; var API_URL_MENUS = API_BASE_URL + '/menus/v1/list2'; var getMenuList = function (options) { options.url = API_URL_MENUS; return Fetch(options); }; module.exports = getMenuList; <file_sep>/inside-chain/src/store/modules/setting/getters.js // 商品基本信息 export const goodsDetailFromBackBaseInfo = state => { let { kindId, kindName, label, name, id, price, memberPrice, account, buyAccount, code, isTwoAccount, discountInclude } = state.common.goods.detailFromBack return { kindId, kindName, label, name, price, memberPrice, account, buyAccount, code, isTwoAccount, id, discountInclude } } // 商品主图 export const goodsdetailFromBackHeadPicList = state => { let { headPicList } = state.common.goods.detailFromBack return headPicList } // 商品规格和做法 export const goodsDetailFromBackSpecAndPractice = state => { let { makeList, specDetailList } = state.common.goods.detailFromBack return { makeList, specDetailList } } // 商品菜肴份量 export const goodsDetailFromBackSpecWeight = state => { let { specWeightList, weight} = state.common.goods.detailFromBack return { specWeightList, weight } } // 商品收银设置 export const goodsDetailToBackCashierSet = state => { let { isRatio, isChangePrice, isBackAuth, isGive, consume } = state.common.goods.detailToBack return { isRatio, isChangePrice, isBackAuth, isGive, consume } } // 商品服务费和提成 export const goodsDetailFromBackServiceFee = state => { let { serviceFeeMode, serviceFee, deductKind, deduct } = state.common.goods.detailFromBack return { serviceFeeMode, serviceFee, deductKind, deduct } } // 商品展示设置 export const goodsDetailToBackShowSetting = state => { let { startNum, mealOnly, stepLength, isTakeout, isReserve, packingBoxName, packingBoxId, packingBoxNum} = state.common.goods.detailToBack return { startNum, mealOnly, stepLength, isTakeout, isReserve, packingBoxName, packingBoxId, packingBoxNum } } // 商品详情图和视频 export const goodsDetailFromBackMediaStream = state => { let { memo, showTop, detailPicList, video } = state.common.goods.detailFromBack return { memo, showTop, detailPicList, video } } // 商品状态 export const goodsDetailToBackGoodsState = val => { let {state} = val.common.goods.detailToBack return state } // 套餐基本信息 export const suitDetailToBackBaseInfo = state => { let {suitId, suitName, kindMenuId, memberPrice, price, suitCode, account, discountInclude} = state.common.suit.detailBaseInfoToBack return { suitId, suitName, kindMenuId: kindMenuId || '', memberPrice, price, suitCode, account: account || '', discountInclude } } // 套餐标签 export const suitDetailToBackLabel = state => { let {acridLevel, recommendLevel, specialTagId} = state.common.suit.detailBaseInfoToBack return { acridLevel, recommendLevel, specialTagId } } // 套餐主图 export const suitDetailToBackMainImg = state => { let {mainPicture} = state.common.suit.detailBaseInfoToBack return mainPicture } // 编辑时候来自后端的默认图片 export const suitDetailToBackDetailImg = state => { let {detailImgList} = state.common.suit.detailBaseInfoToBack return detailImgList } // 套餐详情图和视频 export const suitDetailToBackDetailAndVideo = state => { let {detail, showTop, detailImgList, video} = state.common.suit.detailBaseInfoToBack return { detail, showTop, detailImgList, video } } // 套餐收银设置 export const suitDetailToBackCashierSet = state => { let {isChangePrice, isAllowDiscount, isBackAuth} = state.common.suit.detailBaseInfoToBack return { isChangePrice, isAllowDiscount, isBackAuth } } // 套餐展示设置 export const suitDetailToBackShowSet = state => { let {startNum, isTakeout, isReserve} = state.common.suit.detailBaseInfoToBack return { startNum, isTakeout, isReserve } } // 套餐状态设置 export const suitDetailToBackStateSet = state => { let {status} = state.common.suit.detailBaseInfoToBack return {status} } <file_sep>/inside-boss/src/container/visualConfig/utils/format.js import { isObject, isArray, isUndefined } from './lang' /* 按照 definition 对 data 进行格式化。 为了保险,data 里出现的未定义的字段不会被删除。 definition 格式: { // key: defaultValue normalItem: 123, // value 是 plain object 时会递归深入匹配。object 里还可以再嵌套 object objectItem: { ... }, // value 是数组,且里面各 item 是 plain object 时, // 会把第一个 item 作为新 item 的默认值,后续 item 作为组件添加进来时默认带的 items arrayObjectItem: [{ ... }, { ... }], // value 是数组但里面不是 plain object 时,会把数组整体作为 default value arrayBaseItem: ['a', 'b'] } 例如: { mode: '大图', // normal item orderButton: { // object item mode: '立即下单', orderStyle: '1', cartStyle: '1', }, showFields: ['名称', '价格', '下单按钮'], // normal array item goodsList: [ // array object item { linkType: 'goods', linkGoodsId: '', linkPage: '', }, ] } */ export default function format(definition, data) { if (!definition) return data // 避免直接修改 data data = { ...data } Object.keys(definition).forEach(key => { const defineValue = definition[key] const dataValue = data[key] if (isObject(defineValue)) { data[key] = format(defineValue, dataValue || {}) } else if (isArray(defineValue) && defineValue.length && isObject(defineValue[0])) { const baseItem = defineValue[0] const defaultItems = defineValue.slice(1) data[key] = (dataValue || defaultItems).map(item => format(baseItem, item)) } else if (isUndefined(dataValue)) { data[key] = defineValue } }) return data } // ============== 测试代码 ========================= /* var isUndefined = value => typeof value === 'undefined' var isArray = value => Object.prototype.toString.call(value) === '[object Array]' var isObject = value => Object.prototype.toString.call(value) === '[object Object]' var def = { normal: 'normal_value', obj: { k1: 'v1', k2: 2, }, arr: ['v1', 'v2', 'v3'], arrObj: [ { k1: true, k2: -100, }, { k1: false, k2: 1 }, { k1: true, k2: 2 }, { k1: false, k2: 3 }, ], nest: { subObj: { k1: 'kvalue1', arr: [ { key1: 'arr-obj-k1', sub: { key1: [1,2,3], key2: 'hello' } } ] }, subArr: ['1', 2, 3] } } var v1 = format(def) var v2 = format(def, { other: 1, normal: 'xxx' }) var v3 = format(def, { normal: 'xxx', obj: { k2: 200 } }) var v4 = format(def, { normal: 'xxx', arr: [1] }) var v5 = format(def, { arrObj: [ {}, { k1: false }, { k1: false, k2: 0 }, ] }) var v6 = format(def, { arrObj: [] }) var v7 = format(def, { nest: { subObj: { k1: 'v2', arr: [ {}, { sub: {} }, { sub: { key1: 10 } } ] } } }) */ <file_sep>/inside-chain/src/config/api_setting.js import {API_BASE_URL} from "apiConfig" import Requester from '@/base/requester' import {GW} from '@2dfire/gw-params' const AND = '&' + GW + '&' /** * 获取开店设置/商品和套餐/ 品牌列表 * @returns {*|V} */ export const apiGetBrandList = () => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IPlateBossPcService.getAllPlateByBrand" + AND, { params: {} } ) } /** * 商品获取下拉框内容 */ export const apiGetSelectList = (opEntityId, plateEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.getInitItem" + AND, { params: { opEntityId, initItemReq: JSON.stringify({ plateEntityId }) } } ) } /** * 获取商品/套餐分类列表 * @param isInclude -1-全部 0-商品 1-套餐 * @param plateEntityId * @param opEntityId * @returns {*|V} */ export const apiGetCategory = (isInclude, plateEntityId, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IKindMenuService.kindMenuTreeSelect" + AND, { params: { isInclude, plateEntityId, opEntityId } } ) } /** * 修改商品分类 * @param plateEntityId * @param kindId * @param idList * @param opEntityId * @returns {*|V} */ export const apiChangeGoodsCategory = (plateEntityId, kindId, idList, opEntityId) => { let strIds = JSON.stringify(idList) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.changeItemCategory" + AND, { params: { changeItemCategoryReq: JSON.stringify({ plateEntityId, kindId, idList: strIds }), opEntityId } } ) } /** * 删除商品 * @param plateEntityId 品牌id * @param idList 商品id 数组 * @param opEntityId 单店时候从url的entityId里面取 * @returns {*|V} */ export const apiDeleteGoods = (plateEntityId, idList, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.removeItem" + AND, { params: { removeItemReq: JSON.stringify({ plateEntityId, idList }), opEntityId } } ) } /** * 获取商品列表 * @param opEntityId 单店时候从cookie里面取 * @param kindId * @param keyWord 搜索框内容 * @param pageNum 第几页 * @param pageSize 每页数量 * @param plateEntityId 品牌id * @returns {*|V} */ export const apiFilterGoodsList = (plateEntityId, kindId, keyWord = '', pageNum = 1, pageSize = 20, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.listItem" + AND, { params: { opEntityId, listItemReq: JSON.stringify({ kindId, keyWord, pageNum, pageSize, plateEntityId }) } } ) } /** * 新增商品 * @param opEntityId * @param id * @param kindId * @param label * @param name * @param price * @param memberPrice * @param buyAccount * @param account * @param accountId * @param isTwoAccount * @param code * @param headPicList * @param specDetailList * @param makeList * @param weight * @param specWeightList * @param isRatio * @param isChangePrice * @param isBackAuth * @param isGive * @param consume * @param serviceFeeMode * @param serviceFee * @param deductKind * @param deduct * @param startNum * @param mealOnly * @param stepLength * @param isReserve * @param isTakeout * @param packingBoxId * @param packingBoxNum * @param memo * @param showTop * @param detailPicList * @param state * @param plateEntityId * @returns {V|*} */ export const apiAddGoodsItem = (opEntityId, id, kindId, label = {}, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList = [], specDetailList = [], makeList = [], weight, specWeightList = [], isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList = [], state, plateEntityId, discountInclude) => { return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.addItem" + AND, { opEntityId, addOrModifyItemReq: JSON.stringify({ opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude }) }, {emulateJSON: true} ) } /** * 修改商品 * @param opEntityId * @param id * @param kindId * @param label * @param name * @param price * @param memberPrice * @param buyAccount * @param account * @param accountId * @param isTwoAccount * @param code * @param headPicList * @param specDetailList * @param makeList * @param weight * @param specWeightList * @param isRatio * @param isChangePrice * @param isBackAuth * @param isGive * @param consume * @param serviceFeeMode * @param serviceFee * @param deductKind * @param deduct * @param startNum * @param mealOnly * @param stepLength * @param isReserve * @param isTakeout * @param packingBoxId * @param packingBoxNum * @param memo * @param showTop * @param detailPicList * @param state * @param plateEntityId * @returns {V|*} */ export const apiModifyGoodsItem = (opEntityId, id, kindId, label = {}, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList = [], specDetailList = [], makeList = [], weight, specWeightList = [], isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList = [], state, plateEntityId, discountInclude) => { return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.modifyItem" + AND, { opEntityId, addOrModifyItemReq: JSON.stringify({ opEntityId, id, kindId, label, name, price, memberPrice, buyAccount, buyAccountId, account, accountId, isTwoAccount, code, headPicList, specDetailList, makeList, weight, specWeightList, isRatio, isChangePrice, isBackAuth, isGive, consume, serviceFeeMode, serviceFee, deductKind, deduct, startNum, mealOnly, stepLength, isReserve, isTakeout, packingBoxId, packingBoxNum, memo, showTop, detailPicList, state, plateEntityId, discountInclude }) }, {emulateJSON: true} ) } /** * 获取商品打包盒列表 * @param opEntityId * @param plateEntityId * @returns {*|V} */ export const apiGetPackageList = (opEntityId, plateEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.listPackingBox" + AND, { params: { opEntityId, listPackingBoxReq: JSON.stringify({plateEntityId}) } } ) } /** * 获取商品标签列表 * @param opEntityId * @param plateEntityId * @returns {*|V} */ export const apiGetGoodsLabelList = (opEntityId, plateEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.detailLabel" + AND, { params: { opEntityId, detailLabelReq: JSON.stringify({plateEntityId}) } } ) } /** * 获取规格列表 * @returns {*|V} */ export const apiGetSpecList = () => { return Requester.get( API_BASE_URL + "http://zmfile.2dfire-daily.com/zmfile/imageUpload" + AND, { params: {} } ) } /** * 获取商品详请 * @param itemId * @param plateEntityId * @param opEntityId * @returns {*|V} */ export const apiGetGoodsDetail = (itemId, plateEntityId, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.detailItem" + AND, { params: { detailItemReq: JSON.stringify({ itemId, plateEntityId }), opEntityId } } ) } /** * 修改套餐分类 * @param kindId * @param suitIdList * @param opEntityId * @returns {*|V} */ export const apiChangeSuitCateGory = (kindId, suitIdList, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IKindMenuService.updateGoodsOrSuitKind" + AND, { params: { kindId, suitIdList: JSON.stringify(suitIdList), opEntityId } } ) } /** * 修改套餐标签 * @param opEntityId * @param suitId * @param acridLevel * @param recommendLevel * @param specialTagId * @param plateEntityId * @returns {*|V} */ export const apiChangeSuitLabel = (opEntityId, suitId, acridLevel, recommendLevel, specialTagId, plateEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.ISuitService.updateSuitTag" + AND, { params: { opEntityId, suitId, acridLevel, recommendLevel, specialTagId, plateEntityId } } ) } /** * 删除套餐 * @param opEntityId * @param suitId * @param plateEntityId * @returns {*|V} */ export const apiDeleteSuit = (opEntityId, suitId, plateEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.ISuitService.deleteSuit" + AND, { params: { opEntityId, suitId, plateEntityId } } ) } /** * 筛选套餐列表 * @param opEntityId * @param plateEntityId * @param keyWord * @param kindId * @param pageIndex * @param pageSize * @returns {*|V} */ export const apiFilterSuit = (opEntityId, plateEntityId, keyWord, kindId, pageIndex, pageSize) => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.ISuitService.getSuitList" + AND, { params: { opEntityId, plateEntityId, kindId, keyWord, pageIndex, pageSize } } ) } /** * 获取套餐标签 * @param suitId * @returns {*|V} */ export const apiGetSuitLabel = (suitId) => { return Requester.get( API_BASE_URL + "http://zmfile.2dfire-daily.com/zmfile/imageUpload" + AND, { params: { suitId: '' } } ) } /** * 获取点餐单位下拉选项框列表 * @returns {V|*} */ export const apiGetOrderUnit = () => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IUnitService.getUnitListWithoutConversion" + AND, { params: {} } ) } /** * 获取套餐的标签列表 * @param opEntityId * @returns {*|V} */ export const apiGetSuitLabelList = (opEntityId) => { return Requester.get( API_BASE_URL + 'com.dfire.boss.center.centerpc.item.service.ISuitService.getLabelConf' + AND, { params: { opEntityId } } ) } /** * 获取套餐内的商品 * @param plateEntityId * @param kindId * @param keyWord * @param pageNum * @param pageSize * @param opEntityId * @returns {*|V} */ export const apiGetSuitGoods = (plateEntityId, kindId, keyWord = '', pageNum = 1, pageSize = 20, opEntityId) => { return Requester.get( API_BASE_URL + "com.dfire.boss.center.centerpc.item.service.IItemService.listItemForSuit" + AND, { params: { opEntityId, listItemReq: JSON.stringify({ kindId, keyWord, pageNum, pageSize, plateEntityId }) } } ) } /** * 获取商品/套餐的菜单列表 * @param itemId * @param plateEntityId */ export const apiGetBelongsMenuList = (itemId, plateEntityId) => { return Requester.get( API_BASE_URL + 'com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.listChainMenu' + AND, { params: { listChainMenuReq: JSON.stringify({ itemId, plateEntityId }) } } ) } /** * 获取商品/套餐门店列表 * @param itemId * @param plateEntityId */ export const apiGetBelongsShopList = (itemId, plateEntityId) => { return Requester.get( API_BASE_URL + 'com.dfire.boss.center.centerpc.chainmenu.service.IChainMenuClientService.listIssueShop' + AND, { params: { listIssueShopReq: JSON.stringify({ itemId, plateEntityId }) } } ) } /** * 获取套餐详情的的基本信息(第一步) * @param opEntityId * @param suitId */ export const apiGetSuitBaseInfo = (opEntityId, suitId) => { return Requester.get( API_BASE_URL + 'com.dfire.boss.center.pc.ISuitService.getSuitDetail' + AND, { params: { opEntityId, suitId } } ) } /** * 获取套餐分组详情 * @param opEntityId * @param suitId */ export const apiGetSuitItems = (opEntityId, suitId) => { return Requester.get( API_BASE_URL + 'com.dfire.boss.center.pc.ISuitService.getSuitItems' + AND, { params: { opEntityId, suitId } } ) } /** * 保存套餐基本信息(第一步) * @param suitId * @param suitName * @param account * @param accountId * @param kindMenuId * @param memberPrice * @param price * @param suitCode * @param acridLevel * @param recommendLevel * @param specialTagId * @param status * @param mainPicture * @param detail * @param detailImgList * @param isChangePrice * @param isAllowDiscount * @param isBackAuth * @param startNum * @param isTakeout * @param isReserve * @param discountInclude * @param opEntityId * @param plateEntityId */ export const apiSaveSuitBaseInfo = (suitId, suitName, account, accountId, kindMenuId, memberPrice, price, suitCode, acridLevel, recommendLevel, specialTagId, status, mainPicture = [], detail, detailImgList = [], isChangePrice, isAllowDiscount, isBackAuth, startNum, isTakeout, isReserve, discountInclude, opEntityId, plateEntityId) => { return Requester.post( API_BASE_URL + 'com.dfire.boss.center.pc.ISuitService.saveSuit' + AND, { suitId, suitName: suitName.trim(), account, accountId, kindMenuId, memberPrice, price, suitCode, acridLevel, recommendLevel, specialTagId, status, mainPicture: JSON.stringify(mainPicture), detail, detailImgList: JSON.stringify(detailImgList), isChangePrice, isAllowDiscount, isBackAuth, startNum, isTakeout, isReserve, discountInclude, opEntityId, plateEntityId }, {emulateJSON: true} ) } /** * 保存套餐信息第二步 * @param opEntityId * @param suitId * @param groupList */ export const apiSaveSuitItems = (opEntityId, suitId, groupList) => { return Requester.post( API_BASE_URL + 'com.dfire.boss.center.pc.ISuitService.saveSuitItems' + AND, { opEntityId, suitId, groupList: JSON.stringify(groupList) }, {emulateJSON: true} ) } <file_sep>/static-hercules/src/base/config/daily.js module.exports = { NEW_API_BASE_URL: '../../api', API_BASE_URL: '../../api', SHARE_BASE_URL: 'http://api.l.whereask.com', BOSS_API_URL: 'http://api.2dfire-daily.com/boss-api', DD_API_URL: 'http://yardcontent.2dfire-daily.com', APP_ID: 'dingoahg6mgrhmetpi569j', IMAGE_BASE_URL: 'http://ifiletest.2dfire.com/', API_WEB_SOCKET: 'http://10.1.5.114:9003/web_socket', // 网关 GATEWAY_BASE_URL: 'http://gateway.2dfire-daily.com', // 供应链 SUPPLY_CHAIN_API: 'http://10.1.25.211:8080/supplychain-api', ENV: 'daily', APP_KEY: '200800', REPORT_URL: 'http://d.2dfire-daily.com/pandora/#/', WEBSOCKET_URL: 'http://10.1.5.114:9003', // 接入易观方舟数据埋点系统相关 ANALYSYS_APPKEY: '27e0923002b01e08', ANALYSYS_DEBUG_MODE: 2, ANALYSYS_UPLOAD_URL: 'https://ark.2dfire-daily.com' }; <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/goodsList/TmpEditor.js import React from 'react'; import { Radio, Checkbox, message } from 'antd'; import visualApi from '@src/api/visualConfigApi' import ImgUpload from '@src/container/visualConfig/views/design/common/imgUpload' import GoogsSelect from '@src/container/visualConfig/views/design/common/googsSelect' import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor'; import cx from 'classnames' import style from './TmpEditor.css' import constants from '@src/container/visualConfig/views/design/common/constants' const RadioGroup = Radio.Group; const maxGood = { '大图': 6, '详细列表': 10, '双列小图': 10, } export default class GoodsEditor extends DesignEditor { state = { showFields: ['名称', '价格','下单按钮'], superscriptList: ['新品', '热卖', 'NEW', 'HOT', '自定义'], defaultImg:'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png', isShowImgUpload: false, imgUrl: '', isShowGoods: false, data: [], imgList: [], img: 'http://assets.2dfire.com/frontend/fad1279df20c0a5371eee760e5a47d57.png' } componentDidMount() { this.init() } init = () => { const { value } = this.props; const { config } = value const { mode } = value.config let newGoodsList = Array.from(config.goodsList) if(!newGoodsList.length) return false if(mode == '大图'){ if(newGoodsList.length > 6) { newGoodsList = newGoodsList.splice(0, 6) } } this.getSpecifyRetailGoodsList(newGoodsList) } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } changeGroup = (str, e) => { const { value } = this.props; const { config } = value let target = e.target.value const orderButton = Object.assign({}, config.orderButton) orderButton[str] = target this.configChang({orderButton}) } _selectType = (e) => { // 样式选择 this.configChang({mode: e.target.value}) } _checkboxChange = (item, e) => { // 多选框 ['名称', '价格', '下单按钮'] 事件 const { value } = this.props; const { config } = value let showFields = [...config.showFields] if(e.target.checked) { // 选中 showFields.push(item) } else { showFields = showFields.filter(v => v != item) } this.configChang({showFields}) } _superscriptCheckbox = (e) => { // 角标 const { value } = this.props; const { config } = value let showFields = [...config.showFields] if(e.target.checked) { // 选中 showFields.push('角标') } else { showFields = showFields.filter( v => v!= '角标' ) } this.configChang({showFields}) } _superscriptTypeChange = (e) => { // 角标类型选择 let target = e.target.value let subscript = { type: 'text', text: '新品', image: null, } if (target == '自定义') { subscript.type = 'image' } subscript.text = target this.configChang({subscript}) } close = () => { this.setState({ isShowImgUpload: false, isShowGoods: false, }) } _getImg = (data) => { // 获取角标图片 let subscript = { type: 'image', text: '自定义', image: null, } subscript.image = data this.configChang({subscript}) this.setState({ imgUrl: data }) } closeItem = (index) => { // 删除商品 const { value } = this.props; const { config } = value let goodsList = [...config.goodsList] goodsList.splice(index, 1) let imgList = [...this.state.imgList] imgList.splice(index, 1) this.setState({ imgList }) this.configChang({goodsList}) } getGoodsItem = (data) => { // 商品选择 const { value } = this.props; const { config } = value const length = data.length let goodsList = [...config.goodsList] if(this._maxGoodItem(length)) { for (let i = 0; i < length; i++) { goodsList.push(data[i].itemId) } this.getSpecifyRetailGoodsList(goodsList) this.configChang({goodsList}) } } _maxGoodItem = (len) => { const { value } = this.props; const { config } = value const goodsListLen = config.goodsList.length if(Number(goodsListLen + len) > maxGood[config.mode]) { message.info(`${config.mode}最多添加${maxGood[config.mode]}个商品`); return false } return true } _onChangGoods = () => { this.setState({ isShowGoods: true }) } onChangeBtn = () => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload }) } getSpecifyRetailGoodsList = (idList) => { // 图片列表 let imgArr = [] visualApi.getSpecifyRetailGoodsList({ idList }).then( res=>{ for(let i = 0; i< res.data.length; i++){ if(!res.data[i].imagePath){ imgArr.push(this.img) }else{ imgArr.push(res.data[i].imagePath) } } this.setState({ imgList: imgArr }) }, err=>{ console.log('err', err) } ) } render(){ const { value, prefix } = this.props; const { superscriptList, defaultImg, isShowImgUpload, imgUrl, isShowGoods, showFields, imgList } = this.state const { config } = value const { mode, orderButton, subscript } = value.config let isShopButton = config.showFields.indexOf('下单按钮') > -1 // 是否显示商品按钮 let isShowSuperscript = config.showFields.indexOf('角标') > -1 // 角标是否显示 return ( <div className={`${prefix}-design-component-config-editor`}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <GoogsSelect getGoodsItem={this.getGoodsItem} isShowGoods={isShowGoods} close={this.close} /> <div className={style.componentGoodsEditor}> <ControlGroup label="样式选择:" className={style.groupLabel} > </ControlGroup> <RadioGroup value={mode} className={style.controlGroupControl} onChange={(e) => this._selectType(e)}> <Radio name="mode" value='大图' className={style.radio}>大图</Radio> <Radio name="mode" value='详细列表' className={style.radio}>详细列表</Radio> <Radio name="mode" value='双列小图' className={style.radio}>双列小图</Radio> {/* <Radio name="imgType" value='transverse'>横向滑动</Radio> */} </RadioGroup> </div> <div className={style.componentGoodsEditor}> <ControlGroup label="商品选择:" className={style.groupLabel} > </ControlGroup> <div className={style.shopImgList}> {imgList.map((item, index) => <div className={style.shopImgUl}> <div className={cx(style.imgItem, 'desigeCove')} style={{backgroundImage:`url(${item || constants.defaultGoodsImg})`}}></div> <img className={style.closeBtn} src="https://assets.2dfire.com/frontend/73a3ec09ff1b5814aea734d1e7e226cb.png" onClick={() => this.closeItem(index)} /> </div> )} <img onClick={this._onChangGoods} className={style.goodsBtn} src={defaultImg}></img> </div> </div> <div className={style.componentGoodsEditor}> <ControlGroup label="显示内容:" className={style.groupLabel} > </ControlGroup> <div className={style.showContent}> {showFields.map((item) => <Checkbox defaultChecked={true} className={style.rankEditorCheckbox} onChange={(e) => this._checkboxChange(item, e)}>{item}</Checkbox> )} {isShopButton && <div> <RadioGroup value={orderButton.mode} className={style.controlGroupControl} onChange={(e) => this.changeGroup('mode', e)}> <Radio name="mode" value='立即下单'>立即下单</Radio> <Radio name="mode" value='加入购物车'>加入购物车</Radio> </RadioGroup> {orderButton.mode == '立即下单' ? <RadioGroup value={orderButton.orderStyle} className={style.controlGroupControl} onChange={(e) => this.changeGroup('orderStyle', e)}> <Radio name="orderStyle" value='1'>样式一</Radio> <Radio name="orderStyle" value='2'>样式二</Radio> </RadioGroup> : <RadioGroup value={orderButton.cartStyle} className={style.controlGroupControl} onChange={(e) => this.changeGroup('cartStyle', e)}> <Radio name="cartStyle" value='1'>样式一</Radio> <Radio name="cartStyle" value='2'>样式二</Radio> <Radio name="cartStyle" value='3'>样式三</Radio> </RadioGroup>} </div>} <Checkbox defaultChecked={isShowSuperscript} className={style.rankEditorCheckbox} onChange={this._superscriptCheckbox}>角标</Checkbox> {isShowSuperscript && <RadioGroup value={subscript.text} className={style.controlGroupControl} onChange={this._superscriptTypeChange}> {superscriptList.map((item) => <Radio className={style.rankRadio} name="superscript" value={item}>{item}</Radio> )} {subscript.text == '自定义' && <div className={style.uploadInfo}> <img onClick={this.onChangeBtn} className={style.uploadBtn} src={imgUrl ? imgUrl: defaultImg}></img> <p className={style.uploadTip}>建议尺寸80X30px</p> </div> } </RadioGroup> } </div> </div> </div> ) } static designType = 'goodsList'; static designDescription = '商品列表'; static designTemplateType = '基础类'; static getInitialValue() { return { config: { type: 'goodsList', mode: '大图', // 可选值:大图、详细列表、双列小图、横向滑动 showFields: ['名称', '价格', '下单按钮'],// 可使用值:名称、价格、下单按钮、角标 / 可以为空数组,商品主图是固定显示的 / 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) goodsList: [], // 选中的商品列表,最少1个,最多:大图6个、详细列表10个、双列小图10个、横向滑动6个 orderButton: { // 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) mode: '立即下单', // 可选值:立即下单、加入购物车 orderStyle: '1', // 立即下单按钮样式。可选值:'1'、'2'。仅在 mode=立即下单 时生效 cartStyle: '1', // 加入购物车按钮样式。可选值:'1'、'2'、'3'。仅在 mode=加入购物车 时生效 }, subscript: { // 角标设置(仅在 showFields 里有 '下单按钮' 时生效) type: 'text', // 角标类型。可选值:text、image text: '新品', // 可选值:新品、热卖、NEW、HOT。仅在 type=text 时生效 image: null, // image URL。在 type=image 时有效且必填 }, } }; } } <file_sep>/inside-chain/src/tools/feed-back-auto/share-mask.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.name = exports.hide = exports.show = undefined; var _utils = require('./utils'); var name = 'share-mask'; var show = (0, _utils.createShow)(name); var hide = (0, _utils.createHide)(name); exports.show = show; exports.hide = hide; exports.name = name; exports.default = { show: show, hide: hide, name: name };<file_sep>/inside-boss/src/index.js /* eslint-disable */ import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { Router, hashHistory } from 'react-router' import store from './store' import createRoutes from './routes' import App from './container/rootContainer' import './global.css' const rootRoute = { component: App, childRoutes: createRoutes(store), // onEnter( // { // location: { pathname } // }, // replace // ) { // if (!['/welcome', '/'].includes(pathname)) { // replace('/welcome') // } // } } render( <Provider store={store}> <Router history={hashHistory} routes={rootRoute} /> </Provider>, document.getElementById('root') ) <file_sep>/inside-boss/src/container/visualConfig/utils/lang.js export const isUndefined = value => typeof value === 'undefined' export const isNull = value => Object.prototype.toString.call(value) === '[object Null]' export const isNumber = value => Object.prototype.toString.call(value) === '[object Number]' export const isString = value => Object.prototype.toString.call(value) === '[object String]' export const isFunction = value => Object.prototype.toString.call(value) === '[object Function]' export const isArray = value => Object.prototype.toString.call(value) === '[object Array]' export const isArrayAndEmpty = value => isArray(value) && value.length === 0 export const isObject = value => Object.prototype.toString.call(value) === '[object Object]' export const isObjectAndEmpty = value => isObject(value) && Object.keys(value).length === 0 /** * 返回第一个符合要求的元素的 index,若没有,返回 -1 */ export function indexOf(array, condition) { for (let i = 0; i < array.length; i += 1) { if (condition(array[i])) return i } return -1 } /** * 返回最后一个符合要求的元素的 index,若没有,返回 -1 */ export function lastIndexOf(array, condition) { for (let i = array.length - 1; i > -1; i -= 1) { if (condition(array[i])) return i } return -1 } /** * 返回数组中有多少个元素符合要求 */ export function count(array, condition) { return array.filter(condition).length } /** * 返回 iterator 的第一个元素 * - iterator 可以是数组、Map、Set... * - 若指定了 filter,则返回第一个符合要求的元素 * - iterator 为空或没有符合要求的元素时,返回 defaultValue */ export function first(iterator, filter = () => true, defaultValue = undefined) { for (const value of iterator) { if (filter(value)) return value } return defaultValue } /** * 把 object 中的指定 key 提取成新对象 */ export function pick(obj, ...keys) { const result = {} keys.forEach(key => { if (obj && key in obj) result[key] = obj[key] }) return result } /** * 排除指定 keys,返回新对象 */ export function omit(obj, ...keys) { const result = { ...obj } keys.forEach(key => delete result[key]) return result } /** * 生成 min、max 之间的随机整数(包含 min 和 max) * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive */ export function randint(min, max) { min = Math.ceil(min) max = Math.floor(max) return Math.floor(Math.random() * (max - min + 1)) + min } /** * 生成指定长度的随机字符串 */ export function randstr(len = 16, seed = null) { if (!seed) seed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'.split('') let result = '' while (result.length < len) { const letterIdx = randint(0, seed.length - 1) result += seed[letterIdx] } return result } /** * 生成一个 mirror object * mirror(['a', 'b', 'c']) => { a: 'a', b: 'b', c: 'c' } * mirror('prefix/', ['a', 'b', 'c']) => { a: 'prefix/a', b: 'prefix/b', c: 'prefix/c' } */ export function mirror(prefix, keys) { if (!keys) { keys = prefix prefix = null } return arr2obj(keys, key => [key, prefix ? prefix + key : key]) } /** * 把一个数组转换成 object * callback: item => [key, value] */ export function arr2obj(array, callback) { const obj = {} array.forEach((item, i) => { const [key, value] = callback(item, i) obj[key] = value }) return obj } /** * 判断 value 是否与 compares 的其中某个值全等 */ export function oneOf(value, ...compares) { for (let i = 0; i < compares.length; i += 1) { if (value === compares[i]) return true } return false } <file_sep>/static-hercules/src/base/utils/Fetch.js /** * Created by hupo * on 16/10/11. * * node依赖 : whatwg_fetch fetch polyfill 库, 用于发送 fetch/ajax 请求 (https://github.com/github/fetch) * * option = { * url: "", (必选) * type: "get", * success: callback, (必选) * error: callback, * isShowLoading: true, 加载动画/统计相关 isShowLoading true/静默调用 false 不调用 * params: {}, 请求参数 json格式 * data: {}, post 请求的 data json格式 * beforeSend: callback, * contentType: "", Content-Type * noCookie: false, Sending cookies 默认发送cookie 只有当 options.noCookie == true 时,可以不发送cookie * timeout: "15000" node-fetch 特性 不确定是否生效 待测试 * } * * 返回 promise 对象 */ import 'whatwg-fetch' var AppUtil = require('./AppUtil'); var DfFetch = function (options) { var self = this; self.url = ""; self.method = "get"; self.timeout = 15000; self.config = { mode: 'cors', cache: 'default' }; self.success = undefined; self.error = undefined; self.isShowLoading = true; self.beforeSend = undefined; self.init = function (options) { if (typeof options !== "object") { throw new Error("options must's object"); } self.url = options.url; self.success = options.success; self.error = options.error; self.url = AppUtil.paramsFormat(self.url, options.params); if (options.type != undefined) { self.method = options.type; self.config.method = self.method } if (options.contentType) { var headers = new Headers(); headers.append("Content-Type", options.contentType); self.config['headers'] = headers; } if (!AppUtil.isEmpty(options.data)) { if (self.method == "get") { throw new Error("get method can't send data, please use post method"); } self.config['body'] = JSON.stringify(options.data); } if (!options.noCookie) { self.config['credentials'] = "include"; } if (options.timeout !== undefined) { self.timeout = options.timeout; } if (options.showLoading !== undefined) { self.isShowLoading = options.showLoading; } }; self.init(options); self.checkStatus = function (response) { if (response.status >= 200 && response.status < 300) { return response.json() } else { var error = new Error(response.statusText); error.response = response; throw error } }; self.successHandler = function (response) { var code = parseInt(response.code); if (response.code == 2001) { window.location.href = "../page/blacklist.html?t=grunt_page_time"; return false; } if (code == -1 || response.code == undefined) { if (self.isShowLoading !== false) { console.log("show loading") } if (self.error) { var resp = { msg: "接口返回错误", data: response }; self.error(resp); } } else { if (self.success) { if (!response.data) { response.data = {}; } self.success(response); } } }; self.errorHandler = function (response) { if (self.isShowLoading) { console.log("show loading") } if (self.error) { var resp = { msg: response }; self.error(resp); } }; self.fetch = function () { if (self.isShowLoading) { console.log("show loading") } if (self.beforeSend) { self.beforeSend(); } return fetch(self.url, self.config) .then(self.checkStatus) .then(self.successHandler) .catch(self.errorHandler); }; }; var dFireFetch = function (options) { options.params['token'] = AppUtil.getCookie("token"); var dfFetch = new DfFetch(options); return dfFetch.fetch() }; module.exports = { DfFetch: DfFetch, // 类 dFireFetch: dFireFetch // 实例 }; <file_sep>/static-hercules/src/alipay-agent/constant/index.js export const introduceList = [ { imageUrl: 'https://assets.2dfire.com/frontend/8a461226a20765fc7b096d9ec7d5b4c4.png', title: '实时到账', content: '已开通支付宝特约的商家由此入' }, { imageUrl: 'https://assets.2dfire.com/frontend/2822d3a8a4949a0723eb960e6d058f7e.png', title: '极速开通', content: '最快5分钟即可审核完成,无需漫长等待。' }, { imageUrl: 'https://assets.2dfire.com/frontend/db64132e7247fa497998092e3bb778a2.png', title: '超低门槛', content: '无需营业执照也可以开通支付宝直连。' }, { imageUrl: 'https://assets.2dfire.com/frontend/544eefbf67fc7ef9b8cdc2f31d09cefb.png', title: '超低费率', content: '开通支付宝直连后可申请参与蓝海计划,费率最低可达0.2%。' } ] <file_sep>/inside-boss/src/container/visualConfig/utils/biz.js import * as bridge from '@src/utils/bridge' export function getEntityId() { const { entityId } = bridge.getInfoAsQuery() return entityId } <file_sep>/static-hercules/src/base/utils/touch.js let startY = 0; let startX = 0; let up, down, left, right; let touch = { watchHorizontal(l, r) { // 水平检测 left = left; right = right; // PC端兼容 document.addEventListener("mousedown", this.startH, false); document.addEventListener("mousemove", this.move, false); document.addEventListener("mouseup", this.endH, false); // 移动端的处理 document.addEventListener('touchstart', this.startH, false); document.addEventListener('touchmove', this.move, false); document.addEventListener('touchend', this.endH, false); }, watchVertical(u, d) { // 垂直检测 up = u; down = d; // PC端兼容 document.addEventListener("mousedown", this.startV, false); document.addEventListener("mousemove", this.move, false); document.addEventListener("mouseup", this.endV, false); // 移动端的处理 document.addEventListener('touchstart', this.startV, false); document.addEventListener('touchmove', this.move, false); document.addEventListener('touchend', this.endV, false); }, move(e){ e.preventDefault(); }, startH(e) { if (e.changedTouches) { let x = e.changedTouches[0].screenX; startX = x; } }, endH(e) { if (e.changedTouches) { let x = e.changedTouches[0].screenX; if (x - startX > 10) { //往左拉 left(); } else if (x - startX < -10) { //往右拉 right(); } } }, startV(e) { if (e.changedTouches) { let y = e.changedTouches[0].screenY; startY = y; } }, endV(e) { if (e.changedTouches) { let y = e.changedTouches[0].screenY; if (y - startY > 10) { //往下拉 down(); } else if (y - startY < -10) { //往上拉 up(); } } } } module.exports = touch;<file_sep>/static-hercules/src/alipay-agent/libs/tools.js import sessionStorage from '@2dfire/utils/sessionStorage' export default { // 将对象转换为接口需要的参数对象 MerchantInfoToParam(merchantInfo) { const { alipayAccount, linkman, mobile, email, industryType, licensePhoto, licenseNo, isLongValid, startTime, endTime, shopPhoto } = merchantInfo let paymentAuthInfo = { entityId: sessionStorage.getItem('entityId') || '', alipayAccount, linkman, mobile, email, industryType: industryType === '餐饮' ? 'FOOD' : 'RETAIL', licensePhoto, licenseNo, isLongValid, startTime: startTime ? startTime : '', endTime: endTime ? endTime : '', shopPhoto } return paymentAuthInfo }, // 将接口返回的对象参数转换为merchantInfo对象 paramToMerchantInfo(data) { const { alipayAccount, linkman, mobile, email, industryType, licensePhoto, licenseNo, isLongValid, startTime, endTime, shopPhoto } = data let merchantInfo = { alipayAccount, linkman, mobile, email, industryType: industryType === 'FOOD' ? '餐饮' : '零售', licensePhoto, licenseNo, isLongValid, startTime: startTime ? startTime : '', endTime: endTime ? endTime : '', shopPhoto } return merchantInfo } } <file_sep>/static-hercules/src/alipay-agent/main.js var Vue = require('vue') var VueRouter = require('vue-router') var vueResource = require('vue-resource') var App = require('./App.vue') var Scss = require('./scss/index.scss') var InfoInput = require('./components/info-input.vue') var InfoPhoto = require('./components/info-photo.vue') var InfoSelect = require('./components/info-select.vue') var BaseSwitch = require('./components/base-switch.vue') var InfoSwitch = require('./components/info-switch.vue') var DatePickerNew = require('./components/date-picker-new.vue') import { router } from './router' import store from './store' import { Picker, DatetimePicker, Popup } from 'mint-ui' import Toast from 'base/components/Toast.vue' import FireUi from '@2dfire/fire-ui' import '@2dfire/fire-ui/dist/index.css' Vue.use(VueRouter) Vue.use(vueResource) Vue.use(Scss) Vue.use(FireUi) Vue.component('Toast', Toast) Vue.component(Picker.name, Picker) Vue.component(Popup.name, Popup) Vue.component(DatetimePicker.name, DatetimePicker) Vue.component(DatePickerNew.name, DatePickerNew) Vue.component('info-input', InfoInput) Vue.component('info-photo', InfoPhoto) Vue.component('info-select', InfoSelect) Vue.component('base-switch', BaseSwitch) Vue.component('info-switch', InfoSwitch) Vue.http.options.credentials = true new Vue({ el: '#app', router, store, template: '<App/>', components: { App } }) <file_sep>/static-hercules/src/borrow-money/constant/loan-platform.js /** * 贷款平台基础信息 * @author zipai * @param * institutionName: 机构名称 * productName: 产品名称 * maxLimit: 最高额度 * productFeature: 产品特点 * loanTerm: 借款期限 * monthRatesRang: 月利率范围 * productIntroduction: 产品介绍 * conditionApply: 申请条件 */ export const $_loanPlatform = [ { code: 'u51', institutionName: '51信用卡', productName: '51生e金', maxLimit: 200000, minLimit: 3000, productFeature: [ { title: '无需抵押', stress: true }, { title: '快速审批', stress: true } ], loanTerm: [3, 6, 9, 12], monthRatesRang: '0.5%-1.5%', minRate: '0.5%', productIntroduction: '51生e金是二维火和51信用卡联合为餐饮商家定制的纯信用贷款,主要以商家的信用和店铺经营为基础,商家无抵押,也无需担保,就能直接获取借款额度,进行借款申请,51生e金,让经营生意更轻松!', conditionApply: [ '1、年龄:22-55周岁(含)大陆籍公民', '2、经营地区非偏远地区', '3、申请人经营主体工商注册满3个月' ] }, { code: 'ALLIN_LOAN', institutionName: '通华金科', productName: '火融e', maxLimit: 200000, minLimit: 0, productFeature: [ { title: '费用低', stress: true }, { title: '期限灵活', stress: true }, { title: '线上大额', stress: false } ], loanTerm: [1, 3, 6], monthRatesRang: '1%-2.5%', minRate: '1%', productIntroduction: '火融e是二维火与通华金科联合为餐饮行业商户定制的纯信用贷款。主要针对二维火平台全部注册客户,注册既有预估额度,有营业执照即可申请;费用低,风险定价,按余额计算年化率;期限灵活,30天内随借随还;3,6期分期还款。', conditionApply: [ '1、年龄:22-60岁持有二代身份证的中华人民共和国公民', '2、流水范围:有无流水均可申请', '3、申请人经营主体工商注册满3个月3.客户群体:申请人为企业法定代表人或个体工商户负责人,二维火平台全部注册客户,注册既有预估额度,有营业执照即可申请' ] }, { code: 'jisujie', institutionName: '极速云', productName: '极速借', maxLimit: 2000000, minLimit: 10000, productFeature: [ { title: '无抵押', stress: true }, { title: '高额度', stress: true }, { title: '审核快', stress: false } ], loanTerm: [3, 6, 12], monthRatesRang: '0.83%-1.8%', minRate: '0.83%', productIntroduction: '极速借是二维火携手极速云上线的借款产品,为商户解决在运营中所遇到的资金难题;无抵押,无面审,审核快,让融资更快更简单。二维火商户专享的借款服务!', conditionApply: [ '1、年龄22-55岁(含),中国大陆籍公民', '2、申请人经营主体工商注册满6个月', '3、申请人须为公司占股20%以上股东或法人,或者是账号注册人结算银行卡持卡人', '4、经营地址非新疆、西藏' ] }, { code: 'ppdjy', institutionName: '拍拍贷', productName: '商家经营贷', maxLimit: 200000, minLimit: 0, productFeature: [ { title: '极速特权', stress: true }, { title: '低息特权', stress: true }, { title: '官方信赖', stress: false } ], loanTerm: [3, 6, 9, 12], monthRatesRang: '0.83%-1.5%', minRate: '0.83%', productIntroduction: '商家经营贷是二维火与拍拍贷为二维火商家定制的纯信用贷款。基于商家在平台的经营情况,无需抵押,无需担保,直接获取信用额度,进行借款申请。', conditionApply: [ '1、19岁-55岁中国公民', '2、申请人经营主体在二维火掌柜入驻时间满2个月', '3、经营地区非偏远地区' ] }, { code: 'stddataloan', institutionName: '宜信普惠', productName: '宜信商通贷', maxLimit: 1000000, minLimit: 30000, productFeature: [ { title: '额度高', stress: true }, { title: '放款快', stress: true }, { title: '门槛低', stress: false } ], loanTerm: [6, 12, 24], monthRatesRang: '0.67%-1.5%', minRate: '0.67%', productIntroduction: '本借款产品是宜信商通贷联合二维火为餐饮行业定制的一种全新的金融服务模式,是建立在商户充分授权的基础上,通过宜信金融平台对商户信用及经营数据进行评估,使其原本单一的经营数据具备金融属性,从而解决餐饮行业资金周转难的问题。本产品无需抵押担保,仅在线上即可完成贷款申请,方便快捷。', conditionApply: [ '1、年龄:22岁(含)-55岁(含)', '2、申请人为企业法人或股东(占股20%以上)', '3、工商注册满一年且使用二维火软件6个月及以上时间', '4、经营行业非酒吧、网吧、台球厅、KTV' ] }, { code: 'dianrong', institutionName: '点融', productName: '掌柜贷', maxLimit: 200000, minLimit: 2000, productFeature: [ { title: '自动审批', stress: true }, { title: '无需担保', stress: true }, { title: '申请便捷', stress: false } ], loanTerm: [6, 12], monthRatesRang: '0.9%-1.5%', minRate: '0.9%', productIntroduction: '掌柜贷是点融针对合作商户定制的现金预借解决方案,无需抵押品。通过与POS、SAAS软件商或品牌商等合作伙伴及数据提供方的合作,基于商户历史交易量发放信用贷款,通过强大的技术支持每周或双周等额还款,盘活闲散资金,降低还款压力,并通过合作方或支付公司自动代扣还款,省时省力。', conditionApply: [ '1、经营满6个月且在二维火至少有三个月流水记录', '2、中国大陆公民', '3、申请人年龄22-60周岁', '4、申贷人与营业执照上法定代表人为同一人,且申贷人征信良好,且无其他不良记录(未结诉讼、行政处罚等)' ] }, { code: 'D0001', institutionName: '鑫火', productName: '鑫火餐饮贷', maxLimit: 3000000, minLimit: 50000, productFeature: [ { title: '银行资金', stress: true }, { title: '随借随贷', stress: true }, { title: '快速放款', stress: false } ], loanTerm: [3, 6, 12], monthRatesRang: '0.6%-1.5%', minRate: '0.6%', productIntroduction: '', conditionApply: [] } ] /** * * 月利率表 */ export const interestRateArr = function(steps, maxVal) { let arr = [] const multiple = parseInt(maxVal / steps) for (let index = 0; index < multiple; index++) { arr.push(steps.toFixed(1) + '%') steps = steps + 0.1 } return arr } // dev 环境个线上环境 code 不统一 export const getCode = function(code) { switch (code) { case 'u51_dev': return 'u51' case 'mi': return 'jisujie' case 'dianrong_dev': return 'dianrong' case 'dataloan': return 'stddataloan' default: return code } } /** * 根据code值删选数据 */ export const filterData = function(arr, code) { let res = arr.find(val => { return val.code === code }) return res } <file_sep>/static-hercules/src/examination/config/api.js import {GATEWAY_BASE_URL, ENV, APP_KEY} from 'apiConfig' import axios from './axios' /** * 查询体检结果(头部) */ export const getResultTop = () => { let itemId = sessionStorage.getItem("itemId"); let app_ver = sessionStorage.getItem("app_ver"); return axios({ method: 'post', url: `com.dfire.boss.center.healthcheck.IHealthCheckService.getDiffDetailResult`, params: {itemId,app_ver}, }) } /** * 查询体检结果 */ export const getResult = () => { let itemId = sessionStorage.getItem("itemId"); let app_ver = sessionStorage.getItem("app_ver"); return axios({ method: 'post', url: `com.dfire.boss.center.healthcheck.IHealthCheckService.getItemDetailResult`, params: {itemId,app_ver}, }) } /** * 反馈 */ export const feedback = (params) => { let itemId = sessionStorage.getItem("itemId"); return axios({ method: 'post', url: `com.dfire.boss.center.healthcheck.IHealthCheckService.saveFeedback`, params: { itemId, ...params }, }) } /** * 获取TOKEN信息 */ export const getToken = (params) => { return axios({ method: 'GET', url: 'com.dfire.soa.sso.ISessionManagerService.validateServiceTicket', params: { ...params, appKey: 200800 } }) } /** * 获取session信息(用于埋点) * */ export const getSessionInfo = (params) => { return axios({ method: 'GET', url: 'com.dfire.boss.center.soa.login.service.ILoginService.getSessionMapFromToken', params: { ...params, } }) }<file_sep>/inside-chain/src/store/modules/pass/mutations.js export default{ // 获取传菜下发模块名称品牌及最后编辑时间 _getPassModules(state, obj){ state.passPublishModule = obj }, } <file_sep>/inside-chain/src/core/mixins/table.js import { isPlainObj, isFunc } from '../utils' export default { data() { return { __list: [], __loading: false, __pagination: { current: 1, total: 0 }, __listApi: () => ({}), __params: {} } }, methods: { __paging(p) { console.log(p) }, async __getList(pageNo = this.__pagination.current, params) { this.__loading = true if (isPlainObj(pageNo)) { params = pageNo pageNo = this.__pagination.current } const resParams = { pageIndex: pageNo, ...this.__getParams(this.__pagination), ...params } const data = await this.__getListApi()(resParams) this.__afterGetList(data, pageNo) }, __getParams() { return this.__params }, __getListApi() { return this.__listApi }, __afterGetList(res, page) { if (isFunc(this.__listFormat)) { res = this.__listFormat(res, page) } const { list, total } = res || {} this.__list = list || [] this.__pagination.total = total this.__pagination.current = page this.__loading = false isFunc(this.__extraListOp) && this.__extraListOp(res, page) } } } <file_sep>/inside-chain/src/const/emu-moduleType.js // 模块类型,会员等级特权1,传菜2,收银设置3,价格方案4,不出单商品5,付款方式6,连锁菜单13 const moduleType = { 1: 'member', 2: 'pass', 3: 'cash', 4: 'price', 5: 'goods', 6: 'payKind', 13: 'chainMenu' } export default moduleType <file_sep>/inside-boss/src/container/visualConfig/store/reducers/design.js import store from '@src/store' import { indexOf, first } from '@src/container/visualConfig/utils' import types from '../actionTypes' import { formatPreviewUrl, transformConfigData, sortComponentConfigs, makeComponentConfigItem } from '../formatters/design' import { getPageDesignComponentMap, getInsertableRange, getMoveableRange } from '../selectors' /* componentConfigs 格式 [ { id, name, config }, ... ] - 组件在数组里的顺序就是渲染顺序 - id 随机生成的唯一标识。因为不能用 index 作为组件的 key,只好手动生成一个唯一 key - name 组件名,生成 appConfig 时会包含在组件 config 里 - config 就是是组件的 config */ export const initialState = { // 装修中的 config name configName: null, // 装修中的组件数据 // 加载中:null 加载失败:false 加载成功:[] componentConfigs: null, // 编辑中的组件 editingId: null, // data 加载失败时的提示信息 loadingFailedMessage: null, // config 是否更新过且未发布 updated: false, // 预览 URL previewUrl: null, } export default function designReducer(state, action) { if (!state) return initialState switch (action.type) { case types.DESIGN_CONFIG_LOADING: return { ...initialState, configName: action.name } case types.DESIGN_CONFIG_LOADED: return { ...state, componentConfigs: transformConfigData(action.data), } case types.DESIGN_CONFIG_LOAD_FAILED: return { ...state, componentConfigs: false, loadingFailedMessage: action.message, } case types.DESIGN_CONFIG_SAVED: return { ...state, updated: false, } case types.DESIGN_PREVIEW: return { ...state, previewUrl: formatPreviewUrl(action.url), } case types.DESIGN_LEAVE_PREVIEW: return { ...state, previewUrl: null, } case types.DESIGN_RESET: return initialState default: return editReducer(state, action) } } // 装修编辑相关 function editReducer(state, action) { const fullState = store.getState() const comMap = getPageDesignComponentMap(fullState) function insertable(index) { const [startIndex, endIndex] = getInsertableRange(fullState) return index >= startIndex && index <= endIndex } function moveable(toIndex) { const [startIndex, endIndex] = getMoveableRange(fullState) return toIndex >= startIndex && toIndex <= endIndex } // 报错并原样返回 state function error(message) { console.error(`${action.type}: ${message}`) return state } switch (action.type) { case types.COMPONENT_ADD: { const { name, index = null } = action const def = comMap[name].definition if (!def.choosable) return error(`component ${name} not choosable`) const configItem = makeComponentConfigItem(name) let componentConfigs = [...state.componentConfigs] if (def.position !== null || index === null) { // 对于“指定了 position 的组件”和“没指定 position 但也没指定放置位置的组件”,放到列表最后面,再交给 sort 函数来调整排序 componentConfigs.push(configItem) componentConfigs = sortComponentConfigs(componentConfigs) } else { if (!insertable(index)) return error(`invalid index ${index}`) componentConfigs.splice(index, 0, configItem) } return { ...state, componentConfigs, editingId: configItem.id, // 让新添加的组件处于编辑状态 updated: true, } } case types.COMPONENT_REMOVE: { const { id } = action let { componentConfigs, editingId } = state const configItem = first(componentConfigs, item => item.id === id) if (!configItem) return error(`component of id ${id} not exists`) if (!comMap[configItem.name].definition.choosable) return error(`component ${configItem.name} not choosable`) componentConfigs = componentConfigs.filter(item => item.id !== id) // 修正“编辑中的组件” if (editingId === id) editingId = null return { ...state, componentConfigs, editingId, updated: true, } } case types.COMPONENT_MOVE: { let { id, toIndex } = action const componentConfigs = [...state.componentConfigs] const currIndex = indexOf(componentConfigs, item => item.id === id) if (currIndex === -1) return error(`component of id ${id} not exists`) if (!moveable(toIndex)) return error(`invalid move targe index ${toIndex}`) const configItem = componentConfigs[currIndex] const def = comMap[configItem.name].definition if (def.position !== null) return error(`component of id ${id} cannot move`) // 先把组件从原位置移除 componentConfigs.splice(currIndex, 1) componentConfigs.splice(toIndex, 0, configItem) return { ...state, componentConfigs, updated: true, } } case types.COMPONENT_UPDATED: { const { id, config } = action const componentConfigs = [...state.componentConfigs] const index = indexOf(componentConfigs, item => item.id === id) if (index === -1) return error(`component of id ${id} not exists`) const configItem = componentConfigs[index] componentConfigs[index] = { ...configItem, config } return { ...state, componentConfigs, updated: true, } } case types.COMPONENT_EDITING: { const { id } = action if (!first(state.componentConfigs, item => item.id === id)) return error(`component of id ${id} not exists`) return { ...state, editingId: id } } case types.COMPONENT_LEAVE: return { ...state, editingId: null } default: return state } } <file_sep>/inside-boss/src/container/visualConfig/designComponents/whitespace/definition.js export default { name: 'whitespace', userName: '辅助留白', max: 10, config: { height: 30, }, } <file_sep>/inside-chain/src/utils/README.md # 通用工具库 通用工具库(文档待完善) ## Installation ```shell $ npm i @2dfire/utils --save-dev ``` *@2dfire为私库前缀,请参考[npm私库使用办法](http://npm.2dfire.net:4000/2017/04/25/plibrary_use/)* ## Usage ```js // 引入所有 import Utils, { object, localStorage } from "@2dfire/utils"; // 打包 utils 所有文件进来 Utils.object.clone({ foo: 1 }); object.clone({ foo: 1 }); // 引入utils/object import object, { clone } from "@2dfire/utils/object"; // 只会打包 object.js进来 object.clone({ foo: 1 }); clone({ foo: 1 }); ``` *小程序打包兼容代码设置办法* 在业务中依然用`@2dfire/utils`,在业务的`webpack`添加`alias`如下: ```js module.exports = { resolve: { alias: { "@2dfire/utils": "@2dfire/utils/wxApp" } } }; ``` ## 目录说明 ``` src 开发目录 build webpack打包相关 test 测试相关 ``` ## 内容说明 ### 一级工具目录说明 | 工具集 | 说明 | 备注 | |:---------------|:-----------------------------|:---------------| | index | 所有工具集合/ main | 包括小程序版本 | | array | 数组类型相关方法 | | | date | 日期类型相关方法 | | | object | object和其他所有类型相关方法 | | | string | 字符串类型相关方法 | | | number | 数字类型相关方法 | | | route | 路由相关方法 | 包括小程序版本 | | qs | url参数获取相关方法 | 包括小程序版本 | | url | URL相关方法 | 包括小程序版本 | | validate | 验证相关方法 | | | seesionStorage | seesionStorage相关方法 | 包括小程序版本 | | localStorage | localStorage相关方法 | 包括小程序版本 | | cookie | cookie相关方法 | 包括小程序版本 | `storage & cookie`说明一起都在下方,其它辅助方法文档可以访问[这里](http://10.1.6.28:2233/fed/static/doc/@2dfire/utils/0.0.4/global.html) ### storage & cookie #### apis 各平台的storage & cookie都实现这六个方法: - `set(name, value, [attributes]`): 将属性设置到Storage,设置前JSON.stringify。*无返回* - `setItem(name, value, [attributes])`: 将属性设置到storage。*无返回* - `get(name)`: 从storage获取属性,并且JSON.parse。*返回取到的值进行JSON.parse()转化后的值* - `getItem(name)`: 从storage获取属性。*返回取到的值* - `removeItem(name, [attributes])`: 从storage移除属性。*无返回* - `clear([attributes])`: 清空storage。*无返回* *参数说明* - name: String 设置名称,会被转换为字符串 - value - setItem: String,其余类型值会被转为String - set: Any 值,全部JSON.stringify - attributes: cookie属性 - expires: 过期时间 单位天 - path: 地址如'/shop/page' - domain: 域 - secure: 是否需要https *attributes实际上只有在web下起作用,小程序环境下cookie是假的,保存在内存中,如果需要长久存储,请选择localStorage* **推荐:在已知类型情况下**,使用`set`和`get`。如果未知类型,可能其它地方设置了, 请使用`setItem`、`getItem`,来设置获取字符串。 #### 各平台下api实际实现情况说明 | 类型 | 平台 | 实现 | |:---------------|:-------|:------------------------| | seesionStorage | web | 正常 | | localStorage | web | 正常 | | cookie | web | 正常, 使用 js-cookie 库 | | seesionStorage | 小程序 | 保存在内存中 | | localStorage | 小程序 | wx的Storage | | cookie | 小程序 | 保存在内存中 | #### example ```js import storage from '@2dfire/utils/localStorage'; storage.set('coolName', { a: 'booo' }); // values: { a: '"booo"'} // 和原生Storage(e.g. localStorage) getItem一致 storage.getItem('coolName'); // String: '{"a":"booo"}' // 将通过JSON.parse转化为对象,如果回去到的值不为JSON字符串,则throw Uncaught SyntaxError storage.get('coolName'); // Object: { a: 'booo' } storage.setItem('coolName', { a: 'booo' }); // 和原生Storage(e.g. localStorage) setItem一致 storage.getItem('coolName'); // String: '[object Object]' storage.get('coolName'); // throw Uncaught SyntaxError storage.getItem('unsetName'); // null 这里和原生Storage的getItem一致,原生返回null ``` ## TODOs ## 功能 - globalBasePage - analytics ### 单元测试 > cover: 97.41% Statements 113/116 92.31% Branches 48/52 96.67% Functions 29/30 97.41% Lines 113/116 - [x] base - [x] array.js - [x] date.js - [x] object.js - [x] qs.js - [x] string.js - [x] number.js - [x] url.js - [x] validate.js - [x] utils - [x] createStorage.js - [ ] platforms - [ ] web - [ ] ajax.js - [ ] analytics.js - [x] cookie.js - [x] promise.js - [ ] globalBasePage.js - [x] localStorage.js - [x] location.js - [x] sessionStorage.js - [ ] window.js - [ ] wxApp 暂时没有办法单元测试 - [ ] ajax.js - [ ] analytics.js - [ ] cookie.js - [x] promise.js - [ ] globalBasePage.js - [ ] localStorage.js - [ ] location.js - [ ] query.js - [ ] sessionStorage.js - [x] router.js - [ ] fetch.js <file_sep>/union-entrance/src/views/nav/nav.js import defaultConfig from './defaultConfig' import createNav from './navBar' import util from './util' const init = function(config) { const { loginType, userInfo } = util.getCookie('entrance') // entrance 数据不全,跳转登录页面 if ((!loginType || !userInfo) && util.getEnv() !== 'local') { return util.goToLogin() } config = Object.assign(defaultConfig, config) //创建顶部导航栏 createNav(config) //创建其他 } export default { init } <file_sep>/inside-boss/src/container/goodEdit/reducers.js import { SET_GOOD_ITEM_DETAIL, SET_GOOD_CATEGORY_LIST, SET_GOOD_SKU_LIST, SET_GOOD_UNIT_LIST, SET_FREIGHT_TEMPLATE, SET_SELECTED_SKU_LIST, SET_SKU_TABLE_DATA, SET_GOOD_HEAD_PICTURE, SET_GOOD_DETAIL_PICTURE, SET_GOOD_STRATEGY } from '../../constants' const goodEditReducers = (state = {}, action) => { switch(action.type) { case SET_GOOD_ITEM_DETAIL: return Object.assign({}, state, { goodDetail: action.data }) case SET_GOOD_HEAD_PICTURE: return Object.assign({}, state, { headPicture: action.data }) case SET_GOOD_DETAIL_PICTURE: return Object.assign({}, state, { detailPicture: action.data }) case SET_GOOD_CATEGORY_LIST: return Object.assign({}, state, { goodCategory: action.data }) case SET_GOOD_SKU_LIST: return Object.assign({}, state, { goodSkuList: action.data }) case SET_SELECTED_SKU_LIST: return Object.assign({}, state, { selectedSkuList: action.data }) case SET_GOOD_UNIT_LIST: return Object.assign({}, state, { unitList: action.data }) case SET_FREIGHT_TEMPLATE: return Object.assign({}, state, { freightTemplate: action.data }) case SET_SKU_TABLE_DATA: return Object.assign({}, state, { skuTableData: action.data }) case SET_GOOD_STRATEGY: return Object.assign({}, state, { strategy: action.data}) default: return state } } export default goodEditReducers <file_sep>/inside-chain/src/utils/wxApp/globalBasePage.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.globalBasePage = exports.blink = exports.hideInfo = exports.showInfo = exports.isLoading = exports.stopLoading = exports.startLoading = exports.cm = exports.message = exports.waitTime = exports.type = exports.PAGE_TYPES = undefined; var _feedBackAuto = require('@2dfire/feed-back-auto'); function baseTimeCountDown(second, everyOnceF, endF) { second--; var t = setInterval(function () { if (second < 1) { clearInterval(t); endF(); } everyOnceF(second); second--; }, 1000); } var PAGE_TYPES = { confirm: '0', info: '1', warn: '2', error: '3', cartIsSubmitChange: '4', cartIsSubmit: '5', sessionOut: '6', //授权过期 orderOut: '7', //订单过期,或者已经结单 frost: '8', //服务令禁用, failed: '9' }; var type = PAGE_TYPES; // TODO 会被设置否?by 炒饭 var waitTime = 3; var message = { error: '小二七手八脚的把事情搞砸了' }; var cm = { cartTimeOut: '您太久没有操作啦,我们找不到您的点餐数据啦', cartSubmit: '您的朋友已经下单啦,快去看看吧' }; function startLoading(options) { var content = options && options.content ? options.content : ''; _feedBackAuto.toast.loading({ content: content, duration: -1 }); } function stopLoading() { _feedBackAuto.toast.hide(); } // loading 是否正在显示 true 在显示, false 没有在显示 function isLoading() { // 这个方法应该被废除, 待定 return false; // return $('#fbaij_toast').length > 0; } function showInfo(type, options) { if (type === PAGE_TYPES.confirm) { _feedBackAuto.modal.info({ content: options.message, okText: options.okBtnText || '确定', cancelText: options.cancelBtnText || '取消' }, function (res) { if (res.ok && options.callback) { options.callback(); } }); } else if (type == PAGE_TYPES.error) { _feedBackAuto.alert.error({ content: options.errorMessage || '小二七手八脚的把事情搞砸了', closeText: options.btnText || '重新获取', showIcon: true, duration: -1 }, function (res) { if (res.close && options.reload) { options.reload(); } }); } else if (type == PAGE_TYPES.failed) { _feedBackAuto.alert.error({ content: options.errorMessage || '小二七手八脚的把事情搞砸了', closeText: options.btnText || '我知道了', showIcon: true, duration: -1 }, function (res) { if (res.close && options.callback) { options.callback(); } }); } else if (type == PAGE_TYPES.warn) { _feedBackAuto.alert.warning({ content: options.warnMessage, closeText: '', showIcon: true, duration: 2000 }); } else if (type == PAGE_TYPES.info) { _feedBackAuto.alert.info({ content: options.infoMessage, closeText: '', showIcon: true, duration: 2000 }); } else if (type == PAGE_TYPES.cartIsSubmitChange) { _feedBackAuto.alert.error({ title: '购物车有变动', content: '变化部分已经用红色字体标注', closeText: '', showIcon: false, duration: 2000 }); } else if (type == PAGE_TYPES.cartIsSubmit) { var title = options.message || '您的朋友已提交本桌订单'; _feedBackAuto.alert.error({ title: title, content: '<i>' + waitTime + '</i>秒后进入下单的菜页面', closeText: '', showIcon: false, duration: -1 }); baseTimeCountDown(waitTime, function (s) { _feedBackAuto.alert.error({ title: title, content: s + '秒后进入下单的菜页面', closeText: '', showIcon: false, duration: -1 }); }, function () { if (options.callback) { options.callback(); } }, true); } else if (type == PAGE_TYPES.sessionOut) { _feedBackAuto.alert.error({ title: '您太久没有动静了', content: '请重新扫码', closeText: '', showIcon: false, duration: -1 }); } else if (type == PAGE_TYPES.orderOut) { _feedBackAuto.alert.error({ title: '这张点菜单已经结账完毕啦', content: '请重新扫码', closeText: '', showIcon: false, duration: -1 }); } else if (type == PAGE_TYPES.frost) { _feedBackAuto.alert.error({ title: options.frostTitle, content: options.frostMessage, closeText: '', showIcon: false, duration: 2000 }); } } function hideInfo() { // 这个方法应该被废除, 待定 _feedBackAuto.alert.hide(); } function blink() { // 这个方法应该被废除, 待定 return false; } var globalBasePage = { PAGE_TYPES: PAGE_TYPES, type: type, waitTime: waitTime, message: message, cm: cm, startLoading: startLoading, stopLoading: stopLoading, isLoading: isLoading, showInfo: showInfo, hideInfo: hideInfo, blink: blink }; exports.PAGE_TYPES = PAGE_TYPES; exports.type = type; exports.waitTime = waitTime; exports.message = message; exports.cm = cm; exports.startLoading = startLoading; exports.stopLoading = stopLoading; exports.isLoading = isLoading; exports.showInfo = showInfo; exports.hideInfo = hideInfo; exports.blink = blink; exports.globalBasePage = globalBasePage; exports.default = globalBasePage;<file_sep>/inside-boss/src/components/goods/specification.js import React, {Component} from 'react' import {Table, Pagination} from 'antd' import styles from './style.css' import InitData from "../../container/goods/init"; import * as bridge from "../../utils/bridge"; import * as action from "../../action"; import {setGoodsList} from "../../action"; import {showSpin} from "../../action"; import {errorHandler} from "../../action"; import api from "../../api"; class Specification extends Component { constructor(props) { super(props) this.paginationChange = this.paginationChange.bind(this) this.state = { columns: [ // { // title: '规格名称1', // dataIndex: 'specification1', // key: 'specification1', // }, // { // title: '规格名称2', // dataIndex: 'specification2', // key: 'specification2', // }, // { // title: '规格名称3', // dataIndex: 'specification3', // key: 'specification3', // }, { title: '规格条码', dataIndex: 'code', key: 'code', }, { title: '单价(元)', dataIndex: 'price', key: 'price', }, { title: '会员价(元)', dataIndex: 'vipPrice', key: 'vipPrice', }, { title: '库存', dataIndex: 'inventory', key: 'inventory', } ], records: [], totalRecord: 0, current: 1, id: '' } } componentWillMount() { const id = this.props.data console.log(id) this.setState({ id: id, }); this.paginationChange(1) } componentWillReceiveProps(newProps) { console.log(newProps.data, this.state.id) if (newProps.data !== this.state.id) { this.setState({ id: newProps.data, current: 1, totalRecord: 0 }); this.paginationChange(1, newProps.data) } } paginationChange(pageNum, id) { this.setState({ current: pageNum, }); console.log(this.props.data, this.state.id) api.getSpecification({ id: id || this.props.data, pageNum: pageNum, pageSize: 10 }).then( res => { // res = { // "records": [ // { // "code": "测试内容e2mj", // "id": "测试内容t141", // "inventory": 51106, // "price": 61258, // "specification1": "测试内容9046", // "specification2": "测试内容4i52", // "specification3": "测试内容4488", // "vipPrice": 78650 // } // ], // "totalRecord": 35753 // } res.records.map(item => { if (item.props && item.props.length > 0) { item.props.map(sub => { item[sub.propertyId] = sub.itemValue.name }) } return item }) let autoCol = []; if (res.titles && res.titles.length > 0) { res.titles.map(item => { autoCol.push({ title: item.propertyName, dataIndex: item.propertyId }) }) } let tmp_col = [ { title: '规格条码', dataIndex: 'code', key: 'code', }, { title: '单价(元)', dataIndex: 'price', key: 'price', }, { title: '会员价(元)', dataIndex: 'vipPrice', key: 'vipPrice', }, { title: '库存', dataIndex: 'inventory', key: 'inventory', } ] autoCol = autoCol.concat(tmp_col) this.setState(res); this.setState({ columns: autoCol }); }, err => { errorHandler(err) } ) } render() { const t = this const {data} = t.props const columns = this.state.columns console.log(data) return ( <div> <Table dataSource={this.state.records} columns={columns} pagination={false} rowKey={records => records.id} className={styles.specificationTable} /> {/*<div className={styles.paginationBox}>*/} {/*<Pagination className={styles.paginationHtml} showQuickJumper*/} {/*current={this.state.current}*/} {/*total={this.state.totalRecord}*/} {/*defaultPageSize={10}*/} {/*pageSize={10} onChange={this.paginationChange.bind(this)}/>*/} {/*<p>共{this.state.totalRecord}条,每页10条</p>*/} {/*</div>*/} </div> ) } } export default Specification <file_sep>/inside-boss/src/container/visualConfig/views/new_design/list/ComGroup.js import React, { Component } from 'react' import PropTypes from 'prop-types' import c from 'classnames' import ComItem from './ComItem' import s from './ComGroup.css' export default class ComGroup extends Component { static propTypes = { group: PropTypes.object.isRequired, } constructor(props) { super(props) this.state = { closed: false, } } switchOpen = () => { this.setState({ closed: !this.state.closed, }) } render() { const { name, list } = this.props.group const { closed } = this.state return <div className={s.wrapper}> <div className={s.header} onClick={this.switchOpen}> <span className={s.groupName}>{name}</span> <span className={c(s.switchBtn, closed && s.close)} /> </div> {this.renderComponents(list, closed)} </div> } renderComponents(componentNames, closed) { return <div className={c(s.components, closed && s.close)}> {componentNames.map(name => <ComItem key={name} name={name} />)} </div> } } <file_sep>/inside-boss/src/container/visualConfig/views/new_design/editing/EditorWrapper.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import c from 'classnames' import { indexOf } from '@src/container/visualConfig/utils' import * as actions from '@src/container/visualConfig/store/actions' import { getMoveableRange } from '@src/container/visualConfig/store/selectors' import s from './EditorWrapper.css' @connect(state => ({ moveableRange: getMoveableRange(state), configs: state.visualConfig.design.componentConfigs, })) class EditorWrapper extends Component { static contextTypes = { designId: PropTypes.string.isRequired, designDefinition: PropTypes.object.isRequired, } static propTypes = { className: PropTypes.any, // 附加自定义的 className arrow: PropTypes.bool, // 是否显示一个向左的小箭头 } static defaultProps = { arrow: true, } get definition() { return this.context.designDefinition } get id() { return this.context.designId } get index() { return indexOf(this.props.configs, item => item.id === this.id) } get canMoveUp() { return !this.definition.position && this.index > this.props.moveableRange[0] } get canMoveDown() { return !this.definition.position && this.index < this.props.moveableRange[1] } moveUp = () => { actions.designMoveComponent(this.id, this.index - 1) } moveDown = () => { actions.designMoveComponent(this.id, this.index + 1) } leave = () => { actions.designLeaveComponent() } render() { const { className, arrow } = this.props const { description } = this.definition return <div className={c(s.wrapper, arrow && s.arrow, className)}> <div className={s.inner}> <div className={s.header}> <div className={s.desc}>{description}</div> {this.canMoveUp && <span className={s.moveUp} onClick={this.moveUp} />} {this.canMoveDown && <span className={s.moveDown} onClick={this.moveDown} />} <span className={s.leave} onClick={this.leave} /> </div> <div className={s.body}> {this.props.children} </div> </div> </div> } } export default EditorWrapper <file_sep>/inside-chain/src/store/modules/components/staffManage.js import Requester from '@/base/requester' import catchError from '@/base/catchError' import API from '@/config/api.js' import Obj from '@2dfire/utils/object' import Vue from 'vue'; import iView from "iview"; import router from "@/router"; import Cookie from '@2dfire/utils/cookie' Vue.use(iView) let Message = iView.Message; const Spin = iView.Spin const config = { render: (h) => { return h('div', [ h('Icon', { 'style': 'animation: ani-demo-spin 1s linear infinite', props: { type: 'load-c', size: 18 } }), h('div', 'Loading') ]) } } let shopInfo = { entityId:'', entityType:'', industry:'' } let entrance = [] if(Cookie.getItem('entrance') != undefined){ shopInfo = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).shopInfo entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) } const staffManage = { namespaced: true, state:{ dataLise: [], unifyShopList:[], shopCount: 0, selfShopList:[], roleList:[], activeId:'' }, mutations: { _setUnifyShopList(state,data){ state.unifyShopList = [].concat(data) }, _setSelfShopList(state,data){ state.selfShopList = [].concat(data) }, _getRankList(state,data){ state.roleList = [].concat(data) }, _getUnifyShopsCount(state,data){ state.shopCount = data }, _setDatelist(state,data){ state.dataLise = [].concat(data) }, _setActiveId(state,data){ state.activeId = data }, _clearRoleList(state,data){ state.roleList = [] }, _clearDataLise(state,data){ state.dataLise = [] } }, actions:{ //获取连锁总部管理的门店职级详情 getChainBranchRoleDetailList({commit},params){ const req = { code:'3', industry:shopInfo.industry, } Spin.show(config) Requester.get(API.GET_CHAIN_BRANCH_ROLE_DETAIL_LIST,{params:{...req}}).then(res=>{ let dataList = [] if(!Obj.isEmpty(res.data)){ res.data.map(i=>{ dataList.push({ name:i.name, id:i.id, actionGroupVOList:i.actionGroupVOList.map(j=>{ j.rote = (j.totalCount === 0 ? 0 : Math.round(j.actionCount / j.totalCount * 100)) + '%' return j }) }) }) } Spin.hide() commit('_getRankList',dataList) }).catch(e=>{ Spin.hide() catchError(e) }) }, filterList({commit},params){ const req = { code:'3', industry:shopInfo.industry, } Spin.show(config) Requester.get(API.GET_CHAIN_BRANCH_ROLE_DETAIL_LIST,{params:{...req}}).then(res=>{ let dataList = [] if(!Obj.isEmpty(res.data)){ res.data.map(i=>{ if(i.name.includes(params)){ dataList.push({ name:i.name, id:i.id, actionGroupVOList:i.actionGroupVOList.map(j=>{ j.rote = (j.totalCount === 0 ? 0 : Math.round(j.actionCount / j.totalCount * 100)) + '%' return j }) }) } }) } Spin.hide() commit('_getRankList',dataList) }).catch(e=>{ Spin.hide() catchError(e) }) }, //获取自主和统一管理门店数量 getUnifyShopcount({commit}){ Requester.get(API.COUNT_SHOPS).then(res=>{ if(res.data){ commit('_getUnifyShopsCount',res.data.apply) } }).catch(e=>{ catchError(e) }) }, //获取自主和统一管理门店详情 getApplyAndUnapplyShops({commit}){ Requester.get(API.GET_APPLY_AND_UNAPPLU_SHOPS).then(res=>{ if(res.data){ const unapply = res.data.unapply.map(v=>({ name: v.name, entityId: v.entityId, active: false })) const apply = res.data.apply.map(v=>({ name: v.name, entityId: v.entityId, active: false })) commit('_setUnifyShopList',apply) commit('_setSelfShopList',unapply) } }).catch(e=>{ catchError(e) }) }, //获取连锁总部统一管理的职级权限详情 listRestUnifiedAllActionGroup({commit},params){ const req = { industry:shopInfo.industry, grantedRoleId:params } Spin.show(config) Requester.get(API.LIST_REST_UNIFIED_ALL_ACTION_GROUP,{params:{...req}}).then(res=>{ let new_data = [] let arr = [] const loopSelect = (item)=>{ item.actionVOList.map(i=>{ if(i.actionVOList && i.actionVOList.length > 0){ loopSelect(i) }else{ if(!i.selected && i.hasEditPower){ arr.push(i) } } }) } new_data = res.data.modules.map(item =>{ return { code: item.code, name: item.name, actionCount: item.actionCount, actionVOList: item.actionGroupVOS, totalCount: item.totalCount, rote: item.totalCount === 0 ? '' : Math.round(item.actionCount / item.totalCount * 100) + '%' } }) Spin.hide() new_data.map(i=>{ arr = [] i.actionVOList && loopSelect(i) if(!arr.length){ i.selected = true }else{ i.selected = false } }) let activeId = new_data[0].code commit('_setActiveId',activeId) commit('_setDatelist',new_data) }).catch(e=>{ Spin.hide() catchError(e) }) }, //获取连锁总部统一管理的职级权限详情 getAllActionGroupList({commit},params){ const req = { grantedRoleEntityId: shopInfo.entityId, actionGroupCode: shopInfo.entityType, industry:shopInfo.industry, grantedRoleId: params } Spin.show(config) Requester.get(API.GET_ALL_ACTION_GROUP_LIST,{params:{...req}}).then(res=>{ console.log(res.data) let new_data = [] let arr = [] const loopSelect = (item)=>{ item.actionVOList.map(i=>{ if(i.actionVOList && i.actionVOList.length > 0){ loopSelect(i) }else{ if(!i.selected && i.hasEditPower){ arr.push(i) } } }) } new_data = res.data.modules.map(item =>{ return { code: item.code, name: item.name, actionCount: item.actionCount, actionVOList: item.actionGroupVOS, totalCount: item.totalCount, rote: item.totalCount === 0 ? '' : Math.round(item.actionCount / item.totalCount * 100) + '%' } }) Spin.hide() new_data.map(i=>{ arr = [] i.actionVOList && loopSelect(i) if(!arr.length){ i.selected = true }else{ i.selected = false } }) let activeId = new_data[0].code commit('_setActiveId',activeId) commit('_setDatelist',new_data) }).catch(e=>{ Spin.hide() catchError(e) }) }, //删除职级 deleteRole({commit,dispatch},params){ let req = { entityId:shopInfo.entityId, loginEntityId:shopInfo.entityId, userId:entrance.userInfo.userId, } Requester.get(API.DELETE_ROLE,{ params: { roleId: params, reqParamStr: JSON.stringify( req )}}).then( res =>{ Message.info('删除成功') dispatch('getChainBranchRoleDetailList') }).catch(e=>{ catchError(e) }) }, //更新职级 updateRole({dispatch,commit},params){ let roleReq = { name: params.roleStr, id: params.roleId, unified:params.unified } let req = { entityId:shopInfo.entityId, loginEntityId:shopInfo.entityId, userId:entrance.userInfo.userId, } Requester.get(API.UPDATE_ROLE,{params:{roleStr:JSON.stringify(roleReq), reqParamStr:JSON.stringify(req)}}).then(res=>{ params.Message = '修改成功' dispatch('grantRoleAction',params) }).catch(e=>{ catchError(e) }) }, //创建职级 createRole({commit,dispatch},params){ const { roleStr } = params //name":"测试职级","unified":0 let req = { entityId:shopInfo.entityId, loginEntityId:shopInfo.entityId, userId:entrance.userInfo.userId, } Requester.get(API.CREATE_ROLE,{params:{roleStr:JSON.stringify({name:roleStr,unified:params.unified}), reqParamStr:JSON.stringify(req)}}).then(res=>{ if( !Obj.isEmpty(res.data)){ params.roleId = res.data.id params.Message = '创建成功' dispatch('grantRoleAction',params) } }).catch(e=>{ catchError(e) }) }, //对职权赋值 grantRoleAction({commit},params){ let req = { grantUserEntityId:shopInfo.entityId, grantedRoleEntityId:shopInfo.entityId, grantUserId:entrance.userInfo.userId, grantedRoleId:params.roleId, actionModuleStr: JSON.stringify(params.selectedRole) } Spin.show(config) Requester.post(API.GRANT_ROLE_ACTION,{...req},{emulateJSON: true}).then(res=>{ if(res.data){ Spin.hide() Message.info(params.Message) setTimeout(() => { router.push(params.router) }, 500); } }).catch(e=>{ Spin.hide() catchError(e) }) }, saveRole({dispatch},params){ console.log(params) if(params.roleId){ dispatch('updateRole',params) }else{ dispatch('createRole',params) } }, //添加统一管理门店 addUnifyApplyShops({commit, dispatch},params){ Requester.post(API.ADD_UNIFY_APPLY_SHOPS,{shopEntityIds:JSON.stringify(params)},{emulateJSON: true}).then(res=>{ if(res.data){ Message.info('修改成功') dispatch('getApplyAndUnapplyShops') } }).catch(e=>{ catchError(e) }) }, //删除统一管理门店 delUnifyApplyShops({commit, dispatch},params){ Requester.post(API.DEL_UNIFY_APPLY_SHOPS,{shopEntityIds:JSON.stringify(params)},{emulateJSON: true}).then(res=>{ if(res.data){ Message.info('修改成功') dispatch('getApplyAndUnapplyShops') } }).catch(e=>{ catchError(e) }) }, selectShop({ commit, state },params){ const { item, type} = params let commitType = '' let tmp_list = [] if(type === 'unify'){ tmp_list = state.unifyShopList.concat(); commitType = '_setUnifyShopList' }else if( type === 'self'){ tmp_list = state.selfShopList.concat(); commitType = '_setSelfShopList' }else{ return } tmp_list.map(i => { if (i.entityId === item.entityId) { i.active = !i.active } }) commit(commitType, tmp_list) }, selectedAll({state,commit},params){ let dataLise = state.dataLise const loopSelect = (item,type)=>{ item.actionVOList.map(i=>{ if(i.actionVOList && i.actionVOList.length > 0){ i.selected = type loopSelect(i,type) }else{ if(i.hasEditPower){ i.selected = type } } }) } dataLise.map(i=>{ if(i.code === params.item.code && i.name === params.item.name){ i.selected = params.checked; if(i.actionVOList){ loopSelect(i,params.checked) } } }) commit('_setDatelist',dataLise) }, checkedAllSelected({state,commit},params){ let arr = [] const loopSelect = (item)=>{ item.actionVOList.map(i=>{ if(i.actionVOList && i.actionVOList.length > 0){ loopSelect(i) }else{ if(!i.selected && i.hasEditPower){ arr.push(i) } } }) } let dataLise = state.dataLise dataLise.map(i=>{ if(i.code === params.item.code && i.name === params.item.name){ loopSelect(i) if(!arr.length){ i.selected = true }else{ i.selected = false } } }) commit('_setDatelist',dataLise) }, clearRoleList({commit}){ commit('_clearRoleList') }, clearDataLise({commit}){ commit('_clearDataLise') }, changeActive({commit},params){ commit('_setActiveId',params) } }, getters: { getDataList(state){ return state.dataLise }, getUnifyShopList(state){ return state.unifyShopList }, getSelfShopList(state){ return state.selfShopList }, getRankTableList(state){ return state.roleList }, getShopCount(state){ return state.shopCount }, getTableList(state){ return state.tableList }, getActiveId(state){ return state.activeId } } } export default staffManage<file_sep>/inside-chain/build.sh envtype=$1 npm install NODE_ENV=$envtype npm run build <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/ranking/RankingEditor.js import React from 'react'; import { Radio, Icon, Menu, Dropdown, Button, Checkbox, message } from 'antd'; import ImgUpload from '../../common/imgUpload' import { DesignEditor, ControlGroup } from '../../editor/DesignEditor'; import style from './RankingEditor.css' const RadioGroup = Radio.Group; const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] export default class RankingEditor extends DesignEditor { state = { defaultArr: arr, showFields: ['名称', '价格','下单按钮'], superscriptList: ['新品', '热卖', 'NEW', 'HOT', '自定义'], defaultImg:'https://assets.2dfire.com/frontend/071bac5b44ade2005ad9091d1be18db6.png', isShowImgUpload: false, imgUrl: '' } onChange = (str, e) => { const { value, onChange } = this.props; const { config } = value let target = e.target.value const orderButton = Object.assign({}, config.orderButton) orderButton[str] = target onChange(value, {config:{ ...config, orderButton }}) } _selectType = (e) => { // 样式选择 const { value, onChange } = this.props; const { config } = value const target = e.target.value let _newArr = Array.from(arr); let rankingLimit = 1 if (target == '详细列表') { rankingLimit = 3 _newArr = _newArr.splice(2) } if (target == '双列小图') { rankingLimit = 2 _newArr = _newArr.splice(1) } this.setState({ defaultArr: _newArr, }) onChange(value, {config:{ ...config, mode: target, rankingLimit, }}) } _checkboxChange = (item, e) => { // 多选框 ['名称', '价格', '下单按钮'] 事件 const { value, onChange } = this.props; const { config } = value let showFields = [...config.showFields] if(e.target.checked) { // 选中 showFields.push(item) } else { showFields = showFields.filter(v => v != item) } onChange(value, {config:{ ...config, showFields }}) } _superscriptCheckbox = (e) => { // 角标 const { value, onChange } = this.props; const { config } = value let showFields = [...config.showFields] if(e.target.checked) { // 选中 showFields.push('角标') } else { showFields = showFields.filter( v => v!= '角标' ) } onChange(value, {config:{ ...config, showFields }}) } _superscriptTypeChange = (e) => { // 角标类型选择 const { value, onChange } = this.props; const { config } = value let target = e.target.value const subscript = Object.assign({}, config.subscript) subscript.type = 'text' if (target == '自定义') { subscript.type = 'image' } subscript.text = target onChange(value, {config:{ ...config, subscript }}) } selectRankType = ({key}) => { // 排行类型选择 const { value, onChange } = this.props; const { config } = value onChange(value, {config:{ ...config, ranking: key }}) } selectShopNum = ({key}) => { // 商品数量选择 const { value, onChange } = this.props; const { config } = value let _arrShoplist = Array.from(arr); onChange(value, { arrShopLis:_arrShoplist.splice(0, key), config:{ ...config, rankingLimit: key } }) } close = () => { this.setState({ isShowImgUpload: false, }) } _getImg = (data) => { // 获取图片 const { value, onChange } = this.props; const { config } = value const subscript = Object.assign({}, config.subscript) subscript.image = data this.setState({ imgUrl: data }) onChange(value, {config:{ ...config, subscript }}) } onChangeBtn = () => { this.setState({ isShowImgUpload: !this.setState.isShowImgUpload }) } render(){ const { value, prefix } = this.props; const { config } = value const { defaultArr, superscriptList, defaultImg, isShowImgUpload, imgUrl, showFields } = this.state const { ranking, rankingLimit, mode, orderButton, subscript } = value.config let isShopButton = config.showFields.indexOf('下单按钮') > -1 // 是否显示商品按钮 let isShowSuperscript = config.showFields.indexOf('角标') > -1 // 角标是否显示 // 排行类型: const rankListMenu = ( <Menu onClick={this.selectRankType}> <Menu.Item key="综合排序">综合排序</Menu.Item> <Menu.Item key="销量排行">销量排行</Menu.Item> <Menu.Item key="最新商品">最新商品</Menu.Item> </Menu> ); // 展示商品数: const shopNumMenu = ( <Menu onClick={this.selectShopNum}> {defaultArr.map((item) => <Menu.Item key={item}>{item}</Menu.Item> )} </Menu> ); return ( <div className={`${prefix}-design-component-config-editor`}> <ImgUpload getImg={this._getImg} isShowImgUpload={isShowImgUpload} close={this.close} /> <div className={style.componentConfigEditor}> <ControlGroup label="排行类型:" className={style.groupLabel} > </ControlGroup> <Dropdown overlay={rankListMenu}> <Button style={{ marginLeft: 8 }} className={style.rankButton}> {ranking} <Icon type="down" /> </Button> </Dropdown> </div> <div className={style.componentConfigEditor}> <ControlGroup label="展示商品数:" className={style.groupLabel} > </ControlGroup> <Dropdown overlay={shopNumMenu}> <Button style={{ marginLeft: 8 }} className={style.rankButton}> {rankingLimit} <Icon type="down" /> </Button> </Dropdown> </div> <div className={style.componentConfigEditor}> <ControlGroup label="样式选择:" className={style.groupLabel} > </ControlGroup> <RadioGroup value={mode} className={style.controlGroupControl} onChange={(e) => this._selectType(e)}> <Radio name="mode" value='大图' className={style.radio}>大图</Radio> <Radio name="mode" value='详细列表' className={style.radio}>详细列表</Radio> <Radio name="mode" value='双列小图' className={style.radio}>双列小图</Radio> {/* <Radio name="imgType" value='transverse'>横向滑动</Radio> */} </RadioGroup> </div> <div className={style.componentConfigEditor}> <ControlGroup label="显示内容:" className={style.groupLabel} > </ControlGroup> <div className={style.showContent}> {showFields.map((item) => <Checkbox defaultChecked={true} className={style.rankEditorCheckbox} onChange={(e) => this._checkboxChange(item, e)}>{item}</Checkbox> )} {isShopButton && <div> <RadioGroup value={orderButton.mode} className={style.controlGroupControl} onChange={(e) => this.onChange('mode', e)}> <Radio name="mode" value='立即下单'>立即下单</Radio> <Radio name="mode" value='加入购物车'>加入购物车</Radio> </RadioGroup> {orderButton.mode == '立即下单' ? <RadioGroup value={orderButton.orderStyle} className={style.controlGroupControl} onChange={(e) => this.onChange('orderStyle', e)}> <Radio name="orderStyle" value='1'>样式一</Radio> <Radio name="orderStyle" value='2'>样式二</Radio> </RadioGroup> : <RadioGroup value={orderButton.cartStyle} className={style.controlGroupControl} onChange={(e) => this.onChange('cartStyle', e)}> <Radio name="cartStyle" value='1'>样式一</Radio> <Radio name="cartStyle" value='2'>样式二</Radio> <Radio name="cartStyle" value='3'>样式三</Radio> </RadioGroup>} </div>} <Checkbox className={style.rankEditorCheckbox} onChange={this._superscriptCheckbox}>角标</Checkbox> {isShowSuperscript && <RadioGroup value={subscript.text} className={style.controlGroupControl} onChange={this._superscriptTypeChange}> {superscriptList.map((item) => <Radio className={style.rankRadio} name="superscript" value={item}>{item}</Radio> )} {subscript.text == '自定义' && <div className={style.uploadInfo}> <img onClick={this.onChangeBtn} className={style.uploadBtn} src={imgUrl ? imgUrl: defaultImg}></img> <p className={style.uploadTip}>建议尺寸80X30px</p> </div> } </RadioGroup> } </div> </div> </div> ) } static designType = 'goodsRanking'; static designDescription = '商品排行'; static designTemplateType = '基础类'; static getInitialValue() { return { config: { type: 'goodsRanking', ranking: '综合排序', // 排行类型。可选值:综合排序、销量排行、最新商品 rankingLimit: 1, // 显示多少个排行商品;取值范围:2 ~ 12 mode: '大图', // 可选值:大图、详细列表、双列小图、横向滑动 showFields: ['名称', '价格', '下单按钮'],// 可使用值:名称、价格、下单按钮、角标 / 可以为空数组,商品主图是固定显示的 / 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) orderButton: { // 下单按钮设置(仅在 showFields 里有 '下单按钮' 时生效) mode: '立即下单', // 可选值:立即下单、加入购物车 orderStyle: '1', // 立即下单按钮样式。可选值:'1'、'2'。仅在 mode=立即下单 时生效 cartStyle: '1', // 加入购物车按钮样式。可选值:'1'、'2'、'3'。仅在 mode=加入购物车 时生效 }, subscript: { // 角标设置(仅在 showFields 里有 '下单按钮' 时生效) type: 'text', // 角标类型。可选值:text、image text: '新品', // 可选值:新品、热卖、NEW、HOT。仅在 type=text 时生效 image: null, // image URL。在 type=image 时有效且必填 }, } }; } } <file_sep>/inside-boss/src/components/customBill/main.js /** * Created by air on 2017/7/31. */ import React, { Component } from 'react' import styles from './css/main.css' import { message, Button, Modal, Spin, Select, Row, Col, Input } from 'antd' import cls from 'classnames' const Option = Select.Option import Bill from '../customBillDetail/content' import BillList from './billList' import { Link } from 'react-router' import * as action from '../../action' import { setUseStoreList } from '../../action' class Main extends Component { constructor(props) { super(props) this.state = { importLock: false, exportLock: false, previewText: '请上传excel文件', storeName: '', typeActive: '0_0', typeActiveCode: '', billTitle: '' } } componentDidMount() { const t = this const { dispatch ,data} = t.props dispatch(action.getAllTmplType({entityId:data.importData.entityId})) dispatch(action.getEntityType({entityId:data.importData.entityId})) } componentWillReceiveProps(nextProps) { if (nextProps.data.brandId !== this.state.storeName) this.setState({ storeName: nextProps.data.brandId }) } /** * 左侧列表选择 * @param index1 * @param index2 * @param code itemCode 用于获取 * @param title * **/ typeListChange(index1, index2, code, title) { const { dispatch ,data} = this.props console.log('output',title); this.setState({ typeActive: index1 + '_' + index2, typeActiveCode: code, }) dispatch(action.getTypeTmplList({ tmplCode: code,entityId:data.importData.entityId,codeName:title })) window.scrollTo(0, 0) } render() { const t = this const { dispatch, data } = t.props const { allTmplType, typeTmplList, importData ,entityType} = data console.log('output bill!!!', data); return ( <div className={styles.main_wrapper}> <Row> {/*===========================left*/} <Col span={6} className={styles.bill_type}> <h2 className={styles.bill_type_title}>单据类型</h2> <ul className={styles.type_ul}> {allTmplType && allTmplType.map((val, index) => { return ( <li key={index}> <div className={styles.type_name}>{val.typeName}</div> <ul> {val.tmplCodeList && val.tmplCodeList.map((item, i) => { return ( <li className={cls( styles.type_li, this.state.typeActive === `${index}_${i}` ? styles.type_li_active : '' )} key={i} onClick={this.typeListChange.bind( this, index, i, item.tmplCode, item.codeName )} > {item.codeName} </li> ) })} </ul> </li> ) })} </ul> </Col> <Col span={18}> <div className={styles.main}> <h3 className={styles.main_title}>{data.billTitle}</h3> <Row className={styles.main_center}> {/*===========================center*/} <Col span={24}> <BillList data={{ typeTmplList: typeTmplList, importData, entityType, typeActiveCode: this.state.typeActiveCode }} dispatch={dispatch} /> </Col> {/*===========================right*/} {/*<Col span={12}>*/} {/*<ul>*/} {/*{typeTmplList &&*/} {/*typeTmplList.map(val => {*/} {/*if (val.using) {*/} {/*return (*/} {/*<li key={val.id}>*/} {/*<div className={styles.main_list_title}>*/} {/*{val.name}*/} {/*</div>*/} {/*<div className={styles.bill}>*/} {/*<div className={styles.use_icon}>使用中</div>*/} {/*<Bill data={val} type='SHOW'/>*/} {/*</div>*/} {/*</li>*/} {/*)*/} {/*}*/} {/*})}*/} {/*</ul>*/} {/*</Col>*/} </Row> </div> </Col> </Row> </div> ) } } export default Main <file_sep>/inside-chain/src/utils/doc/@2dfire/utils/0.2.64/base_image.js.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>@2dfire/utils Source: base/image.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.simplex.css"> </head> <body> <div class="navbar navbar-default navbar-fixed-top "> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">@2dfire/utils</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="imageUtil.html">imageUtil</a></li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="global.html#arrayFind">arrayFind</a></li><li><a href="global.html#arrayFindIndex">arrayFindIndex</a></li><li><a href="global.html#arrayUnique">arrayUnique</a></li><li><a href="global.html#clone">clone</a></li><li><a href="global.html#createUrl">createUrl</a></li><li><a href="global.html#dFireFetch">dFireFetch</a></li><li><a href="global.html#dFireFetchWithoutGlobal">dFireFetchWithoutGlobal</a></li><li><a href="global.html#enterSocketRoom">enterSocketRoom</a></li><li><a href="global.html#extract">extract</a></li><li><a href="global.html#getGlobalOptions">getGlobalOptions</a></li><li><a href="global.html#getRealUrl">getRealUrl</a></li><li><a href="global.html#isArray">isArray</a></li><li><a href="global.html#isEmpty">isEmpty</a></li><li><a href="global.html#isFunction">isFunction</a></li><li><a href="global.html#isJson">isJson</a></li><li><a href="global.html#isMobilePhone">isMobilePhone</a></li><li><a href="global.html#isNull">isNull</a></li><li><a href="global.html#isNumber">isNumber</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#isUndefined">isUndefined</a></li><li><a href="global.html#navigateBack">navigateBack</a></li><li><a href="global.html#navigateTo">navigateTo</a></li><li><a href="global.html#numberFixedFen">numberFixedFen</a></li><li><a href="global.html#numberFixedYuan">numberFixedYuan</a></li><li><a href="global.html#numberFormat">numberFormat</a></li><li><a href="global.html#objectAssign">objectAssign</a></li><li><a href="global.html#objectForEach">objectForEach</a></li><li><a href="global.html#objectMap">objectMap</a></li><li><a href="global.html#parse">parse</a></li><li><a href="global.html#parseMessage">parseMessage</a></li><li><a href="global.html#redirectTo">redirectTo</a></li><li><a href="global.html#selectKeys">selectKeys</a></li><li><a href="global.html#setGlobalOptions">setGlobalOptions</a></li><li><a href="global.html#setSocketGlobalOptions">setSocketGlobalOptions</a></li><li><a href="global.html#setUrlMirror">setUrlMirror</a></li><li><a href="global.html#startWith">startWith</a></li><li><a href="global.html#stringify">stringify</a></li><li><a href="global.html#stringifyMessage">stringifyMessage</a></li><li><a href="global.html#stringTrim">stringTrim</a></li><li><a href="global.html#stringTrimLeft">stringTrimLeft</a></li><li><a href="global.html#stringTrimRight">stringTrimRight</a></li><li><a href="global.html#toInt">toInt</a></li><li><a href="global.html#toIntBool">toIntBool</a></li><li><a href="global.html#toJson">toJson</a></li><li><a href="global.html#toNonNegativeInteger">toNonNegativeInteger</a></li><li><a href="global.html#toStr">toStr</a></li><li><a href="global.html#urlMirror">urlMirror</a></li><li><a href="global.html#zipCDNImage">zipCDNImage</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-12"> <div id="main"> <h1 class="page-title">Source: base/image.js</h1> <section> <article> <pre class="sunlight-highlight-javascript ">/** * Created by hongpao on 2017/9/26. */ /** * 关于图片的处理 * @param options * */ class imageUtil { getSuffixName(imageUrl) { //图片地址 imageUrl = imageUrl || ''; //获取图片地址的后缀名 let imageUrlAry = imageUrl.split('.'); let lastIndex = imageUrlAry.length - 1; let suffixName = imageUrlAry[lastIndex]; if (suffixName === 'png') { return 'jpg'; } else { return suffixName; } } getRectImageUrl(options) { options = options || {}; let imageUrl = options.imageUrl || ''; let source = options.source || 1; //来源判断(1:H5, 2小程序) let defaultImageUrl = 'http://d.2dfire.com/file/images/menulist/default-large.png'; let rightFlag = true; //图片地址协议处理 if (imageUrl &amp;&amp; imageUrl.length > 0) { if (imageUrl.substr(0, 5) === 'https') { imageUrl.replace("https:", ""); } else if (imageUrl.substr(0, 4) === 'http') { imageUrl.replace("http:", ""); } else { imageUrl = `//${imageUrl}`; } } else { rightFlag = false; } if (rightFlag) { let subUrl = ''; let index = 0; //老图片地址的处理 //http://rest3.zm1717.com/upload_files/00031985/menu/84d4ea26438063fcdf6162b41c79d932.png let flagStr = "upload_files"; if (imageUrl.indexOf(flagStr) > -1) { index = imageUrl.indexOf(flagStr) + flagStr.length + 1; imageUrl = imageUrl.replace("_s", ""); subUrl = imageUrl.substring(index, imageUrl.length); } //新图片地址的处理 //http://ifile.2dfire.com/00031985/menu/be4c0716b89e47869cc0d4b610d211e4.jpg let newFlagStr = ['ifile.2dfire.com', 'ifiletest.2dfire.com', 'file1.2dfire.com']; newFlagStr.map((item) => { if (imageUrl.indexOf(item) > -1) { index = imageUrl.indexOf(item) + item.length + 1; subUrl = imageUrl.substring(index, imageUrl.length); } }); //默认图片的宽高设置 let width = options.width || 144; let height = options.height || 144; //有些图片不需要裁剪,要等比缩放 let h = (height !== -1) ? ("_" + height + "h") : ""; // 新增分辨率判断 let ratio; if (source !== 2) { ratio = window.devicePixelRatio || 2; ratio = ratio === 3 ? 2 : ratio; //降级 } else { ratio = 2; } //图片质量 let quality = options.quality || 80; //图片后缀名的判断 let imgUrlArr = subUrl.split('.'); let l = imgUrlArr.length; //图片后缀名 let suffixName = options.suffixName || imgUrlArr[l - 1]; //图片是否支持webp格式 let isWebpSupport = options.isWebpSupport || false; //gif图是否显示动图(默认是) let isShowGif = options.isShowGif || true; /** * gif图特殊处理(默认动图) * 其他图片判断是否支付webp */ if (suffixName === 'gif') { if (!isShowGif) { suffixName = isWebpSupport ? 'webp' : 'jpg'; } } else { suffixName = isWebpSupport ? 'webp' : suffixName; } //不同环境下的域名地址 let imageBaseUrl = options.imageBaseUrl || '//ifile.2dfire.com/'; imageUrl = `${imageBaseUrl}${subUrl}@1e_${width}w${h}_1c_0i_0o_${quality}Q_${ratio}x.${suffixName}`; } //有图片地址,并且格式正确,则返回处理后的图片地址,否则返回默认图片地址; if (rightFlag) { return imageUrl; } else { if (source !== 2) { return defaultImageUrl; } else { return ''; } } } } export { imageUtil }; export default { imageUtil }; </pre> </article> </section> </div> </div> <div class="clearfix"></div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on 2018-01-16T14:37:15+08:00 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : false, showMenu : true, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html> <file_sep>/inside-boss/src/container/goodEdit/init.js import { currentAPIUrlPrefix, currentEnvString } from '../../utils/env' const protocol = (currentEnvString === 'PUBLISH' ? 'https://' : 'http://') const templateDomainPrefix = (currentEnvString === 'PUBLISH' || currentEnvString === 'PRE' ? 'ifile' : 'ifiletest') const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query) => { const { entityType='0', industry} = query; var options = { 'item': { entityType, industry, } } return options[key] }<file_sep>/inside-boss/src/container/visualConfig/sences/retail/commonComponents.js export default [ 'banner', 'title', 'coupons', 'searchInput', 'announce', 'hotline', 'whitespace', 'goodsList', 'goodsRanking', 'pictureAds', 'pictureTextNav', ] <file_sep>/inside-boss/src/components/couponPush/rechargeList.js /** * Created by air on 2018/3/15. */ import React, {Component} from 'react' import {Button, Pagination, Icon, Popover, Modal, Input} from 'antd' import styles from './rechargeList.css' import * as action from '../../action' class RechargeList extends Component { constructor(props) { super(props) this.changeModalValue = this.changeModalValue.bind(this); this.state = { current: 1, loading: false, funcitonId: '', failType: 0, modelValue: '', functionId: '' } } changeModalValue(e) { this.setState({modelValue: e.target.value}); } handleCancel = () => { const t = this const {dispatch} = t.props const value = this.state.modelValue const functionId = this.state.functionId if (value) { this.setState({ loading: true, functionId: '' }); dispatch(action.reupload({iphone: value, functionId: functionId})) } } handleClose = () => { const t = this const {dispatch} = t.props dispatch(action.visible(false)) } reupload(index) { const t = this const {dispatch, data} = t.props const {rechargeList} = data t.setState({ failType: rechargeList[index].failType, loading: false, modelValue: '', functionId: rechargeList[index].functionId }) if (rechargeList[index].failType === 1) { dispatch(action.visible(true)) } else if (rechargeList[index].failType === 4) { dispatch(action.visible(true)) } else { dispatch(action.reupload(rechargeList[index])) } } allReupload() { const t = this const {dispatch, data} = t.props const {rechargeList} = data dispatch(action.reupload(rechargeList)) } paginationChange(pageNumber) { console.log('Page: ', pageNumber); const t = this const {dispatch, data} = t.props const {name} = data this.setState({ current: pageNumber, }); dispatch(action.setPageNumber(pageNumber, status,)) } render() { const t = this const {data, dispatch} = t.props const {status, rechargeList, total, visible} = data const {current, failType} = t.state const {loading} = t.state return ( <div className={styles.rechargeListBox}> { status === '2' ? <Button className={styles.allReupload} onClick={t.allReupload.bind(t)}>批量重发</Button> : null } <ul className={styles.rechargeListUl}> <li className={styles.rechargeTitle}> <p>会员</p> <p>手机号码</p> <p>优惠券名称</p> <p>发券状态</p> <p>操作</p> </li> {rechargeList ? rechargeList.map((recharge, index) => { return ( recharge.status === 1 ? ( <li className={styles.rechargeLi} key={index}> <p>{recharge.userName}</p> <p>{recharge.iphone}</p> <p>{recharge.couponName}</p> <p>发送成功</p> <p></p> </li> ) : ( <li className={styles.rechargeLi} style={{background: '#fceeef'}} key={index}> <p>{recharge.userName}</p> <p>{recharge.iphone}</p> <p>{recharge.couponName}</p> <p>发送失败 { recharge.failType === 1 ? <Popover content='因手机号码错误发券失败'> <Icon type="exclamation-circle-o" className={styles.popoverHint}/> </Popover> : ( recharge.failType === 2 ? <Popover content='因网络原因发券失败'> <Icon type="exclamation-circle-o" className={styles.popoverHint}/> </Popover> : ( recharge.failType === 3 ? <Popover content='因其他原因发券失败'> <Icon type="exclamation-circle-o" className={styles.popoverHint}/> </Popover> : <Popover content='因查询不到该会员发券失败'> <Icon type="exclamation-circle-o" className={styles.popoverHint}/> </Popover> )) } </p> <p> <Button ref="reuploadBtn" id={recharge.functionId} size="small" onClick={t.reupload.bind(t, index)}>重发</Button> </p> </li> ) ) }) : ''} </ul> { (status !== 2) ? <div className={styles.paginationBox}> <Pagination className={styles.paginationHtml} showQuickJumper current={current} total={total} defaultPageSize={50} pageSize={50} onChange={this.paginationChange.bind(this)}/> <p>共{total}条记录</p> </div> : null } { (failType === 1) ? <Modal visible={visible} onOk={t.handleOk} onCancel={t.handleClose} footer={null} > <p className={styles.modelTitle}>编辑修改</p> <p className={styles.modelWord}>手机号码填写有误,请修改后重新发券</p> <p style={{margin: '30px 0 0 86px'}}> <span className={styles.star}>* </span>手机号码 : <Input style={{width: '240px'}} ref="iphone" value={t.state.modelValue} onChange={this.changeModalValue} placeholder="请填写手机号码"/> </p> <Button style={{margin: '30px 0 0 200px'}} type="primary" loading={loading} onClick={this.handleCancel}> 保存并发券 </Button> </Modal> : <Modal visible={visible} onCancel={t.handleClose} footer={null} > <p style={{margin: '20px 0 0 184px', fontSize: '16px'}}>查询不到该会员</p> <Button style={{margin: '28px 0 0 211px'}} type="primary" onClick={this.handleClose}> 确定 </Button> </Modal> } </div> ) } } export default RechargeList <file_sep>/static-hercules/src/static/js/jsSdkUtil.js /** * Created by hupo on 16/8/30. */ /* 微信 & QQ & 支付宝 & 百度统计 jsSdk 的封装 * * 不依赖任何其他js文件 * * 请使用全局的 "JsSdkUtil" 或 "window.JsSdkUtil" * * 在此js文件加载后(可以是加载后的任何地方), 根据所需要使用的功能, 配置 JsSdkUtil, 配置完成后, 显式调用 JsSdkUtil.initialize() 执行初始化 * * 使用示例: * <script src="../js/jsSdkUtil.js"></script> 加载此文件 * <script> * JsSdkUtil.scanCodeId = "scanCode"; (或 JsSdkUtil.scanCodeId = "wrapper"; JsSdkUtil.scanCodeConfirmId = "scanCode";) 根据需要配置所使用的功能 (可选) * JsSdkUtil.scanCallback = function (result) { 配置功能回调 (可选) * console.log("scanCallback run"); * window.location.href = result * }; * JsSdkUtil.initialize() 初始化 (必须) * </script> */ (function () { var BASE_URL = "http://api.l.whereask.com"; //grunt打包时的环境参数 var grunt_env = "grunt_env_dev"; if (grunt_env == 'grunt_env_daily') { //公共环境 BASE_URL = "http://api.l.whereask.com"; } else if (grunt_env == 'grunt_env_pre') { //预发地址 BASE_URL = 'https://meal.2dfire-pre.com'; } else if (grunt_env == 'grunt_env_release') { //发布地址 BASE_URL = 'https://meal.2dfire.com'; } var WX_JS_SDK_URL = "//res.wx.qq.com/open/js/jweixin-1.2.0.js"; var ALIPAY_JS_SDK_URL = "https://as.alipayobjects.com/g/component/antbridge/1.1.4/antbridge.min.js"; // var ALIPAY_JS_SDK_URL = "https://static.alipay.com/aliBridge/1.0.0/aliBridge.min.js"; var QQ_JS_SDK_URL = "https://mp.gtimg.cn/open/js/openApi.js"; var QQ_PAY_JS_SDK_URL = "//pub.idqqimg.com/qqmobile/qqapi.js?_bid=152"; var APP_JS_SDK_URL = "../public/js/FRWCardApp.js"; var BAIDU_ANALYSIS_URL = "//hm.baidu.com/hm.js?24910471637fcf3fc7f8a730579094d1"; var WX_CONFIG_URL = BASE_URL + "/share/v1/get_jsapi_ticket"; var QQ_CONFIG_URL = BASE_URL + "/share/v1/get_qq_jsapi_ticket"; // BASE_URL = 'http://mock.2dfire-daily.com/mockjs/27/mockjsdata/7/' var SHARE_INFO = BASE_URL + "/share/v1/info"; //获取分享所需的数据 var jsSdk, JsSdkUtil; var isInit = false; // 是否已经开始初始化 var isGetShareDataRetry = false; // 获取分享信息失败重试一次 var isGetSdkConfigRetry = false; // 获取分享信息失败重试一次 JsSdkUtil = { client: 0, // 客户端类型 1 微信; 2 支付宝; 3 qq; 4 app内嵌 debug: false, // 是否开启微信或qqSDk的调试 默认关闭 在init执行前配置 useShare: true, // 是否使用分享功能(包括朋友圈和分享给好友) 默认开启 在init执行前配置 useHideMenu: true, // 是否使用隐藏菜单功能 默认开启 在init执行前配置 useLocation: false, // 是否使用定位功能 默认关闭 在init执行前配置 userProtectMenu: false, // 是否开启传播类菜单 在init执行前配置 scanCodeId: undefined, // 是否使用扫码功能(直接指定 dom ID 自动开启, 应保证事件绑定时此ID对应的DOM已存在) 默认关闭 scanCodeConfirmId: undefined, // 此时 scanCodeId 作为wrapper用来绑定事件, scanCodeConfirmId 作为实际触发的 target(主要用于处理事件绑定时,扫码DOM元素还未生成的情况) shareInfo: undefined, // 分享的内容, 默认使用获取分享内容的接口 shareUrlParam: undefined, // 获取分享内容的url, 默认使用获取分享内容的接口 hideMenuList: undefined, // 隐藏的menuList, 有默认list,可以不传 scanCallback: undefined, // 扫码后的回调, 默认自动跳转到扫码地址 locationCallback: undefined, // 定位后的回调, 默认设置到 sessionStorage 名称: gps shareCallback: undefined, // 分享成功后的回调, 默认无 showProtectMenus: showProtectMenus, // init执行后 通过执行function 开启传播类菜单 bindShareData: bindShareData, // init执行后 通过执行function 绑定分享数据, 用于需要临时指定分享内容的情况, 会自动开启传播发送给好友和分享到朋友圈的菜单 initialize: initialize, // sdk配置初始化, 请再此文件加载后调用 (必须!) useGetNetworkType: false, getNetworkTypeCallback: undefined }; window.JsSdkUtil = JsSdkUtil; /* * 工具类方法 start */ // 简单封装 ajax 只用 get 方法 function ajax(url, arg1, arg2, arg3) { var params, success, error; if (typeof (arg1) == "object") { params = arg1; success = arg2; error = arg3 } else { params = undefined; success = arg1; error = arg2 } var xmlHttp = new XMLHttpRequest(); if (params && Object.keys(params).length > 0) { url += "?"; for (var k in params) { if (params.hasOwnProperty(k)) { url = url + k + "=" + encodeURIComponent(params[k]) + "&" } } if (url[url.length - 1] === "&") { url = url.slice(0, -1) } } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { var resp = JSON.parse(xmlHttp.responseText); if (resp.code == 1 && success) { success(resp.data) } else if (error) { error(resp) } } else if (error) { error("error status: " + xmlHttp.status) } } }; xmlHttp.open("get", url, true); xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.timeout = 15000; xmlHttp.ontimeout = function () { error("timeout") }; xmlHttp.send(); } // 简单封装获取 cookie 的方法 function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(/.*\s/, ""); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // 动态加载sdk和指定回调 function loadScript(src, callback) { var script = document.createElement('script'); var head = document.getElementsByTagName('head')[0]; script.type = 'text/javascript'; script.charset = 'UTF-8'; script.src = src; // script.onload = function () { // if (callback) { // callback(); // } // script.onLoad = null // }; script.addEventListener('load', function () { if (callback) { callback(); } script.removeEventListener('load', function () { }); }, false) head.appendChild(script); } // 地址栏参数替换 url 原始地址:如/hello/:id/ arg 如果只有一个参数,则为string,多个需传递数组 function api_get_request_url(url, arg) { if (typeof arg === "string") { return url.replace(':id', arg); } else if (typeof arg === "object" && arg.length > 0) { return api_get_request_url(url.replace(':id', arg[0]), arg.slice(1, arg.length)); } else { return url; } } /* 工具类方法 end */ // 设置 js api config 到 sessionStorage function setJsApi(page, data) { var obj = {}; obj.time = new Date().getTime(); obj.data = data; sessionStorage.setItem(page, JSON.stringify(obj)); } function getJsApi(page) { var result = JSON.parse(sessionStorage.getItem(page)); try { if (new Date().getTime() - result.time > 1.5 * 60 * 60 * 100) { result = null; } else { result = result.data; } } catch (ex) { result = null; } return result; } // 设置 shareInfo 到 sessionStorage function setShareInfo(shareInfo) { if (typeof shareInfo === "object" && shareInfo != null) { shareInfo = JSON.stringify(shareInfo); } else { shareInfo = ""; } sessionStorage.setItem("shareInfo", shareInfo); } function getShareInfo() { var shareInfo = null; try { shareInfo = JSON.parse(sessionStorage.getItem("shareInfo")); } catch (ex) { console.log("share need init"); } return shareInfo; } // 初始化sdk function initialize() { isInit = true; // client有值说明scriptInit先完成, 那么在此处初始化, client无值说明scriptInit后完成, 则在scriptInit回调中自动初始化. 以此保证初始化绝对执行 if (JsSdkUtil.client === 1) { getSdkConfig(WX_CONFIG_URL) } else if (JsSdkUtil.client === 2) { aliPayInit() } else if (JsSdkUtil.client === 3) { getSdkConfig(QQ_CONFIG_URL) } else if (JsSdkUtil.client === 4) { appInit() } } // 获取sdk验证信息 function getSdkConfig(url) { var page = "jsapi-" + window.location.href; // 使用完整url进行存储 解决url来回跳转细节时hash变动问题 var jsApi = getJsApi(page); if (jsApi) { wxQqInit(jsApi) } else { ajax(url, { url: window.location.href.split("#")[0] }, function (resp) { wxQqInit(resp); setJsApi(page, resp) }, function (resp) { if (!isGetSdkConfigRetry) { isGetSdkConfigRetry = true; getSdkConfig(url) } } ) } } // 获取分享数据 function getShareData() { var entityId = getCookie('entity_id'); var token = getCookie('token'); var params = { xtoken: token, entityId: entityId, type: 0 }; if (JsSdkUtil.shareUrlParam && typeof JsSdkUtil.shareUrlParam === 'object') { for (var k in JsSdkUtil.shareUrlParam) { if (JsSdkUtil.shareUrlParam.hasOwnProperty(k)) { params[k] = JsSdkUtil.shareUrlParam[k] } } } if (entityId) { ajax(SHARE_INFO, params, function (resp) { bindShareData(resp); setShareInfo(resp) }, function (resp) { if (!isGetShareDataRetry) { isGetShareDataRetry = true; getShareData() } } ) } } // 添加微信卡券 function addCard(list) { jsSdk.addCard({ cardList: list, success: function (res) { console.log("调用微信卡券接口成功"); }, }) } // 调用分享接口 function bindShareData(shareInfo) { // if (window.DFAnalytics) { // DFAnalytics.fire("Er", "marketing-url-1-bindShareData:" + shareInfo.friend.shareUrl); // DFAnalytics.fire("Er", "jssdk: " + JsSdkUtil.client); // } var friend = shareInfo.friend;//朋友 var moment = shareInfo.moment;//朋友圈 if (JsSdkUtil.client == 4) { // 调用app分享接口 jsSdk.share({ icon: friend.imgUrl || "../images/shop/wechatshare.png", title: friend.title, desc: friend.memo, link: friend.shareUrl, success: function (res) { }, cancel: function (res) { }, fail: function (res) { } }); } else if (JsSdkUtil.client == 1 || JsSdkUtil.client == 3) { // if (window.DFAnalytics) { // DFAnalytics.fire("Er", "marketing-url-1-bindShareData:" + friend.shareUrl); // } jsSdk.showMenuItems({ menuList: [ "menuItem:share:appMessage", "menuItem:share:timeline" ] // 要显示的菜单项,所有menu项见附录3 }); //分享给朋友 jsSdk.onMenuShareAppMessage({ title: friend.title, // 分享标题 desc: friend.memo, // 分享描述 link: friend.shareUrl, // 分享链接 imgUrl: friend.imgUrl || "../images/shop/wechatshare.png", // 分享图标 success: function () { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback("shareToFriend") } }, cancel: function () { // 用户取消分享后执行的回调函数 } }); //分享到朋友圈 jsSdk.onMenuShareTimeline({ title: moment.title, // 分享标题 link: moment.shareUrl, // 分享链接 imgUrl: moment.imgUrl || "../images/shop/wechatshare.png", // 分享图标 success: function () { // 用户确认分享后执行的回调函数 if (JsSdkUtil.shareCallback) { JsSdkUtil.shareCallback("shareToTimeLine") } }, cancel: function () { // 用户取消分享后执行的回调函数 } }); } } // 开启保护类菜单 function showProtectMenus() { jsSdk.showMenuItems({ menuList: [ "menuItem:copyUrl", "menuItem:openWithQQBrowser", "menuItem:openWithSafari" ] // 要显示的菜单项,所有menu项见附录3 }); } /* * wx 和 qq 初始化 */ function wxQqInit(config) { jsSdk.config({ debug: JsSdkUtil.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: config.appId, // 必填,公众号的唯一标识 timestamp: config.timestamp, // 必填,生成签名的时间戳 nonceStr: config.noncestr, // 必填,生成签名的随机串 signature: config.sign,// 必填,签名,见附录1 jsApiList: [ "getLocation", "onMenuShareTimeline", "onMenuShareAppMessage", "scanQRCode", "hideMenuItems", "showMenuItems", "getNetworkType", "chooseImage", "uploadImage" ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); //这里把checkApi改为ready,因为版本较低的微信不支持check jsSdk.ready(function () { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.getNetworkType({ success: function (res) { var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } if (JsSdkUtil.useHideMenu) { var menuList = [ "menuItem:favorite", "menuItem:share:qq", "menuItem:copyUrl", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:weiboApp", "menuItem:share:QZone", "menuItem:share:facebook", "menuItem:share:appMessage", "menuItem:share:timeline" ]; // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3 jsSdk.hideMenuItems({ menuList: (JsSdkUtil.hideMenuList && JsSdkUtil.hideMenuList.length > 0) ? JsSdkUtil.hideMenuList : menuList }); } // 微信扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanQRCode() { jsSdk.scanQRCode({ needResult: 1, desc: "scanQRCode desc", success: function (res) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(res.resultStr) } else { window.location.href = res.resultStr } return false; } }); } function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } }; scanCodeDom.onclick = null; scanCodeDom.onclick = scanCodeClickListener; } // 分享接口调用 if (JsSdkUtil.useShare) { var shareData = JsSdkUtil.shareInfo || getShareInfo(); if (shareData) { bindShareData(shareData); } else { getShareData(); } } // 开启保护类接口 if (JsSdkUtil.userProtectMenu) { showProtectMenus() } // 微信定位 if (JsSdkUtil.useLocation) { jsSdk.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90 var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。 var speed = res.speed; // 速度,以米/每秒计 var accuracy = res.accuracy; // 位置精度 window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(res) } }, fail: function (res) { console.log('获取位置失败'); } }); } }); } /* * 支付宝初始化 */ function aliPayInit() { if ((jsSdk.alipayVersion).slice(0, 3) >= 8.1) { // 支付宝获取网络类型 if (JsSdkUtil.useGetNetworkType) { jsSdk.network.getType({ timeout: 5000 }, function (result) { if (result.errorCode) { //没有获取网络状态的情况 //errorCode=5,调用超时 if (result.errorCode == 5) { jsSdk.alert({ title: '亲', message: '调用超时', button: '确定' }); } } else { //成功获取网络状态的情况 //result.isWifi bool 是否在Wifi下使用 //result.isOnline bool 是否联网 //result.type string 网络类型'fail': 无网络,或网络断开'wifi': wifi网络'wwan': 移动网络 8.2 //result.networkAvailable bool 网络是否连网可用 8.2 var networkType = result.type; window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } // 支付宝扫码 if (JsSdkUtil.scanCodeId) { var scanCodeDom = document.getElementById(JsSdkUtil.scanCodeId); function scanQRCode() { jsSdk.scan({ type: 'qr' //qr(二维码) / bar(条形码) / card(银行卡号) }, function (result) { if (result.errorCode) { //没有扫码的情况 //errorCode=10,用户取消 //errorCode=11,操作失败 if (result.errorCode == 11) { //alert('操作失败'); } } else { //成功扫码的情况 if (result.qrCode !== undefined) { if (JsSdkUtil.scanCallback) { JsSdkUtil.scanCallback(result.qrCode) } else { window.location.href = result.qrCode } } } }); } function scanCodeClickListener(e) { if (JsSdkUtil.scanCodeConfirmId) { if (JsSdkUtil.scanCodeConfirmId === e.target.id) { scanQRCode() } } else { scanQRCode() } } scanCodeDom.onclick = null; scanCodeDom.onclick = scanCodeClickListener; } // 支付宝定位 if (JsSdkUtil.useLocation) { jsSdk.geolocation.getCurrentPosition({ timeout: 5000 //超时时间 }, function (res) { if (res.errorCode) { //没有定位的情况 //errorCode=5,调用超时 } else { //成功定位的情况 var latitude = res.coords.latitude; var longitude = res.coords.longitude; window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(res) } } }); } } else { jsSdk.alert({ title: '亲', message: '请升级您的钱包到最新版', button: '确定' }); } } /* * App内嵌初始化 */ function appInit() { //获取网络状态接口 if (JsSdkUtil.useGetNetworkType) { jsSdk.getNetworkType({ success: function (res) { var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi window.sessionStorage.removeItem("networkType"); window.sessionStorage.setItem("networkType", networkType); if (JsSdkUtil.getNetworkTypeCallback) { JsSdkUtil.getNetworkTypeCallback(networkType); } } }); } // App定位 if (JsSdkUtil.useLocation) { if (jsSdk.getLocation) { jsSdk.getLocation({ type: 'wgs84', // 坐标系类型,默认为wgs84的gps坐标 success: function (res) { //成功定位的情况 var latitude = res.latitude; var longitude = res.longitude; window.localStorage.removeItem("gps"); window.localStorage.setItem("gps", parseInt(longitude * 1000000) + ":" + parseInt(latitude * 1000000)); if (JsSdkUtil.locationCallback) { JsSdkUtil.locationCallback(res) } }, cancel: function (res) { console.log("cancel") }, fail: function (res) { console.log("fail") } }); } } } // 根据客户端加载对应的sdk文件 function scriptInit() { var userAgent = navigator.userAgent; if (userAgent.indexOf("MicroMessenger") !== -1) { loadScript(WX_JS_SDK_URL, function () { // 用 setTimeOut 保证 加载后的jsSdk执行完成 setTimeout(function () { jsSdk = wx; JsSdkUtil.client = 1; if (isInit) { getSdkConfig(WX_CONFIG_URL) } }, 0); }); } else if (userAgent.indexOf("AlipayClient") !== -1) { loadScript(ALIPAY_JS_SDK_URL, function () { setTimeout(function () { jsSdk = Ali; JsSdkUtil.client = 2; if (isInit) { aliPayInit() } }, 0); }); } else if (userAgent.indexOf("QQ") !== -1) { loadScript(QQ_JS_SDK_URL, function () { // 加载qq钱包 loadScript(QQ_PAY_JS_SDK_URL, function () { }); setTimeout(function () { jsSdk = mqq; JsSdkUtil.client = 3; if (isInit) { getSdkConfig(QQ_CONFIG_URL) } }, 0); }); } else if (userAgent.indexOf("cardapp.client") !== -1) { loadScript(APP_JS_SDK_URL, function () { setTimeout(function () { jsSdk = FRWCardApp; JsSdkUtil.client = 4; if (isInit) { appInit() } }, 0); }); } // 加载百度统计脚本 loadScript(BAIDU_ANALYSIS_URL) } scriptInit() })(); // 安卓阻止手机字体放大xiangpitang // (function () { // //判断是否是安卓手机 true=是;false=不是 // var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") >0 ? true : false; // if(isAndroid){ // if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") { // handleFontSize(); // } else { // if (document.addEventListener) { // document.addEventListener("WeixinJSBridgeReady", handleFontSize, false); // } else if (document.attachEvent) { // document.attachEvent("WeixinJSBridgeReady", handleFontSize); // document.attachEvent("onWeixinJSBridgeReady", handleFontSize); // } // } // } // // // function handleFontSize() { // //安卓会有延迟,因此安卓手机下给用户提示,并不做字体大小的限制 // // // 设置网页字体为默认大小 // // WeixinJSBridge.invoke('setFontSizeCallback', { // // 'fontSize': 0 // // }); // // // // // 重写设置网页字体大小的事件 // // WeixinJSBridge.on('menu:setfont', function () { // // WeixinJSBridge.invoke('setFontSizeCallback', { // // 'fontSize': 0 // // }); // // }); // alert("请调整字体大小为标准字体大小"); // } // })(); <file_sep>/inside-boss/src/components/retailManage/main.js import React, {Component} from 'react' import CateList from '../cateManage/main' import GoodsProperty from '../goodsProperty/main' import ItemList from '../itemList/main' import styles from './main.css' class RetailMain extends Component { constructor(props) { super(props) this.state = { tabs: [{ name: '商品管理', active: true, }, { name: '分类管理', active: false, }, { name: '商品属性', active: false, }, ] } } /** * 切换tab标签 * @param item * @private */ _switchTab(item) { const { name } = item const { tabs } = this.state tabs.map(function(data) { data.active = false if(data.name === name){ data.active = true } }) this.setState({ tabs, }) } render() { const { tabs=[] } = this.state const { data, dispatch } = this.props return ( <div className={styles.retail_manage_container}> <ul className={styles.goods_cate_tab}> { tabs.map((item, i) => { return ( <li key={i} className={item.active ? styles.active : ''} onClick={() => this._switchTab(item)} > {item.name} </li> ) }) } </ul> { tabs[0].active === true && <ItemList data={data} dispatch={dispatch} _switchTab={this._switchTab.bind(this, {name: '分类管理',active: true})}></ItemList> } { tabs[1].active === true && <CateList data={data} dispatch={dispatch}></CateList> } { tabs[2].active === true && <GoodsProperty data={data} dispatch={dispatch}>商品属性</GoodsProperty> } </div> ) } } export default RetailMain <file_sep>/static-hercules/src/ocean-zl/router.js var Router = require('vue-router') export var router = new Router({ routes: [ { path: '*', redirect: '/result' }, { path: '/input', name: 'input', component: require('./views/inputshopinfo/Input.vue') }, { path: '/input-tl', name: 'input-tl', component: require('./views/inputshopinfo/Input-tl.vue') }, { path: '/result', name: 'result', component: require('./views/result/ApplyResult.vue') }, { path: '/result-tl', name: 'result', component: require('./views/result/ApplyResult-tl.vue') }, { path: '/inactive-tl', name: 'inactive-tl', component: require('./views/result/inactive-tl.vue') } ] }) router.beforeEach((to, from, next) => { // console.log(to,from,next); // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) <file_sep>/static-hercules/src/wechat-direct-con/store/mutation-types.js // 在input页面修改商户信息 export const MODIFY_MERCHANT = 'MODIFY_MERCHANT' //底部弹出选择 export const PICKER_CHANGE = 'PICKER_CHANGE' //底部弹出日期选择 export const DATE_PICKER_CHANGE = 'DATE_PICKER_CHANGE' //底部弹出地址选择器 export const ADDRESS_PICKER_CHANGE = 'ADDRESS_PICKER_CHANGE' //修改switch开关 export const SWITCH_CONTROL = 'SWITCH_CONTROL' //修改当前编辑状态 export const CHANGE_VIEWSTATE = 'CHANGE_VIEWSTATE' //保存表单初始值 export const SAVE_MERCHANT_INFO = 'SAVE_MERCHANT_INFO' //是否是修改省市区字段 export const IS_EDIT_ADDRESS = 'IS_EDIT_ADDRESS' //修改是否展示底部弹框的值 export const IS_SHOW_POP = 'IS_SHOW_POP'<file_sep>/inside-boss/src/components/goods/tableSetting.js import React, {Component} from 'react' import { Modal, Checkbox, Row, Col, Button, Icon } from 'antd' import * as action from '../../action' import cx from 'classnames' import style from './style.css' const CheckGroup = Checkbox.Group const ButtonGroup = Button.Group; const VariableBtn = (props)=>{ const { num = 1, maxNum = Infinity , minNum = -Infinity, handleComputed, disabled, size='small' } = props return( <ButtonGroup> <Button onClick = {handleComputed.bind(null,-1)} disabled = { disabled || num <= minNum } size={size}><Icon type="minus" /></Button> <Button disabled= {disabled} size={size} >{num}</Button> <Button onClick = {handleComputed.bind(null,1)} disabled = { disabled || num >= maxNum } size={size}><Icon type="plus" /></Button> </ButtonGroup> ) } const CreateForm = (props) => { const { visible, onCancel, handleChange, handleCheckAll, data, title, footer, handleComputed, state } = props; return ( <Modal wrapClassName = {style.templateSelectWarp} width={780} visible={visible} title={title} footer={null} onCancel={onCancel} > <div> { data.fromFieldsList && data.fromFieldsList.map(item=>( <div className={style.boxItem} key={item.baseName}> <div className={style.itemTitle}> <Checkbox checked={item.allChecked} onChange={handleCheckAll.bind(null,item.baseName)}></Checkbox> <span style={{fontSize:'16px',color:'#333'}}>{item.baseName}</span> </div> <CheckGroup onChange={handleChange.bind(null,item.baseName)} value={item.selected} > <Row> { item.baseList.map(i=>( <Col key={i.name} span={item.span}> <Checkbox className={style.itemColor} disabled={i.disabled && !item.selected.includes(i.toggle) } value={i.name}>{i.name}</Checkbox> </Col> )) } </Row> <div> <Row> { item.variable && item.variable.map(i=>( <Col span={i.span} key={i.name}> <Checkbox className={style.itemColor} disabled={i.disabled} value={i.name}>{i.name}</Checkbox> <VariableBtn num={state.variable[i.name]} maxNum = {i.maxNum} minNum ={i.minNum } handleComputed = { handleComputed.bind(null,i) } disabled={ i.disabled || !item.selected.includes(i.name) } > </VariableBtn> </Col> )) } </Row> </div> <div> <Row> { item.categroy.map(i=>( <Col span={i.span} key={i.name}> <span>{i.name}:</span> <Row> { i.list.map(v=>( <Col key={v.name} span={v.span}> <Checkbox className={cx(style.categroy,style.itemColor)} disabled={v.disabled} value={v.name} key={v.name}>{v.name}</Checkbox> </Col> )) } </Row> </Col> )) } </Row> </div> </CheckGroup> </div> )) } </div> <div className={style.itemFooter}> {footer} </div> </Modal> ); } class view extends Component{ constructor(){ super() this.state={ variable:{} } } handleComputed=(item,value)=>{ this.setState(()=>({variable:{...this.state.variable,[item.name]:this.state.variable[item.name] + value}})) } handleChange=(baseName,value)=>{ } handleCheckAll=(baseName,e)=>{ } componentWillReceiveProps(nextProps){ if(this.props.data.fromFieldsList !== nextProps.data.fromFieldsList){ let obj = {} nextProps.data.fromFieldsList.map(item=>{ if(item.variable && item.variable.length > 0 ){ item.variable.map(i=>{ if(item.selected.includes(i.name)){ obj[i.name] = this.state.variable[i.name]?this.state.variable[i.name]:i.value }else{ obj[i.name] = i.value } }) } }) this.setState(()=>({variable:{...obj,}})) } } render() { const { data = [], title = '表头字段设置', children, visible, handleHide } = this.props return ( <CreateForm data={data} state={this.state} title={title} footer={children} handleComputed={this.handleComputed} handleChange={this.handleChange} handleCheckAll={this.handleCheckAll} visible={visible} onCancel = {handleHide} /> ); } } export default view<file_sep>/static-hercules/src/oasis/store/mutation-types.js /** * Created by zyj on 2018/4/3. */ // 获取shopInfo export const GET_APPLY_MATERIALS = 'GET_APPLY_MATERIALS' // 在input页面修改店铺信息 export const MODIFY_SHOPINFO = 'MODIFY_SHOPINFO' // 修改pickerslot export const MODIFY_PICKER_SLOT = 'MODIFY_PICKER_SLOT' // 保存省列表 export const SAVE_PROVINCE_LIST = 'SAVE_PROVINCE_LIST' // 修改pickerChangeValue的值 export const MODIFY_PICKER_CHANGE_VALUE = 'MODIFY_PICKER_CHANGE_VALUE' //修改示例图片图片显示 export const CHANGE_EXAMPLE_PHOTO = 'CHANGE_EXAMPLE_PHOTO' // hide 区县 export const HIDE_TOWN = 'HIDE_TOWN'<file_sep>/inside-boss/src/container/importHistory/init.js const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query) => { const {entityId} = query; const options = { "import_history": { exportData: { ...APP_AUTH, entityId: entityId }, records:[], totalRecord:0, pageNum:1, pageSize:10 } } return options[key] }; <file_sep>/inside-chain/src/core/utils/is.js function isOO(obj) { return Object.prototype.toString.call(obj) === '[object Object]' } export function isObj(obj) { return obj !== null && typeof obj === 'object' && !isArr(obj) } export function isPlainObj(obj) { if (!isOO(obj)) return false let ctor = obj.constructor if (!isFunc(ctor)) return false let prot = ctor.prototype if (!isOO(prot)) return false return prot.hasOwnProperty('isPrototypeOf') } export function isFunc(obj) { return typeof obj === 'function' } export function isNum(value, isStrict) { if (!isStrict) { value = +value } return typeof value === 'number' && value - value + 1 === 1 } export function isStr(obj) { return typeof obj === 'string' } export function isBool(obj) { return typeof obj === 'boolean' } export function isArr(obj) { return Array.isArray(obj) } export function isUNN(obj) { return obj === null || obj === undefined || Number.isNaN(obj) } export function isEmptyObj(obj) { for (let key in obj) { return false } return true } export function isEmptyArr(obj) { return isArr(obj) && obj.length === 0 } export function isPromise(obj) { return isFunc(obj) && obj.then } <file_sep>/static-hercules/src/bindPhone/config/interception.js import { GATEWAY_BASE_URL, ENV } from 'apiConfig'; import { APP_KEY } from '../config/index'; import axios from 'axios'; import { GW } from '@2dfire/gw-params'; import qs from 'qs'; import sessionStorage from '@2dfire/utils/sessionStorage'; import handleError from '../utils/catchError'; const GWObject = qs.parse(GW); const API_PARAMS = `?app_key=${APP_KEY}&method=`; let getEnv = function (env) { if (ENV === 'publish' || ENV === 'pre' || ENV === 'daily') { return ENV } else { return env } } // 超时时间 axios.defaults.timeout = 30000; axios.defaults.headers.common['env'] = getEnv("0355c5250fb945a1b83235dae80850d6"); // http请求拦截器 axios.interceptors.request.use( config => { let token = sessionStorage.getItem('token'); config.headers.common['token'] = token || ''; config.url = GATEWAY_BASE_URL + API_PARAMS + config.url; config.params = Object.assign({}, config.params, GWObject); return config; }, error => { return Promise.reject(error); } ); // http响应拦截器 axios.interceptors.response.use( res => { // 响应成功关闭loading let data = res.data; if (data.code === 1) { return data.data.data; } else { handleError(data); return Promise.reject(res); } }, error => { handleError(error.data); return Promise.reject(error); } ); export default axios; <file_sep>/static-hercules/src/wechat-direct-con/store/state.js /** * Created by huaixi on 2019/3/28. */ export default { //提交的所有字段信息 merchantInfo: { //商户号 merchantNum: "", //主体类型 merchantType: "", //营业执照照片 businessLicensePic: "", //营业执照注册号 businessLicenseNum: "", //商户名称 merchantName: "", //注册地址 registerAddress: { province: {}, city: {}, }, //法人名称 corporationName: "", //营业期限 businessDeadLine: true, //营业开始时间 businessStartTime: "", //营业结束时间 businessEndTime: "", //营业执照类型 businessLicenseType: "", //个体工商户, 企业商户-三证合一, 企业商户-未三证合一 merchantKind: 3, //组织机构代码证照片 orgPhoto: "", //组织机构代码 orgNo: "", //组织机构有效期开始时间 orgStartTime: "", //组织机构有效期结束时间 orgEndTime: "", wechatAuditType: 1, //特殊资质照片 qualification: [], //====企业商户对公收款账号====// //开户名称 businessAccountName: "", //开户银行 businessAccountBank: "", businessAccountBankCode: "", //银行卡号 businessAccountNumber: "", //开户省市 businessAccountAddressProvince: "", businessAccountAddressProCode: "", businessAccountAddressCity: "", businessAccountAddressCityCode: "", //开户支行 businessAccountSubBank: "", //微信审核提交时间 applyTime: '', //小微升级提交时间 upgradeTime: '', //=================================小微商户部分填写信息 //门店名称 shopName: "", //店铺所在地 shopAddress: { province: {}, city: {} }, //详细地址 detailAddress: "", //店铺门头照 shopLicensePic: "", //店铺环境照 shopEnvironmentPic: "", //客服电话 serviceTel: "", //服务类型 serviceType: "", //身份证正面 idCardFront: "", //身份证反面 idCardReverse: "", //身份证姓名 idCardName: "", //证件号码 idCardNumber: "", //身份证是否长久有效 idCardEffLongTime: false, //开始时间 startDate: "", //结束时间 endDate: "", //商户简称 userSimpleName: "", //开户名称 accountName: "", //开户银行 accountBank: "", accountBankCode: "", //银行卡号 accountNumber: "", //开户省市 accountAddressProvince: "", accountAddressProCode: "", accountAddressCity: "", accountAddressCityCode: "", //开户支行 accountSubBank: "", //手机号码 userTelNumber: "", //联系邮箱 userEmailNumber: "", //是否已启用小微 isXWEnable: false }, // 保存的id saveId: '', //底部选择弹出 picker: { showPicker: false, pickerName: '', //当前选择的字段 pickerSlots: [{ defaultIndex: 0 }, //默认选中第一个 ], pickerTitle: '', other: '', //其他需要设置的值,省份需要设置id的值 }, //底部日期选择弹出 dateNewPicker: { showPicker: false, pickerName: '', //当前选择的字段 pickerTitle: '', //当前标题 pickerValue: '', //当前选中日期值 }, //底部地址选择器 addressPicker: { showPicker: false, pickerName: '', pickerTitle: { province: {}, city: {} }, topTitle: '选择地址' }, //switch开关 switchControl: { switchName: '', switchValue: false, }, //图片展示 examplePhoto: { img: '', isShow: false }, /** * 显示状态 * detail: 查看详情,不可修改; * edit: 编辑修改,已提交之后,申请通过,并为可修改状态; * first: 第一次提交 * */ viewState: 'first', //状态,number类型,当为31时代表进件成功报名失败,只可修改部分数据 subStatus: 0, //服务端所需的小微部分字段信息 paymentWxXwAuthInfo: { entityId: "", //门店名称 shopName: "", //店铺所在地 shopProvince: "", shopCity: "", //详细地址 detailAddress: "", //店铺门头照 shopPhoto: "", //店铺环境照 indoorPhoto: "", //客服电话 servicePhone: "", //服务类型 industryType: "", //身份证正面 certFront: "", //身份证反面 certBack: "", //身份证姓名 certName: "", //证件号码 certNo: "", //开始时间 certValidStartTime: "", //结束时间 certValidEndTime: "", wxXwBankInfo: { //开户名称 accountName: "", //开户银行 accountBank: "", //银行卡号 accountNo: "", //开户省 accountProvince: "", //开户市 accountCity: "", //开户支行 accountSubBank: "", }, wxXwContactInfo: { //商户简称 merchantShortName: "", //手机号码 contactPhone: "", //联系邮箱 email: "", } }, paymentWxXwUpgradeInfo: { entityId: "", merchantType: "", businessLicensePhoto: "", businessLicenseNo: "", address: "", merchantName: "", legalPerson: "", licenseStartTime: "", licenseEndTime: "", isIntegrade: "", orgPhoto: "", orgNo: "", orgStartTime: "", orgEndTime: "", qualification1: "", qualification2: "", qualification3: "", qualification4: "", qualification5: "", wxXwBankInfo: { //开户名称 accountName: "", //开户银行 accountBank: "", //银行卡号 accountNo: "", //开户省 accountProvince: "", //开户市 accountCity: "", //开户支行 accountSubBank: "", } }, accountVerifyInfo: { //付款户名 accountName: "", //汇款金额 payAmount: "", //收款卡号 destinationAccountNumber: "", //收款户名 destinationAccountName: "", //开户银行 destinationAccountBank: "", //省市信息 city: "", //备注 remark: "", //截止日期 deadlineTime: "", }, wxXwContactInfo: { //商户简称 merchantShortName: "", //手机号码 contactPhone: "", //联系邮箱 email: "", }, wxXwBankInfo: { accountName: "", //开户银行 accountBank: "", //银行卡号 accountNo: "", //开户省 accountProvince: "", //开户市 accountCity: "", //开户支行 accountSubBank: "", }, merchantInfoString: '', // 保存表单初始的参数内容 //小微升级页面数据有修改 xwUpgradeChanged: false, // 是否是修改省市区字段 isEditAddress: false, // 是否展示底部弹框 ispopShow: false, }<file_sep>/inside-boss/src/components/goodsPicture/main.js /** * Created by air on 2017/7/10. */ import React, { Component } from 'react' import styles from './style.css' import Handle from './handle' import PictureList from './pictureList' import PictureDetailList from './pictureDetailList' import EditGoodsTemplate from './templateDetail/editGoodsTemplate' import * as action from '../../action' import {Select} from 'antd' const Option = Select.Option; class Main extends Component { constructor(props) { super(props) this.state = { storeName: '' } } componentDidMount() { const t = this const {dispatch} = t.props // dispatch(action.getPictureList(1)) } componentWillReceiveProps(nextProps) { // console.log(nextProps) // if (nextProps.data.brandId !== this.state.storeName) // this.setState({ // storeName: nextProps.data.brandId // }) } handleChange(e) { console.log(e); this.setState({ storeName: e, }); const {dispatch} = this.props dispatch(action.setBrandId(e)); // dispatch(action.getPictureList(1)) dispatch(action.setPageNumber(1)) dispatch(action.backPictureList()) dispatch(action.getPictureList(1,'',e)) dispatch(action.getDuplicatedItems('',e)) dispatch(action.detailChange({detail:false})) dispatch(action.editTemplate({edit:false,templateId:""})) } render() { const t = this const { data, dispatch, detail } = this.props // console.log(data) const { pictureListLength } = data return (<div className={styles.wraperBox}> { data.isShowBrand === "fixed" ? (<div className={styles.select_wrapper}> <span className={styles.select_title}> 品牌: </span> <Select className={styles.base_select} defaultValue={t.state.storeName || '请选择'} value={t.state.storeName || '请选择'} onChange={(e) => t.handleChange(e)}> { data.brandList ? data.brandList.map(function (val) { return <Option value={val.entityId} key={val.entityId}>{val.name}</Option> }) : '' } </Select> <span> {t.state.storeName ? '' : '说明:请先选择品牌。如果没有品牌请在掌柜APP内创建一个品牌。'} </span> {t.state.storeName ? '' : (function () { return <hr/> }())} </div> ) : "" } { (!data.isShowBrand && (data.isShowBrand !== null)) ? '' : (((t.state.storeName && data.isShowBrand === "fixed") || data.isShowBrand !== "fixed") ? ( <div className={styles.viewBox}> { !detail.edit&& <Handle data={data} dispatch={dispatch}/> } { !!detail.edit && !detail.detail&& <EditGoodsTemplate data={data} dispatch={dispatch} detail={detail} /> } { (() => { if (pictureListLength > 0 && !detail.detail && !detail.edit) { return ( <PictureList data={data} dispatch={dispatch}/> ) } else { if (!!detail.detail && !detail.edit) { return ( <PictureDetailList data={data} dispatch={dispatch} detail={detail}/> ) } else { return null } } })() } </div> ) : '') } </div> ) } } export default Main <file_sep>/static-hercules/src/ocean-zl/store/getters.js /** * Created by zipai on 2019/7/11. */ // 店铺原始基本信息 export const applyInfo = state => { return state.applyInfo } <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/hotline/TmpEditor.js import React, {Component} from 'react' import { Radio, Button, Input } from 'antd'; import { SketchPicker } from 'react-color'; import style from './TmpEditor.css' import { DesignEditor, ControlGroup } from '@src/container/visualConfig/views/design/editor/DesignEditor'; import BanckgrondSelect from '@src/container/visualConfig/views/design/common/banckgrondSelect' const RadioGroup = Radio.Group; export default class TelephoneEditor extends DesignEditor { constructor(props) { super(props); this.state= { isSketchPicker: false, isSketchPickerbg: false, } } configChang = (obj) => { const { value, onChange } = this.props; const { config } = value onChange(value, { config: { ...config, ...obj }}) } changeGroup = (str, val) => { this.configChang({[str]: val.target.value}) } showSkentPick = (str) => { this.setState({ [str]: !this.state[str] }) } handleChangeComplete = (str, color) => { // 拾色器的回调 this.configChang({[str]: color.hex}) } render() { const { value, prefix, validation, onChange } = this.props; const { config } = value const { textColor, backgroundColor, mode } = config const { isSketchPicker, isSketchPickerbg } = this.state return ( <div className={`${prefix}-design-component-line-editor`}> <div className={style.componentTitleEditor}> <ControlGroup label="框体样式:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={mode} className={style.controlGroupControl} onChange={(e) => this.changeGroup('mode', e)}> <Radio name="mode" value='1'>样式一</Radio> {/* <Radio name="mode" value='2'>圆角</Radio> */} </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="框体颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <BanckgrondSelect value = {value} onChange = {onChange} backgroundColor = {backgroundColor} isSketchPickerbg= {isSketchPickerbg} showSkentPick = {this.showSkentPick} /> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本位置:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <RadioGroup value={value.config.textAlign} className={style.controlGroupControl} onChange={(e) => this.changeGroup('textAlign', e)}> <Radio name="textAlign" value='left'>居左</Radio> <Radio name="textAlign" value='center'>居中</Radio> </RadioGroup> </div> <div className={style.componentTitleEditor}> <ControlGroup label="文本颜色:" error={validation.hasPadding} className={style.groupLabel} > </ControlGroup> <div className={style.titlePickColor}> <Button style={{backgroundColor: textColor}} className={style.pickColorBtn} onClick={() => this.showSkentPick('isSketchPicker')} type="primary" /> {isSketchPicker && <SketchPicker className={style.titleSketchPicker} onChangeComplete={(e) => this.handleChangeComplete('textColor', e)} />} </div> </div> </div> ) } static designType = 'hotline'; static designDescription = '客服电话'; static designTemplateType = '其他类'; static getInitialValue() { return { config: { type: 'hotline', mode: '1', // 显示样式。可选值:'1'(暂时只支持这一个值) backgroundColor: '#f5f5f5', // 背景色 textAlign: 'left', // 文字位置。可选值:left、center textColor: '#5a5a5a', // 文字颜色 } } } } <file_sep>/static-hercules/src/nav/main.js // 通过 CommonJS 规范导入 CSS 模块 require('./main.css'); // 通过 CommonJS 规范导入 nav 函数 require('./nav.js');<file_sep>/inside-boss/src/components/routeInfoImport/main.js /** * Created by air on 2017/7/31. */ import React, { Component } from 'react' import cx from 'classnames' import styles from './style.css' import { message, Button, Modal, Spin } from 'antd' import RouteList from './routeList' import * as action from '../../action' import saveAs from '../../utils/saveAs' import * as bridge from '../../utils/bridge' import FileUpload from 'react-fileupload' class Main extends Component { constructor (props) { super(props) this.state = { importLock: false, exportLock: false, previewText: '请上传excel文件' } } componentDidMount(){ const t =this const { dispatch } = t.props dispatch(action.getRouteList(1)) } setOptions () { const t = this const {dispatch, data} = t.props const {importUrl, importData, isRecharge} = data const {token} = bridge.getInfoAsQuery() return { baseUrl: importUrl, param: importData, fileFieldName: 'file', dataType: 'json', wrapperDisplay: 'inline-block', multiple: false, numberLimit: 1, accept: '*/*', chooseAndUpload: false, paramAddToField: importData, withCredentials: false, requestHeaders: { 'X-Token': token }, chooseFile: function (files) { var name = (typeof files === 'string') ? files : files[0].name if (/\.(xls|xlsx)$/.test(name)) { if (files[0] && files[0].size < 1024 * 1024 * 20) { t.setState({ previewText: name }) } else { message.info('文件太大,无法上传!') if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1500) } t.setState({ previewText: '请上传excel文件' }) } } else { message.info('仅允许上传格式为.xls或.xlsx的文件!') if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1500) } t.setState({ previewText: '请上传excel文件' }) } }, beforeUpload: function (files, mill) { if (!files || files.length <= 0) { if(t.state.previewText === '请上传excel文件'){ dispatch(action.globalMessageError('请先选择合适的文件!')) return false }else{ dispatch(action.globalMessageError('选择文件已取消,请重新选择文件')) setTimeout(function () { t.clearFn(undefined, dispatch) }, 1500) return false } } else { //此块逻辑可以省略,留着做为双重保险 var name = (typeof files === 'string') ? files : files[0].name if (/\.(xls|xlsx)$/.test(name)) { if (files[0] && files[0].size < 1024 * 1024 * 20) { files[0].mill = mill return true } else { message.info('文件太大,无法上传!') if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1500) } t.setState({ importLock: false, previewText: '请上传excel文件' }) return false } } else { message.info('仅允许上传格式为.xls或.xlsx的文件!') if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1500) } t.setState({ importLock: false, previewText: '请上传excel文件' }) return false } } }, doUpload: function (files, mill) { // console.log('you just uploaded', typeof files === 'string' ? files : files[0]); }, uploading: function (progress) { // console.log('loading...', progress.loaded / progress.total + '%') t.setState({ importLock: true }) }, uploadSuccess: function (resp) { let code = resp.code if (code === 1) { const errorList = resp.data let messageList = errorList ? errorList : [] const {dispatch ,data} = t.props dispatch(action.setCurIndex(1)) dispatch(action.getRouteList(1)) Modal.info({ title: '导入信息', onOk: () => { if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1000) } t.setState({ importLock: false, previewText: '请上传excel文件' }) }, content: <div> { messageList.length > 0? <div> <p className={styles.titleTip}> 文件中有错误信息,请仔细检查修改后,重新选择文件导入 </p> <div className={styles.errorBox}> <ul> <li>错误位置</li> <li>错误信息</li> </ul> { messageList.map((e, i) => { return <ul key={i}> <li>第{e.lineNum}行</li> <li>{e.msg}</li> </ul> }) } </div> </div> :<p className={styles.importSuccess}>导入成功</p> } </div>, width: 720 }) } else { if (resp.errorCode === '401') { bridge.callParent('logout') return } Modal.info({ title: '导入信息', onOk: () => { if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1000) } t.setState({ importLock: false, previewText: '请上传excel文件' }) }, content: <div>{resp.message}</div> }) } }, uploadError: function (err) { if (err.errorCode === '401') { bridge.callParent('logout') return } message.info(err.message) t.setState({ importLock: false, previewText: '请上传excel文件' }) }, uploadFail: function (resp) { message.info('很抱歉,本次导入失败,请稍后重试。') if (!isRecharge) { setTimeout(function () { t.clearFn(undefined, dispatch) }, 1000) } t.setState({ importLock: false, previewText: '请上传excel文件' }) }, textBeforeFiles: true } } clearFn (e, dispatch) { (e !== undefined) && e.preventDefault() window.location.reload() } json2url (json) { var url = '' var arr = [] for (let i in json) { arr.push(i + '=' + json[i]) } url = arr.join('&') return url } handleExport (url) { const t = this const {token} = bridge.getInfoAsQuery() t.setState({ exportLock: true }) const {isRecharge} = this.props.data if (!!isRecharge) { message.warn('没有选择有效的文件!') setTimeout(() => { t.setState({ exportLock: false }) }, 2000) return } saveAs(url, token).then( filename => message.success('导出成功!'), // 成功返回文件名 err => { if (err.code === 0) { if (err.errorCode === '401') { bridge.callParent('logout') return } message.error(err.message || '导出失败') } } ).then(e => this.setState({exportLock: false})) } handleDownload (url) { location.href = url } render () { const t = this const {dispatch, data} = t.props const testList = Object.keys(data) if (testList.length === 0) {return null} // isRecharge 是否为会员卡批量充值入口 const {exportUrl, exportData, exportBtnText, templateFile, isRecharge, showSpin} = data const showBtn = (t.state.previewText === '请上传excel文件') ? false : true const _exportUrl = exportUrl + '?' + t.json2url(exportData) return ( <div className={styles.main_wrapper}> <div className={styles.top_line}> <div className={styles.import_part}> <Button className={styles.secondButton} onClick={t.handleDownload.bind(t, templateFile)}>下载空白模版</Button> <div className={styles.vertical_line}></div> <div className={styles.view_area}> <p className={styles.view_text}>{t.state.previewText}</p> { (() => { if (showBtn) { return ( <div className={styles.delete_btn} onClick={e => { t.clearFn(e, dispatch) }}> <div className={styles.delete_vertical}/> <div className={styles.delete_horizontal}/> </div> ) } else { return null } })() } </div> <FileUpload options={t.setOptions()} className={styles.fileupload}> <Button className={styles.chose_area} ref="chooseBtn"> <span>选择文件</span> </Button> <div style={{width:'16px', display:'inline-block'}}></div> <Button type="primary" className={styles.chooseFile} ref="uploadBtn" loading={this.state.importLock}>导入</Button> </FileUpload> <Button type="primary" loading={this.state.exportLock} className={cx(styles.primaryButton, styles.export_btn)} onClick={t.handleExport.bind(t, _exportUrl)}> {exportBtnText} </Button> </div> </div> <RouteList data={data} dispatch={dispatch}/> { showSpin && showSpin.bool ? ( <div className={styles.cover}> <Spin tip={showSpin.content} style={{marginTop: 160, marginLeft: -160}} size="large"></Spin> </div> ) : null } </div> ) } } export default Main <file_sep>/inside-boss/src/container/visualConfig/views/design/editor/DesignEditorItem.js import React, { PureComponent } from 'react'; import { findDOMNode } from 'react-dom'; import cx from 'classnames'; import PropTypes from 'prop-types'; import style from './DesignEditorItem.css' export default class DesignEditorItem extends PureComponent { static propTypes = { children: PropTypes.node.isRequired, disabled: PropTypes.bool, prefix: PropTypes.string, className: PropTypes.string, move: PropTypes.bool, compName: PropTypes.string, index: PropTypes.number }; static defaultProps = { disabled: false, move: false, compName: '', index: -1 }; render() { const { disabled, prefix, move, compName, handleClickBySortUp, handleClickBySortDown, index, onCloseEditor } = this.props; return ( <div className={cx(style.editorItem)}> {disabled && <div className={`${prefix}-design__disabled-mask`} />} {move && <div className={style.disabledMove}> <span className={style.editorItemName}>{compName}</span> <span className={style.editorItemUp} onClick={(e) => handleClickBySortUp(index, e)}></span> <span className={style.editorItemDown} onClick={(e) => handleClickBySortDown(index, e)}></span> <span className={style.editorItemDele} onClick={(e) => onCloseEditor()}></span> </div>} <div className={style.editorComponentEditor}>{this.props.children}</div> </div> ); } getBoundingBox() { const node = findDOMNode(this); return node && node.getBoundingClientRect(); } } <file_sep>/inside-chain/src/utils/wxApp/cookie.js 'use strict'; var _createStorage = require('./createStorage'); var _createStorage2 = _interopRequireDefault(_createStorage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var values = {}; /** * 小程序设置假cookie数据 */ module.exports = (0, _createStorage2.default)({ clear: function clear() { values = {}; }, getAll: function getAll() { return values; }, setItem: function setItem(name, value) { values[name] = value; }, getItem: function getItem(name) { return values[name]; }, removeItem: function removeItem(name) { if (name in values) { delete values[name]; } } }); module.default = module.exports;<file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/title/TmpPreview.js import React, { PureComponent } from 'react'; import { Icon } from 'antd'; import cx from 'classnames' import style from'./TmpPreview.css' export default class TitleEditorPreview extends PureComponent { render() { const { config } = this.props.value; const { text, size, linkGoodsId, linkPage } = config return ( <div className="zent-design-component-title-preview"> <div className={cx(style.titlePreview + ' ' + style[`title${size}`] )} style={createStyle(config)} > <p>{text ? text : '请输入标题内容' }</p> {(linkGoodsId || linkPage) && <Icon type="right" />} </div> </div> ); } } function createStyle(value) { const { textColor, textAlign, backgroundColor } = value; return { color: textColor, textAlign: textAlign, backgroundColor: backgroundColor }; } <file_sep>/inside-boss/src/action/index.js /* eslint-disable */ /** * App Actions * * 位于 `/src/container/App` 下的 action 是相对于全局使用,集成错误提示、弹窗等。 */ import React from 'react' import api from '../api' import apiNetwork from '../api/networkApi' import uploadApi from '../api/uploadApi' import * as bridge from '../utils/bridge' import { message as MessageComponent, Modal } from 'antd' import { currentAPIUrlPrefix } from '../utils/env' import {hashHistory} from 'react-router' import Cookie from '@2dfire/utils/cookie' const APP_AUTH = '?app_key=200800&s_os=pc_merchant_back' import ActionTypes from './type' /****************************************************** * 全局 */ import { GLOBAL_LOADING, GLOBAL_LOADING_HIDE } from '../constants' export const globalMessageError = message => dispatch => { MessageComponent.error(message) } export const globalMessageSuccess = message => dispatch => { MessageComponent.success(message) } export const globalLoading = () => ({ type: GLOBAL_LOADING }) export const globalLoadingHide = () => ({ type: GLOBAL_LOADING_HIDE }) export const errorHandler = err => dispatch => { if (err.status && err.status > 200) { dispatch(globalMessageError('服务器连接失败,请稍后重试')) return } dispatch(globalMessageError(err.message)) } export const successHandler = (message) => dispatch => { dispatch(globalMessageSuccess(message)) } /** * **************************************************** * 导入导出模块 */ import { INIT_DATA, SHOW_SPIN, INIT_DATA_IMPORT_HISTORY, SET_WHITE, SET_TEBLE_FIELDS_LIST, SET_TABLE_FIELDS_OPTIONS, SET_TABLE_OPTION_KEY, SET_MENU_LIST, SET_MODAL_VISIBLE, SET_RESULT_DATA, SET_TABLE_HEADER, SET_MENU_LANGUAGE, SET_TWINS_FILEDID, SET_GOODS_PARAMS, SET_HISTORY_DATA } from '../constants' import FormatImportOrExport from '../components/goods/format' export const initData = data => ({ type: INIT_DATA, data }) export const initDataImportHostory = (data) => ({ type: INIT_DATA_IMPORT_HISTORY, data }) export const showSpin = data => ({ type: SHOW_SPIN, data }) export const setWhite = data => ({ type: SET_WHITE, data }) export const setMenuList = data=>({ type: SET_MENU_LIST, data }) export const setModalVisible = data=>({ type: SET_MODAL_VISIBLE, data }) export const setResultData = data=>({ type: SET_RESULT_DATA, data }) export const setHistoryData = data=>({ type: SET_HISTORY_DATA, data }) export const setTableHeader = data =>({ type: SET_TABLE_HEADER, data }) export const setMenuLanguage = data=>({ type: SET_MENU_LANGUAGE, data }) export const setTwinsFiledId = data=>({ type: SET_TWINS_FILEDID, data }) export const setGoodsParams = data =>({ type: SET_GOODS_PARAMS, data }) export const setTableFiledOptions = data =>({ type: SET_TABLE_FIELDS_OPTIONS, data }) export const checkWhiteList = () => dispatch => { apiNetwork.checkWhiteList().then( res => { console.log('output',res); dispatch(setWhite(res.data)) dispatch((getIsShowBrand('',res.data))) }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({ bool: false, content: '' })) } ) } //获取历史记录 export const getImportResultList = (plateEntityId,pageIndex = 1)=>(dispatch)=>{ const params = { plateEntityId, gridType:'1', pageSize: 10, pageIndex } apiNetwork.getImportResultList(params).then(res=>{ if(res.data){ const data = [] res.data.list.map((i,index)=>{ data.push({ key:index, createTime: i.createTime || '', successAdd: i.successAdd || 0, success: i.success || 0, successUpdate: i.successUpdate || 0, failed: i.failed || 0, successFilePath: i.successFilePath || '', failedFilePath: i.failedFilePath || '', }) }) dispatch(setHistoryData({data: data,total:res.data.total})) } },err=>{ dispatch(errorHandler(err)) }) } //查询双语设置 export const canSetupMenuLanguage = (plateEntityId)=> dispatch =>{ apiNetwork.canSetupMenuLanguage({plateEntityId}).then(res=>{ dispatch(setMenuLanguage(res.data)) },err=>{ console.log(err) }) } //下载空白模板 export const startDownload = ({kindMenuIdList,plateEntityId})=>(dispatch)=>{ const params = { kindMenuIdList: kindMenuIdList, gridType: '1', plateEntityId: plateEntityId } return apiNetwork.setupTemplate(params) // apiNetwork.setupTemplate(params).then(res=>{ // if(res.data){ // window.location.href = res.data // } // },err=>{ // dispatch(errorHandler(err)) // }) } //保存选择字段 export const batchCreatUserGridField = ({data,plateEntityId,gridType=1}) => (dispatch)=>{ const params = { gridType, gridFieldIds:[].concat(data), plateEntityId } apiNetwork.batchCreatUserGridField(params).then(res=>{ if(res.data){ // MessageComponent.success('字段保存成功') console.log(res.data) } },err=>{ dispatch(errorHandler(err)) }) } //导入导出模板字段状态更新 export const setTableOptionKey = (key,list)=>(dispatch)=>{ dispatch({ type:SET_TABLE_OPTION_KEY, data: {key,list} }) } export const flatDeep= arr => { return arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatDeep(b) : b), []) } const createInfo = (list=[],dispatch,type=false)=>{ let obj = {},twinsFiledIdList = {} list.map(i=>{ obj[i.groupName] = { defaultList:[], selectedList:[], allList:[], toggleList:[] } let itemList = i.children ? i.fields.concat(i.children.map(h=>h.fields)): [].concat(i.fields) // itemList.flat(Infinity).map(j=>{ flatDeep(itemList).map( j=>{ if ( j.isDisabled && j.isSelected ){ obj[i.groupName]['defaultList'].push(j.gridFieldId) } if (j.isSelected && j.relType != "22" ){ obj[i.groupName]['selectedList'].push(j.gridFieldId) } if(j.childrenFidldId && j.childrenFidldId != '0' ){ obj[i.groupName]['toggleList'].push({parentKey:j.gridFieldId,childKey:j.childrenFidldId}) } if(j.twinsFiledId && j.twinsFiledId != '0'){ twinsFiledIdList[j.twinsFiledId] = j.gridFieldId } //过滤掉relType == 22 和 (isDisable == true && isSelected == false )的 if(j.relType != "22" && !(j.isDisabled && !j.isSelected )){ obj[i.groupName]['allList'].push(j.gridFieldId) } }) }) if(type){ const data = [] Object.values(obj).map(i=>{ data = data.concat(i.selectedList) }) dispatch(setTableHeader(data)) }else{ dispatch(setTwinsFiledId(twinsFiledIdList)) dispatch(setTableFiledOptions(obj)) dispatch({ type: SET_TEBLE_FIELDS_LIST, data: list }) } } //获取空白模板字段信息 export const getTableFieldsList = ({plateEntityId,MenuLanguage=false})=>(dispatch)=>{ const params = { gridType:1, plateEntityId } apiNetwork.queryUserGridFieldForDisplay(params).then(res=>{ const data = FormatImportOrExport.formatTableHeader(res.data,MenuLanguage,false,plateEntityId) createInfo(data,dispatch) },err=>{ dispatch(errorHandler(err)) }) } //获取自定义表头字段 export const getCustomTableHeader = (plateEntityId,type=true,MenuLanguage)=> dispatch =>{ const params = { gridType:2, plateEntityId } apiNetwork.queryUserGridFieldForDisplay(params).then(res=>{ const data = FormatImportOrExport.formatTableHeader(res.data,MenuLanguage,true,plateEntityId) createInfo(data,dispatch,type) },err=>{ dispatch(errorHandler(err)) }) } //重置表格字段 export const resetFromFieldsList=(plateEntityId,MenuLanguage)=>(dispatch)=>{ const params = { plateEntityId, gridType:1, } apiNetwork.createResetForDisplay(params).then(res=>{ const data = FormatImportOrExport.formatTableHeader(res.data,MenuLanguage,false,plateEntityId) createInfo(data,dispatch) },err=>{ dispatch(errorHandler(err)) }) } //获取分类信息 export const getMenuTree = (plateEntityId='')=> dispatch =>{ const entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) const params = { isInclude: 0, plateEntityId: plateEntityId, opEntityId: plateEntityId?'':entrance.shopInfo.entityId } apiNetwork.kindMenuTreeSelect(params).then(res=>{ if(res.data){ const data = res.data.map(item=>{ let obj = { addSub:item.addSub, entityId:item.entityId, id:item.id, isInclude:item.isInclude, name:item.name, } if(item.subList){ obj.subList = [].concat(item.subList) } return obj }) dispatch(setMenuList(data)) } },err=>{ dispatch(errorHandler(err)) }) } /** * **************************************************** * 商品库列表 */ import { SET_GOODS_LIST, SET_PAGE_INDEX, SET_IS_SHOW_BRAND, SET_BRAND_LIST, SET_BRAND_ID, SET_SHOW_SPECIFICATION } from '../constants' export const setGoodsList = data => ({ type: SET_GOODS_LIST, data }) export const setPageIndex = data => ({ type: SET_PAGE_INDEX, data }) /** * 判断是否显示品牌(新版本或者旧版本) * */ export const setIsShowBrand = data => ({ type: SET_IS_SHOW_BRAND, data }) /** * 获取数据订正状态(是否显示品牌) * type :1是图片管理 * */ export const getIsShowBrand = (type,inWhite) => dispatch => { api.getIsShowBrand().then( res => { dispatch(setIsShowBrand(res)) if (res === 'fixed') { dispatch(getBrandList(type)) } else { if(!!!inWhite) { dispatch(getCustomTableHeader()) dispatch(getMenuTree()) dispatch(canSetupMenuLanguage()) dispatch(getGoodsList(1)) } dispatch(getShowSpecification()) if(type === 1) { dispatch(getPictureList(1)) } } }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({ bool: false, content: '' })) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } /** * 获取品牌列表 * type 1图片 * */ export const getBrandList = (type) => dispatch => { api.getBrandList().then( res => { // res=[{entityId: "99925699", // name: "品牌一"}]; dispatch(setBrandList(res)); console.log(res) if (res.length === 1) { dispatch(setBrandId(res[0].entityId)) // type===1?dispatch(getPictureList(1, '',res[0].entityId)): dispatch(getGoodsList(1, res[0].entityId)) if(type === 1){ dispatch(getPictureList(1, '',res[0].entityId)) }else{ dispatch(getGoodsList(1, res[0].entityId)) dispatch(getMenuTree(res[0].entityId)) dispatch(getCustomTableHeader(res[0].entityId)) dispatch(canSetupMenuLanguage(res[0].entityId)) } } }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({ bool: false, content: '' })) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const setBrandList = data => ({ type: SET_BRAND_LIST, data }) /** * 获取是否可设置多规格商品 * */ export const getShowSpecification = () => dispatch => { apiNetwork.getShowSpecification().then( res => { res=true dispatch(setShowSpecification(res)) }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({bool: false, content: ''})) } ) } export const setShowSpecification = (data) => ({ type: SET_SHOW_SPECIFICATION, data }) /** * 设置品牌id * @param data string 当前选中品牌 * */ export const setBrandId = data => ({ type: SET_BRAND_ID, data }) /** * 获取商品列表 * @param pageNumber 分页 * @param brandId 当前选中品牌id,不是必须 * */ export const getGoodsList = (pageNumber, brandId, params) => dispatch => { let data = { pageSize: 10, pageNum: pageNumber, ...params }; const entrance = JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))) if( entrance && entrance.shopInfo && entrance.shopInfo.industry != 3 ){ data.plateEntityId = brandId || '' apiNetwork.listItemDetail(data).then( res => { const data = FormatImportOrExport.formatTableMain(res.data) dispatch(setGoodsList(data)) }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({bool: false, content: ''})) } ) }else{ if (brandId) { data.plateEntityId = brandId; api.getGoodsListNew(data).then( res => { dispatch(setGoodsList(res)) }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({bool: false, content: ''})) } ) } else { api.getGoodsList(data).then( res => { // res.records.map((val) => { // val.specification = true; // return val // }) dispatch(setGoodsList(res)) }, err => { dispatch(errorHandler(err)) } ).then( e => { dispatch(showSpin({bool: false, content: ''})) } ) } } } /** * **************************************************** * 交路信息导入导出 */ import { INIT_ROUTE_DATA, SET_ROUTE_LIST, SET_CUR_INDEX } from '../constants' export const initRouteData = data => ({ type: INIT_ROUTE_DATA, data }) export const setRouteList = data => ({ type: SET_ROUTE_LIST, data }) export const setCurIndex = data => ({ type: SET_CUR_INDEX, data }) export const getRouteList = pageNumber => dispatch => { api .getRouteList({ pageSize: 10, pageNum: pageNumber }) .then( res => { dispatch(setRouteList(res)) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } /** * **************************************************** * 车次时刻信息导入导出 */ import { INIT_TRAIN_DATA, SET_TRAIN_LIST, SET_CUR_NUM } from '../constants' export const initTrainData = data => ({ type: INIT_TRAIN_DATA, data }) export const setTrainList = data => ({ type: SET_TRAIN_LIST, data }) export const setCurNum = data => ({ type: SET_CUR_NUM, data }) export const getTrainList = pageNumber => dispatch => { api .getTrainList({ pageSize: 10, pageNum: pageNumber }) .then( res => { dispatch(setTrainList(res)) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } /** * **************************************************** * 根据类目下载商品模板 */ import { INIT_TYPE_DATA, CHECK_TYPE, DEL_TABLE_ITEM, CHECKED_TYPE, ADD_CATEGORY } from '../constants' // 初始化类目数据 export const initTypeData = data => ({ type: INIT_TYPE_DATA, data }) export const addCatrgory = data => ({ type: ADD_CATEGORY, data }) //获取类目数据 export const getCategory = ({ entityId }, name) => dispatch => { api .getCategory({ entityId: entityId, name: name || null }) .then( res => { console.log(res) dispatch(addCatrgory(res)) }, err => { console.log('err!!', err) MessageComponent.info(err.message) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const checkedType = data => ({ type: CHECKED_TYPE, data }) export const delTableItem = data => ({ type: DEL_TABLE_ITEM, data }) /** * **************************************************** * 上传商品模板文件 */ import { INIT_UPLOAD_DATA } from '../constants' // 初始化上传文件的地址和下载模板的地址 export const initUploadData = data => ({ type: INIT_UPLOAD_DATA, data }) /** * **************************************************** * 导入日志 */ import { INIT_IMPORT_LOG_DATA, GET_IMPORT_LOG_DATA, INIT_LOG_DETAIL_DATA, INIT_LOG_DATA } from '../constants' export const InitLogData = data => ({ type: INIT_LOG_DATA, data }) export const InitImportLogData = data => ({ type: INIT_IMPORT_LOG_DATA, data }) export const InitLogDetailData = data => ({ type: INIT_LOG_DETAIL_DATA, data }) export const getImportLogData = data => ({ type: GET_IMPORT_LOG_DATA, data }) export const getImportLogByPage = ( { entityId, businessType }, pageIndex, pageSize ) => dispatch => { dispatch(showSpin({ bool: true, content: '正在加载数据....' })) api .getImportLog({ start: pageIndex || 1, limit: pageSize || 15, entityId: entityId, businessType: businessType }) .then( res => { sessionStorage.setItem('pageIndex', pageIndex) console.log('res', res.bizLogList) dispatch(InitImportLogData(res)) }, err => dispatch(InitImportLogData([])) ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const getImportLogDetail = (logId, pageIndex, pageSize) => dispatch => { api .getImportLogDetail({ start: pageIndex || 1, limit: pageSize || 15, bizLogId: logId }) .then( res => { dispatch(InitLogDetailData(res)) }, err => dispatch(InitLogDetailData([])) ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } /** * ****************************************************** * 会员卡批量充值 */ import { FETCH_BATCH_LIST, FETCH_RECHARGE_LIST, RECHARGE_IMPORT_EVENT, SHOW_EDIT_LAYER, SET_SELECTED_COUNTER, SET_SELECTED_ROW_KEYS, BTN_LOCK, SET_STATUS, SET_LAYER_DEFAULT_VALUES, SET_START_VALUE, SET_END_VALUE } from '../constants' export const btnLock = data => ({ type: BTN_LOCK, data }) export const updateBatchList = list => ({ type: FETCH_BATCH_LIST, list: list }) export const fetchBatchList = dispatch => { dispatch(globalLoading()) sessionStorage.setItem('dropDownButtonLock', 'loading') api .fetchBatchList() .then( res => dispatch(updateBatchList(res)), err => dispatch(errorHandler(err)) ) .then(e => { dispatch(globalLoadingHide()) sessionStorage.setItem('dropDownButtonLock', '') }) } export const deleteBatch = value => dispatch => { dispatch(globalLoading()) api .deleteBatch({ rechargeBatchId: value }) .then( res => { const oldBatchId = sessionStorage.getItem('oldBatchId') if (oldBatchId === value) { window.location.reload() } else { MessageComponent.success('删除成功!', 2) } }, err => dispatch(errorHandler(err)) ) .then(e => { dispatch(globalLoadingHide()) }) } export const updateRechargeList = data => ({ type: FETCH_RECHARGE_LIST, data }) export const setStartValue = value => ({ type: SET_START_VALUE, value }) export const setEndValue = value => ({ type: SET_END_VALUE, value }) /** * [充值列表模块,查询表格数据接口] * @param {[type]} options.batchId [批次id] * @param {[type]} options.startTime [开始时间] * @param {[type]} options.endTime [截止时间] * @param {[type]} options.statusList [包含选取充值状态的列表] * @param {[type]} options.pageSize [每页条数] * @param {[type]} options.pageIndex [页码] * @return {[type]} [description] */ export const fetchRechargeList = ({ rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, tag }) => dispatch => { dispatch(showSpin({ bool: true, content: '正在加载数据....' })) api .fetchRechargeList({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex }) .then( res => { sessionStorage.setItem('oldBatchId', rechargeBatchId) const list = res.rechargeBatchDetailsViewList || [] if (list.length === 0) { MessageComponent.warning('查询结果为空!') } dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) if (tag === 'fromBatchSelector') { dispatch(setStartValue(0)) dispatch(setEndValue(0)) sessionStorage.setItem('endTime', 0) sessionStorage.setItem('startTime', 0) } if (tag === 'fromSearchBtn') { sessionStorage.setItem('pageSize', 50) } }, err => dispatch(errorHandler(err)) ) .then(e => { dispatch(btnLock({ name: 'search', bool: false })) dispatch(showSpin({ bool: false, content: '' })) }) } export const rechargeImportEvent = data => ({ type: RECHARGE_IMPORT_EVENT, data: data }) export const showEditLayer = data => ({ type: SHOW_EDIT_LAYER, data: data }) export const rechargeMultiple = ({ rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, rechargeBatchDetailsVoList }) => dispatch => { dispatch(showSpin({ bool: true, content: '充值中......' })) api .rechargeMultiple({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex, rechargeBatchDetailsVoList: rechargeBatchDetailsVoList }) .then( res => { dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) Modal.info({ title: '充值信息', content: ( <div> {(() => { if (!res.failNum) { return ( <p> {res.successNum} 条数据充值成功 </p> ) } else if (!res.successNum) { return ( <p> {res.failNum} 条数据充值失败 </p> ) } else { return ( <p> {res.successNum} 条数据充值成功, {res.failNum} 条数据充值失败 </p> ) } })()} </div> ) }) }, err => { if (err.status && err.status > 200) { dispatch(globalMessageError('服务器连接失败,请稍后重试')) return } Modal.info({ title: '错误信息', content: <p>{err.message}</p> }) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const deleteMultiple = ( rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, rechargeBatchDetailsVoList ) => dispatch => { dispatch(showSpin({ bool: true, content: '删除中......' })) api .deleteMultiple({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex, rechargeBatchDetailsVoList: rechargeBatchDetailsVoList }) .then( res => { dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) MessageComponent.success('删除成功!', 2) }, err => { if (err.status && err.status > 200) { dispatch(globalMessageError('服务器连接失败,请稍后重试')) return } Modal.info({ title: '错误信息', content: <p>{err.message}</p> }) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const deleteSingle = ( rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, id ) => dispatch => { dispatch(showSpin({ bool: true, content: '删除中......' })) api .deleteSingle({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex, id: id }) .then( res => { dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) MessageComponent.success('删除成功!', 2) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const refund = ({ rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, rechargeBatchDetailsVoList }) => dispatch => { dispatch(showSpin({ bool: true, content: '红冲中......' })) api .refund({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex, rechargeBatchDetailsVoList: rechargeBatchDetailsVoList }) .then( res => { dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) Modal.info({ title: '充值信息', content: ( <div> {(() => { if (!res.failNum) { return ( <p> 红冲成功 {res.successNum}条 </p> ) } else if (!res.successNum) { return ( <p> 红冲失败 {res.failNum} 条,请重新核对后再次红冲 </p> ) } else { return ( <p> 红冲成功 {res.successNum} 条,红冲失败 {res.failNum} 条,请重新核对后红冲 </p> ) } })()} </div> ) }) }, err => { if (err.status && err.status > 200) { dispatch(globalMessageError('服务器连接失败,请稍后重试')) return } Modal.info({ title: '错误信息', content: <p>{err.message}</p> }) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const setSelectedCounter = len => ({ type: SET_SELECTED_COUNTER, len }) export const setSelectedRowKeys = selectedRowKeys => ({ type: SET_SELECTED_ROW_KEYS, selectedRowKeys }) export const modifyInfo = ( rechargeBatchId, startTime, endTime, rechargeStatusList, pageSize, pageIndex, rechargeBatchDetailsVo, form ) => dispatch => { api .modifyInfo({ rechargeBatchId: rechargeBatchId, startTime: startTime, endTime: endTime, rechargeStatusList: rechargeStatusList, pageSize: pageSize, pageIndex: pageIndex, rechargeBatchDetailsVo: rechargeBatchDetailsVo }) .then( res => { dispatch(updateRechargeList(res)) dispatch(setSelectedCounter(0)) form.resetFields() MessageComponent.success('保存成功!', 2) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(btnLock({ name: 'saveModifyBtn', bool: false })) dispatch(showEditLayer(false)) }) } export const setStatus = list => ({ type: SET_STATUS, list }) export const setLayerDefaultValues = data => ({ type: SET_LAYER_DEFAULT_VALUES, data }) // 导入视频 import { SET_VIDEO_LIST, INIT_VIDEO_DATA, CHANGE_VIDEO_TYPE } from '../constants' export const setVideoList = data => ({ type: SET_VIDEO_LIST, data }) export const initVideoData = data => ({ type: INIT_VIDEO_DATA, data }) export const checkNameResult = data => ({ type: CHECK_NAME_RESULT, data }) export const getVideoList = (videoType, pageNumber) => dispatch => { api .videoList({ videoType: videoType, pageSize: 24, pageIndex: pageNumber }) .then( res => { dispatch(setVideoList(res)) }, err => { dispatch(errorHandler(err)) } ) .then // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } () } export const changeVideoType = data => ({ type: CHANGE_VIDEO_TYPE, data }) //会员信息导入导出 import { INIT_MEMBER_DATA, LIST_INIT_DATA, SET_MEMBER_EXPORT } from '../constants' export const initMemberData = data => ({ type: INIT_MEMBER_DATA, data }) export const listInitData = data => ({ type: LIST_INIT_DATA, data }) export const getMemberExportBtn = ( orderType, pageNumber, startTime, endTime, invoiceCode ) => dispatch => { api .isShowMemberExportBtn() .then( res => { dispatch(setMemberExport(res)) }, err => {} ) .then // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } () } export const setMemberExport = data => ({ type: SET_MEMBER_EXPORT, data }) // 商品图片管理 import { INIT_PICTURE_DATA, DETAIL_CHANGE, SET_PICTURE_LIST, LIST_DUPLICATED_ITEMS, BACK_TO_PICTURE_LIST, GET_DUPLICATED_ITEMS, SET_PICTURE_DETAIL_LIST, SET_PAGE_NUMBER, SET_SEARCH_NAME, EDIT_TEMPLATE, TEMPLATE_DETAIL_DATA, TEMPLATE_LIST } from '../constants' export const initPictureData = data => ({ type: INIT_PICTURE_DATA, data }) export const detailChange = data => ({ type: DETAIL_CHANGE, data }) export const editTemplate = (data) => ({ type: EDIT_TEMPLATE, data }) export const setTemplateData = (data) => ({ type: TEMPLATE_DETAIL_DATA, data }) export const setTemplateList = (data) => ({ type: TEMPLATE_LIST, data }) export const getTemplateList = (entityId, pictureFileId) => dispatch => { apiNetwork.getTemplateList({ page: 1, pageSize: 500, entityId: entityId, itemId: pictureFileId }).then( res => { dispatch(setTemplateList(res)) }, err => { dispatch(errorHandler(err)) } ) } export const getTemplateDetail = (id, pictureFileId, entityId) => dispatch => { apiNetwork.getTemplateDetail({ entityId: entityId, itemId: pictureFileId }).then( res => { dispatch(setTemplateData(res)) }, err => { dispatch(errorHandler(err)) } ) } export const saveTemplate = (ItemDetailVO, type, pictureFileId, entityId) => dispatch => { apiNetwork.saveEditTemplate({ itemDetailConvertVO: JSON.stringify(ItemDetailVO) }).then( res => { if (res.data) { if (type == 1) {//默认、老版本自动刷新状态 dispatch(getTemplateList(entityId, pictureFileId)) } else { dispatch(detailChange({detail: true, pictureFileId: pictureFileId})); dispatch(editTemplate({edit: false})) } } }, err => { dispatch(errorHandler(err)) } ) } export const setPictureList = (data) => ({ type: SET_PICTURE_LIST, data }) export const setPictureDetailList = data => ({ type: SET_PICTURE_DETAIL_LIST, data }) export const setPageNumber = data => ({ type: SET_PAGE_NUMBER, data }) export const setSearchName = data => ({ type: SET_SEARCH_NAME, data }) export const backPictureList = (name, entityId) => { return dispatch => { dispatch({ type: BACK_TO_PICTURE_LIST, }) } } export const getDuplicatedItems = (name, entityId) => { return dispatch => { return api.getDuplicatedItems({ pageSize: 24, pageNum: 1, name, plateEntityId:entityId, }).then( res => { dispatch({ type: GET_DUPLICATED_ITEMS, data: res, }) }, err => { dispatch(errorHandler(err)) } ) } } export const listDuplicatedItems = () => { return dispatch => { dispatch({ type: LIST_DUPLICATED_ITEMS, }) } } export const getPictureList = (pageNumber, name ,entityId) => dispatch => { api.pictureList({ pageSize: 24, pageNum: pageNumber, name, plateEntityId:entityId, }).then( res => { dispatch(setPictureList(res)) }, err => { dispatch(errorHandler(err)) } ).then( // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } ) .then // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } () } export const getPictureDetailList = id => dispatch => { api .pictureDetailList({ menuId: id }) .then( res => { dispatch(setPictureDetailList(res)) }, err => { dispatch(errorHandler(err)) } ) .then // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } () } export const changeListSort = (sortList, callback) => dispatch => { api .changeListSort({ menuDetailData: sortList }) .then( res => { callback(res) }, err => { dispatch(errorHandler(err)) } ) .then // e => { // // dispatch(btnLock({name: 'saveModifyBtn', bool: false})) // // dispatch(showEditLayer(false)) // } () } //订单存照 import { CHANGE_ORDER_TYPE, SET_ORDER_START_VALUE, SET_ORDER_END_VALUE, SET_ORDER_LIST, INIT_ORDER_DATA, SET_INVOICE_CODE } from '../constants' export const initOrderData = data => ({ type: INIT_ORDER_DATA, data }) export const changeOrderType = data => ({ type: CHANGE_ORDER_TYPE, data }) export const setOrderStartValue = value => ({ type: SET_ORDER_START_VALUE, value }) export const setOrderEndValue = value => ({ type: SET_ORDER_END_VALUE, value }) export const setInvoiceCode = value => ({ type: SET_INVOICE_CODE, value }) export const getOrderList = ( orderType, pageNumber, startTime, endTime, invoiceCode ) => dispatch => { dispatch(showSpin({ bool: true, content: 'loading....' })) api .orderList({ billType: orderType, pageSize: 10, pageIndex: pageNumber, startTime: startTime, endTime: endTime, invoiceCode: invoiceCode }) .then( res => { dispatch(setOrderList(res)) }, err => { dispatch(errorHandler(err)) } ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const setOrderList = data => ({ type: SET_ORDER_LIST, data }) //发放优惠券 import { INIT_COUPON_DATA, INIT_COUPON_TYPE, GET_BATCH_LIST, SET_OLD_BATCH_ID, RECHARGE_LIST, CHANGE_STATUS, CHANGE_COUPON_TYPE, VISIBLE, SHOW } from '../constants' export const initCouponData = data => ({ type: INIT_COUPON_DATA, data }) export const initCouponType = data => ({ type: INIT_COUPON_TYPE, data }) export const getBatchList = data => ({ type: GET_BATCH_LIST, data }) export const getCouponType = () => dispatch => { api .getCouponType({}) .then( res => { dispatch(initCouponType(res)) }, err => { dispatch(errorHandler(err)) } ) .then(e => {}) } /** * 选择已上传的文件 * @param type string 'UPLOAD_DEFAULT'表示为优惠券批量发放之后获取默认获取当前上传的内容 * */ export const fetchImportFileList = type => dispatch => { api .importFileList({}) .then( res => { if (type && type === 'UPLOAD_DEFAULT') { const { id } = res.importFileList[res.importFileList.length - 1] const rechargeBatchId = id const pageSize = 50 const pageIndex = 1 dispatch(changeStatus(null)) dispatch(getRechargeList(rechargeBatchId, null, pageSize, pageIndex)) } else { dispatch(getBatchList(res)) } }, err => { dispatch(errorHandler(err)) } ) .then(e => {}) } /** * 获取发券列表 * @param rechargeBatchId string 可fetchImportFileList中获取,props中oldBatchId的值,session storage中oldBatchId的值 * @param status string 当前发券选中状态,为null的时候为默认 * @param pageSize number * @param pageIndex number * */ export const getRechargeList = ( rechargeBatchId, status, pageSize, pageIndex ) => dispatch => { dispatch(showSpin({ bool: true, content: '正在加载数据....' })) let pramData = { id: rechargeBatchId, pageSize: pageSize, pageIndex: pageIndex } if (status) { pramData.status = status } api .rechargeList(pramData) .then( res => { dispatch(setOldBatchId(rechargeBatchId)) sessionStorage.setItem('oldBatchId', rechargeBatchId) const list = res.rechargeList || [] if (list.length === 0) { MessageComponent.warning('查询结果为空!') } dispatch(rechargeList(res)) }, err => dispatch(errorHandler(err)) ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const setOldBatchId = data => ({ type: SET_OLD_BATCH_ID, data }) export const rechargeList = data => ({ type: RECHARGE_LIST, data }) /** * 修改发券选中状态 * @param data string 1:发券成功 * 2:发券失败 * null:未选状态,默认,getRechargeList中为null则status值不传 * */ export const changeStatus = data => ({ type: CHANGE_STATUS, data }) export const changeCouponType = data => ({ type: CHANGE_COUPON_TYPE, data }) export const reupload = rechargeList => dispatch => { dispatch(showSpin({ bool: true, content: '正在加载数据....' })) const oldBatchId = sessionStorage.getItem('oldBatchId') rechargeList = Array.isArray(rechargeList) ? rechargeList : [rechargeList] api .reupload({ rechargeList: JSON.stringify(rechargeList), oldBatchId: oldBatchId }) .then( res => { Modal.info({ title: '' + '发劵完成', onOk: () => { dispatch(visible(false)) dispatch(changeStatus(null)) const pageSize = 50 const pageIndex = 1 dispatch(getRechargeList(oldBatchId, null, pageSize, pageIndex)) }, content: ( <div> <p> {/*共{res.total}条数据,*/} 发送成功 {res.successNum} 条,发送失败 {res.failNum}条 </p> </div> ) }) }, err => dispatch(errorHandler(err)) ) .then(e => { dispatch(showSpin({ bool: false, content: '' })) }) } export const visible = data => ({ type: VISIBLE, data }) export const show = data => ({ type: SHOW, data }) export const deleteBatch_ = value => dispatch => { api .deleteBatch_({ rechargeBatchId: value }) .then( res => { const oldBatchId = sessionStorage.getItem('oldBatchId') if (oldBatchId === value) { window.location.reload() } else { MessageComponent.success('删除成功!', 2) } }, err => dispatch(errorHandler(err)) ) .then(e => { dispatch(fetchImportFileList()) }) } export const pushProgress = processId => dispatch => { api .pushProgress({ processId: processId }) .then( res => { sessionStorage.setItem('progressNum', res.process_num) }, err => dispatch(errorHandler(err)) ) .then() } /** * 高铁日常监控 * */ import { SET_HIGH_MONITOR, INIT_HIGH_MONITOR } from '../constants' export const setMonitor = data => ({ type: SET_HIGH_MONITOR, data }) export const initHighMonitor = data => ({ type: INIT_HIGH_MONITOR, data }) export const getHighMonitor = page => dispatch => { apiNetwork.getMonitorList({ trainInfoQuery: JSON.stringify({ pageSize: 20, pageIndex: page || 1 }) }) .then( res => { dispatch(setMonitor(res.data)) }, err => dispatch(errorHandler(err)) ) .then() } /** * 自定义单据模板 * */ import { INIT_DATA_BILL, SET_BILL_STORE_MODAL, SET_BILL_STORE_SHOP_LIST, SET_BILL_STORE_BRANCH, SET_BILL_STORE_PROVINCE, SET_BILL_ACTIVE_SHOP, SET_ALL_TMPL_TYPE, SET_TYPE_TMPL_LIST, SET_TYPE_TMPL_TITLE, SET_ENTITY_TYPE } from '../constants' export const billStoreModelSet = data => ({ type: SET_BILL_STORE_MODAL, data }) export const initDataBill = data => { return{ type: INIT_DATA_BILL, data }} export const getAllShopList = data => dispatch => { apiNetwork.getAllShopList(data) .then( res => { dispatch(setAllShopList(res.data)) }, err => dispatch(errorHandler(err)) ) .then() } export const setAllShopList = data => ({ type: SET_BILL_STORE_SHOP_LIST, data }) export const getBranch = page => dispatch => { apiNetwork .getBranch({}) .then( res => { dispatch(setBranch(res.data)) }, err => dispatch(errorHandler(err)) ) .then() } export const setBranch = data => ({ type: SET_BILL_STORE_BRANCH, data }) export const getAllProvince = page => dispatch => { apiNetwork .getAllProvince({}) .then( res => { dispatch(setAllProvince(res.data)) }, err => dispatch(errorHandler(err)) ) .then() } export const setAllProvince = data => ({ type: SET_BILL_STORE_PROVINCE, data }) export const setBillActiveShop = data => ({ type: SET_BILL_ACTIVE_SHOP, data }) // 获取所有的模板分类 export const getAllTmplType = params => dispatch => { apiNetwork .getAllTmplType(params) .then( res => { dispatch(setAllTmplType(res.data)) console.log({tmplCode:res.data[0].tmplCodeList[0].tmplCode,entityId:params.entityId}) dispatch(getTypeTmplList({tmplCode:res.data[0].tmplCodeList[0].tmplCode,entityId:params.entityId,codeName:res.data[0].tmplCodeList[0].codeName})) }, err => dispatch(errorHandler(err)) ) .then() } export const setAllTmplType = data => ({ type: SET_ALL_TMPL_TYPE, data }) // 获取所有的模板分类 export const getTypeTmplList = data => dispatch => { apiNetwork .getTypeTmplList(data) .then( res => { console.log('getTypeTmplList!!',data,'getTypeTmplList!!',res) dispatch(setTypeTmplList(res.data)) dispatch(setTypeTmplTitle(data.codeName)) }, err => dispatch(errorHandler(err)) ) .then() } export const setTypeTmplList = data => ({ type: SET_TYPE_TMPL_LIST, data }) export const setTypeTmplTitle = data => ({ type: SET_TYPE_TMPL_TITLE, data }) // 获取店铺分类 export const getEntityType = params => dispatch => { apiNetwork .getEntityType(params) .then( res => { dispatch(setEntityType(res.data)) console.log('output setEntityType',res.data); }, err => dispatch(errorHandler(err)) ) .then() } export const setEntityType = data => ({ type: SET_ENTITY_TYPE, data }) /** * 不记名优惠券 * */ import { SET_NO_OWNER_COUPON, INIT_NO_OWNER_COUPON, SET_NO_OWNER_COUPON_LIST, SET_NO_OWNER_PAGE_NUM, SET_SEARCH_PARAM, IS_SHOW_SET_PAGE, SET_NO_SET_PAGE_NUM, SET_NO_OWNER_SET_LIST } from '../constants/index'; //不记名优惠券初始获取下拉框内容 // export const pushProgress = processId => dispatch => { export const getNoOwnerCoupon = () => dispatch => { // debugger api.getNoOwnerCoupon({}).then( res => { dispatch(setNoOwnerCoupon(res)) }, err => dispatch(errorHandler(err)) ).then(e => { }) } // 设置下拉框查询内容 export const setNoOwnerCoupon = (data) => ({ type: SET_NO_OWNER_COUPON, data }) // 优惠券初始查询 export const initNoOwnerCoupon = (data) => ({ type: INIT_NO_OWNER_COUPON, data }) //不记名优惠券查询 export const noOwnerCouponSearch = (data) => dispatch => { api.noOwnerCouponSearch({ ...data }).then( res => { // let res = { // goodsListTotal: 3, // pageNumber: 1, // list: [{ // numId: '1', // couponId: '<NAME>', // couponName: '¥300,000.00', // status: 'New York No. 1 Lake Park', // worth: 'New', // endTime: 'New', // store: 'New', // time: 'New', // }, { // numId: '2', // couponId: '<NAME>', // couponName: '¥300,000.00', // status: 'New York No. 1 Lake Park', // worth: 'New', // endTime: 'New', // store: 'New', // time: 'New', // }, { // numId: '3', // couponId: '<NAME>', // couponName: '¥300,000.00', // status: 'New York No. 1 Lake Park', // worth: 'New', // endTime: 'New', // store: 'New', // time: 'New', // }] // } dispatch(setNoOwnerCouponList(res)) dispatch(setNoOwnerCouponPageNum(data.pageNumber)) }, err => { dispatch(errorHandler(err)) } ).then(e => { }) } // 设置优惠券列表 export const setNoOwnerCouponList = (data) => ({ type: SET_NO_OWNER_COUPON_LIST, data }) //设置优惠券列表页数 export const setNoOwnerCouponPageNum = (data) => ({ type: SET_NO_OWNER_PAGE_NUM, data }) //设置查找条件 export const setSearchParam = (data) => ({ type: SET_SEARCH_PARAM, data }) //设置查找条件 export const isShowSetPage = (data) => ({ type: IS_SHOW_SET_PAGE, data }) //不记名优惠券操作记录查询 export const noOwnerSetList = (data) => dispatch => { api.noOwnerGetCoupon({ ...data }).then( res => { dispatch(setNoOwnerSetList(res)) dispatch(setNoOwnerSetPageNum(data.pageNumber)) }, err => { dispatch(errorHandler(err)) } ).then(e => { }) } // 获取banner列表 export const initBannerList = ({ entityId }) => dispatch => (data = {}) => { const { page = 1, size = 20 } = data apiNetwork.getMallBannerList({ entityId, pageNo: page, pageSize: size, }).then( res => { return dispatch({ type: ActionTypes.FETCH_BANNER_LIST_SUCCESS, data: res.data }) }, err => { return dispatch({ type: ActionTypes.FETCH_BANNER_LIST_FAILURE, data: err }) } ).then() } // 编辑banner export const editBannerItem = ({ entityId, userId }) => dispatch => ({ data = {}, success, failure }) => { const { type = 0, form = {} } = data || {} apiNetwork.postEditBannerItem({ entityId, userId, operateType: type, mallBannerReq: JSON.stringify(form) }).then( res => { success && success() return dispatch({ type: ActionTypes.EDIT_BANNER_ITEM_SUCCESS, data: res.data }) }, err => { failure && failure(err) return dispatch({ type: ActionTypes.EDIT_BANNER_ITEM_FAILURE, data: err }) } ).then() } // 编辑banner排序 export const editBannerIndex = ({ entityId, userId }) => dispatch => ({ data = {}, success, failure }) => { const { editList = [] } = data apiNetwork.postEditBannerIndex({ entityId, userId, mallBannerReqList: JSON.stringify(editList) }).then( res => { success && success() return dispatch({ type: ActionTypes.EDIT_BANNER_INDEX_SUCCESS, data: res.data }) }, err => { failure && failure(err) return dispatch({ type: ActionTypes.EDIT_BANNER_INDEX_FAILURE, data: err }) } ).then() } // 获取活动列表 export const initActivityList = ({ entityId }) => dispatch => (data = {}) => { const { page = 1, size = 20 } = data apiNetwork.getMallActivityList({ entityId, pageNo: page, pageSize: size, }).then( res => { return dispatch({ type: ActionTypes.FETCH_ACTIVITY_LIST_SUCCESS, data: res.data }) }, err => { return dispatch({ type: ActionTypes.FETCH_ACTIVITY_LIST_FAILURE, data: err }) } ).then() } // 编辑活动 export const editActivityItem = ({ entityId, userId }) => dispatch => ({ data = {}, success, failure }) => { const { type = 0, form = {} } = data || {} apiNetwork.postEditActivityItem({ entityId, userId, operateType: type, mallPromotionReq: JSON.stringify(form) }).then( res => { success && success() return dispatch({ type: ActionTypes.EDIT_ACTIVITY_ITEM_SUCCESS, data: res.data }) }, err => { failure && failure(err) return dispatch({ type: ActionTypes.EDIT_ACTIVITY_ITEM_FAILURE, data: err }) } ).then() } /** *导入履历 */ import { SET_IMPORT_HISTORY_LIST, SET_IMPORT_PAGE_NUM } from '../constants/index'; export const getImportHistoryList = (data) => dispatch => { console.log(data) api.getImportHistoryList({ pageNum: data.pageNum, pageSize: 10 }).then( res => { console.log(res); // res = { // "records": [ // { // "date": "2018-12-10", // "hint": "共导入3条,成功2条,失败1条", // "id": "测试内容3q25", // "messageUrl": "http://www.baidu.com/111.txt", // "name": "测试内容810c" // } // ], // "totalRecord": 86207 // } dispatch(setImportHistoryList(res)) dispatch(setImportPageNum((data.pageNum))) }, err => { dispatch(errorHandler(err)) } ).then(e => { }) } export const setImportHistoryList = (data) => ({ type: SET_IMPORT_HISTORY_LIST, data }) export const setImportPageNum = (data) => ({ type: SET_IMPORT_PAGE_NUM, data }) import { SET_CATEGORY_LIST, SET_SPEC_LIST, SET_UNIT_LIST, } from '../constants' import FormatProperty from '../components/goodsProperty/format' /** * 获取零售的分类列表 */ export const getCategoryList = () => dispatch => { apiNetwork.getCateList({industry: 3}).then( res => { if(Object.keys(res.data).length>0) { const { categoryList } = res.data dispatch(setCateList(categoryList)) } }, err => { dispatch(errorHandler(err)) } ) } export const setCateList = (data) => ({ type: SET_CATEGORY_LIST, cateList: FormatProperty.formatCateList(data), cateFlat: FormatProperty.formatCateListFlat(data), }) /** * 获取零售的规格列表 */ export const getSpecList = (industry) => dispatch => { apiNetwork.getSpecList({industry}).then( res => { if(Object.keys(res.data).length>0) { const { skuPropertyList = [] } = res.data const list = FormatProperty.formatSpec(skuPropertyList) dispatch(setSpecList(list)) } }, err => { dispatch(errorHandler(err)) } ) } export const setSpecList = (data) => ({ type: SET_SPEC_LIST, data, }) /** * 获取零售的单位列表 */ export const getUnitList = (industry) => dispatch => { apiNetwork.getUnitList({industry}).then( res => { if(Object.keys(res.data).length>0) { const { unitList = []} = res.data dispatch(setUnitList(unitList)) } }, err => { dispatch(errorHandler(err)) } ) } export const setUnitList = (data) => ({ type: SET_UNIT_LIST, data }) /** * 新增规格值 * @param args * @returns {Function} */ export const saveSpecName = (args) => dispatch => { const { industry, specId, specName, addSpecList=[] } = args const params = { industry, propertyId: specId, propertyName: specName, valueNames: JSON.stringify(addSpecList) } apiNetwork.saveSpec(params).then( res => { if(res.data) { dispatch(successHandler('添加成功~')) dispatch(getSpecList(industry)) } }, err => { dispatch(errorHandler(err)) } ) } /** * 切换规格值的停用和启用状态 * @param args * @returns {Function} */ export const switchSpecItemStatus = (args) => dispatch => { const { industry, id, flag, specList } = args apiNetwork.specItemSwitch({industry, status: flag, ids: JSON.stringify([id])}).then( res => { dispatch(successHandler('操作成功~')) const list = FormatProperty.updateSpecList(specList, id) dispatch(setSpecList(list)) }, err => { dispatch(errorHandler(err)) } ) } /** * 切换规格名称的停用和启用状态 * @param args * @returns {Function} */ export const switchSpecNameStatus = (args) => dispatch => { const { industry, id, flag, specList } = args apiNetwork.specNameSwitch({industry, status: flag, ids: JSON.stringify([id])}).then( res => { dispatch(successHandler('操作成功~')) const list = FormatProperty.updateSpecList(specList, id) dispatch(setSpecList(list)) }, err => { dispatch(errorHandler(err)) } ) } /** * 删除单位名称 * @param args * @returns {Function} */ export const deleteUnit = (args) => dispatch => { const { id, industry } = args apiNetwork.deleteUnit({id, industry}).then( res => { if(res.data) { dispatch(successHandler('操作成功~')) dispatch(getUnitList(industry)) } }, err => { dispatch(errorHandler(err)) } ) } /** * 新增分类信息 * @param args * @returns {Function} */ export const addCate = (args) => dispatch => { const {industry} = args apiNetwork.saveCate(args).then( res => { dispatch(successHandler('操作成功~')) dispatch(getCategoryList({industry})) }, err => { dispatch(errorHandler(err)) } ) } /** * 更新分类信息 * @param args * @returns {Function} */ export const updateCate = (args) => dispatch => { const {industry} = args apiNetwork.updateCate(args).then( res => { dispatch(successHandler('操作成功~')) dispatch(getCategoryList({industry})) }, err => { dispatch(errorHandler(err)) } ) } /** * 删除分类 * @param args * @returns {Function} */ export const deleteCate = (args) => dispatch => { apiNetwork.deleteCate(args).then( res => { dispatch(successHandler('操作成功~')) dispatch(getCategoryList()) }, err => { dispatch(errorHandler(err)) } ) } /** * 获取商品列表 * @param args * @returns {Function} */ export const getItemList = (args) => dispatch => { const { pageSize = 20, pageIndex, keyword = '', categoryId = '' } = args apiNetwork.getItemList({pageSize, pageIndex, keyword, categoryId, searchType: 1}).then( res => { if(res.data.itemList&&res.data.itemList.length>0) { res.data.itemList.forEach((value)=>{ value.isRatio = value.isRatio ? '是' : '否' value.isTwoAccount = value.isTwoAccount ? '是' : '否' }) dispatch(setItemList(res.data)) } else { dispatch(setItemList({goodsCategoryList: { categoryList: [] }})) } }, err => { dispatch(errorHandler(err)) } ) } /** * 验证想删除商品是否是组合商品或者下发商品 * @param args * @returns {Function} */ import { SET_CHILD_GOODS_RESULT } from '../constants' export const getChildGoodResult = (args) => dispatch => { const params = { req: JSON.stringify({ itemType: 0, itemIdList: args.itemIdList }) } apiNetwork.getChildGoodResult(params).then( res => { if (res.data) { dispatch(setChildGoodResult(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } export const setChildGoodResult = data => ({ type: SET_CHILD_GOODS_RESULT, data }) /** * 删除商品 * @param args * @returns {Function} */ export const deleteItem = (args) => dispatch => { let { idList = [], pageSize = 20, pageIndex, keyword = '', categoryId = '' } = args const params = { industry:3, req: JSON.stringify({ idList:idList, industry: 3 }) } apiNetwork.deleteItem(params).then( res => { if(res.data) { dispatch(getItemList({pageSize, pageIndex, keyword, categoryId})) } }, err => { dispatch(errorHandler(err)) } ) } import { SET_ITEM_LIST } from '../constants' export const setItemList = (data) => ({ type: SET_ITEM_LIST, data }) /** * 商品多规格导入 * @param args * @returns {Function} */ export const uploadSpec = (args) => dispatch => { api.uploadSpec(args).then( res => { dispatch(setUpload(res.data)) }, err => { dispatch(errorHandler(err)) } ) } /** * 商品无规格导入 * @param args * @returns {Function} */ export const uploadNospec = (args) => dispatch => { for (var value of args.values()) { console.log(value); } api.uploadNospec(args).then( res => { dispatch(setUpload(res.data)) }, err => { dispatch(errorHandler(err)) } ) } /** * 商品信息导出 * @param args * @returns {Function} */ export const exportItems = (args) => dispatch => { let {menu_ids = []} = args menu_ids = menu_ids.join(',') api.exportItems({menu_ids}).then( res => { location.href = res }, err => { dispatch(errorHandler(err)) } ) } /** * 换分类 * @param args * @returns {Function} */ export const changeCateSave = (args) => dispatch => { let {idList = [], changeCategoryId = '', pageSize = 20, pageIndex, keyword = '', categoryId = '' } = args // idList = JSON.stringify(idList) const params = { industry: 3, req: JSON.stringify({ industry: 3, idList, categoryId: changeCategoryId }) } apiNetwork.changeCategory(params).then( res => { dispatch(successHandler('操作成功~')) dispatch(getItemList({pageSize, pageIndex, keyword, categoryId})) }, err => { dispatch(errorHandler(err)) } ) } /** * 换分类 * @param args * @returns {Function} */ export const changeCombinedCateSave = (args) => dispatch => { let {idList = [], changeCategoryId = '', pageSize = 20, pageIndex, keyword = '', categoryId = '' } = args // idList = JSON.stringify(idList) const params = { industry: 3, req: JSON.stringify({ industry: 3, idList, categoryId: changeCategoryId }) } apiNetwork.changeCombinedCategory(params).then( res => { dispatch(successHandler('操作成功~')) dispatch(getCombinedGoodsList({ pageSize, pageIndex, keyword, categoryId })) }, err => { dispatch(errorHandler(err)) } ) } /** * 添加单位 * @param args * @returns {Function} */ export const addUnit = (args) => dispatch => { const { industry, unitName } = args apiNetwork.addUnit({industry, name: unitName}).then( res => { dispatch(getUnitList(industry)) }, err => { dispatch(errorHandler(err)) } ) } import { SET_UPLOAD } from '../constants' export const setUpload = (data) => ({ type: SET_UPLOAD, data }) /** * 商品编辑模块 start * */ import { SET_GOOD_ITEM_DETAIL, SET_GOOD_CATEGORY_LIST, SET_GOOD_SKU_LIST, SET_GOOD_UNIT_LIST, SET_FREIGHT_TEMPLATE, SET_SELECTED_SKU_LIST, SET_SKU_TABLE_DATA, SET_GOOD_DETAIL_PICTURE, SET_GOOD_HEAD_PICTURE, SET_GOOD_STRATEGY, SET_GOOD_FACADE } from '../constants' import FormatEdit from '../components/goodEdit/format' import { basename } from 'path'; //拉取商品详情 export const getGoodItemDetail = (id) => dispatch => { const args = { industry: 3, req: JSON.stringify({ id, }) } apiNetwork.getGoodItemDetail(args).then( res => { const { skuVOList = [], headPicList = [], detailPicList = [] } = res.data dispatch(setGoodItemDetail(res.data)) dispatch(setDetailPicture(detailPicList)) dispatch(setHeadPicture(headPicList)) dispatch(setSkuTableData(skuVOList)) // 将初始sku数据存储起来 localStorage.setItem('initSkuVOList',JSON.stringify(skuVOList)) }, err => { dispatch(errorHandler(err)) } ) } // 设置商品详情 export const setGoodItemDetail = (data) => ({ type: SET_GOOD_ITEM_DETAIL, data }) // 设置商品头图 export const setHeadPicture = (data) => ({ type: SET_GOOD_HEAD_PICTURE, data }) // 设置商品详情图 export const setDetailPicture = (data) => ({ type: SET_GOOD_DETAIL_PICTURE, data }) // 拉取商品分类 export const getGoodCategory = () => dispatch => { apiNetwork.getCateList({ industry: 3 }).then( res => { if(Object.keys(res.data).length>0) { dispatch(setGoodCategory(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } // 获取策略 export const getGoodStrategy = () => dispatch => { apiNetwork.getStrategy({ param: JSON.stringify({ shopStrategyType: 1}) }).then( res => { if( Object.keys(res).length>0) { dispatch(setGoodStrategy(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } // 获取商品转自建策略 export const getFacadeService = (param) => dispatch => { apiNetwork.getFacadeService(param).then( res => { dispatch(setGoodFacade(res.data)) }, err => { dispatch(errorHandler(err)) } ) } // 设置商品分类 export const setGoodCategory = (data) => ({ type: SET_GOOD_CATEGORY_LIST, data }) // 设置商品策略 export const setGoodStrategy = (data) => ({ type: SET_GOOD_STRATEGY, data }) // 设置商品转自建策略 export const setGoodFacade = (data) => ({ type: SET_GOOD_FACADE, data }) /** * 拉取商品sku列表 * @params queryStatus 0 停用,1 启用 ,-1 全部 * @params menuId 商品Id */ export const getGoodSkuList = (id, queryStatus) => dispatch => { apiNetwork.getSpecList({ industry: 3, menuId: id, queryStatus }).then( res => { const { skuPropertyList = [] } = res.data const selectedSku = FormatEdit.formatSelectedSku(skuPropertyList) dispatch(setGoodSkuList(skuPropertyList)) dispatch(setSelectedSkuList(selectedSku)) // 将初始数据保存起来 localStorage.setItem('initSelectedSku', JSON.stringify(selectedSku)) }, err => { dispatch(errorHandler(err)) } ) } // 设置商品sku列表 export const setGoodSkuList = (data) => ({ type: SET_GOOD_SKU_LIST, data }) // 设置已选择的规格列表 export const setSelectedSkuList = (data) => ({ type: SET_SELECTED_SKU_LIST, data }) // 拉取单位列表 /** * @params industry 行业,0餐饮,1,3零售 */ export const getGoodUnitList = (industry) => dispatch => { apiNetwork.getUnitList(industry).then( res => { const { unitList = [] } = res.data dispatch(setGoodUnitList(unitList)) }, err => { dispatch(errorHandler(err)) } ) } // 设置单位列表 export const setGoodUnitList = (data) => ({ type: SET_GOOD_UNIT_LIST, data }) // 拉取运费模版 export const getFreightTemplate = (data) => dispatch => { apiNetwork.getFreightTemplate().then( res => { dispatch(setFreightTemplate(res.data)) }, err => { dispatch(errorHandler(err)) } ) } // 设置运费模版 export const setFreightTemplate = (data) => ({ type: SET_FREIGHT_TEMPLATE, data }) // 更新规格table数据 export const setSkuTableData = (data) => ({ type: SET_SKU_TABLE_DATA, data }) // 新建分类 export const addNewCategory = (data) => dispatch => { apiNetwork.saveCate(data).then( res => { if (res.data) { MessageComponent.success('分类新建成功') } }, err => { dispatch(errorHandler(err)) } ) } // 新建单位 export const addNewUnit = (data) => dispatch => { apiNetwork.addUnit({ industry: 3, name: data }).then( res => { if (res.data) { MessageComponent.success('单位新建成功') } }, err => { dispatch(errorHandler(err)) } ) } // 保存商品 export const saveGoodItem = (industry, data) => dispatch => { apiNetwork.saveGoodItem( industry, data ).then( res => { if (res.data) { MessageComponent.success('商品保存成功', 1) setTimeout(() => { hashHistory.push('/ITEM_EXPORT/item') }, 1000) } }, err => { dispatch(errorHandler(err)) } ) } import { SET_PRICE_TAG_MODULE, SET_MODULE_DETAIL,SET_GOOD_TAG_IMAGE,SET_UPDATE_MODULE_RESULT, } from '../constants' // 生成标签图片 export const uploadGoodTagImage = ( data) => dispatch => { uploadApi.uploadGoodTagImage(data).then( (res) => { if (res) { dispatch(setGoodTagImage(res)) } }, err => { dispatch(errorHandler(err)) } ) } export const setGoodTagImage = (data) => ({ type: SET_GOOD_TAG_IMAGE, data }) import { SET_COMBINED_GOODS_LIST, SET_COMBINED_GOOD_DETAIL, SET_SELECT_COMBINED_LIST, SET_CHILD_SPEC_ITEMS, SET_SELECT_GOODS_SPEC, } from '../constants' // 拉取组合商品列表 export const getCombinedGoodsList= (args) => dispatch => { const { pageSize = 20, pageIndex, keyword = '', categoryId = ''} = args apiNetwork.getCombinedGoodsList({pageSize, pageIndex, keyword, categoryId, searchType: 1}).then( res => { if (res.data) { res.data.itemList.forEach(value => { value.isRatio = value.isRatio ? '是' : '否' value.isTwoAccount = value.isTwoAccount ? '是' : '否' }) dispatch(setCombinedGoodsList(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } // 获取商品贴标签模板 export const getPriceTagModule = (data) => dispatch => { apiNetwork.getPriceTagModule(data).then( res => { if (res.data) { dispatch(setPriceTagModule(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } // 设置组合商品列表信息 export const setCombinedGoodsList = data => ({ type: SET_COMBINED_GOODS_LIST, data }) export const deleteCombinedGoodDetail = (args) => dispatch => { let { idList = [],pageSize, pageIndex, keyword, categoryId } = args const params = { industry:3, req: JSON.stringify({ idList:idList, industry: 3 }) } apiNetwork.deleteCombinedGoodDetail(params).then( res => { if(res.data) { dispatch(getCombinedGoodsList({pageSize, pageIndex, keyword, categoryId})) MessageComponent.success('删除成功!', 1) } }, err => { dispatch(errorHandler(err)) } ) } export const setPriceTagModule = data => ({ type: SET_PRICE_TAG_MODULE, data }) // 复制商品贴标签模板 export const copyPriceTagModule = (data) => dispatch => { apiNetwork.copyPriceTagModule(data).then( res => { if (res.data) { dispatch(getPriceTagModule(data)) } }, err => { dispatch(errorHandler(err)) } ) } // 拉取组合商品详细信息 export const getCombinedGoodDetail= (id) => dispatch => { const args = { req: JSON.stringify({ id, }) } apiNetwork.getCombinedGoodDetail(args).then( res => { if (res.data) { const { headPicList = [] } = res.data dispatch(setCombinedGoodDetail(res.data)) dispatch(setSelectCombinedGoodsList(res.data.childItems)) dispatch(setHeadPicture(headPicList)) } }, err => { dispatch(errorHandler(err)) } ) } // 查询模板信息 export const getModuleDetail = (data) => dispatch => { apiNetwork.getModuleDetail(data).then( res => { if (res.data) { dispatch(setModuleDetail(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } export const setCombinedGoodDetail = data => ({ type: SET_COMBINED_GOOD_DETAIL, data }) // 修改组合商品详细信息 export const updateCombinedGood = (data) => dispatch => { apiNetwork.updateCombinedGood(data).then( res => { if (res.data) { dispatch(setCombinedGoodDetail(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } // 新增组合商品详细信息 export const addCombinedGood = (data) => dispatch => { apiNetwork.addCombinedGood(data).then( res => { if (res.data) { console.log('add success') // dispatch(setCombinedGoodDetail(res.data)) } }, err => { dispatch(errorHandler(err)) } ) } export const setSelectCombinedGoodsList = data => ({ type: SET_SELECT_COMBINED_LIST, data }) export const setChildSpecItems = data => ({ type: SET_CHILD_SPEC_ITEMS, data }) export const setSelectGoodsSpec = data => ({ type: SET_SELECT_GOODS_SPEC, data }) export const setFormatSpecGoods = data => ({ type: SET_FORAMT_SPEC_GOODS, data }) export const setModuleDetail = data => ({ type: SET_MODULE_DETAIL, data }) // 修改模板信息 export const updatePriceTagModule = (data) => dispatch => { apiNetwork.updatePriceTagModule(data).then( res => { if (res.data) { dispatch(setUpdatePriceTag(res.data)) } }, err => { dispatch(setUpdatePriceTag(err)) } ) } export const setUpdatePriceTag = data => ({ type: SET_UPDATE_MODULE_RESULT, data }) /** * 商品编辑模块 end * */ <file_sep>/inside-boss/src/container/videoImport/reducers.js import { SET_VIDEO_LIST, INIT_VIDEO_DATA, CHANGE_VIDEO_TYPE } from '../../constants' export default (state = {}, action) => { switch (action.type) { case SET_VIDEO_LIST: return Object.assign({},state,{ videolist:action.data.records, total : action.data.totalRecord, length : action.data.records.length }) case INIT_VIDEO_DATA: return action.data case CHANGE_VIDEO_TYPE : return Object.assign({},state ,{ videoType : action.data }) default: return state } } <file_sep>/inside-chain/src/const/emu-suitDefaultValue.js export const suitDefaultValue = { opEntityId: '', plateEntityId: '', suitId: '', suitName: '', account: '份', accountId: '991801476208c1e8016209fab06267fa', kindMenuId: '', memberPrice: '', price: '', suitCode: '', acridLevel: 0, recommendLevel: 0, specialTagId: '', status: 1, mainPicture: [], // {id, path, sortCode, isValid} detail: '', detailImgList: [], // {id, path, sortCode, isValid} isChangePrice: 0, isAllowDiscount: 1, isBackAuth: 1, startNum: 1, isTakeout: 1, isReserve: 1, discountInclude: 1 } <file_sep>/static-hercules/src/base/config/pre.js module.exports = { NEW_API_BASE_URL: 'https://meal.2dfire-pre.com', API_BASE_URL: 'https://meal.2dfire-pre.com', BOSS_API_URL: 'https://boss-api.2dfire-pre.com', DD_API_URL: 'https://yardcontent.2dfire-pre.com', APP_ID: 'dingoa49flkdpwskqhw4hh', SHARE_BASE_URL: 'http://live-pre.zm1717.com', IMAGE_BASE_URL: '//ifile.2dfire.com/', API_WEB_SOCKET: 'https://websocket.2dfire-pre.com/web_socket', //网关 GATEWAY_BASE_URL: 'https://gateway.2dfire-pre.com', // 供应链 SUPPLY_CHAIN_API: 'https://api.2dfire-pre.com/supplychain-api', ENV: 'pre', APP_KEY: '200800', REPORT_URL: 'https://d.2dfire-pre.com/pandora/#/', WEBSOCKET_URL: 'https://websocket.2dfire-pre.com', // 接入易观方舟数据埋点系统相关 ANALYSYS_APPKEY: '27e0923002b01e08', ANALYSYS_DEBUG_MODE: 2, ANALYSYS_UPLOAD_URL: 'https://ark.2dfire-daily.com' }; <file_sep>/inside-chain/src/config/api_menu.js import {API_BASE_URL} from "apiConfig"; import Requester from '@/base/requester' import {GW} from '@2dfire/gw-params'; const AND = '&' + GW; const API = { /** * 获取品牌下菜单列表 * params: * plateEntityId: 品牌id * */ getAllMenus(plateEntityId) { console.log('ll', plateEntityId) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.getAllMenus" + AND, { params: { plateEntityId: plateEntityId } } ) }, /** * 获取品牌下菜单列表 * params: * plateEntityId: 品牌id * */ getAllRemenus(plateEntityId) { console.log('ll', plateEntityId) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.center.business.chainmenu.IChainMenuClientService.getAllMenusAndSort" + AND, { params: { plateEntityId: plateEntityId, sortType: 1 } } ) }, /** * 编辑菜单 * params: * menuId: 菜单id * menuName: 菜单名称 * menuRemark: 菜单备注 * */ updateMenu(params) { console.log('update menu: ', params) return Requester.get( // API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.updateMenu" + AND, API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.updateMenuV2" + AND, { params: { menuId: params.menuId, menuName: params.menuName, menuRemark: params.menuRemark, detailMenuPriceNotPublish: params.detailMenuPriceNotPublish, } } ) }, /** * 新建菜单 * params: * plateEntityId: 品牌id * menuName: 菜单名称 * menuRemark: 菜单备注 * */ createMenu(params) { console.log('create menu: ', params) return Requester.get( // API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.createNewMenu" + AND, API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.createNewMenuV2" + AND, { params: { plateEntityId: params.plateEntityId, menuName: params.menuName, menuRemark: params.menuRemark, detailMenuPriceNotPublish: false } } ) }, /** * 删除菜单 * params: * menuId: 菜单id * */ deleteMenu(id) { console.log('del menu: ', id) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.deleteMenu" + AND, { params: { menuId: id } } ) }, /** * 删除菜单中的商品 * params: * plateEntityId: 品牌id * menuId: 菜单id * itemIds: 商品ids * */ removeGoodsOfMenu(params) { console.log('del menu goods: ', params) return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.deleteGoods" + AND, { plateEntityId: params.plateEntityId, menuId: params.menuId, itemIds: params.itemIds }, { emulateJSON: true } ) }, /** * 获取菜单中的商品的价格信息 * params: * plateEntityId: 品牌id * menuId: 菜单id * itemId: 商品id * */ getGoodsPrice(params) { console.log('get menu goods price: ', params) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.getGoodsPrice" + AND, { params: { plateEntityId: params.plateEntityId, menuId: params.menuId, itemId: params.itemId } } ) }, /** * 更新菜单中的商品的价格信息 * params: * plateEntityId: 品牌id * menuId: 菜单id * itemId: 商品id * price: 菜单中价格 * memberPrice: 菜单中会员价格 * useDefaultPriceSwitch: int 是否使用默认价格 * specPrices: [] 规格价格 */ updateGoodsPrice(params) { console.log('update menu goods price: ', params) return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.updateGoodsPrice" + AND, { plateEntityId: params.plateEntityId, menuId: params.menuId, itemId: params.itemId, price: params.price, memberPrice: params.memberPrice, useDefaultPriceSwitch: params.useDefaultPriceSwitch, specPrices: params.specPrices, }, {emulateJSON: true} ) }, /** * 复用菜单 * params: * plateEntityId: 品牌id * menuId: 被复用的菜单id * newMenuId: 菜单id */ multiplexMenu(params) { console.log('multiplexMenu: ', params) return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.multiplexMenu" + AND, { plateEntityId: params.plateEntityId, menuId: params.menuId, newMenuId: params.newMenuId }, {emulateJSON: true} ) }, /** * 获取菜单内商品 * params: * * plateEntityId: 品牌Id, * menuId: 菜单id * kindId: 分类id * goodsName: 商品名称, * pageIndex: 页码, * paging: 1 分页, * */ getGoodsByMenuId(params) { console.log('getGoodsByMenuId: ', params) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.getGoodsByMenuId" + AND, { params: { plateEntityId: params.plateEntityId, menuId: params.menuId, kindId: params.kindId, goodsName: params.goodsName, pageIndex: params.pageIndex, paging: 1, } } ) }, /** * 获取菜单内商品 (仅商品及套餐简单信息) * params: * plateEntityId: 品牌Id, * menuId: 菜单id * kindId: 分类id * goodsName: 商品名称, * paging: 0 不分页, * */ getGoodsByMenuIdSimple(params) { console.log('getGoodsByMenuIdSimple: ', params) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.getGoodsByMenuId" + AND, { params: { plateEntityId: params.plateEntityId, menuId: params.menuId, kindId: params.kindId, goodsName: params.goodsName, paging: 0, } } ) }, /** * 获取所有商品的简单信息 * params: * menuId: 菜单id * */ listAllSimpleItem(params) { console.log('listAllSimpleItem: ', params) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.item.service.IItemService.listAllSimpleItem" + AND, { params: { opEntityId: params.opEntityId, // 筛选项 json字符串形式 listSimpleItemReq: JSON.stringify({ plateEntityId: params.plateEntityId, kindId: params.kindId, name: params.name, }) } } ) }, /** * 批量添加商品 * params: * plateEntityId: 品牌id * menuId: 菜单id * itemIds: 商品id串 * */ addGoods(params) { console.log('listAllSimpleItem: ', params) return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.addGoods" + AND, { plateEntityId: params.plateEntityId, menuId: params.menuId, itemIds: params.itemIds }, { emulateJSON: true } ) }, /** * 获取菜单内商品分类 * params: * plateEntityId: 品牌id * menuId: 菜单id * */ getGoodsKindsByMenuId(params) { console.log('getGoodsKindsByMenuId: ', params) return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainmenu.service.IChainMenuClientService.getGoodsKindsByMenuId" + AND, { params: { plateEntityId: params.plateEntityId, menuId: params.menuId, } } ) }, /** * 获取商品/套餐分类列表 * @param isInclude -1-全部 0-商品 1-套餐 * @param plateEntityId * @param opEntityId * @returns {*|V} */ kindMenuTree(params) { return Requester.get( API_BASE_URL + "com.dfire.boss.center.pc.IKindMenuService.kindMenuTreeSelect" + AND, { params: { isInclude: -1, plateEntityId: params.plateEntityId, opEntityId: params.opEntityId } } ) }, /** * 菜单下发 */ /** * 获取下发类型 * */ getPublishType() { console.log('getPublishType') return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainpublish.service.IChainPublishClientService.getPublishType" + AND ) }, /** * 获取下发时间类型 * */ getPublishTimeType() { console.log('getPublishTimeType') return Requester.get( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainpublish.service.IChainPublishClientService.getPublishTimeType" + AND ) }, /** * 下发菜单 * plateEntityId: 品牌Id, * menuId: 菜单Id, * publishType: 下发Type, * timeType: 下发时间Type, * publishTime: 下发时间Time, not must * shops: 下发商家 */ publishMenu(params) { console.log('publishMenu') return Requester.post( API_BASE_URL + "com.dfire.soa.boss.centerpc.chainpublish.service.IChainPublishClientService.publishMenu" + AND, { plateEntityId: params.plateEntityId, menuId: params.menuId, name: params.name, publishType: params.publishType, timeType: params.timeType, publishTime: params.publishTime, shops: params.shops }, {emulateJSON: true} ) }, } export default API; <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/slider/index.js import Editor from './SliderEditor' import Preview from './SliderPreview' export default { type: Editor.designType, editor: Editor, preview: Preview }; <file_sep>/static-hercules/src/give-key/libs/catchError.js import Vue from 'vue'; let ERR_INFO = { "ERR_OPS999": "登录超时,请重新登录", } function commonCatchError (e) { let message = ERR_INFO[e.errorCode] if (e.code === -1) { return Vue.prototype.$toast("授权失败,请重新扫码进入", false) } if (message) { return Vue.prototype.$toast(message, false) } return null } export default function (e) { let res = commonCatchError(e) if (res === null && e.message) { return Vue.prototype.$toast(e.message) } }<file_sep>/inside-boss/src/components/cateManage/main.js import React, { Component } from 'react' import styles from './cateList.css' import { Modal, Button, Select } from 'antd' import * as action from '../../action' import CateTable from "../cateTable" const { Option } = Select // 商品分类管理组件 class CateManage extends Component { constructor(props) { super(props) this.state = { isShowAddCatePop: false, // 是否显示添加弹窗的标识 currentCate: { mode: '', // 模式(新增-edit、更新-addChild) classifyId: '', // 销售额归类Id parentId: '', // 上级分类 name: '', // 商品分类 code: '', // 分类编码 parentDisabled: false, // 上级分类是否可选 classifyName: '', // 销售额归类名称 }, // 当前弹窗的分类信息 isShowConfirmModal: false, // 是否显示确认弹唱 currentDeleteCate: {}, // 当前要删除的分类 cateList: [], // 分类列表 } } componentWillMount() { const { dispatch } = this.props dispatch(action.getCategoryList()) } /** * 编辑或者新增分类 */ _editCate(data, mode) { const { currentCate } = this.state const { id, name, parentId="", code, groupCategoryId } = data this._toggleCatePop(true) // debugger if(mode === 'edit') { // 编辑 const { cateFlat=[] } = this.props.data let parentName = '无上级分类' let classifyName = '不设置' cateFlat.forEach(function(item) { if(item.id === parentId) { parentName = item.name } if(item.id === groupCategoryId) { classifyName = item.name } }) currentCate.id = id currentCate.parentName = parentName currentCate.name = name currentCate.parentId = parentId currentCate.code = code currentCate.classifyId = groupCategoryId currentCate.classifyName = classifyName } else if (mode === 'addChild') { // 新增子类 currentCate.parentId = id currentCate.parentName = name currentCate.name = '' currentCate.parentDisabled = true currentCate.classifyId = groupCategoryId } else if(mode === 'addCate') { // 新增分类 currentCate.parentId = id currentCate.parentName = name currentCate.name = '' currentCate.parentDisabled = false currentCate.classifyId = groupCategoryId } currentCate.mode = mode this.setState({ currentCate, }) } /** * 切换添加分类弹窗的显示状态 */ _toggleCatePop(flag) { if(!flag) { const obj = { classifyId: '', parentId: '', name: '', code: '', } this.setState({ currentCate: obj, }) } this.setState({ isShowAddCatePop: flag, }) } /** * 删除分类 */ _deleteCate(item) { this.setState({ isShowConfirmModal: true, currentDeleteCate: item, }) } /** * 改变商品分类 */ _changeCateName(e) { const { currentCate } = this.state currentCate.name = e.target.value this.setState({ currentCate, }) } /** * 修改分类编码 */ _changeCateCode(e) { const { currentCate } = this.state currentCate.code = e.target.value this.setState({ currentCate, }) } // 点击弹窗确认事件 handleOk() { this.setState({ isShowConfirmModal: false }) const { data, dispatch } = this.props const { industry } = data const { currentDeleteCate } = this.state const args = { industry, req: JSON.stringify({ id: currentDeleteCate.id }) } dispatch(action.deleteCate(args)) } // 弹窗取消事件 handleCancel() { this.setState({ isShowConfirmModal: false, currentDeleteCate: {} }) } // 上级分类 _handleAddCateSelect(value) { console.log(value) const parentId = value const { cateFlat=[] } = this.props.data let parentName = '' cateFlat.forEach(function(item) { if(item.id === parentId) { parentName = item.name } }) const { currentCate } = this.state currentCate.parentId = parentId currentCate.parentName = parentName this.setState({ currentCate, }) } // 销售额归属分类 _handleAddCateClassify(value) { const { currentCate } = this.state currentCate.classifyId = value this.setState({ currentCate, }) } /** * 保存商品分类信息 */ _saveCate() { const { dispatch } = this.props const { currentCate } = this.state const { industry } = this.props.data const { id='', code, name='', classifyId, parentId, mode } = currentCate if(name.toString().trim().length === 0) { dispatch(action.errorHandler({message: '分类名称不能为空!'})) return } const args = { industry, req: JSON.stringify({ code: code, name: name, parentId: parentId, groupCategoryId: classifyId, id, }) } if(mode === 'addChild' || mode == 'addCate') { delete args.id dispatch(action.addCate(args)) } else if(mode === 'edit') { dispatch(action.updateCate(args)) } this._toggleCatePop(false) } render() { const { cateList=[], cateFlat=[], } = this.props.data const { isShowAddCatePop, currentCate, isShowConfirmModal, currentDeleteCate, } = this.state return ( <div className={styles.cate_content}> <Button type="primary" className={styles.add_cate_btn} onClick={() => this._editCate(currentCate, 'addCate')}> 添加商品分类 </Button> <div className={styles.cate_manage_body}> <CateTable dataSource={cateList} editCate={this._editCate.bind(this)} deleteCate={this._deleteCate.bind(this)}/> </div> { isShowAddCatePop && <div className={styles.add_cate_container}> <div className={styles.add_cate_bg} onClick={() => this._toggleCatePop(false)}></div> <div className={styles.add_cate_box}> <div className={styles.add_cate_title}>商品分类添加</div> <div className={styles.add_base_conf}>基础设置</div> <div className={styles.add_cate_item}> <span>*商品分类</span> <input type="text" maxLength="40" value={currentCate.name || ''} onChange={this._changeCateName.bind(this)}/> </div> <div className={styles.add_cate_item}> <span>上级分类</span> <Select placeholder="无上级分类" defaultValue={currentCate.parentName} // value={currentCate.parentName} style={{width: '200px', fontSize: '12px'}} disabled={currentCate.parentDisabled} onChange={this._handleAddCateSelect.bind(this)} > <Option value="">无上级分类</Option> { cateFlat.map( item => { if(!item.chain) { // 不展示连锁下发的分类 return ( <Option value={item.id} key={item.id}>{item.name}</Option> ) } }) } </Select> </div> <div className={styles.add_cate_item}> <span>分类编码</span> <input type="text" value={currentCate.code || ''} onChange={this._changeCateCode.bind(this)}/> </div> <div className={styles.add_high_conf}>高级设置</div> <div className={styles.add_cate_item}> <span>销售额归到其他分类</span> <Select placeholder="不设置" defaultValue={currentCate.classifyName} style={{width: '200px', fontSize: '12px'}} onChange={this._handleAddCateClassify.bind(this)} > <option value="">不设置</option> { cateFlat.map( item => { return ( <Option value={item.id} key={item.id}>{item.name}</Option> ) }) } </Select> </div> <div className={styles.add_cate_bottom}> <div className={styles.btn_cancel} onClick={() => this._toggleCatePop(false)}>取消</div> <div className={styles.btn_save} onClick={() => this._saveCate()}>保存</div> </div> </div> </div> } { <Modal title="确认弹窗" visible={isShowConfirmModal} onOk={() => this.handleOk()} onCancel={() => this.handleCancel()} > 确认要删除 [{currentDeleteCate.name}] 吗? </Modal> } </div> ) } } export default CateManage <file_sep>/inside-boss/src/components/goodCombined/main.js import React, { Component } from 'react' import { Cascader, Input, Table, Modal, message, Popconfirm } from 'antd' import styles from './style.css' import * as action from '../../action' import * as bridge from '../../utils/bridge' import { hashHistory } from 'react-router' import Cookie from '@2dfire/utils/cookie' const Search = Input.Search; class Main extends Component { constructor(props) { super(props) this.state = { selectedRowKeys: [], current: 1, tableData: [], selectedCategoryId: '', keyword: '', isShowConfirmModal: false, deleteValue: [], changeCate: false, deleteTip: '', delType: '', isShowDetailPop: false, entityType: null, currentChooseId: '', pageSource:[] } } componentWillMount() { const { dispatch } = this.props dispatch(action.getCombinedGoodsList({ pageSize: 20, pageIndex: 1 })) dispatch(action.getGoodCategory()) } options = [] columns = [ { title: '商品', key: '1', render: (text, record) => ( <div className={styles.title}> <img className={styles.img} src={ record.imageUrl || 'https://assets.2dfire.com/frontend/eae523b1a01aba73903009489818b177.png' } ></img> <div className={styles.ml10}> <div className={styles.titleContent}> {record.name}{' '} {record.chain && ( <div className={styles.isChainIcon}>连锁</div> )} </div> <div className={styles.titleCode}> 商品编码:{record.code} </div> </div> </div> ) }, { title: '所属分类', dataIndex: 'kindMenuName' }, { title: '单价(元)', dataIndex: 'price' }, { title: '会员价(元)', dataIndex: 'memberPrice' }, { title: '结账单位', dataIndex: 'account' }, { title: '是否打折', dataIndex: 'isRatio' }, { title: '组合明细', dataIndex: 'combinedDetail', render: (text, record) => ( <span> <a onClick={this.goToDetail.bind(this, record.id)}> 查看明细 </a> </span> ) }, { title: '商品介绍', width: 150, dataIndex: 'detail' }, { title: '操作', key: 'action', render: (text, record) => ( <span> <a onClick={this.editCombinedList.bind( this, 'edit', record.id, record.chain )} > 编辑 </a> <div className={styles.divider}></div> <a onClick={this.showModal.bind(this, record, 'single')}> 删除 </a> </span> ) } ] detailColumns = [ { title: '商品名称', dataIndex: 'itemName' }, { title: '商品编码', dataIndex: 'code' }, { title: '规格', dataIndex: 'skuDesc' }, { title: '单位', dataIndex: 'unitName' }, { title: '组合数量', dataIndex: 'num' }, { title: '商品单价', dataIndex: 'price' } ] goToDetail(id) { const { dispatch } = this.props this.setState({ isShowDetailPop: true, currentChooseId: id, // pageSource:[] }) dispatch(action.getCombinedGoodDetail(id)) } strSubstring = (str = '') => { const len = str.length if (len > 50) return str.substring(0, 50) + '...' return str } CateSearch = true issuedPreview = (record, bloon) => { const { data } = this.props const { facadeService } = data // changeToSelf: 允许门店下发商品转自建 if (facadeService.changeToSelf) { return ( <span> {bloon && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } else { return ( <span> {!!record.itemShelfLifeConfig && record.itemShelfLifeConfig == '1' && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } } strategyPriew = (record, bloon) => { // isShelfLife 1:有保质期, 0:无保质期 return ( <span> {bloon && !!Number(record.isShelfLife) ? `${record.shelfLife}` : '-'} </span> ) } onChange(value) { const { data, dispatch } = this.props document.getElementById('search').value = '' this.setState({ selectedCategoryId: value[value.length - 1], keyword: '', current: 1 }) if (this.CateSearch) { dispatch( action.getCombinedGoodsList({ pageSize: 20, pageIndex: 1, keyword: '', categoryId: value[value.length - 1] }) ) } this.CateSearch = true } showModal(value, type) { let idList = [] if (type === 'single') { this.setState({ deleteTip: `删除商品后,将同步删除供应链端该商品信息!您确认要删除 ${value.name} 吗?` }) idList.push(value.id) } else { if (this.state.selectedRowKeys.length === 0) { message.error('请先选择商品再进行删除操作') return } this.setState({ deleteTip: `删除商品后,将同步删除供应链端该商品信息!您确认要删除吗?` }) idList = value } this.setState({ isShowConfirmModal: true, deleteValue: idList, delType: type }) } handleCancel() { this.setState({ isShowConfirmModal: false }) } del() { const { data, dispatch } = this.props const page = this.state.delType === 'single' ? this.state.current : 1 dispatch( action.deleteCombinedGoodDetail({ idList: this.state.deleteValue, pageSize: 20, pageIndex: page, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ selectedRowKeys: [], deleteValue: [], isShowConfirmModal: false, current: page }) } searchItem(value) { const { data, dispatch } = this.props const {selectedCategoryId} = this.state this.setState({ keyword: value, selectedCategoryId: '', current: 1 }) // this.CateSearch = false // if (document.getElementsByClassName('ant-cascader-picker-clear')[0]) { // document // .getElementsByClassName('ant-cascader-picker-clear')[0] // .click() // } document.getElementById('search').value = value dispatch( action.getCombinedGoodsList({ pageSize: 20, pageIndex: 1, keyword: value, categoryId: selectedCategoryId }) ) } showChangeCate(type) { if (this.state.selectedRowKeys.length === 0 && type !== 'cancel') { message.error('请先选择商品再进行换分类操作') return } this.setState({ changeCate: !this.state.changeCate, changeToCate: '' }) } setChangeCate(value) { this.setState({ changeToCate: value[value.length - 1] }) } changeCateSave() { if (this.state.selectedRowKeys.length === 0) { message.error('请先选择商品') return } if (!this.state.changeToCate) { message.error('请先选择分类') return } const { data, dispatch } = this.props dispatch( action.changeCombinedCateSave({ idList: this.state.selectedRowKeys, changeCategoryId: this.state.changeToCate, pageSize: 20, pageIndex: 1, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ changeCate: !this.state.changeCate, current: 1, selectedRowKeys: [] }) } goEdit(id, chain) { hashHistory.push(`/ITEM_EDIT/item?id=${id}&chain=${chain}`) } goImportPage() { hashHistory.push(`/ITEM_IMPORT/item`) } goManageCate() { this.props._switchTab() } exportItems() { const { data, dispatch } = this.props dispatch(action.exportItems({ menu_ids: this.state.selectedRowKeys })) } editCombinedList(type, id, chain) { if (type === 'edit') { hashHistory.push( `/COMBINED_GOODS_EDIT/item?id=${id}&chain=${chain}` ) } else { hashHistory.push(`/COMBINED_GOODS_EDIT/item`) } } kk() { this.setState({ changeCate: false, changeToCate: '' }) } closeDetailPop() { this.setState({ isShowDetailPop: false }) } render() { const { data = {}, dispatch } = this.props const { goodCombinedList = [], goodCombinedDetail = {} } = data const totalDetailPage = goodCombinedDetail.childItems?goodCombinedDetail.childItems.length:0 const {pageSource} = this.state const childItems = pageSource.length>0?pageSource:goodCombinedDetail.childItems||[] let selectList = [] let changeCategoryList = [1, 23] if (data.goodsCategoryList.categoryList.length > 0){ selectList = JSON.stringify(data.goodsCategoryList.categoryList) selectList = selectList.replace(/"categoryId"/g, '"value"').replace(/"categoryName"/g, '"label"').replace(/"categoryList"/g, '"children"') selectList = JSON.parse(selectList) changeCategoryList = selectList.filter(value => value.chain === false) } // const { // getFieldDecorator, // getFieldValue, // setFieldsValue // } = self.props.form const pagination = { current: this.state.current, defaultPageSize: 20, total: goodCombinedList.totalRecord || 0, showTotal: total => { ;`Total ${total} items` }, onChange: page => { // this.setState({ tableData: [] }); dispatch( action.getCombinedGoodsList({ pageSize: 20, pageIndex: page, keyword: this.state.keyword, categoryId: this.state.selectedCategoryId }) ) this.setState({ current: page }) } } const detailPagination = { current: this.state.current, defaultPageSize: 5, total: totalDetailPage , showTotal: total => { ;`Total ${total} items` }, onChange: page => { const { goodCombinedDetail = {} } = this.props.data const detailList = goodCombinedDetail.childItems || [] const afterSliceList = detailList.slice( (page - 1) * 5, page * 5 - 1 ) this.setState({ pageSource: afterSliceList, current:page }) } } const rowSelection = { selectedRowKeys: this.state.selectedRowKeys, onChange: (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys }) } } const { isShowDetailPop } = this.state return ( <div className={styles.baseInfo_wrapper}> <div> <Cascader className={styles.cascaderId} size="large" options={selectList} onChange={this.onChange.bind(this)} placeholder="全部分类" /> <Search id="search" className={styles.search} size="large" placeholder="商品名称/条形码" onSearch={this.searchItem.bind(this)} style={{ width: 200 }} /> <div className={styles.exportButton} onClick={this.editCombinedList.bind(this, 'add')} > 新增组合商品 </div> </div> <div> <div className={styles.relative}> <Table className={styles.table} columns={this.columns} rowSelection={rowSelection} rowKey="id" pagination={pagination} dataSource={goodCombinedList.itemList} /> <div className={styles.batchActionsPosition}> <div className={styles.batchActions} onClick={this.showChangeCate.bind(this)} > 换分类 </div> {this.state.changeCate && ( <div> <div className={styles.cover} onClick={this.kk.bind(this)} ></div> <div className={styles.changeCateWrapper}> <div className={styles.changeCateTitle}> <span>换分类</span> <span className={styles.goCate} onClick={this.goManageCate.bind( this )} > 管理分类 </span> </div> <Cascader size="large" options={changeCategoryList} onChange={this.setChangeCate.bind( this )} placeholder="请选择分类" /> <div className={styles.action}> <Popconfirm placement="topLeft" title={ '是否更换选中商品的分类?' } onConfirm={this.changeCateSave.bind( this )} okText="确定" cancelText="取消" > <span className={ styles.changeCateSave } > 保存 </span> </Popconfirm> <span className={ styles.changeCateCancel } onClick={this.showChangeCate.bind( this, 'cancel' )} > 取消 </span> </div> </div> </div> )} <div className={styles.batchActions} onClick={this.showModal.bind( this, this.state.selectedRowKeys )} > 删除 </div> </div> </div> </div> <div></div> <Modal title="确认弹窗" visible={this.state.isShowConfirmModal} onOk={() => this.del()} onCancel={() => this.handleCancel()} > {this.state.deleteTip} </Modal> {isShowDetailPop && ( <div className={styles.good_combined_add_cate_container}> <div className={styles.add_cate_bg} /> <div className={styles.add_cate_box}> <div className={styles.add_cate_title}> 商品组合明细 </div> <Table className={styles.table} columns={this.detailColumns} // rowSelection={rowDetailSelection} rowKey="id" pagination={detailPagination} dataSource={childItems} /> <div className={styles.closeBtn} onClick={this.closeDetailPop.bind(this)} > 关闭弹窗 </div> </div> </div> )} </div> ) } } export default Main <file_sep>/inside-boss/src/container/visualConfig/designComponents/retail/title/definition.js export default { name: 'title', userName: '标题', group: '基础类', max: 10, config: { text: '', size: 'medium', textAlign: 'left', textColor: '#000000', backgroundColor: 'transparent', linkType: 'goods', linkGoodsId: '', linkPage: '', }, } <file_sep>/inside-boss/src/container/orderPhotos/index.js /** * Created by air on 2017/7/10. */ import React, { Component }from 'react' import Main from '../../components/orderPhotos/main' import InitData from './init' import { connect } from 'react-redux' import * as action from '../../action' import * as bridge from '../../utils/bridge' class OrderPhotosContainer extends Component { componentWillMount () { const query = bridge.getInfoAsQuery() const {dispatch, params} = this.props const data = InitData(params.pageType, query) dispatch(action.initOrderData(data)) } render () { const {params,data,dispatch} = this.props return ( <div> <Main params={params} data={data} dispatch={dispatch}/> </div> ) } } const mapStateToProps = (state) => { return { data: state.orderPhotos } } const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(OrderPhotosContainer) <file_sep>/inside-chain/src/utils/cookie.js 'use strict'; var _jsCookie = require('js-cookie'); var _createStorage = require('./createStorage'); var _createStorage2 = _interopRequireDefault(_createStorage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 主域名 不支持国家地区代码顶级域名(ccTLDs,如 .com.cn、.com.uk、.com.hk 等) * @type {String} * * document.domain ==> rootDomain * localhost localhost * 127.0.0.1 127.0.0.1 * a.b.qq.com .qq.com * 123.2dfire.com .2dfire.com * 123.2dfi-re.com .2dfi-re.com * 123.中文.com .中文.com * asd..com asd..com * asd?1.23asd.com .23asd.com */ /** * @see also https://github.com/js-cookie/js-cookie * @example * * set('name', 'value', { expires: 365, domain: '2dfire.net', path: '/static-noble' }); * get('name'); * remove('name', { domain: '2dfire.net', path: '/static-noble' }); * clear('name', { domain: '2dfire.net' }); */ var rootDomain = function getRootDomain(domain) { return (domain.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) || domain.match(/(\.[^\ \.]+){2}$/i) || [domain])[0]; }(document.domain); function setItem(name, value, attributes) { attributes = attributes || {}; // 设默认域为主域 attributes.domain = attributes.domain || rootDomain; (0, _jsCookie.set)(name, value, attributes); } function getItem(name, attributes) { attributes = attributes || {}; // 设默认域为主域 attributes.domain = attributes.domain || rootDomain; return (0, _jsCookie.get)(name, attributes); } function removeItem(name, attributes) { attributes = attributes || {}; // 设默认域为主域 attributes.domain = attributes.domain || rootDomain; (0, _jsCookie.remove)(name, attributes); } function clear(attributes) { attributes = attributes || {}; // 设默认域为主域 attributes.domain = attributes.domain || rootDomain; Object.keys((0, _jsCookie.get)()).forEach(function (cookie) { (0, _jsCookie.remove)(cookie, attributes); }); } module.exports = (0, _createStorage2.default)({ clear: clear, setItem: setItem, getItem: getItem, removeItem: removeItem }); module.default = module.exports;<file_sep>/inside-chain/src/base/tab-badge.js // Created by zeqi // 直接应用于TabPane的徽标render函数 // 使用了render函数,自定义创建了tab头显示内容 // 传入参数: // name: tabPane名称,String // count: 显示的数量,String or Number, 为 0 时,不显示徽标 // max: 显示的最大数值,默认'99',超出显示'99+' // Usage: // <Tabs> // <TabPane :label="label"></TabPane> // </Tabs> // ... // computed: { // label(){ // return tabBadge('主料', 10) // } // } // function tabBadge(name, count, max) { return (h) => { return h('div', [ h('span', name || ''), h('Badge', { props: { count: count, 'class-name': 'tab-badge', 'overflow-count': max || 99 } }), ] ) } } export default tabBadge <file_sep>/inside-boss/src/api/networkAxios.js import axios from 'axios' import {currentAPIUrlNetwork, currentAPIUrlPrefix,currentUrlUploadRul} from '../utils/env' // 获取当前运行时环境变量 export const currentEnvString = __ENV__ || 'DEV' // eslint-disable-line import * as bridge from '../utils/bridge' import cookie from '@2dfire/utils/cookie' // 超时时间 // axios.defaults.timeout = 30000 // 不设置超时时间 axios.defaults.timeout = 0 // 全局 AppKey const APP_KEY = '200800' import { GW } from '@2dfire/gw-params' import qs from 'qs' import getUserInfo from "../utils/getUserInfo"; const GWObject = qs.parse(GW) /** * http请求拦截器 * */ axios.interceptors.request.use( config => { if(config.isWg===true) { const {token} = bridge.getInfoAsQuery() config.headers.common['token'] = config.headers.token || cookie.getItem('new-token') || token || '' config.headers.common['lang'] = 'zh_CN' config.headers.common['X-Token'] = undefined if (currentEnvString === 'PUBLISH') { config.headers.common['env'] = 'publish' } else if (currentEnvString === 'PRE') { config.headers.common['env'] = 'pre' } else { config.headers.common['env'] = 'daily' } config.params = Object.assign({}, config.params, GWObject) config.params.method = config.url || '' config.params.app_key = config.params.app_key || APP_KEY config.url = currentAPIUrlNetwork if (config.name) config.url += `/${config.name}` // 在 url 上带上接口名称,便于调试 // formdata形式的传参 对参数做进一步处理转换为 a=b&c=d&e=f 的格式 if (config.postType === 'formData') { config.headers['Content-Type'] = 'application/x-www-form-urlencoded' config.transformRequest = [function(data) { let newData = '' for (const k in data) { newData += `${encodeURIComponent(k)}=${encodeURIComponent(data[k])}&` } return newData }] } }else if(config.isUploadImg===true){ config.headers.common['Content-Type'] = 'multipart/form-data'; config.headers.common['app-id'] = '200800'; config.headers.common['session-id'] = getUserInfo().token; config.url = currentUrlUploadRul+config.url }else { config.headers.common['X-Token'] = getUserInfo().token; config.headers.common['Accept'] = 'application/json, text/json'; if(!config.url.includes('http')){ config.url=currentAPIUrlPrefix+config.url; } config.headers.common['X-Requested-With'] ='XMLHttpRequest '; config.responseType ='json'; config.withCredentials =false; } return config }, error => { return Promise.reject(error) } ) /** * http响应拦截器 * */ axios.interceptors.response.use( response => { let data = response.data if (data.code === 1) { return data.data } else { return Promise.reject({ success: data.code && data.code === 1, message: data.message, errorCode: data.errorCode }) } }, error => { return Promise.reject(error) } ) export default axios <file_sep>/inside-boss/src/container/visualConfig/views/design/common/constants.js module.exports = { defaultGoodsImg: 'http://assets.2dfire.com/frontend/fad1279df20c0a5371eee760e5a47d57.png' } <file_sep>/inside-boss/src/container/visualConfig/views/design/compoents/announce/index.js import Editor from './AnnounceEditor' import Preview from './AnnouncePreview' export default { type: Editor.designType, editor: Editor, preview: Preview }; <file_sep>/static-hercules/src/marketPlan/components/confirm/index.js import Confirm from './index.vue' let confirm = {} confirm.install = (Vue) => { let constructor = Vue.extend(Confirm) let instance = new constructor({ el: document.createElement('div') }); document.body.appendChild(instance.$el); Vue.prototype.$confirm = (options) => { if (typeof options === 'string') { instance.content = options } else if (typeof options === 'object') { Object.assign(instance, options) } instance.type = 'confirm'; instance.show = true } Vue.prototype.$alert = (options) => { if (typeof options === 'string') { instance.content = options } else if (typeof options === 'object') { Object.assign(instance, options) } instance.type = 'alert'; instance.show = true } } export default confirm <file_sep>/static-hercules/src/examination/utils/arrows.js let commonCss = `position: absolute; width: 0; height: 0;`; let borderDiv = document.createElement('span'); let arrowsDiv = document.createElement('span'); /** * 获取箭头指向css * */ const getCss = (top, bottom, left, right, width, halfWidth, color) => { return `border-${top}: 0; border-${bottom}: ${width}px solid ${color}; border-${left}:${halfWidth}px solid transparent; border-${right}: ${halfWidth}px solid transparent; ${top}: -${width}px; ${left}: 50%; margin-${left}: -${halfWidth}px;` } /** * 获得不同箭头指向的DOM节点 * */ export default { top() { borderDiv.style = `${commonCss}${getCss('top', 'bottom', 'left', 'right', 11, 6, '#999')}`; arrowsDiv.style = `${commonCss}${getCss('top', 'bottom', 'left', 'right', 10, 5, '#fff')}`; return borderDiv.outerHTML + arrowsDiv.outerHTML; }, right() { borderDiv.style = `${commonCss}${getCss('right', 'left', 'top', 'bottom', 11, 6, '#999')}`; arrowsDiv.style = `${commonCss}${getCss('right', 'left', 'top', 'bottom', 10, 5, '#fff')}`; return borderDiv.outerHTML + arrowsDiv.outerHTML; }, bottom() { borderDiv.style = `${commonCss}${getCss('bottom', 'top', 'left', 'right', 11, 6, '#999')}`; arrowsDiv.style = `${commonCss}${getCss('bottom', 'top', 'left', 'right', 10, 5, '#fff')}`; return borderDiv.outerHTML + arrowsDiv.outerHTML; }, left() { borderDiv.style = `${commonCss}${getCss('left', 'right', 'top', 'bottom', 11, 6, '#999')}`; arrowsDiv.style = `${commonCss}${getCss('left', 'right', 'top', 'bottom', 10, 5, '#fff')}`; return borderDiv.outerHTML + arrowsDiv.outerHTML; }, /** * 点的颜色 * */ spot(color){ return `<span style="vertical-align:middle;display: inline-block;width: 5px;height: 5px;background: ${color}; position: absolute;left: 0"></span>` } };<file_sep>/inside-chain/src/store/modules/payKind/getters.js const getters = { payKindList: (state) => { return state.payKindList }, selectPayKind: (state) => { return state.selectPayKind }, selectPayKindSingle: (state) => { return state.selectPayKindSingle }, payKindInfo: (state) => { return state.payKindInfo }, allPayKindList: (state) => { return state.allPayKindList }, payKindListSingle: (state) => { return state.payKindListSingle }, payKindInfoSingle: (state) => { return state.payKindInfoSingle }, allPayKindListSingle: (state) => { return state.allPayKindListSingle }, isAlipay: (state) => { return state.isAlipay } } export default getters <file_sep>/inside-boss/src/components/couponPush/init.js /** * Created by air on 2018/3/14. */ import { currentAPIUrlPrefix, currentEnvString } from '../../utils/env' const protocol = (currentEnvString === 'PUBLISH' ? 'https://' : 'http://') const templateDomainPrefix = (currentEnvString === 'PUBLISH' || currentEnvString === 'PRE' ? 'ifile' : 'ifiletest') const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query,couponId,couponNum,processId) => { const {entityId, memberId, userId} = query; var options = { 'coupon': { importUrl: currentAPIUrlPrefix + 'coupon/back/v1/importCoupon', // importUrl: currentAPIUrlPrefix + 'merchant/import/v2/card', importData: { ...APP_AUTH, entityId: entityId, memberId: memberId, userId: userId, couponId:couponId, couponNum:couponNum, processId:processId }, exportUrl: currentAPIUrlPrefix + 'coupon/back/v1/couponCard', exportData: { ...APP_AUTH, entityId: entityId, memberId: memberId, userId: userId }, // templateFile: protocol + templateDomainPrefix + '.2dfire.com/template/merchant/excelImportCard.xls', templateFile: 'https://assets.2dfire.com/background/%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx', title: '会员信息导入导出', exportBtnText: '导出会员信息', isRecharge: false, showSpin: { boole: false, content: '' } } } return options[key] }; <file_sep>/static-hercules/src/alipay-agent/store/actions.js /** * Created by zipai on 2019/5/20. */ import * as types from './mutation-types' // 修改商户信息 export const modifyInputInfo = ({ commit }, params) => { commit(types.MODIFY_MERCHANT, params) } // 重置商户信息 export const modifyInfo = ({ commit }, params) => { commit(types.MODIFY_MERCHANT_INFO, params) } //底部弹出选择 export const pickerChange = ({ commit }, params) => { commit(types.PICKER_CHANGE, params) } //底部弹出日期选择 export const openDatePicker = ({ commit }, params) => { commit(types.DATE_PICKER_CHANGE, params) } //修改switch开关 export const changeSwitchControl = ({ commit }, params) => { commit(types.SWITCH_CONTROL, params) } // 修改当前编辑状态 export const changeViewState = ({ commit }, params) => { commit(types.CHANGE_VIEWSTATE, params) } //保存表单初始值 export const saveMerchantInfo = ({ commit }, params) => { commit(types.SAVE_MERCHANT_INFO, params) } export const saveIsPopShow = ({ commit }, params) => { commit(types.IS_SHOW_POP, params) } <file_sep>/inside-boss/src/container/rootContainer/Header/index.js import React, { Component } from 'react' import styles from '../style.css' import { observer } from 'mobx-react' import store from '../store' @observer export default class extends Component { render() { const { header: { menuName } } = store return menuName ? ( <div className={styles.header}> <p className={styles.title}>{menuName}</p> </div> ) : null } } <file_sep>/inside-boss/src/container/downComm/init.js import { currentAPIUrlPrefix } from '../../utils/env' const APP_AUTH = { app_key: '200800', s_os: 'pc_merchant_back', } export default (key, query) => { const {entityId, userName, memberId, userId} = query; const options = { "template": { treeData : [], tableData: [], exportUrl: currentAPIUrlPrefix + 'merchant/import/v1/create_import_template', exportData: { ...APP_AUTH, entityId: entityId }, checkedList: [], entityId: entityId, userName: userName, memberId: memberId, userId: userId } } return options[key] }; <file_sep>/static-hercules/src/alibi/config/api.js const {SHARE_BASE_URL, API_BASE_URL} = require("apiConfig"); const ACTIVITY_API_URL = API_BASE_URL + '/koubei_cash_server'; const ACTIVITY_SHARE_URL = SHARE_BASE_URL+ '/koubei_cash_server'; module.exports = { // 发送验证码 GET_PHONE_CODE:API_BASE_URL+'/bind/v1/get_code', // 验证码有效性验证并换绑手机号 GET_BIND_PHONE:API_BASE_URL+'/bind/v1/verify', // 离线登录 OFF_LINE_CODE:API_BASE_URL+'/cash/v1/cash_offline_login', // 在线登录 GET_LOGIN:API_BASE_URL+'/cash/v1/cash_online_login', // 区码 GET_AREA_CODE:API_BASE_URL+'/bind/v1/get_country_code', // 单纯校验验证码 VERIFY_CODE: API_BASE_URL + '/bind/v1/verify_code', };<file_sep>/static-hercules/src/login/config/api.js const { GATEWAY_BASE_URL, WEBSOCKET_URL, ENV } = require('apiConfig'); import { GW } from '@2dfire/gw-params' const APP_AUTH = '&' + GW + '&'; let getEnv = function (env) { console.log(ENV); if (ENV === 'publish' || ENV === 'pre' || ENV === 'daily') { return ENV } else { return env } } let getSocketUrl = function () { // if (ENV === 'publish') { // return 'https://websocket.2dfire.com' // } else if (ENV === 'pre') { // return 'https://websocket.2dfire-pre.com' // } else { // return 'http://10.1.5.114:9003' // } return WEBSOCKET_URL; } console.log(APP_AUTH); let config = { GET_CODE: { url: GATEWAY_BASE_URL + '?method=com.dfire.boss.center.login.service.IScanQrCodeLoginService.createScanQrCode' + APP_AUTH, env: getEnv('0355c5250fb945a1b83235dae80850d6') }, SOCKET: getSocketUrl() } module.exports = { // 购买详情页 ...config }<file_sep>/static-hercules/src/examination/main.js import Route from "@2dfire/utils/router"; import sessionStorage from "@2dfire/utils/sessionStorage"; var Vue = require("vue"); var Router = require("vue-router"); Vue.use(Router); var App = require('./App.vue'); sessionStorage.setItem('id', encodeURIComponent(Route.route.query["id"])); import Charts from '@2dfire/charts' import '@2dfire/charts/dist/charts.css' Vue.use(Charts); // 开启debug模式 Vue.config.debug = true; var router = new Router({ routes: [{ path: "*", redirect: "/index" }, { path: "/index", name: "index", title: "活动首页", component: require("./views/index.vue") }] }); /** * 埋点 * */ import logger from '@2dfire/logger' console.log('****************',logger) Vue.use(logger, { product: '7.1', //产品线 project: 'shop_exam', //项目名称 router: router }); new Vue({ el: '#app', router, template: "<App/>", components: {App}, }); <file_sep>/inside-chain/src/store/modules/setting/state.js import { goodsDefaultValue } from '@/const/emu-goodsDefaultValue' import { suitDefaultValue } from '@/const/emu-suitDefaultValue' export default{ // 获取品牌列表 brandList: [], // 分类列表 categoryList: [], // 连锁商品列表 chain: { goodsList: { total: 0, itemList: [] }, suitList: { total: 0, list: [] } }, // 单店商品列表 single: { goodsList: { total: 0, itemList: [] }, suitList: { total: 0, list: [] } }, common: { goods: { detailFromBack: Object.assign({}, goodsDefaultValue), detailToBack: Object.assign({}, goodsDefaultValue), labelList: {}, // 新增/编辑时候所有select下面的内容 allSelectList: {} }, suit: { // 套餐基本信息 detailBaseInfoToBack: Object.assign({}, suitDefaultValue), labelList: {}, // 获取新增/编辑时候点菜单位的select列表 orderUnitSelectList: [], suitGoodsList: {}, suitGoodsCategory: [] } } } <file_sep>/inside-boss/src/container/rootContainer/store.js import {observable} from 'mobx' import api from '../../api' import React from 'react' import {Modal} from 'antd' import img from './advertising.png' import cookie from '@2dfire/utils/cookie' import pathMap from './pathMap' import {hashHistory} from 'react-router' import getUserInfo from '../../utils/getUserInfo' import { currentFHYUrl } from '../../utils/env' const entrance = JSON.parse(cookie.getItem('entrance')) import * as bridge from '../../utils/bridge' class Store { @observable menuList = [] @observable header = {} getMenuList = async () => { // cookie.removeItem('new-token') const active = cookie.getItem('active') const entityId = JSON.parse(cookie.getItem('entrance')).shopInfo.entityId const menuVo = await api[ active === '掌柜工具' ? 'getBossMenuList' : 'getRailwayMenuList' ]() // if ( active === '掌柜工具'&& ) { // 00229806这家店为需要设置高铁开店监控的店 // console.log(entityId) // if ( active === '掌柜工具'&& (entityId === "99930005"||entityId === "00229806"||entityId==='00143255')) { if (active === '掌柜工具' && (entityId === "00229806" || entityId === '00143255'|| entityId === '99180147')) { // if ( active === '掌柜工具'&& (entityId === "00229806")) { if (menuVo && menuVo.menuName === '掌柜' && menuVo.children && menuVo.children[0] && menuVo.children[0].menuName === '数据导入导出') { if (menuVo.children[0].children) { menuVo.children[0].children.push({ "menuId": "e450d5e7bb9a4567a7c5fb00000000000", "menuName": "开店监控", "businessType": "boss", "pageType": "HIGH_DAILY_MONITOR", "parentId": menuVo.children[0].menuId, "query": {reportId: "e450d5e7bb9a4567a7c5fb00000000000"} }) } else { menuVo.children[0].children = [{ "menuId": "e450d5e7bb9a4567a7c5fb00000000000", "menuName": "开店监控", "businessType": "boss", "pageType": "HIGH_DAILY_MONITOR", "parentId": menuVo.children[0].menuId, "query": {reportId: "e450d5e7bb9a4567a7c5fb00000000000"} }] } } } // cookie.setItem('new-token', token) const menuList = (menuVo || {}).children || [] // const { industry } = (JSON.parse(cookie.getItem('entrance')).shopInfo || {}) // if (industry == 3) { // menuList.push({ // menuId: 'visual_config_parent', // menuName: '店铺装修', // pageType: 'node', // businessType: 'boss', // children: [ // { // menuId: 'visual_config_design', // menuName: '自定义装修', // pageType: 'visual_config_design', // businessType: 'boss', // parentId: 'visual_config_parent', // }, // { // menuId: 'visual_config_pages', // menuName: '页面管理', // pageType: 'visual_config_pages', // businessType: 'boss', // parentId: 'visual_config_parent', // }, // { // menuId: 'visual_config_templates', // menuName: '装修模板', // pageType: 'visual_config_templates', // businessType: 'boss', // parentId: 'visual_config_parent', // }, // { // menuId: 'visual_config_backups', // menuName: '备份', // pageType: 'visual_config_backups', // businessType: 'boss', // parentId: 'visual_config_parent', // }, // ] // }) // } this.menuList = menuList } setHeader = header => { this.header = header || {} } linkRoute = info => { const {pageType} = info const path = pathMap(info)[pageType] // if(pageType === 'FHY_EXTERNAL_LINK') window.location.href = currentFHYUrl if (path) { hashHistory.push(path) //`${path}?${getUserInfo(true)}&token=${cookie.getItem('new-token')}` } } //点击侧边栏之后的操作 setInfo = info => { const {query = {}} = info const {withAd, isVipOpen} = query if ((isVipOpen === '1' || !isVipOpen) && withAd === '1') { this.showAdvertisingModal() } } showNoVipModal = info => { Modal.info({ title: '公告', content: ( <div> <p>您没有开通</p> <p style={{color: '#f00'}}>{info.menuName}</p> <p>的查看权限,请登录供应链APP,在高级模块商城中进行开通。</p> </div> ) }) } showAdvertisingModal = () => { Modal.info({ content: <img src={img} alt=""/> }) } } export default new Store() <file_sep>/inside-chain/src/store/modules/distCenter/state.js export default { // 下发任务列表 publishTaskList: { total: 0, tasks: [] }, // 下发任务详情 taskInfo: { timeType: 0, chainPublishTaskContent: { publishType: 0, shopList: [], failureReason: '' }, id: "", name: "", plateEntityId: "", plateName: "", publishStartTime: 0, publishStartTimeStr: "", status: 0, menuInfo: { menuName: '', menuCount: 0 }, // 传菜方案 passInfo: { name: '', time: '' } }, // 筛选用所有品牌列表 brandList: [ // { // name: '全部', // entityId: "all" // } ], publishTimeType: [], } <file_sep>/inside-boss/src/utils/uploadFile.js import { UPLOAD_BASE_URL } from '../utils/env' import Cookie from '@2dfire/utils/cookie' // 'mis/temp/' || 'mis/permanent/' export default function () { const bindData = { name: 'file', multiple: true, action: `${ UPLOAD_BASE_URL }/api/uploadfile`, data: { projectName: 'OssDownload', path: 'mis/permanent/' }, headers: { 'app-id': '200800', 'session-id': encodeURIComponent(JSON.parse(decodeURIComponent(Cookie.getItem('entrance'))).token), 'X-Requested-With': null, }, } return bindData } <file_sep>/inside-boss/src/components/downComm/main.js /** * Created by air on 2017/7/31. */ import React, {Component} from 'react' import styles from './style.css' import {message, Button, Modal, Spin, Tree, Table, Input} from 'antd' import * as action from '../../action' import * as bridge from '../../utils/bridge' import saveAs from '../../utils/saveAs' import TreeList from './treeList' import {setPageNumber} from "../../action/index"; // 使用到的antD组件 const TreeNode = Tree.TreeNode; const Search = Input.Search; class Main extends Component { constructor(props) { super(props) } //表格 表头 columns = [{ title: '序号', dataIndex: 'no', width: 100, render: (text, record, index) => ( <span> {index + 1} </span> ) }, { title: '类目', dataIndex: 'type' }, { title: '操作', dataIndex: 'key', width: 100, render: (text, record) => ( <span> <a onClick={() => { this.del(text,record) }}>删除</a> </span> ), }]; handleExport (url) { const t = this const {token} = bridge.getInfoAsQuery() saveAs(url, token).then( filename => message.success('导出成功!'), // 成功返回文件名 err => { if (err.code === 0) { if (err.errorCode === '401') { bridge.callParent('logout') return } message.error(err.message || '导出失败') } } ).then(e => this.setState({exportLock: false})) } json2url (json) { var url = '' var arr = [] for (let i in json) { arr.push(i + '=' + json[i]) } url = arr.join('&') return url } del =(text,record)=> { console.log(text,record); const {data, dispatch} = this.props; const {tableData, checkedList} = data; let tmp = [].concat(checkedList); let tmpBlank = []; let j=0,k=0 ; for(let i =0; i< tableData.length; i++){ if(tableData[i].key == text){ j = i; } } for(let m =0; m< checkedList.length; m++){ if(checkedList[m] == text){ k = m; } } tableData.splice(j,1); console.log(tmp,'tmp',k,tmp.splice(k,1)); dispatch(action.delTableItem(tableData)); dispatch(action.checkedType(tmp)); if(tableData.length == 0){ console.log('blank table~') dispatch(action.checkedType([])); } }; // 本组件状态,可以在当前组件内setState(异步)修改数据 state = { expandedKeys: [], searchValue: '', autoExpandParent: true, } //展开 onExpand = (expandedKeys) => { this.setState({ expandedKeys, autoExpandParent: false, }); } //筛选框输入值 onChange = (e) => { const value = e.target.value; console.log(e.target); console.log(value) // const expandedKeys = dataList.map((item) => { // if (item.title.indexOf(value) > -1) { // return getParentKey(item.key, treeData); // } // return null; // }).filter((item, i, self) => item && self.indexOf(item) === i); // this.setState({ // expandedKeys, // searchValue: value, // autoExpandParent: true, // }); } render() { const t = this const {dispatch, data} = t.props const {tableData, exportUrl, exportData, checkedList} = data; let final = exportData; let categoryIds = checkedList ? checkedList.toString() : null; final = Object.assign({}, exportData, {categoryIds: categoryIds}) // const _exportUrl = exportUrl + '?' + t.json2url(final) const _exportUrl = exportUrl + '?' + t.json2url(final) //table 属性控制 const table_state = { pagination: false, bordered: true, size: "middle", scroll: { y: 390 } } //tree 属性控制 const tree_state = { checkable: true, multiple: true, showLine: true, showIcon: false } const { searchValue, expandedKeys, autoExpandParent } = this.state; const loop = (data) => { if(data){ console.log(data) data.map((item) => { const index = item.title.indexOf(searchValue); const beforeStr = item.title.substr(0, index); const afterStr = item.title.substr(index + searchValue.length); const title = index > -1 ? ( <span> {beforeStr} <span style={{color: '#f50'}}>{searchValue}</span> {afterStr} </span> ) : <span>{item.title}</span>; if (item.children) { return ( <TreeNode key={item.key} title={title}> {loop(item.children)} </TreeNode> ); } return <TreeNode key={item.key} title={title} third/>; }); } } return ( <div className={styles.main_wrapper}> <div className={styles.top_line}> <div className={styles.treeSelect}> <p className={styles.title}>请选择需要导入的类目,一次不超过50个:</p> <div className={styles.tree}> <div> {<TreeList data={data} dispatch={dispatch}/>} </div> </div> </div> <div className={styles.selectedList}> <p className={styles.title}>已选择类目:{tableData?tableData.length:0}</p> { <Table {...table_state} columns={this.columns} dataSource={tableData}/> } <Button type="primary" className={styles.downBtn} onClick={t.handleExport.bind(t, _exportUrl)} disabled={tableData == ''}>确认并下载模板</Button> </div> </div> {/*{*/} {/*showSpin && showSpin.bool ? (*/} {/*<div className={styles.cover}>*/} {/*<Spin tip={showSpin.content} style={{marginTop: 160, marginLeft: -160}} size="large"></Spin>*/} {/*</div>*/} {/*) : null*/} {/*}*/} </div> ) } } export default Main <file_sep>/static-hercules/src/guide/config/api.js const { GATEWAY_BASE_URL} = require("apiConfig"); module.exports = { GATEWAY_BASE_URL };<file_sep>/inside-boss/src/components/couponPush/select.js /** * Created by air on 2018/3/14. */ import React, { Component } from 'react' import { Dropdown, Menu, Button, Icon, Popconfirm } from 'antd' import * as action from '../../action' import styles from './select.css' import cx from 'classnames' const MySelect = ({content, onClickLeft, onClickRight}) => ( <div style={{overflow: 'hidden', height: '100%'}}> <div onClick={onClickLeft} className={styles.options_left}>{content}</div> <Popconfirm title="是否确认删除该文件?" onConfirm={onClickRight}> <div className={styles.options_right}><Icon type="close"/></div> </Popconfirm> </div> ) class BatchSelector extends Component { onClick () { // const buttonLock = sessionStorage.getItem('dropDownButtonLock') // if (buttonLock === 'loading') { // return false // } const {dispatch} = this.props dispatch(action.fetchImportFileList()) } handleClickDropdownItem (position, index) { const {dispatch} = this.props const {importFileList} = this.props.data const {id} = importFileList[index] const rechargeBatchId = id const pageSize = 50 const pageIndex = 1 if (position === 'left') { dispatch(action.changeStatus(null)) dispatch(action.getRechargeList( rechargeBatchId, null, pageSize, pageIndex, )) } else if (position === 'right') { dispatch(action.deleteBatch_(rechargeBatchId)) } } render () { const t = this const {importFileList, name} = this.props.data const menu = ( <Menu className={cx(styles.dropdown_wrapper)}> {importFileList? importFileList.map((e, i) => { return ( <Menu.Item key={i} className={cx(styles.dropdown_item)}> <MySelect content={e.name} onClickLeft={t.handleClickDropdownItem.bind(t, 'left', i)} onClickRight={t.handleClickDropdownItem.bind(t, 'right', i)}/> </Menu.Item> ) }):null } </Menu> ) return ( <Dropdown overlay={menu} trigger={['click']}> <Button className={cx(styles.select_btn)} onClick={t.onClick.bind(t)}> <span className={styles.sel_text}>{name ? name : '选择已上传的文件'}</span> <Icon type="down" className={cx(styles.icon)}/> </Button> </Dropdown> ) } } export default BatchSelector <file_sep>/inside-boss/src/container/visualConfig/views/design/preview/DesignPreviewItem.js import React, { PureComponent } from 'react'; import style from './DesignpreviewItem.css' export default class DesignPreviewItem extends PureComponent { render() { const { children } = this.props; return <div className={style.designPreviewItem}>{children}</div>; } }<file_sep>/inside-chain/src/tools/feed-back-auto/eventEmitter.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultStates = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _events = require('events'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var baseOptions = { content: '', // 提示内容 callback: null, // 接口调用结束的回调函数 level: 'info', mask: true, visible: false }; /** * 默认状态 * @type {Object} * TODO freeze */ var defaultStates = { // Alert警告提示 alert: _extends({}, baseOptions, { name: 'alert', title: '', // 提示标题 closeText: '', // 关闭按钮文本 duration: -1, // 自动关闭的延时,单位毫秒 showIcon: true, iconImage: '' }), // Toast 弹框 toast: _extends({}, baseOptions, { name: 'toast', duration: -1, // 自动关闭的延时,单位毫秒 showIcon: true, iconImage: '' }), // Message全局提示 message: _extends({}, baseOptions, { name: 'message', duration: 3000, // 自动关闭的延时,单位毫秒 showIcon: true, iconImage: '', mask: false }), // Modal对话框 modal: _extends({}, baseOptions, { name: 'modal', title: '', // 提示标题 okText: '确定', cancelText: '取消', showIcon: true, iconImage: '' }), 'share-mask': _extends({}, baseOptions, { name: 'share-mask', showIcon: true, iconImage: '' }) }; function getDefaultState(name) { return name in defaultStates ? _extends({}, defaultStates[name]) : null; } var FeedBackEventEmitter = function (_EventEmitter) { _inherits(FeedBackEventEmitter, _EventEmitter); function FeedBackEventEmitter() { _classCallCheck(this, FeedBackEventEmitter); return _possibleConstructorReturn(this, (FeedBackEventEmitter.__proto__ || Object.getPrototypeOf(FeedBackEventEmitter)).apply(this, arguments)); } _createClass(FeedBackEventEmitter, [{ key: 'show', value: function show(name, options) { var defaultOptions = getDefaultState(name); if (defaultOptions) { var showOptions = _extends({}, defaultOptions, { visible: true }, options); this.emit(name, showOptions); this.emit('change', showOptions); return showOptions; } } }, { key: 'hide', value: function hide(name) { var defaultOptions = getDefaultState(name); if (defaultOptions) { var hideOptions = _extends({}, defaultOptions, { visible: false }); this.emit(name, hideOptions); this.emit('change', hideOptions); } } }]); return FeedBackEventEmitter; }(_events.EventEmitter); exports.defaultStates = defaultStates; exports.default = new FeedBackEventEmitter();<file_sep>/inside-chain/src/tools/feed-back-auto/modal.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.hide = exports.alert = exports.confirm = exports.warn = exports.warning = exports.success = exports.error = exports.info = undefined; var _utils = require('./utils'); var type = 'modal'; var info = (0, _utils.createShowWithLevel)(type, 'info'); var warning = (0, _utils.createShowWithLevel)(type, 'warning'); var warn = warning; var error = (0, _utils.createShowWithLevel)(type, 'error'); var success = (0, _utils.createShowWithLevel)(type, 'success'); // 两个按钮 alias info var confirm = info; // 一个按钮 var alert = (0, _utils.createShow)(type, { level: 'info', cancelText: '' }); // 隐藏 var hide = (0, _utils.createHide)(type); exports.info = info; exports.error = error; exports.success = success; exports.warning = warning; exports.warn = warn; exports.confirm = confirm; exports.alert = alert; exports.hide = hide; exports.default = { info: info, error: error, success: success, warning: warning, warn: warn, confirm: confirm, alert: alert, hide: hide };<file_sep>/inside-chain/src/store/modules/organ/actions.js /** * 门店管理相关路由页面store */ import Requester from '@/base/requester' import catchError from '@/base/catchError' import API from '@/config/api' import Obj from '@2dfire/utils/object' import Cookie from '@2dfire/utils/cookie' const actions = { selectOrgan(context, item) { let organs = context.state.shop_filter.organs_show.concat(); let organs_checked = context.state.shop_filter.organs_checked.concat(); let sub_organs = []; organs.map(v => { console.log('id', v.id, item.id) if (v.id == item.id) { if (v.children && v.children.length > 0) { sub_organs = v.children; organs_checked.push(item) console.log(organs_checked) context.commit('_setOrganChecked', organs_checked) } else { v.active = true; sub_organs = organs; } console.log('sub', sub_organs) } }) context.commit('_selectOrgan', sub_organs) context.commit('_setOrgan', item.id) }, backOrgan(context, params) { let organs_checked = context.state.shop_filter.organs_checked.concat(); console.log(organs_checked.length, params.index) let new_organ = organs_checked.splice(0, params.index + 1) context.commit('_setOrganChecked', new_organ) context.commit('_selectOrgan', params.item.children) context.commit('_setOrgan', params.item.id) }, setOrganHead(context) { let name = ''; // 从cookie中获取店铺的名称 let shopInfo = Cookie.getItem('shopInfo'); if(shopInfo){ name = JSON.parse(shopInfo).entityName; } context.commit('_setOrganHead', name); // context.dispatch('getHeadInfo'); }, // 获取总部信息 getHeadInfo(context) { let params = { entityId: '' } let shopInfo = Cookie.getItem('shopInfo'); if(shopInfo){ params.entityId = JSON.parse(shopInfo).entityId; } console.log(params, 'id!!!') context.dispatch('getOrganInfo', params) }, // 获取分支机构 getOrganMap(context, params) { Requester.get(API.GET_ORGAN_MAP).then(data => { // 数据处理 // ... // 提交mutation console.log('data', data) // let data = [ // { // branchName: '华东大区', // entityId: '1', // expand: false, // children: [ // { // branchName: '浙江省', // entityId: '2', // expand: false, // "shopCount": 19, // children: [ // { // branchName: '西湖区店', // entityId: '3', // expand: false, // children: [ // { // branchName: '西湖区1', // entityId: '6123123' // }, // { // branchName: '西湖区12', // entityId: '466', // }, // { // branchName: '西湖区13', // entityId: '17666' // } // ] // }, // { // branchName: '拱墅区', // entityId: '42345', // }, // { // branchName: '外滩', // entityId: '17', // organ_info: { // name: '哈哈', // code: '123', // num: '333253', // found_date: '2018-09-18', // manager: 'wuwuw', // phone: '13988888888', // address: 'asdasdasd' // } // } // ] // }, // { // branchName: '上海市', // entityId: '5', // expand: false, // children: [ // { // branchName: '黄埔一号店', // entityId: '6', // }, // { // branchName: '老外滩', // entityId: '7' // } // ] // } // ] // }] let true_data = data.data context.commit('_searchOrgan', true_data); }).catch(e => { catchError(e); }); }, // 获取分支机构详情 getOrganInfo(context, params) { console.log('getoInfo') let param = { branchEntityId: params.entityId } Requester.get(API.GET_ORGAN_INFO, {params: param}).then(data => { let true_data = data.data console.log('data!!',Obj.isEmpty(true_data)) // let data = { // "brandEntityId": "", // "industry": 0, // "parentEntityId": "", // "cityId": "", // "townId": "", // "attributeExt": "", // "countryId": "", // "countryCode": "", // "tel": "电话", // "id": "", // "lastVer": 0, // "email": "", // "branchId": "", // "spell": "", // "address": "地址", // "foundDate": "成立日期", // "isValid": 0, // "branchName": "名称", // "entityId": "实体ID", // "provinceId": "", // "sortCode": 0, // "branchCode": "编号", // "opTime": 0, // "createTime": 0, // "contacts": "联系人" // } let tmp_flow = []; let new_data = {}; if(Obj.isEmpty(true_data)) { new_data = { name: '-', num: 0, code: '-', found_date: '-', manager: '-', phone:'-', address: '-', organ_flow: [] } } else{ true_data.parentList.map(v=> { tmp_flow.push(v.branchName); }) new_data = { name: true_data.branchName, num: params.shopCount || 0, code: true_data.branchCode, found_date: true_data.foundDate || '-', manager: true_data.contacts || '-', phone: true_data.tel || '-', address: true_data.address || '-', organ_flow: tmp_flow } } context.commit('_getOrganInfo', new_data); }).catch(e => { catchError(e); }); // 注释不用 // 改成请求接口,返回组织详情 // context.commit('_clearTmpFlow'); // context.dispatch('setOrganFlow', params).then(() => { // let tmp_flow = context.state.tmp_flow.concat(); // // 第二级:判断循环得到临时组织长度为1,且第一项名称与选中的不同;第三级以上:临时组织list长度超过1 // if ((tmp_flow.length == 1 && tmp_flow[0] != params.title ) || tmp_flow.length > 1) { // // 从顶部塞入当前选中的节点的名称 // tmp_flow.unshift(params.title); // } // tmp_flow = tmp_flow.reverse(); // // 设置当前选中组织流 // context.commit('_setOrganFlow', tmp_flow); // // 设置当前选中组织详情 // context.commit('_getOrganInfo', params.organ_info); // }) }, // setOrganFlow(context, params) { // 弃用 // // let organ_flow = context.state.tmp_flow.concat(); // if (params.parent) { // organ_flow.push(params.parent.title) // context.commit('_setOrganTmpFlow', organ_flow) // if (params.parent.parent) { // context.dispatch('setOrganFlow', params.parent) // } // } else { // organ_flow.push(params.title) // context.commit('_setOrganTmpFlow', organ_flow) // } // // }, // 筛选分支机构 // 查找输入名称的组织 searchOrgan(context, params) { let organs = context.state.organ.organs.slice(); console.log(context.state.organ.organs) context.commit('_clearOrgan') context.dispatch('expandOrgan', {organ: organs, filter: params}).then(() => { let new_organs = context.state.tmp_organs; console.log('_searchOrgan', new_organs) setTimeout(function () { context.commit('_searchOrgan', new_organs) }, 0) }) }, clearOrgan(context) { context.commit('_clearOrgan'); }, // 展开选中节点 expandOrgan(context, params) { let new_organ = params.organ let filter = params.filter new_organ.map(v => { if (filter && v.branchName && v.branchName.indexOf(filter) >= 0) { v.active = true; } else { v.active = false; } v.expand = true; if (v.children && v.children.length > 0) { context.dispatch('expandOrgan', {organ: v.children, filter: filter}) // console.log('return be') return false // console.log('return after') } }); console.log('loop: ', new_organ) context.commit('_expandOrgan', new_organ) }, toggleNode(context, params) { console.log('in: ', params) let organs = context.state.organ.organs.concat(); context.dispatch('mapNode', {organ: organs, filter: params.entityId}).then(() => { let new_organs = context.state.tmp_organs; console.log('new_organs', new_organs) context.commit('_searchOrgan', new_organs) }) }, mapNode(context, params) { let new_organ = params.organ let filter = params.filter new_organ.map(v => { console.log('judeg', v.entityId, filter) if (filter && v.entityId == filter) { v.expand = !v.expand; console.log('v.expand', v.expand) } if (v.children && v.children.length > 0) { context.dispatch('mapNode', {organ: v.children, filter: filter}) } }); context.commit('_expandOrgan', new_organ) } } export default actions; <file_sep>/inside-boss/src/format/mall.js export function toInt(num, min = 0) { let res = parseInt(num) || 0 if (res < min) { res = min } return res } export function toBool(n) { return n ? 1 : 0 } export const formatBannerList = (data = []) => { const formatedList = data.map((d) => { return { id: d.id, index: d.sequenceNumber, mallEntityId: d.mallEntityId, title: d.title, img: d.imgUrl, url: d.link, totalNum: d.totalNum, isSelected: toBool(d.isOnShelf), isValid: toBool(d.isValid), } }) return formatedList } // 目前和banner列表一样 以防接口改动 export const formatActivityList = (data = []) => { const formatedList = data.map((d, i) => { return { id: d.id, index: d.sequenceNumber, udInde: i + 1, mallEntityId: d.mallEntityId, title: d.title, img: d.imgUrl, url: d.link, totalNum: d.totalNum, isSelected: toBool(d.isOnShelf), isValid: toBool(d.isValid), isTop: toBool(d.isTop) } }) return formatedList } export const bridgeItem = (data = {}) => { return { id: data.id, sequenceNumber: data.index, title: data.title, imgUrl: data.img, link: data.url, isOnShelf: data.isSelected, } } <file_sep>/static-hercules/src/fin-action/main.js var Vue = require('vue') var VueRouter = require('vue-router') var vueResource = require('vue-resource') var App = require('./App.vue') import toast from './components/toast/index.js' import logger from '@2dfire/logger' Vue.use(toast) Vue.use(VueRouter) Vue.use(vueResource) Vue.http.options.credentials = true var router = new VueRouter({ routes: [ { path: '*', redirect: '/index' }, { path: '/index', name: 'index', title: '活动首页', component: require('./views/index/index.vue') } ] }) router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) Vue.use(logger, { product: '4.2', //产品线 project: 'fin_action', //项目名称 router: router }) new Vue({ el: '#app', router, template: '<App/>', components: { App } }) <file_sep>/static-hercules/src/give-key/main.js var Vue = require("vue"); var VueRouter = require("vue-router"); var vueResource = require("vue-resource"); var App = require('./App.vue'); import { router } from "./router" import FireUi from '@2dfire/fire-ui' import '@2dfire/fire-ui/dist/index.css' import logger from '@2dfire/logger' Vue.use(VueRouter); Vue.use(vueResource); Vue.use(FireUi); Vue.http.options.credentials = true; Vue.use(logger, { product: '2.7', //产品线 project: 'give_key', //项目名称 router: router }); router.beforeEach((to, from, next) => { // 路由变换后,滚动至顶 window.scrollTo(0, 0) next() }) new Vue({ el: '#app', router, template: "<App/>", components: { App }, });<file_sep>/inside-boss/src/container/welcome/index.js import React from "react"; import getUserInfo from "../../utils/getUserInfo"; import styles from "./style.css"; const Welcome = () => { const { userInfo:{name} } = getUserInfo(); return ( <div className={styles.wrapper}> <p className={styles.user_name}> <span className={styles.hi}>Hi, </span> <span>{name}</span> </p> <p className={styles.welc}>welcome</p> <p className={styles.disc}> 欢迎使用<span className={styles.erweihuo}> 二维火商家管理系统, </span>请尽情使用吧! </p> </div> ); }; export default Welcome; <file_sep>/inside-chain/src/tools/feed-back-auto/index.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.shareMask = exports.toast = exports.modal = exports.message = exports.eventEmitter = exports.alert = undefined; var _alert = require('./alert'); var _alert2 = _interopRequireDefault(_alert); var _eventEmitter = require('./eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _message = require('./message'); var _message2 = _interopRequireDefault(_message); var _modal = require('./modal'); var _modal2 = _interopRequireDefault(_modal); var _toast = require('./toast'); var _toast2 = _interopRequireDefault(_toast); var _shareMask = require('./share-mask'); var _shareMask2 = _interopRequireDefault(_shareMask); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.alert = _alert2.default; exports.eventEmitter = _eventEmitter2.default; exports.message = _message2.default; exports.modal = _modal2.default; exports.toast = _toast2.default; exports.shareMask = _shareMask2.default; exports.default = { alert: _alert2.default, eventEmitter: _eventEmitter2.default, message: _message2.default, modal: _modal2.default, toast: _toast2.default, shareMask: _shareMask2.default };<file_sep>/inside-chain/src/utils/wxApp/debug.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.debug = undefined; var _debug = require("debug"); var debug = exports.debug = _debug.Debug; /** * Created by hupo. * on 17/6/15. */ exports.default = { debug: debug };<file_sep>/inside-boss/src/container/visualConfig/sences/index.js import { formatSenceDefinition } from '@src/container/visualConfig/store/formatters/definition' import retail from './retail' import union from './union' const sences = [ retail, union ] export default sences.map(formatSenceDefinition) <file_sep>/inside-chain/src/utils/wxApp/validate.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var mobilePhoneReg = /^1[3|4|5|7|8]\d{9}$/; /** * 检验字符串是否符合手机规则 * @param {String} v * @return {Boolean} */ function isMobilePhone(v) { return mobilePhoneReg.test(v); } exports.isMobilePhone = isMobilePhone; exports.default = { isMobilePhone: isMobilePhone };<file_sep>/static-hercules/README.md # static-herclues ## Build Setup ``` bash # install dependencies 首次使用,请运行 此命令安装node.js依赖 npm install # serve with hot reload at localhost:8888 开发 请运行此命令进行调试 npm run dev # build for production with minification 发布 npm run build For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). ``` # vue + webpack 的各种坑 `"vue-resource": "0.9"` 以后的版本 get请求无法直接使用{foo: bar}传递参数,需要使用{params: {foo: bar}}, 返回结果也无法自动编译为json 需要使用 resp.json() 建议所有ajax使用 post请求 简单使用全局数据的方法, 在router外层加一层 vue (即app.vue), 需要放在全局的数据可以放在app.vue下 更复杂的数据和状态管理, 请使用 vux (https://github.com/vuejs/vuex) webpack 打包sass 的时候 引用的共有部分无法自动去除, 会被重复打包进来 所以, common.scss 文件中只能放 公用的 变量 方法 和 mixin 等 # 其他说明 设置 代理跳转的地方 : ./config/index.js proxyTable 使用postcss的 1 autoprefixer插件, 添加浏览器兼容的css前缀 设置规则参考地址: (官方)https://github.com/postcss/autoprefixer (中文)http://www.ydcss.com/archives/94 使用postcss的 2 cssnano插件, 简化和压缩css (discardUnused等四个选项是不安全选项,所以关闭,如果css出现未知错误,请关闭此插件!! http://cssnano.co/optimisations/) 使用postcss的 3 使用 pxtorem 插件来进行 px => rem 的转换 ```bash # 目录结构 ├── build/ # webpack config files │ └── ... ├── config/ │ ├── index.js # main project config │ └── ... ├── src/ │ ├── main.js # app entry file │ ├── App.vue # main app component │ ├── components/ # ui components │ │ └── ... # main app component │ ├── views/ # vue-router component │ │ └── ... │ └── static/ # pure static assets (directly copied) │ └── ... ├── test/ │ └── unit/ # unit tests │ │ ├── specs/ # test spec files │ │ ├── index.js # test build entry file │ │ └── karma.conf.js # test runner config file │ └── e2e/ # e2e tests │ │ ├── specs/ # test spec files │ │ ├── custom-assertions/ # custom assertions for e2e tests │ │ ├── runner.js # test runner script │ │ └── nightwatch.conf.js # test runner config file ├── .babelrc # babel config ├── .editorconfig.js # editor config ├── .eslintrc.js # eslint config ├── index.html # index.html template └── package.json # build scripts and dependencies ``` <file_sep>/inside-boss/src/container/goodEdit/index.js /** * Created by xueliu on 2018/02/15. * 商品编辑 */ import React, { Component }from 'react' import { connect } from 'react-redux' import InitData from './init' import * as action from '../../action' import * as bridge from '../../utils/bridge' import Main from '../../components/goodEdit/main' import styles from './style.css' class goodEditContainer extends Component { constructor(props) { super(props) } componentWillMount() { const {dispatch, location} = this.props const { query } = location const {id} = query dispatch(action.getGoodItemDetail(id)) dispatch(action.getGoodCategory()) dispatch(action.getGoodSkuList(id, 1)) dispatch(action.getGoodUnitList(3)) dispatch(action.getFreightTemplate()) dispatch(action.getGoodStrategy()) } render() { const { data, location, dispatch, params} = this.props const { query } = location // id 商品id // chain 是否是连锁下发的商品 const {id, chain} = query const info = bridge.getInfoAsQuery() /** * 店铺类型 * 0 - 单店 * 1 - 连锁 * 2 - 连锁下的门店 * 3 - 分公司 * 4 - 商圈 */ const { entityType, industry } = InitData(params.pageType, info) return ( <div className={styles.goodEdit_container}> <Main data={data} menuId={id} chain={chain} dispatch={dispatch} entityType={entityType} industry={industry}/> </div> ) } } const mapStateToProps = (state) => ({ data: state.goodEdit }) const mapDispatchToProps = (dispatch) => ({ dispatch }) export default connect(mapStateToProps, mapDispatchToProps)(goodEditContainer)
c11378b01dad77900d9f9369eb6826ce93dc789f
[ "JavaScript", "HTML", "Markdown", "Shell" ]
471
JavaScript
hexiaoah/hexiao
cdae42856566322c7a91dbd6a90b3fea8f3ff353
07cad4679a4bae6f6f41c3bd523f9d8ce2f5de2c
refs/heads/main
<file_sep># Basic-Tuner Basic Tuner implemented using Yin Algorithm <file_sep>class Yin { constructor(bSize, thresh) { this.samplingRate = 48000; this.bufferSize = bSize; this.halfBufferSize = Math.floor(bSize / 2); this.buffer = new Array(this.halfBufferSize).fill(0); this.probability = 0; this.threshold = thresh; } _difference(sig) { let tau; for (tau = 0; tau < this.halfBufferSize; tau++) { for (let i = 0; i < this.halfBufferSize; i++) { let delta = sig[i] - sig[i + tau]; this.buffer[tau] += delta * delta; } } } _cumulativeNormalizedMeanDifference() { this.buffer[0] = 1; let curSum = 0; for (let tau = 1; tau < this.halfBufferSize; tau++) { curSum += this.buffer[tau]; this.buffer[tau] *= tau / curSum; } } _absoluteThreshold() { let tau; for (tau = 2; tau < this.halfBufferSize; tau++) { if (this.buffer[tau] < this.threshold) { while (tau + 1 < this.halfBufferSize && this.buffer[tau] > this.buffer[tau + 1]) tau++; this.probability = 1 - this.buffer[tau]; break; } } if (tau == this.halfBufferSize || this.buffer[tau] >= this.threshold) { tau - 1; this.probability = 0; } return tau; } _parabolicInterpolation(approxTau) { let x0, x2; let improvedTau; if (approxTau < 1) x0 = approxTau; else x0 = approxTau - 1; if (approxTau + 1 < this.halfBufferSize) x2 = approxTau + 1; else x2 = approxTau; if (x0 == approxTau) { if (this.buffer[approxTau] < this.buffer[x2]) improvedTau = approxTau; else improvedTau = x2; } else if (x2 == approxTau) { if (this.buffer[approxTau] < this.buffer[x0]) improvedTau = approxTau; else improvedTau = x0; } else { let a, b, c; a = this.buffer[x0]; b = this.buffer[approxTau]; c = this.buffer[x2]; improvedTau = approxTau + (c - a) / (2 * (2 * b - c - a)); } return improvedTau; } getPitch(sig) { let approxTau = -1; let improvedTau = -1; let pitch = -1; this._difference(sig); this._cumulativeNormalizedMeanDifference(); approxTau = this._absoluteThreshold(); if (approxTau != -1) { improvedTau = this._parabolicInterpolation(approxTau); pitch = this.samplingRate / improvedTau; } return pitch; } }
0a9d703510a5e5ae46c47b13bf60a30f74ab95cf
[ "Markdown", "JavaScript" ]
2
Markdown
Shubhranshu0103/Basic-Tuner
44838fb7ab13f7376fc3bb5c5918063d73731b73
04004bb377ec82d675b377710ba9506a93cc690e
refs/heads/master
<file_sep># compilador Diagrama Sintático ![alt text](DiagramaSintatico.png) EBNF > PROGRAM = '<<?php , { COMMAND } , '?>>' ; > BLOCK = '{', { COMMAND }, '}' ; > COMMAND = ( λ | ASSIGNMENT | PRINT ), ';' | BLOCK | LOOP | CONDITIONAL ; > ASSIGNMENT = IDENTIFIER, '=', RELEXPR, ';' ; > PRINT = 'echo', RELEXPR, ';' ; > LOOP = 'while' , '(' , RELEXPR , ')' , COMMAND ; > CONDITIONAL = 'if' , '(', RELEXPR , ')' , COMMAND , λ | ('else' , COMMAND ) > RELEXPR = EXPRESSION, { ('==' | '>' | '<' ) , EXPRESSION} ; > EXPRESSION = TERM, { ('+' | '-' | 'or' | '.'), TERM } ; > TERM = FACTOR, { ('\*' | '/' | 'and' ), FACTOR } ; > FACTOR = (('+' | '-' | '!' ), FACTOR) | NUMBER | '(', RELEXPR, ')' | IDENTIFIER | 'readline()' | STRING | BOOL; > IDENTIFIER = '\$', LETTER, { LETTER | DIGIT | '\_' } ; > NUMBER = DIGIT, { DIGIT } ; > STRING = '"', ((' ' | LETTER | DIGIT | '_' ) , { ( ' ' | LETTER | DIGIT | '_') }); > LETTER = ( a | ... | z | A | ... | Z ) ; > DIGIT = ( 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 ) ; > BOOL = ( True | False) ; <file_sep>import sys import re from abc import abstractmethod, ABC list_reserved = ['echo', '$', ';', '=', '+', '-', '/', '*', 'if', 'else', ' ', 'while', 'readline', 'and', 'or', '<', '>', '==', '!', '(', ')', 'true', 'false', "."] id_base = 0 class ASM_JUNCT(): lista = ['; constantes', 'SYS_EXIT equ 1', 'SYS_READ equ 3', 'SYS_WRITE equ 4', 'STDIN equ 0', 'STDOUT equ 1', 'True equ 1', 'False equ 0', 'segment .data', 'segment .bss ; variaveis', 'res RESB 1', 'section .text', 'global _start', 'print: ; subrotina print', 'PUSH EBP ; guarda o base pointer', 'MOV EBP, ESP ; estabelece um novo base pointer', 'MOV EAX, [EBP+8] ; 1 argumento antes do RET e EBP', 'XOR ESI, ESI', 'print_dec: ; empilha todos os digitos', 'MOV EDX, 0', 'MOV EBX, 0x000A', 'DIV EBX', "ADD EDX, '0'", 'PUSH EDX', 'INC ESI ; contador de digitos', 'CMP EAX, 0', 'JZ print_next ; quando acabar pula', 'JMP print_dec', 'print_next:', 'CMP ESI, 0', 'JZ print_exit; quando acabar de imprimir', 'DEC ESI', 'MOV EAX, SYS_WRITE', 'MOV EBX, STDOUT', 'POP ECX', 'MOV[res], ECX', 'MOV ECX, res', 'MOV EDX, 1', 'INT 0x80', 'JMP print_next', 'print_exit:', 'POP EBP', 'RET', '; subrotinas if/while', 'binop_je:', 'JE binop_true', 'JMP binop_false', 'binop_jg:', 'JG binop_true', 'JMP binop_false', 'binop_jl:', 'JL binop_true', 'JMP binop_false', 'binop_false:', 'MOV EBX, False', 'JMP binop_exit', 'binop_true:', 'MOV EBX, True', 'binop_exit:', 'RET', '_start:', 'PUSH EBP; guarda o base pointer', 'MOV EBP, ESP; estabelece um novo base pointer'] def add_lista(self, str): self.lista.append(str) def flush(self): self.add_lista("POP EBP") self.add_lista("MOV EAX, 1") self.add_lista("INT 0x80") return '\n'.join(self.lista) class SymbolTable(): mainDict = {} displacement = [4] def setter(self, chave, valor, tipo): self.mainDict[chave] = valor, tipo def getter(self, chave): return self.mainDict[chave] def exist(self,chave): return (chave in self.mainDict) def getDisplacement(self): temp = self.displacement[0] self.displacement[0] += 4 return temp class Node(ABC): value = None children = None def newId(self): global id_base id_base += 1 return id_base @abstractmethod def Evaluate(self): pass class BinOp(Node): def __init__(self, value): self.children = [] self.value = value def Evaluate(self): # BIN OP ''' EVALUATE child1 PUSH EBX ; guarda na Pilha o valor de child1 Evaluate child2 POP EAX; ADD EAX, EBX; MOV EBX, EAX; ''' self.children[0].Evaluate() ASM_JUNCT().add_lista("PUSH EBX ;") self.children[1].Evaluate() ASM_JUNCT().add_lista("POP EAX ;") if(self.value in ['+','-','/','*','and','or']): if(self.value == '+'): ASM_JUNCT().add_lista("ADD EAX, EBX ;") elif(self.value == '-'): ASM_JUNCT().add_lista("SUB EAX, EBX ;") elif(self.value == '*'): ASM_JUNCT().add_lista("IMUL EBX ;") elif(self.value == '/'): ASM_JUNCT().add_lista("IDIV EBX ;") elif(self.value == 'and'): ASM_JUNCT().add_lista("AND EAX, EBX ;") elif(self.value == 'or'): ASM_JUNCT().add_lista("OR EAX, EBX ;") ASM_JUNCT().add_lista("MOV EBX, EAX ;") else: raise Exception("Error in BinOp: Value unexpected") class UnOp(Node): def __init__(self, value): self.value = value self.ID = super().newId() def Evaluate(self): if(self.value in ['-','+','!']): self.children.Evaluate() if(self.value == '-'): ASM_JUNCT().add_lista("XOR EBX, 0xFFFFFFFF ; ") ASM_JUNCT().add_lista("ADD EBX, 1 ; ") elif(self.value == '!'): jmp_point = 'UNOP_%d' % (self.ID) ASM_JUNCT().add_lista("CMP EBX, 0 ;") ASM_JUNCT().add_lista("JE %s ;" % jmp_point) ASM_JUNCT().add_lista("MOV EBX, 1 ;") ASM_JUNCT().add_lista("%s:" % jmp_point) else: raise Exception("Error in UnOp: Value unexpected") class IntVal(Node): def __init__(self, value): self.children = None self.value = value def Evaluate(self): # MOV EBX, self.value\n; ASM_JUNCT().add_lista("MOV EBX, %d ;"%(self.value)) # return self.value, "INT" class BoolVal(Node): def __init__(self, value): self.children = None self.value = value def Evaluate(self): ASM_JUNCT().add_lista("MOV EBX, %s ;"%(self.value)) #return self.value, "BOOL" class NoOp(Node): def __init__(self): pass def Evaluate(self): pass class Commands(Node): def __init__(self): self.children = [] self.value = None def Evaluate(self): for i in self.children: i.Evaluate() class IdentifierOp(Node): def __init__(self, value): self.children = None self.value = value def Evaluate(self): ''' ''' ASM_JUNCT().add_lista("MOV EBX, [EBP-%d] ; " % SymbolTable().getter(self.value)[0]) class AssingnmentOp(Node): def __init__(self, IDENTIFIER): self.children = [IDENTIFIER] self.value = None def Evaluate(self): temp_val = 0 if( SymbolTable().exist(self.children[0])): temp_val = SymbolTable().getter(self.children[0])[0] else: ASM_JUNCT().add_lista("PUSH DWORD 0 ;") temp_val = SymbolTable().getDisplacement() SymbolTable().setter(self.children[0], temp_val, "INT") self.children[1].Evaluate() ASM_JUNCT().add_lista("MOV [EBP-%d], EBX ;" % temp_val) class EchoOp(Node): def __init__(self, Expression): self.children = Expression self.value = None def Evaluate(self): self.children.Evaluate() ASM_JUNCT().add_lista("PUSH EBX ;") ASM_JUNCT().add_lista("CALL print ;") ASM_JUNCT().add_lista("POP EBX ;") class WhileOp(Node): def __init__(self, expr): self.value = None self.children = [expr] self.ID = super().newId() def Evaluate(self): ASM_JUNCT().add_lista("LOOP_%d:" % self.ID) self.children[0].Evaluate() ASM_JUNCT().add_lista("CMP EBX, False ;") ASM_JUNCT().add_lista("JE EXIT_%d ;" % (self.ID)) self.children[1].Evaluate() ASM_JUNCT().add_lista("JMP LOOP_%d" % (self.ID)) ASM_JUNCT().add_lista("EXIT_%d:" % self.ID) class IfOp(Node): def __init__(self, child1): self.value = None self.children = [child1] self.ID = super().newId() def Evaluate(self): if(len(self.children) == 3): self.children[0].Evaluate() ASM_JUNCT().add_lista("CMP EBX, False ;") ASM_JUNCT().add_lista("JE ELSE_%d ;" % (self.ID)) self.children[1].Evaluate() ASM_JUNCT().add_lista("JMP EXIT_%d ;" % (self.ID)) ASM_JUNCT().add_lista("ELSE_%d:" % (self.ID)) self.children[2].Evaluate() ASM_JUNCT().add_lista("EXIT_%d:" % (self.ID)) else: self.children[0].Evaluate() ASM_JUNCT().add_lista("CMP EBX, False ;") ASM_JUNCT().add_lista("JE EXIT_%d ;" % (self.ID)) self.children[1].Evaluate() ASM_JUNCT().add_lista("EXIT_%d:" % (self.ID)) class RelaxOp(Node): def __init__(self, value, first): self.value = value self.children = [first] self.ID = super().newId() def Evaluate(self): self.children[0].Evaluate() ASM_JUNCT().add_lista("PUSH EBX ;") self.children[1].Evaluate() ASM_JUNCT().add_lista("POP EAX ;") ASM_JUNCT().add_lista("CMP EBX, EAX ;") if(self.value == "=="): ASM_JUNCT().add_lista("jne FALSE_%d" % self.ID) elif(self.value == ">"): ASM_JUNCT().add_lista("jge FALSE_%d" % self.ID) elif(self.value == "<"): ASM_JUNCT().add_lista("jle FALSE_%d" % self.ID) ASM_JUNCT().add_lista("MOV EBX, True ; ") ASM_JUNCT().add_lista("JMP END_%d " % self.ID) ASM_JUNCT().add_lista("FALSE_%d:" % self.ID) ASM_JUNCT().add_lista("MOV EBX, False ; ") ASM_JUNCT().add_lista("END_%d:" % self.ID) class Token: Type = None value = None class Tokenizer: def __init__(self, origin): self.position = 0 self.origin = origin self.actual = Token() def selectNext(self): goAgain = True while goAgain: goAgain = False self.position += 1 while((self.origin[self.position-1: self.position] == ' ') and (self.position < (len(self.origin)))): self.position += 1 if(self.position > len(self.origin)): self.actual.Type = "EOF" self.actual.value = "" elif(self.origin[self.position-1: self.position+4] == "<?php"): self.actual.Type = "PROGOPEN" self.actual.value = self.origin[self.position - 1: self.position+4] self.position += 4 elif(self.origin[self.position-1: self.position+1] == "?>"): self.actual.Type = "PROGCLOSE" self.actual.value = self.origin[self.position - 1: self.position+1] self.position += 1 elif((self.origin[self.position-1: self.position+3]).lower() == "true"): self.actual.Type = "BOOL" self.actual.value = self.origin[self.position - 1: self.position+3] self.position += 3 elif((self.origin[self.position-1: self.position+4]).lower() == "false"): self.actual.Type = "BOOL" self.actual.value = self.origin[self.position - 1: self.position+4] self.position += 4 elif(self.origin[self.position-1].isdigit()): init = self.position-1 while (self.origin[init: self.position+1].isdigit() and (self.position+1 <= len(self.origin))): self.position += 1 end = self.position self.actual.Type = "INT" self.actual.value = int(self.origin[init: end]) elif(self.origin[self.position-1] == '"'): init = self.position-1 while (self.origin[self.position+1] != '"'): self.position += 1 end = self.position + 1 self.actual.Type = "STR" self.actual.value = str(self.origin[init+1: end]) self.position += 2 elif(self.origin[self.position-1] == "+"): self.actual.Type = "PLUS" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "."): self.actual.Type = "CONCAT" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "-"): self.actual.Type = "MINUS" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "*"): self.actual.Type = "MULT" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "/"): self.actual.Type = "DIV" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "("): self.actual.Type = "OPENPAR" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == ")"): self.actual.Type = "CLOSEPAR" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "{"): self.actual.Type = "OPENBLOCK" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "}"): self.actual.Type = "CLOSEBLOCK" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "!"): self.actual.Type = "NOT" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == ">"): self.actual.Type = "MORETHAN" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "<"): self.actual.Type = "LESSTHAN" self.actual.value = (self.origin[self.position-1]) elif(str.lower(self.origin[self.position-1: self.position+3]) == "echo"): self.actual.Type = "ECHO" self.actual.value = ("echo") self.position += 3 elif(str.lower(self.origin[self.position-1: self.position+3]) == "else"): self.actual.Type = "ELSE" self.actual.value = (self.origin[self.position-1]) self.position += 3 elif(str.lower(self.origin[self.position-1: self.position+1]) == "if"): self.actual.Type = "IF" self.actual.value = (self.origin[self.position-1]) self.position += 1 elif(str.lower(self.origin[self.position-1: self.position+4]) == "while"): self.actual.Type = "WHILE" self.actual.value = (self.origin[self.position-1]) self.position += 4 elif(str.lower(self.origin[self.position-1: self.position+7]) == "readline"): self.actual.Type = "READLINE" self.actual.value = (self.origin[self.position-1]) self.position += 7 elif(str.lower(self.origin[self.position-1: self.position+1]) == "=="): self.actual.Type = "EQUALCMPR" self.actual.value = ( self.origin[self.position-1:self.position+1]) self.position += 1 elif(str.lower(self.origin[self.position-1:self.position+1]) == "or"): self.actual.Type = "OR" self.actual.value = (self.origin[self.position-1]) self.position += 1 elif(str.lower(self.origin[self.position-1:self.position+2]) == "and"): self.actual.Type = "AND" self.actual.value = (self.origin[self.position-1]) self.position += 2 elif(self.origin[self.position-1] == "="): self.actual.Type = "EQUAL" self.actual.value = (self.origin[self.position-1]) elif(self.origin[self.position-1] == "$"): init = self.position-1 while ((self.origin[self.position] not in list_reserved) and (self.position+1 <= len(self.origin))): self.position += 1 end = self.position if(self.origin[init+1:end] in list_reserved): raise Exception("Error, token reserved: %s" % self.origin[init+1:end]) elif(not re.match(r'[$]+[A-Za-z]+[A-Za-z0-9_]*$', self.origin[init:end])): raise Exception("Error, token does not follow the rules of var type. (%s) " % ( self.origin[init+1:end])) self.actual.value = (self.origin[init:end]) self.actual.Type = "IDENTIFIER" elif(self.origin[self.position-1] == ";"): self.actual.Type = "ENDLINE" self.actual.value = (self.origin[self.position-1]) else: raise Exception( "ERRO", "Operando '%s' não reconhecido na posição %d" % (self.origin[self.position-1], self.position-1)) class Parser: tokens = None @staticmethod def parseFactor(tokens): Parser.tokens.selectNext() try: if(Parser.tokens.actual.Type == "IDENTIFIER"): val = IdentifierOp(Parser.tokens.actual.value) Parser.tokens.selectNext() return val elif(Parser.tokens.actual.Type == "INT"): val = IntVal(Parser.tokens.actual.value) Parser.tokens.selectNext() return val elif(Parser.tokens.actual.Type == "BOOL"): val = BoolVal(Parser.tokens.actual.value) Parser.tokens.selectNext() return val elif (Parser.tokens.actual.Type in ["MINUS", "PLUS", "NOT"]): if(Parser.tokens.actual.Type == "MINUS"): un = UnOp("-") un.children = Parser.parseFactor(tokens) elif(Parser.tokens.actual.Type == "PLUS"): un = UnOp("+") un.children = Parser.parseFactor(tokens) else: un = UnOp("!") un.children = Parser.parseFactor(tokens) return un elif (Parser.tokens.actual.Type == "OPENPAR"): temp = Parser.parseRelexpr(tokens) if(Parser.tokens.actual.Type == "CLOSEPAR"): Parser.tokens.selectNext() return temp raise Exception("ERROR IN READLINE") raise Exception("ERROR IN FACTOR") except Exception as e: print(e) @staticmethod def parseTerm(tokens): temp_value = Parser.parseFactor(tokens) if(Parser.tokens.actual.Type == "MULT"): term = BinOp("*") term.children.append(temp_value) term.children.append(Parser.parseFactor(tokens)) elif(Parser.tokens.actual.Type == "DIV"): term = BinOp("/") term.children.append(temp_value) term.children.append(Parser.parseFactor(tokens)) elif(Parser.tokens.actual.Type == "AND"): term = BinOp("and") term.children.append(temp_value) term.children.append(Parser.parseFactor(tokens)) else: return temp_value return term @staticmethod def parseExpression(tokens): temp_value = Parser.parseTerm(tokens) if(Parser.tokens.actual.Type not in ["EOF"] and Parser.tokens.actual.Type in ["PLUS", "MINUS", "OR", "CONCAT"]): if(Parser.tokens.actual.Type == "PLUS"): main = BinOp("+") main.children.append(temp_value) elif(Parser.tokens.actual.Type == "MINUS"): main = BinOp("-") main.children.append(temp_value) elif(Parser.tokens.actual.Type == "OR"): main = BinOp("or") main.children.append(temp_value) elif(Parser.tokens.actual.Type == "CONCAT"): main = BinOp(".") main.children.append(temp_value) main.children.append(Parser.parseTerm(tokens)) return main return temp_value @staticmethod def parseRelexpr(tokens): temp_value = Parser.parseExpression(tokens) if(Parser.tokens.actual.Type not in ["EOF"] and Parser.tokens.actual.Type in ["EQUALCMPR", "MORETHAN", "LESSTHAN"]): if(Parser.tokens.actual.Type == "EQUALCMPR"): main = RelaxOp("==", temp_value) elif(Parser.tokens.actual.Type == "MORETHAN"): main = RelaxOp(">", temp_value) elif(Parser.tokens.actual.Type == "LESSTHAN"): main = RelaxOp("<", temp_value) main.children.append(Parser.parseExpression(tokens)) return main return temp_value @staticmethod def parseCommand(tokens): if(Parser.tokens.actual.Type == "ENDLINE"): Parser.tokens.selectNext() return NoOp() elif(Parser.tokens.actual.Type == "IDENTIFIER"): temp = AssingnmentOp(Parser.tokens.actual.value) Parser.tokens.selectNext() if(Parser.tokens.actual.Type != "EQUAL"): raise Exception("Error, equal not found after Assignment") temp.children.append(Parser.parseExpression(tokens)) if(Parser.tokens.actual.Type == "ENDLINE"): Parser.tokens.selectNext() else: raise Exception("Missing ';' after IDENTIFIER") return temp elif (Parser.tokens.actual.Type == "OPENBLOCK"): return Parser.parseBlock(tokens) elif(Parser.tokens.actual.Type == "ECHO"): ecc = EchoOp(Parser.parseRelexpr(tokens)) if(Parser.tokens.actual.Type == "ENDLINE"): Parser.tokens.selectNext() else: raise Exception("Missing ';' after IDENTIFIER") return ecc elif(Parser.tokens.actual.Type == "WHILE"): Parser.tokens.selectNext() if(Parser.tokens.actual.Type != "OPENPAR"): raise Exception("Error, '(' expected") whil = WhileOp(Parser.parseRelexpr(tokens)) if(Parser.tokens.actual.Type != "CLOSEPAR"): raise Exception("Error, ')' expected (%s)" % (Parser.tokens.actual.value)) Parser.tokens.selectNext() whil.children.append(Parser.parseCommand(tokens)) return whil elif(Parser.tokens.actual.Type == "IF"): Parser.tokens.selectNext() if(Parser.tokens.actual.Type != "OPENPAR"): raise Exception("Error, '(' expected") iff = IfOp(Parser.parseRelexpr(tokens)) if(Parser.tokens.actual.Type != "CLOSEPAR"): raise Exception("Error, ')' expected (%s)" % (Parser.tokens.actual.value)) Parser.tokens.selectNext() iff.children.append(Parser.parseCommand(tokens)) if(Parser.tokens.actual.Type == "ELSE"): Parser.tokens.selectNext() iff.children.append(Parser.parseCommand(tokens)) return iff else: return Parser.parseBlock(tokens) @staticmethod def parseBlock(tokens): commands = Commands() if (Parser.tokens.actual.Type == "OPENBLOCK"): Parser.tokens.selectNext() while(Parser.tokens.actual.Type != "CLOSEBLOCK"): temp = Parser.parseCommand(tokens) commands.children.append(temp) Parser.tokens.selectNext() return commands raise Exception( "Error on ParseBlock, failed to open/close block properly.") @staticmethod def parseProgram(tokens): commands = Commands() if (Parser.tokens.actual.Type == "PROGOPEN"): Parser.tokens.selectNext() temp = Parser.parseCommand(tokens) commands.children.append(temp) while(Parser.tokens.actual.Type != "PROGCLOSE"): temp = Parser.parseCommand(tokens) commands.children.append(temp) Parser.tokens.selectNext() return commands raise Exception("Error on program definition.") @staticmethod def run(origin): Parser.tokens = Tokenizer(PrePro.filter(origin)) Parser.tokens.selectNext() final = Parser.parseProgram(Parser.tokens) if(Parser.tokens.actual.Type == "EOF"): return final else: raise Exception("Erro", "Input is wrong at position %d (%s) " % ( Parser.tokens.position-1, Parser.tokens.origin[Parser.tokens.position-1])) class PrePro: @staticmethod def filter(origin): pattern = re.compile("/\*.*?\*/", re.DOTALL | re.MULTILINE) line = pattern.sub("", origin) return line if __name__ == '__main__': file_php = (sys.argv[1]) if(".php" in file_php): with open(file_php) as fp: lines = fp.read() line = lines.replace('\n', '') # line = line.replace(' ', '') value = Parser.run(line) value.Evaluate() print(ASM_JUNCT().flush()) else: raise Exception("Type error: %s is not a '.php' file" % (file_php))
e5301ee99200e49bb77386a3e97e83e520e70f80
[ "Markdown", "Python" ]
2
Markdown
franciol/compilador
42d2907d2133d6997e7070bc1bae23c3c1edd0dc
382c52cca6832effafa02dcff0d3adee496982c4
refs/heads/master
<repo_name>khuyennv/tokio_example<file_sep>/Cargo.toml [package] authors = ["khuyennv <<EMAIL>>"] name = "tokio_fast" version = "0.1.0" [dependencies] bytes = "0.4.8" futures = "0.1.22" tokio = "0.1.17" socket2 = { version = "0.3.15", features = ["reuseport", "unix"] } [profile.release] codegen-units = 1 lto = true opt-level = 3 <file_sep>/src/main.rs extern crate tokio; #[macro_use] extern crate futures; extern crate bytes; extern crate socket2; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; use bytes::BytesMut; use std::{thread, io, mem}; use socket2::Socket; use std::net::SocketAddr; fn main() { let addr: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap(); let mut threads = Vec::new(); for _ in 0..12 { threads.push(thread::spawn(move || { let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); let server = future::lazy(move || { let sock = crate::bind_ephemeral(addr); let listener = crate::listen(sock); listener.incoming().for_each(move |socket| { process(socket); Ok(()) }) .map_err(|err| eprintln!("accept error = {:?}", err)) }); runtime.spawn(server); runtime.run().unwrap(); })); } println!("Server running on {}", addr); for thread in threads { thread.join().unwrap(); } } fn process(socket: TcpStream) { let (reader, writer) = socket.split(); let connection = Connection { socket: reader, buffer: BytesMut::new(), scan_pos: 0, line_pos: 0, } .map_err(|err| { eprintln!("connection error: {}", err) }) .fold(writer, |writer, _| { let amt = tokio::io::write_all(writer, &b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nHello, World!"[..]); let amt = amt.map(|(writer, _)| writer); amt.map_err(|err| { eprintln!("connection error: {}", err) }) }) .map(|_| { println!("connection closed"); () }); tokio::spawn(connection); } struct Connection<S> { socket: S, buffer: BytesMut, scan_pos: usize, line_pos: usize, } impl<S: AsyncRead> Connection<S> { fn fill_read_buf(&mut self) -> Poll<(), tokio::io::Error> { loop { self.buffer.reserve(1024); let n = try_ready!(self.socket.read_buf(&mut self.buffer)); if n == 0 { return Ok(Async::Ready(())); } } } } impl<S: AsyncRead> Stream for Connection<S> { type Item = (); type Error = tokio::io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { let sock_closed = self.fill_read_buf()?.is_ready(); if sock_closed { return Ok(Async::Ready(None)); } loop { if let Some(newline) = self.buffer[self.scan_pos..].iter().position(|&x| x == b'\n') { let empty_line = { let mut line = &self.buffer[self.line_pos..self.scan_pos + newline]; if line[line.len() - 1] == b'\r' { line = &line[..line.len() - 1]; } //let line = std::str::from_utf8(line).unwrap(); //println!("Received line: `{}`", line); line.len() == 0 }; self.buffer.advance(self.scan_pos + newline + 1); self.line_pos = 0; self.scan_pos = 0; if empty_line { return Ok(Async::Ready(Some(()))); } } else { self.scan_pos = self.buffer.len(); break; } } Ok(Async::NotReady) } } pub(crate) fn bind_ephemeral(addr: SocketAddr) -> Socket { use socket2::{Domain, Protocol, Type}; // let addr = SocketAddr::from(([127, 0, 0, 1], 0)); let sock = Socket::new(Domain::ipv4(), Type::stream(), Some(Protocol::tcp())).expect("Socket::new"); let _ = sock.set_reuse_address(true); let _ = sock.set_reuse_port(true); sock.bind(&addr.into()).expect("Socket::bind"); sock } pub(crate) fn listen(sock: Socket) -> TcpListener { sock.listen(2048) .expect("socket should be able to start listening"); let listener = sock.into_tcp_listener(); listener.set_nonblocking(true).expect("Cannot set non-blocking"); TcpListener::from_std(listener, &tokio::reactor::Handle::current()).expect("socket should be able to set nonblocking") } <file_sep>/README.md # Tokio_example Example idea solution for tokio faster than active-web # Related Projects [Tokio](https://github.com/tokio-rs/tokio) [socket2](https://github.com/rust-lang/socket2) [actix-web](https://github.com/actix/actix-web)
40c66b796689352fb297d4177c24c1261c6d0fe6
[ "TOML", "Rust", "Markdown" ]
3
TOML
khuyennv/tokio_example
6617f038fe2a4bbe875ae6107d2af3f0783db7ff
51b0eee7a01a452179c9625b4cb61a8cda7c959c
refs/heads/master
<file_sep><?php namespace Lexik\Bundle\MonologBrowserBundle\Model; use Doctrine\DBAL\Driver\Connection; use Doctrine\DBAL\Schema\Schema; /** * @author <NAME> <<EMAIL>> */ class SchemaBuilder { /** * @var Connection $conn */ protected $conn; /** * @var Schema $schema */ protected $schema; public function __construct(Connection $conn, $tableName) { $this->conn = $conn; $this->schema = new Schema(); $entryTable = $this->schema->createTable($tableName); $entryTable->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true)); $entryTable->addColumn('channel', 'string', array('length' => 255, 'notNull' => true)); $entryTable->addColumn('level', 'integer', array('notNull' => true)); $entryTable->addColumn('level_name', 'string', array('length' => 255, 'notNull' => true)); $entryTable->addColumn('message', 'text', array('notNull' => true)); $entryTable->addColumn('datetime', 'datetime', array('notNull' => true)); $entryTable->addColumn('context', 'text'); $entryTable->addColumn('extra', 'text'); $entryTable->addColumn('server', 'text'); $entryTable->addColumn('post', 'text'); $entryTable->addColumn('get', 'text'); $entryTable->setPrimaryKey(array('id')); } public function create(\Closure $logger) { $this->conn->beginTransaction(); try { $queries = $this->schema->toSql($this->conn->getDatabasePlatform()); foreach ($queries as $query) { $logger($query); $this->conn->query($query); } $this->conn->commit(); } catch (\Exception $e) { $this->conn->rollback(); throw $e; } } }
031a6c3780aba4ec871050d251e15a446eb60464
[ "PHP" ]
1
PHP
dinamic/LexikMonologBrowserBundle
a6e0db9c84276b961d2f91317c3463c44eb34bed
3a9607ccdf1263d8b5b0dcb6b8e9257db361a377
refs/heads/master
<repo_name>meowsome/example-material-site<file_sep>/js/click.js //Adapted from https://paulund.co.uk/smooth-scroll-to-internal-links-with-jquery $('a[href^="#"].link').on('click', function () { $("html, body").animate({ scrollTop: 0 }); setTimeout(function () { var pageTitle = window.location.hash.charAt(1).toUpperCase() + window.location.hash.slice(2); document.title = pageTitle + " | Example Title"; }, 100); }); $(".ellipsis-menu").click(function () { var clicks = $(this).data('clicks'); if (clicks) { $(".ellipsis-menu li").removeClass("ellipsis-menu-active"); $(".ellipsis-menu li").delay(100).hide(0); } else { $(".ellipsis-menu li").show(0); $(".ellipsis-menu li").delay(100).addClass("ellipsis-menu-active"); } $(this).data("clicks", !clicks); }); $(".selector").click(function () { var clicks = $(this).data('clicks'); if (clicks) { $(".selector li").removeClass("selector-active"); $(".selector li").delay(100).hide(0); } else { $(".selector li").removeClass("selector-main"); $(".selector li").show(0); $(".selector li").delay(100).addClass("selector-active"); } $(this).data("clicks", !clicks); }); $(".selector-1").click(function () { $(".demo-background").css("background", "#d14747"); $(".demo-accent").css("background", "#a83939"); $(".demo-accent-2").css("background", "#efc2c2"); $(this).addClass("selector-main"); }); $(".selector-2").click(function () { $(".demo-background").css("background", "#45a845"); $(".demo-accent").css("background", "#388938"); $(".demo-accent-2").css("background", "#b0e8b0"); $(this).addClass("selector-main"); }); $(".selector-3").click(function () { $(".demo-background").css("background", "#4747d1"); $(".demo-accent").css("background", "#343499"); $(".demo-accent-2").css("background", "#bebef7"); $(this).addClass("selector-main"); }); $(".selector-4").click(function () { $(".demo-background").css("background", "#9b4a9b"); $(".demo-accent").css("background", "#7a397a"); $(".demo-accent-2").css("background", "#edc4ed"); $(this).addClass("selector-main"); }); $(".selector-5").click(function () { $(".demo-background").css({ "background": "url('images/mountain.jpg') no-repeat center fixed", "background-size": "cover" }); $(".demo-accent").css("background", "rgba(0,0,0,0.25)"); $(".demo-accent-2").css("background", "#BFBFBF"); $(this).addClass("selector-main"); }); $(".selector-6").click(function () { $(".demo-background").css({ "background": "url('images/palm-trees.jpg') no-repeat center fixed", "background-size": "cover" }); $(".demo-accent").css("background", "rgba(0,0,0,0.25)"); $(".demo-accent-2").css("background", "#e08c79"); $(this).addClass("selector-main"); }); $(".hamburger").click(function () { $(".mobile-navigation-wrapper").show(0); $(".mobile-navigation-wrapper").delay(100).addClass("mobile-navigation-wrapper-active"); $(".mobile-navigation").delay(200).addClass("mobile-navigation-active"); }); $(".mobile-navigation-wrapper").click(function () { $(this).removeClass("mobile-navigation-wrapper-active"); $(".mobile-navigation").delay(100).removeClass("mobile-navigation-active"); $(".mobile-navigation-wrapper").delay(200).hide(0); }); <file_sep>/README.md # Example Material Site An example mockup website mimicking Google's Material Design concepts. Originally created December 2017. <file_sep>/js/main.js $(document).ready(function () { if (!window.location.hash) { window.location.hash = "first"; $('html,body').scrollTop(0); } setTimeout(function () { var pageTitle = window.location.hash.charAt(1).toUpperCase() + window.location.hash.slice(2); document.title = pageTitle + " | Example Title"; }, 1); }); setTimeout(function () { $("html, body").animate({ scrollTop: 0 }); }, 50); $(document).ready(function () { var url = window.location.href; $(".navigation-item").each(function () { if (url == (this.href)) { $(".navigation-item").removeClass("navigation-item-active"); $(this).delay(100).addClass("navigation-item-active"); } }); }); $(window).on('hashchange', function () { var url = window.location.href; $(".navigation-item").each(function () { if (url == (this.href)) { $(".navigation-item").removeClass("navigation-item-active"); $(this).delay(100).addClass("navigation-item-active"); } }); $('html,body').scrollTop(0); }); document.onreadystatechange = function () { var state = document.readyState if (state == 'complete') { $('.loader').hide(); } else { $('.loader').show(); } }
9add58b79dd1dd97ed56351dfca1649f5481f4a1
[ "JavaScript", "Markdown" ]
3
JavaScript
meowsome/example-material-site
bf3acea3215d7e12a9cb04aa532bb3125a49adec
2253b4b542b254caf038ceb0d0707e31222d5542
refs/heads/master
<file_sep>// Variables var password = ""; var passwordLength; var lowerCaseConfirm; var upperCaseConfirm; var numericConfirm; var specialCharConfirm; var generateBtn = document.querySelector("#generate"); var copyBtn = document.querySelector("#copy"); // Arrays var passwordArr = []; var specialChar = ["~","!","@","#","$","%","^","&","*","(",")","+","=","?","/","{","}","|","<",">",":",";",".",",","[","]"]; var numeric = [1,2,3,4,5,6,7,8,9,0]; var lowerCase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; var upperCase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]; // Functions // Password Length function pwLength() { passwordLength = window.prompt("How many characters in password? (8-128)"); passwordLength = Number(passwordLength); if (passwordLength >= 8 && passwordLength <= 128) { console.log(passwordLength); return; } else { window.alert("Password length must be between 8 and 128 characters."); pwLength(); }; } // Lowercase Letters function lowLetters() { lowerCaseConfirm = window.confirm("Would you like lowercase letters?"); console.log(lowerCaseConfirm); return; } // Uppercase Letters function upLetters() { upperCaseConfirm = window.confirm("Would you like uppercase letters?"); console.log(upperCaseConfirm); return; } // Numbers function numCharacters() { numericConfirm = window.confirm("Would you like numeric characters?"); console.log(numericConfirm); return; } // Special Characters function specCharacters() { specialCharConfirm = window.confirm("Would you like special characters?"); console.log(specialCharConfirm); return; } // Character Specification function charSpec() { lowLetters(); upLetters(); numCharacters(); specCharacters(); } // Password Array Creation function passArrGen() { passwordArr = []; if (lowerCaseConfirm === true) { passwordArr = passwordArr.concat(lowerCase); console.log(passwordArr); } if (upperCaseConfirm === true) { passwordArr = passwordArr.concat(upperCase); console.log(passwordArr); } if (numericConfirm === true) { passwordArr = passwordArr.concat(numeric); console.log(passwordArr); } if (specialCharConfirm === true) { passwordArr = passwordArr.concat(specialChar); } return; } // Pasword Generation function generatePW() { password = ""; for (var i = 0; i <= passwordLength - 1; i++) { password = password + passwordArr[Math.floor(Math.random() * Math.floor(passwordArr.length - 1))]; console.log(password); displayPassword(); }}; // Check atleast one character type is selected function checkChar() { if (lowerCaseConfirm === false && upperCaseConfirm === false && numericConfirm === false && specialCharConfirm === false) { window.alert("Password must contain atleast one character type."); charSpec(); } else { passArrGen(); generatePW(); } } // Add Password to Display function displayPassword() { document.querySelector("#display").textContent = password; } // Copy to Clipboard function copyPassword() { document.getElementById("display").select(); document.execCommand("copy"); alert("Password copied to clipboard!"); } // Call Functions generateBtn.addEventListener("click", function clickGenBtn() { pwLength(); charSpec(); checkChar(); }); copyBtn.addEventListener("click", copyPassword); <file_sep># Password-Generator ## Description This random-password generator was created to create passwords that are randomly generated based on the criteria of the user. This criteria includes: - password length (8-128 characters) - inclusion of lower case letters, upper case letters, special characters and/or numbers There is also a function to copy the pasword to clipboard. ## Screen Shots <img width="1429" alt="Screen Shot 2019-12-03 at 6 49 38 PM" src="https://user-images.githubusercontent.com/54684022/70101113-f20df200-1601-11ea-8c04-1ab27be7ddec.png"> ## Link https://mms211.github.io/Password-Generator/ ## License Copyright (c) 2019 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
893e790f8c092103280be88d9af1f9c1d6d467ea
[ "JavaScript", "Markdown" ]
2
JavaScript
mms211/Password-Generator
03af72b5ca7cbedffced5c890dfcc8ebe960c4ee
02eee85cfa99107603aa4ec3725ae1293886aef6
refs/heads/master
<file_sep>#!/bin/bash session=$1 proj=$2 BASE="$HOME" work () { SLABS="$BASE/work/staples-lab" proj=$1 tmux start-server tmux new-session -d -s $session -n $proj tmux send-keys -t $session:1 "cd $SLABS/$proj && git pull" C-m tmux select-window -t $session:1 tmux attach-session -t $session } home () { tmux start-server tmux new-session -d -s $session -n local tmux new-window -t $session:2 -n ssh tmux send-keys -t $session:1 "cd $BASE" C-m tmux send-keys -t $session:2 "cd $BASE" C-m tmux select-window -t $session:1 tmux attach-session -t $session } $session $proj <file_sep># should be in bashrc but using ubuntu default, which sources this file # git prompt GIT_PS1_SHOWDIRTYSTATE=true #export PS1='\033[0;32m\u@\h:\033[0;32m\w\033[01;32m\033[00m \n[\w][$?]$("__git_ps1")$ ' export PS1='[\h:\w][$?]$("__git_ps1")$ ' # default editor export EDITOR="emacsclient -n" # Aliases alias h="history | grep" alias f="find ~/. -iname" alias g="git grep" alias a='tmux attach -d -t' alias n='tmux new-window -n' alias ?="tmux copy-mode; tmux send-keys '?'" alias u="tmux copy-mode -u" alias e="emacsclient -n" alias ef='e $(fzf)' alias c="xmodmap ~/rcfiles/xmodmaprc" alias s="pkill ssh; pkill vpn; sudo pm-suspend" alias ss=". ~/.bashrc" alias t='~/rcfiles/bin/tcs.sh' alias loc="find . -name '*.clj' -exec wc -l {} \; | awk '{sum+=$1}{print sum}' | tail -1" alias cc="sudo sh -c 'echo 3 >/proc/sys/vm/drop_caches'" alias kp='pkill -SIGUSR2 emacs' alias spcap='sudo tcpdump -w snmp_traffic.pcap -vv -A -T snmp -s 0 "(dst port 25) or (dst port 465)"' alias gk='cd ~/work/sparx/Krikkit && git pull' alias gt='cd ~/work/sparx/Trillian && git pull' alias gg='cd ~/work/sparx/GargleBlaster && git pull' alias gf='cd ~/work/sparx/Furtive && git pull' alias vpn='~/<EMAIL>/kone/etc/ssh/vpn' alias magit='e -e "(magit-status \"$(pwd)\")"' <file_sep># my usefull bash utils function first () { head -1 $1 } function rest () { f=$1 size=$(wc -l $f | awk '{print $1}') rest=`expr $size - 1` tail -$rest $f } <file_sep># echo bash_profile sourced # fzf [ -f ~/.fzf.bash ] && source ~/.fzf.bash # git prompt GIT_PS1_SHOWDIRTYSTATE=true export PS1='\033[0;32m\u@\h:\033[0;32m\w\033[01;32m$("__git_ps1")\033[00m \n[\w][$?]$ ' # default editor export EDITOR="emacsclient -n" # source alias . ~/rcfiles/bash_aliases # source autojump . /usr/share/autojump/autojump.sh # source git prompt . ~/rcfiles/git-prompt.sh # unlimited history in one file wihout duplicates export HISTCONTROL=ignoreboth:erasedups shopt -s histappend export HISTSIZE="" if [ "$TERM" == "screen-256color" ] || [ "$TERM" == "xterm-256color" ]; then PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"' # else # PROMPT_COMMAND='echo "Your term is not color terminal"' fi # end of kasim's config export PKG_CONFIG_PATH=":/usr/local/lib/pkgconfig" PROTOBUF_HOME="/home/kasim/work/sparx/protobuf-2.5.0" export PROTOBUF_HOME PATH="/home/kasim/work/sparx/protobuf-2.5.0/src:/home/kasim/work/sparx/protobuf-2.5.0/src:/usr/local/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:~/rcfiles/bin:~/.fzf/bin" export PATH JAVA_HOME="/usr" export JAVA_HOME <file_sep>#! /bin/bash function installed? () { which $1 } function remove_emacs () { echo Removing sudo apt-get remove --purge emacs* } function install_emacs () { cd && git clone git://git.savannah.gnu.org/emacs.git sudo apt-get build-dep emacs24 cd emacs && make && sudo make install } confirm () { # call with a prompt string or use a default read -r -p "${1:-Are you sure? [y/N]} " response case $response in [yY][eE][sS]|[yY]) true ;; *) false ;; esac } if installed? "emacs" then echo You have emacs, reinstall? confirm && remove_emacs && install_emacs else install_emacs fi <file_sep>#!/bin/bash xmodmap ~/rcfiles/xmodmaprc <file_sep>#!/bin/bash # install xcode xcode-select --install # install brew ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" # install git brew doctor brew install git # clone rcfiles git clone <EMAIL>:kasim/rcfiles.git # make magic links ln -s ~/kone/etc/ssh .ssh ln -s ~/rcfiles/emacs .emacs.d ln -s ~/rcfiles/bash_profile .bash_profile ln -s ~/rcfiles/bashrc .bashrc chmod 600 ~/.ssh/id_rsa # install emacs brew install emacs --HEAD --use-git-head --cocoa --srgb ln -s /usr/local/Cellar/emacs/HEAD/Emacs.app /Applications # brew install vcprompt brew install vcprompt source ~/.bashrc # brew install lein java -version brew install leiningen <file_sep>source ~/rcfiles/bash_profile <file_sep>#!/bin/bash if [ -f $HOME/.my_windows_config.txt ]; then echo -e "Information: Previous configuration file \"$HOME/.my_windows_config.txt\" already exists.\nTo save a new configuration remove it manually using the following command,\n\n\trm $HOME/.my_windows_config.txt" exit 1 else wmctrl -p -G -l | awk '($2 != -1)&&($3 != 0)&&($NF != "Desktop")' | awk '{print $1}' | while read mywinid do xwininfo -id "$mywinid" >> $HOME/.my_windows_config.txt done fi <file_sep>#!/bin/bash cdir () { founded=$(find ~ -name $1); echo ${founded}; for f in ${founded}; do echo $f; if [ -d "$f" ] then echo cding into $f; cd "$f"; fi done } cdir $1; <file_sep>#!/bin/bash tmux start-server for s in "$@"; do echo creating $s session... tmux new-session -d -s $s done
3f789b9dfac035a2b80a92764fb3f7f3e95292af
[ "Shell" ]
11
Shell
oneness/rcfiles
7b18ace2060f33410d6752988757a6de48dcdb06
e523bf6b51de8c18b5d6ecbad78bb9be00eef773
refs/heads/master
<repo_name>chenjuyu/RadioButton<file_sep>/app/src/main/java/com/fuxi/myapplication/MainActivity.java package com.fuxi.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; public class MainActivity extends AppCompatActivity { String TAG ="MainActivity"; private RadioGroup sex; private TextView jump; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sex =(RadioGroup) findViewById(R.id.sex); jump =(TextView) findViewById(R.id.jump); // 方法一监听事件,通过获取点击的id来实例化并获取选中状态的RadioButton控件 sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // 获取选中的RadioButton的id int id = group.getCheckedRadioButtonId(); /* 通过id实例化选中的这个RadioButton */ RadioButton choise = (RadioButton) findViewById(id); // choise.setTextColor(Color.WHITE); // choise.setChecked(true); // 获取这个RadioButton的text内容 String output = choise.getText().toString(); Toast.makeText(MainActivity.this, "你的性别为:" + output, Toast.LENGTH_SHORT).show(); } }); jump.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN) { Intent intent = new Intent(MainActivity.this, TabActivity.class); startActivity(intent); } return false; } }); } }
e48c11d3b5e4912752383e5231178cc453000cd1
[ "Java" ]
1
Java
chenjuyu/RadioButton
1d094f4843f7ca81163564caed04452a8d3a36a3
1e30a38e8c2f8623fc1bf30b57e026a03bc03f57
refs/heads/master
<repo_name>treasure2013-groupwork/jenkins-test<file_sep>/tests/src/calc.php <?php function calc($arg){ return $arg; } <file_sep>/tests/test/CalcTest.php <?php require_once(dirname(__FILE__). '/../src/calc.php'); class CalcTest extends PHPUnit_Framework_TestCase { public function testcalc1(){ $this->assertEquals(1,calc(1)); } public function testcalc2(){ $this->assertEquals(2,calc(2)); } public function testcalc3(){ $this->assertEquals(3,calc(3)); } public function testcalc4(){ $this->assertEquals(4,calc(4)); } public function testcalc5(){ $this->assertEquals(5,calc(5)); } public function testcalc6(){ $this->assertEquals(6,calc(6)); } public function testcalc7(){ $this->assertEquals(7,calc(7)); } public function testcalc8(){ $this->assertEquals(8,calc(8)); } }
f0e3aa84d67b8e58c0186b22fcce6b281b15248e
[ "PHP" ]
2
PHP
treasure2013-groupwork/jenkins-test
e2a92fe34a5a2ad4548d15293ab34c10e2d5d226
807afa832bba4981472e5f71f0c74cdcfc261eac
refs/heads/master
<file_sep>#Aug. 29 # as.numeric(c("one", "two", "three")) as.logical(c("TRUE", "FALSE", "NA", "true", "false")) as.integer(c(1.2, -0.9999, -pi, exp(1)/exp(1))) as.character(c(1, 2, 3)) as.numeric("1") + as.numeric("2") #Attribute x <- c(a = 1, b = 2.5, c = 3.7, d = 10) x names(x) attributes(x) attr(x, "units") = 'feet' attr(x, "etc") = 'whatever' x attributes(x) #Dimension x <- 1:8 x dim(x) class(x) # integer # change dimension dim(x) = c(2,4) x class(x) # matrix mode(x) # change dimension again dim(x) = c(2,2,2) x attributes(x) class(x) # array #Vectorization x = 1:3 y = 3:1 x;y;x+y sqrt(x) x+1 #Aug.31 x = c(T, F) y = c(T, T) x & y x && y #Named vector vec <- 1:5 names(vec) <- letters[1:5] vec vec[1];vec[-1] vec[c(1, 3, 4)] vec[c(T, F)] vec[T] vec['a'] vec[rep('e',10)] { 5 + 3 4 * 2 1 + 1 } square <- function(x) { x*x } square(3) #Sep.02 if (5 > 2) 5 * 2 else 5 / 2 ####HW Hint#### switches <- c("off", "off", "off") ifelse(switches == 'off', "on", 'off') #show the result x = 2 cat("here is", x) #### here is 2 print("here is", x) ##### "here is" print(sprintf("here is %s",x)) #### here is 2 value <- 2 repeat { value <- value * 2 print(value) if (value >= 40) break } ##na.rm means REMOVE NA VECTORS
76d2a40ad7c2fe975504dc4d64c3ca4bf333f197
[ "R" ]
1
R
Yue-You/Stat-243
2f5003b5bf926989ef4a1d0a4d90303ca5d84b2a
398f6dc8710295364883fd09f451162114a0e912
refs/heads/master
<file_sep>package com.example.administrator.keepservicealive.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.administrator.keepservicealive.R; public class SingleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single); } } <file_sep>package com.example.administrator.keepservicealive.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.example.administrator.keepservicealive.activity.SingleActivity; import java.lang.ref.WeakReference; /** * @author libohan * 邮箱:<EMAIL> * create on 2017/11/2. */ public class ScreenManager { private final String TAG="ScreenManager"; private Context context; private static ScreenManager instance; private WeakReference<Activity> mactivityRef; private ScreenManager(Context context) { this.context = context; } public static ScreenManager getInstance(Context context) { if (instance==null) { return new ScreenManager(context); } return instance; } public void setMactivity(Activity mactivity) { this.mactivityRef = new WeakReference<Activity>(mactivity); } public void startActivity() { Intent intent=new Intent(context, SingleActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } public void onDestoryActivity() { if (mactivityRef!=null) { Activity mactivity=mactivityRef.get(); if (mactivity!=null) { mactivity.finish(); } } } }
9616048a69b5352801c32ed47fc9d865adc00946
[ "Java" ]
2
Java
lbhlc/KeepServiceAlive
cf643fe426ee458f78e21113f02dfdf8c86808e0
0c7f1bd32dba2dc8b5d0eb9a21c5bdf8cb03d846
refs/heads/master
<file_sep>import instruments.Drum; import instruments.InstrumentType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DrumTest { Drum drum; @Before public void before() { drum = new Drum("Wood", "Blue", InstrumentType.PERCUSSION, 10, 20, "Snare"); } @Test public void hasDrumType() { assertEquals("Snare", drum.getDrumType()); } @Test public void canPlay() { assertEquals("Bang bang", drum.play()); } } <file_sep>import accessories.Accessory; import instruments.InstrumentType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AccessoryTest { Accessory accessory; @Before public void before() { accessory = new Accessory("Drum sticks", 4, 8); } @Test public void hasDescription() { assertEquals("Drum sticks", accessory.getDescription()); } @Test public void hasBuyPrice() { assertEquals(4, accessory.getBuyPrice(), 0); } @Test public void hasSellPrice() { assertEquals(8, accessory.getSellPrice(), 0); } @Test public void canSetSellPrice() { accessory.setSellPrice(16); assertEquals(16, accessory.getSellPrice(), 0); } @Test public void canCalculateMarkup() { assertEquals(1, accessory.calculateMarkup(), 0); } }
489d76a91eaceb810c357b692583b73f8d7e998d
[ "Java" ]
2
Java
nimbus117/cc_w12_weekend_hw
9beb76a2ee46172f69e3ba4ccb5502a06bcfb45c
55a9b2a54cc5674e78d53e51d8ab790fb5491dea
refs/heads/master
<repo_name>Deamon87/blsreader<file_sep>/src/com/wow/blsreader/BlsReaderMain.java package com.wow.blsreader; import com.peterfranza.LittleEndianDataInputStream; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; import java.util.zip.DataFormatException; import java.util.zip.Inflater; /** * Created by Deamon on 23/11/2015. */ public class BlsReaderMain { public static String combine(String[] split, int length) { StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < length; i++){ stringBuffer.append(split[i]); stringBuffer.append("."); } stringBuffer.setLength(stringBuffer.length()-1); return stringBuffer.toString(); } public static void read16Record(int offset, int size, LittleEndianDataInputStream istream) throws IOException { istream.reset(); istream.skipBytes(offset); int[] unkrec1 = new int[size]; int[] unkrec2 = new int[size]; int[] unkrec3 = new int[size]; int[] unkrec4 = new int[size]; for (int i = 0; i < size; i++) { unkrec1[i] = istream.readInt(); unkrec2[i] = istream.readInt(); unkrec3[i] = istream.readInt(); unkrec4[i] = istream.readInt(); } for (int i = 0; i < size; i++) { istream.reset(); istream.skipBytes(unkrec1[i]); String param1 = istream.readCString(); istream.reset(); istream.skipBytes(unkrec3[i]); String param2 = istream.readCString(); //System.out.println("param1= "+param1+" param2= "+param2); } } public static void readUniformBuffer(int offset, int size, LittleEndianDataInputStream istream) throws IOException { istream.reset(); istream.skipBytes(offset); int[] unkrec1 = new int[size]; int[] unkrec2 = new int[size]; int[] unkrec3 = new int[size]; for (int i = 0; i < size; i++) { unkrec1[i] = istream.readInt(); unkrec2[i] = istream.readInt(); unkrec3[i] = istream.readInt(); } for (int i = 0; i < size; i++) { istream.reset(); istream.skipBytes(unkrec1[i]); String param1 = istream.readCString(); //System.out.println("uniformBuffer"+i+"= "+param1); } } public static void readTextUniforms(int offset, int size, LittleEndianDataInputStream istream) throws IOException { istream.reset(); istream.skipBytes(offset); int[] unkrec1 = new int[size]; int[] unkrec2 = new int[size]; int[] unkrec3 = new int[size]; int[] unkrec4 = new int[size]; for (int i = 0; i < size; i++) { unkrec1[i] = istream.readInt(); unkrec2[i] = istream.readInt(); unkrec3[i] = istream.readInt(); unkrec4[i] = istream.readInt(); } for (int i = 0; i < size; i++) { istream.reset(); istream.skipBytes(unkrec1[i]); String param1 = istream.readCString(); //System.out.println("textUniform"+i+"= "+param1); } } public static boolean seekGLS3(LittleEndianDataInputStream istream) throws IOException { istream.mark(8192); int j = 0; int len = istream.readInt(); char[] magic = new char[4]; magic[0] = (char) istream.readByte(); magic[1] = (char) istream.readByte(); magic[2] = (char) istream.readByte(); magic[3] = (char) istream.readByte(); while (istream.available()>0 && magic[0]!='3' && magic[1]!='S' && magic[2]!='L' && magic[3]!='G') { magic[0] = magic[1]; magic[1] = magic[2]; magic[2] = magic[3]; magic[3] = (char) istream.readByte(); j++; } if (istream.available()>0) { istream.reset(); istream.skipBytes(j); return true; } return false; } public static void unpackShaders(String unpackedFileName, int shaders, String template) throws IOException { FileInputStream file = new FileInputStream(unpackedFileName); //BufferedInputStream bufferedInputStream= new BufferedInputStream(file); RandomAccessFile randomAccessFile = new RandomAccessFile(unpackedFileName, "r"); LittleEndianDataInputStream istream = new LittleEndianDataInputStream(randomAccessFile); istream.mark(0); int i = 0; while (istream.available() > 0){ //BLSBlock int flags = istream.readInt(); int flags2 = istream.readInt(); int unknown = istream.readInt(); int unknown2 = istream.readInt(); int unknown3 = istream.readInt(); int unknown4 = istream.readInt(); int unknown5 = istream.readInt(); if (!seekGLS3(istream)) break; int len = istream.readInt(); //GLS3 block istream.mark(len); char[] magic = new char[4]; magic[0] = (char) istream.readByte(); magic[1] = (char) istream.readByte(); magic[2] = (char) istream.readByte(); magic[3] = (char) istream.readByte(); int size = istream.readInt(); int type2 = istream.readInt(); // ?, 3 = GLSL int unk = istream.readInt(); // 0 int target = istream.readInt(); // as in GL_FRAGMENT_SHADER // 8b31 int codeOffset = istream.readInt(); int codeSize = istream.readInt(); int unk2 = istream.readInt(); //0 int unk3 = istream.readInt(); //-1 int inputParamOffset = istream.readInt(); int inputParamSize = istream.readInt(); //sizeof record 16 int outputOffset = istream.readInt(); int outputSize = istream.readInt(); //sizeof record 16 int uniformBufferOffset = istream.readInt(); int uniformBufferSize = istream.readInt(); //sizeof record 12 int textUniforms = istream.readInt(); int textUniformsSize = istream.readInt(); //sizeof record 16 int unk5Offset = istream.readInt(); int unk5Size = istream.readInt(); int unk6Offset = istream.readInt(); int unk6Size = istream.readInt(); int variableStringsOffset = istream.readInt(); int variableStringsSize = istream.readInt(); istream.reset(); istream.skipBytes(codeOffset); String glslCode = istream.readCString(codeSize); FileOutputStream fileOut = new FileOutputStream(template+"/"+ i++ +".glsl"); fileOut.write(glslCode.getBytes(StandardCharsets.UTF_8)); fileOut.close(); read16Record(inputParamOffset, inputParamSize, istream); read16Record(outputOffset, outputSize, istream); readUniformBuffer(uniformBufferOffset, uniformBufferSize, istream); readTextUniforms(textUniforms, textUniformsSize, istream); istream.reset(); istream.skipBytes(len); System.gc(); } istream.close(); } public static void unpackBlsFile(String fileName) throws IOException, DataFormatException { String split[] = fileName.split("\\."); if (split.length < 2 || !split[split.length-1].equals("bls")) return; //FileInputStream file = new FileInputStream(fileName); RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "r"); //BufferedInputStream bufferedInputStream= new BufferedInputStream(file); LittleEndianDataInputStream istream = new LittleEndianDataInputStream(randomAccessFile); istream.mark(0); char[] magic = new char[4]; magic[0] = (char) istream.readByte(); magic[1] = (char) istream.readByte(); magic[2] = (char) istream.readByte(); magic[3] = (char) istream.readByte(); int version = istream.readInt(); int nShaders = istream.readInt(); int unk = istream.readInt(); //istream.skipBytes(16); int ofsCompressedChunks = istream.readInt(); int nCompressedChunks = istream.readInt(); int ofsCompressedData = istream.readInt(); String fileDirectory = combine(split, split.length - 1); String outFileName = fileDirectory + "/fullSteam.decomp"; File outFileD = new File(fileDirectory); outFileD.mkdirs(); FileOutputStream fileOut = new FileOutputStream(outFileName); int compressedChunksOffsets[] = new int[nCompressedChunks]; istream.reset(); istream.skipBytes(ofsCompressedChunks); for (int i =0; i < nCompressedChunks; i++) { compressedChunksOffsets[i] =istream.readInt(); } for (int i =0; i < nCompressedChunks; i++) { istream.reset(); int length; if (i != nCompressedChunks-1) { length = compressedChunksOffsets[i+1] - compressedChunksOffsets[i]; } else { length = istream.available(); } istream.mark(ofsCompressedData+compressedChunksOffsets[i]+length); istream.skipBytes(ofsCompressedData + compressedChunksOffsets[i]); byte [] readBuffer = new byte[length]; istream.read(readBuffer, 0, length); Inflater decompresser = new Inflater(); decompresser.setInput(readBuffer, 0, length); byte[] result = new byte[100]; int resultLength = decompresser.inflate(result); while (resultLength > 0) { byte[] resultToWrite; if (resultLength < 100) { resultToWrite = new byte[resultLength]; System.arraycopy(result, 0, resultToWrite, 0, resultLength); } else { resultToWrite = result; } fileOut.write(resultToWrite); resultLength = decompresser.inflate(result); } decompresser.end(); } fileOut.close(); unpackShaders(outFileName, nShaders, fileDirectory); } public static void main(String[] args) throws IOException, DataFormatException { Stream.concat( Stream.concat( Files.walk(Paths.get("d:\\Games\\wow_shaders\\21846\\shaders\\pixel/glfs_420/")), Files.walk(Paths.get("d:\\Games\\wow_shaders\\21846\\shaders\\vertex/glvs_420/")) ), Stream.concat( Files.walk(Paths.get("d:\\Games\\wow_shaders\\21846\\shaders\\geometry/glgs_420/")), Files.walk(Paths.get("d:\\Games\\wow_shaders\\21846\\shaders\\geometry/glgs_420/")) ) ).forEach(filePath -> { if (Files.isRegularFile(filePath)) { try { unpackBlsFile(filePath.toString()); } catch (Exception ignored) { //System.out.print(ignored.getMessage()); } System.gc(); } }); } }
2444da5a2eca7d969ea55edcde1e7b0ebecf4c59
[ "Java" ]
1
Java
Deamon87/blsreader
b78a9535f8462e7670ca018a94aaa80434a6f663
058212d5d2ac58b4be99eac042f7489f0e1142b3
refs/heads/master
<repo_name>raphaelthurnherr/mqttHostCom<file_sep>/hostCom/src/messagesManager.h /* * messagesManager.h * * Created on: 15 mars 2016 * Author: raph */ #ifndef MESSAGESMANAGER_H_ #define MESSAGESMANAGER_H_ extern char ClientID[50]; // Initialisation de la messagerie system (JSON<->MQTT) int InitMessager(void); int CloseMessager(void); #endif /* MESSAGESMANAGER_H_ */ <file_sep>/hostCom/src/main.c /* ============================================================================ Name : hostCom.c Author : raph Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "messagesManager.h" #include "linux_json.h" #include "udpPublish.h" #include "main.h" int processMsgCommand(void); int processMsgRequest(void); int make2WDaction(void); int getWDvalue(char * wheelName); int move2WDbuggy(int leftWheelSpeed, int rightWheelSpeed); int main(void) { if(InitMessager()) printf ("# Creation tache messagerie : ERREUR\n"); else { printf ("# Demarrage tache Messager: OK\n"); } initUDP(); while(1){ char myChar; int endState; //printf("\n->"); //myChar=getchar(); // COMMANDE ALGOID RECUE if(pullMsgStack(0)){ // printf("[main] messageID: %d param: %d cmd: %d\n\n",AlgoidCommand.msgID,AlgoidCommand.msgParam,AlgoidCommand.msgType ); switch(AlgoidCommand.msgType){ case COMMAND : processMsgCommand(); break; case REQUEST : processMsgRequest(); break; default : break; } } if(myChar=='q'){ endState=CloseMessager(); if(!endState) printf( "# ARRET tache Messager - status: %d\n", endState); else printf( "# ARRET tache Messager erreur - status: %d\n", endState); break; } if(myChar=='h'){ char udpMessage[50]; sprintf(&udpMessage[0], "[ %s ] I'm here",ClientID); sendUDPHeartBit(udpMessage); printf("\n MYMAC %s", getMACaddr()); } if(myChar=='d'){ char stackPtr; char i; for(stackPtr=0;stackPtr<10;stackPtr++){ printf("----- PILE DATA %d -----\n", stackPtr); // AFFICHAGE DES DONNEES printf("Message to %s from %s with ID %d \n",AlgoidMsgRXStack[stackPtr].msgTo,AlgoidMsgRXStack[stackPtr].msgFrom, AlgoidMsgRXStack[stackPtr].msgID ); printf("type: %d\n",AlgoidMsgRXStack[stackPtr].msgType); printf("param: %d\n",AlgoidMsgRXStack[stackPtr].msgParam); if(AlgoidMsgRXStack[stackPtr].msgParam==LL_WD){ for(i=0;i<AlgoidMsgRXStack[stackPtr].msgValueCnt;i++){ printf("wheel: %s velocity: %d time: %d\n", AlgoidMsgRXStack[stackPtr].msgValArray[i].wheel, AlgoidMsgRXStack[stackPtr].msgValArray[i].velocity, AlgoidMsgRXStack[stackPtr].msgValArray[i].time); } } else{ for(i=0;i<AlgoidMsgRXStack[stackPtr].msgValueCnt;i++){ printf("mode: %s value: %d\n", AlgoidMsgRXStack[stackPtr].msgValArray[i].mode, AlgoidMsgRXStack[stackPtr].msgValArray[i].value); } } printf("\n"); } } usleep(100000); } return EXIT_SUCCESS; } // ------------------------------------------------------------------- // PROCESSCOMMAND // ------------------------------------------------------------------- int processMsgCommand(void){ switch(AlgoidCommand.msgParam){ case LL_WD : make2WDaction(); break; default : printf("\n blabla\n"); break; } return 0; } // ------------------------------------------------------------------- // PROCESSMSGRQUEST // ------------------------------------------------------------------- int processMsgRequest(void){ return 0; } // ------------------------------------------------------------------- // MAKE2WDACTION // ------------------------------------------------------------------- int make2WDaction(void){ int ptrData; char test[10]=""; //wheel.left.velocity=0; //wheel.right.velocity=0; ptrData=getWDvalue("left"); if(ptrData >=0) wheel.left.velocity=AlgoidCommand.msgValArray[ptrData].velocity; ptrData=getWDvalue("right"); if(ptrData >=0) wheel.right.velocity=AlgoidCommand.msgValArray[ptrData].velocity; move2WDbuggy(wheel.left.velocity, wheel.right.velocity); return 0; } // ------------------------------------------------------------------- // GETWDVALUE // ------------------------------------------------------------------- int getWDvalue(char* wheelName){ int i; int searchPtr = -1; char searchText[50]; char * mySearch; // Recherche dans les donnée recues la valeur correspondante au paramètre "wheelName" for(i=0;i<AlgoidCommand.msgValueCnt;i++){ memset(searchText, 0, 50); mySearch=AlgoidCommand.msgValArray[i].wheel; strncpy(searchText,mySearch, strlen(AlgoidCommand.msgValArray[i].wheel)); if(!strcmp(searchText, wheelName)) searchPtr=i; } return searchPtr; } // ------------------------------------------------------------------- // MOVE2WDBUGGY // ------------------------------------------------------------------- int move2WDbuggy(int leftWheelSpeed, int rightWheelSpeed){ printf("\n ROBOT AVANCE DE %d GAUCHE, %d DROITE\n", leftWheelSpeed,rightWheelSpeed); return 0; }
093032cb0c2c43cb02c6783aeef45bdedd1e208e
[ "C" ]
2
C
raphaelthurnherr/mqttHostCom
2dda04c81ea00f7f6ca0d42674e4839c7f817ba7
95b3d83f4d142d60608ad31c92c606bd7a4c8132
refs/heads/master
<file_sep>import torch.nn as nn import torch import torchvision from dv_code import cnn_autoencoder print(dir(cnn_autoencoder)) <file_sep>import torch import torch.nn as nn import torchvision from torch.utils.data import DataLoader import os,sys from tqdm.auto import tqdm from PIL import Image, ImageFilter import numpy as np from dv_code import dataloading import time import datetime import pickle import argparse class CNNAutoencoder(nn.Module): """ Convolutional autoencoder """ def __init__(self, image_size=(128,128)): """ :io_channels: number of channels of input and output, should be 3, unless grayscale """ super().__init__() self.image_size = image_size # Encoder learnable layers self.ae_shape = { 'conv1' : (3,12,3), 'conv2' : (12,24,3), 'conv3' : (24,48,3), 'conv4' : (48,96,3), 'conv5' : (96,192,3), 'conv6' : (192,384,3), 'upconv1' : (384,192,3), 'upconv2' : (192,96,3), 'upconv3' : (96,48,3), 'upconv4' : (48,24,3), 'upconv5' : (24,12,3), 'upconv6' : (12,3,3) } self.conv1 = nn.Conv2d(*self.ae_shape['conv1'], padding=1) self.batchnorm1 = nn.BatchNorm2d(self.ae_shape['conv1'][1]) self.conv2 = nn.Conv2d(*self.ae_shape['conv2'], padding=1) self.batchnorm2 = nn.BatchNorm2d(self.ae_shape['conv2'][1]) self.conv3 = nn.Conv2d(*self.ae_shape['conv3'], padding=1) self.batchnorm3 = nn.BatchNorm2d(self.ae_shape['conv3'][1]) self.conv4 = nn.Conv2d(*self.ae_shape['conv4'], padding=1) self.batchnorm4 = nn.BatchNorm2d(self.ae_shape['conv4'][1]) self.conv5 = nn.Conv2d(*self.ae_shape['conv5'], padding=1) self.batchnorm5 = nn.BatchNorm2d(self.ae_shape['conv5'][1]) self.conv6 = nn.Conv2d(*self.ae_shape['conv6'], padding=1) self.batchnorm6 = nn.BatchNorm2d(self.ae_shape['conv6'][1]) # Decoder learnable layers self.upconv1 = nn.ConvTranspose2d(*self.ae_shape['upconv1'], stride=1, padding=1,output_padding=0) self.batchnorm7 = nn.BatchNorm2d(self.ae_shape['upconv1'][1]) self.upconv2 = nn.ConvTranspose2d(*self.ae_shape['upconv2'], stride=2, padding=1, output_padding=1) self.batchnorm8 = nn.BatchNorm2d(self.ae_shape['upconv2'][1]) self.upconv3 = nn.ConvTranspose2d(*self.ae_shape['upconv3'], stride=2, padding=1, output_padding=1) self.batchnorm9 = nn.BatchNorm2d(self.ae_shape['upconv3'][1]) self.upconv4 = nn.ConvTranspose2d(*self.ae_shape['upconv4'], stride=2, padding=1, output_padding=1) self.batchnorm10 = nn.BatchNorm2d(self.ae_shape['upconv4'][1]) self.upconv5 = nn.ConvTranspose2d(*self.ae_shape['upconv5'], stride=2, padding=1, output_padding=1) self.batchnorm11 = nn.BatchNorm2d(self.ae_shape['upconv5'][1]) self.upconv6 = nn.ConvTranspose2d(*self.ae_shape['upconv6'], stride=2, padding=1, output_padding=1) # Activation and pooling layers self.relu = nn.ReLU() self.pool2d = nn.MaxPool2d(2) def forward(self, x): out = self.pool2d(self.batchnorm1(self.relu(self.conv1(x)))) out = self.pool2d(self.batchnorm2(self.relu(self.conv2(out)))) out = self.pool2d(self.batchnorm3(self.relu(self.conv3(out)))) out = self.pool2d(self.batchnorm4(self.relu(self.conv4(out)))) out = self.pool2d(self.batchnorm5(self.relu(self.conv5(out)))) out = self.batchnorm6(self.relu(self.conv6(out))) out = self.batchnorm7(self.relu(self.upconv1(out))) out = self.batchnorm8(self.relu(self.upconv2(out))) out = self.batchnorm9(self.relu(self.upconv3(out))) out = self.batchnorm10(self.relu(self.upconv4(out))) out = self.batchnorm11(self.relu(self.upconv5(out))) out = self.upconv6(out) return out def train(ae, dataloader, criterion, optimizer, use_gpu=True, epochs=5): t_begin = time.time() if use_gpu: ae.cuda() criterion.cuda() losses = [] for epoch in tqdm(range(epochs), desc='Epoch'): for step, example in enumerate(tqdm(dataloader, desc='Batch')): if use_gpu: example = example.cuda() optimizer.zero_grad() prediction = ae(example) loss = criterion(example, prediction) loss.backward() optimizer.step() losses.append(float(loss)) if (step % 300) == 0: tqdm.write('Loss: {}\n'.format(loss)) t_end = time.time() timestamp = datetime.datetime.fromtimestamp(t_end).strftime('%Y-%m-%d-%H-%M-%S') time_training = t_end - t_begin return losses, timestamp, time_training if __name__ == "__main__": #Defaults batch_size = 128 meta_folder_path = './' parser = argparse.ArgumentParser(description='Train CNN autoencoder') parser.add_argument('--input', required=True, type=str, help='Folder containing training images.') parser.add_argument('--output', required=False, type=str, help='Results folder will be created in the specified folder.') parser.add_argument('--batch_size', required=False, type=int, help='Default 128. The more, the better but limited by your GPU memory.') parser.add_argument('--device', required=False, type=int, help='Index that pytorch uses to select your GPU.') args = parser.parse_args() data_path = args.input if args.input is not None else 0 meta_folder_path = args.output if args.output is not None else meta_folder_path batch_size = args.batch_size if args.batch_size is not None else batch_size torch.cuda.device(args.device) if args.device is not None else 0 ae = CNNAutoencoder() transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(ae.image_size), torchvision.transforms.ToTensor(), ]) data = dataloading.CellImages(data_path, transforms=transforms) dataloader = DataLoader(data, batch_size=batch_size, shuffle=True) criterion = nn.MSELoss() optimizer = torch.optim.Adam(ae.parameters()) print(ae) losses, timestamp, time_training = train(ae, dataloader, criterion, optimizer, use_gpu=True) model_folder_path = '{}/cnn_autoencoder_{}'.format(meta_folder_path, timestamp) if not os.path.exists(model_folder_path): os.makedirs(model_folder_path) torch.save(ae.state_dict(), '{}/cnn_autoencoder{}.ckpt'.format(model_folder_path, timestamp)) with open("{}/losses{}.pickle".format(model_folder_path, timestamp), "wb") as outfile: pickle.dump(losses, outfile) with open("{}/cnn_autoencoder_info{}.log".format(model_folder_path, timestamp), "w+") as log_file: print("Model\n",ae, file=log_file) print("Criterion\n", criterion, file=log_file) print("Optimizer\n", optimizer, file=log_file) print("Transforms\n", transforms, file=log_file) print("Time Training\n", time_training) <file_sep># Dependencies 1. pytorch 2. torchvision 3. tqdm 4. python3 Installing with conda: ~~~ conda create -n ae_rbc python=3.7 pytorch torchvision tqdm ~~~ Activate the environment before running: ~~~ conda activate ae_rbc ~~~ <file_sep>import torch import torch.nn as nn import torchvision from torch.utils.data import DataLoader from tqdm.auto import tqdm import numpy as np from dv_code import dataloading import time import datetime import pickle class FCAutoencoder(nn.Module): """ Fully connected autoencoder """ def __init__(self, size_input, image_size=(100,100)): """ :size_input: dimensions of input images """ super().__init__() self.image_size = image_size self.input_layer = nn.Linear(size_input,400) self.h1 = nn.Linear(400,100) self.h2 = nn.Linear(100,100) self.encoded = nn.Linear(100,100) self.h3 = nn.Linear(100,400) self.output = nn.Linear(400,size_input) self.relu = nn.ReLU() def forward(self, x): out = self.input_layer(x) out = self.relu(out) out = self.h1(out) out = self.relu(out) out = self.h2(out) out = self.relu(out) self.encoder_vals = out out = self.encoded(out) out = self.relu(out) out = self.h3(out) out = self.relu(out) out = self.output(out) return out #class MnistVectors(torch.utils.data.Dataset): # # def __init__(self, digit=0): # super().__init__() # # (Xtr, Ytr), (Xte, Yte) = keras.datasets.mnist.load_data() # X = np.concatenate((Xtr, Xte)) # Y = np.concatenate((Ytr, Yte)) # # # Use only the training dataset, I don't need a test one for an AE since it maps data onto itself. # self.mnist_vectors, self.labels = convert_mnist_to_vectors((X, Y)) # self.mnist_vectors = prepare_data(self.mnist_vectors) # # if digit is not None: # self.mnist_vectors = self.mnist_vectors[self.labels == digit] # self.labels = np.zeros(self.mnist_vectors.shape[0]) + digit # # def __getitem__(self, idx): # mvec = torch.autograd.Variable(torch.tensor(self.mnist_vectors[idx]).float(), requires_grad=True) # label = torch.tensor(self.labels[idx]).float() # # return mvec, label # # def __len__(self): # return len(self.labels) # def train(ae, dataloader, criterion, optimizer, use_gpu=True, epochs=5): t_begin = time.time() if use_gpu: ae.cuda() criterion.cuda() losses = [] for epoch in tqdm(range(epochs), desc='Epoch'): for step, example in enumerate(tqdm(dataloader, desc='Batch')): if use_gpu: example = example.cuda() optimizer.zero_grad() prediction = ae(example) loss = criterion(example, prediction) loss.backward() optimizer.step() losses.append(float(loss)) if (step % 300) == 0: tqdm.write('Loss: {}\n'.format(loss)) t_end = time.time() timestamp = datetime.datetime.fromtimestamp(t_end).strftime('%Y-%m-%d-%H-%M-%S') torch.save(ae.state_dict(), 'autoencoder{}.ckpt'.format(timestamp)) time_training = t_end - t_begin return losses, timestamp, time_training if __name__ == "__main__": image_size = (100,100) data_path = "/export/home/dv/dv016/datasets/cell_images/Uninfected" ae = FCAutoencoder(image_size[0] * image_size[1]) transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(image_size), torchvision.transforms.ToTensor(), dataloading.Flatten() ]) data = dataloading.CellImages(data_path, transforms=transforms) dataloader = DataLoader(data, batch_size=256, shuffle=True) criterion = nn.MSELoss() optimizer = torch.optim.Adam(ae.parameters()) losses, timestamp, time_training = train(ae, dataloader, criterion, optimizer, use_gpu=True) with open("./losses{}.pickle".format(timestamp), "wb") as outfile: pickle.dump(losses, outfile) with open("./autoencoder_info{}.log".format(timestamp), "w+") as log_file: print("Model\n",ae, file=log_file) print("Criterion\n", criterion, file=log_file) print("Optimizer\n", optimizer, file=log_file) print("Transforms\n", transforms, file=log_file) print("Time Training\n", time_training) <file_sep>import torch import torch.nn as nn import torchvision from torch.utils.data import DataLoader from tqdm.auto import tqdm import numpy as np from PIL import Image import os class CellImages(torch.utils.data.Dataset): def __init__(self, path, transforms=None): """ :transforms: torchvision.transforms.Compose object :path: where the Uninfected and Parasitised folders are located """ self.transforms = transforms self.image_names_raw = self._load_data_names(path) assert "Uninfected" in path or "Parasitized" in path, "Expected path of format ../Uninfected or ../Parasitized, but got {}".format(path) assert len(self.image_names_raw) != 0, "Found no .png in {}".format(path) def _load_data_names(self, path): """ Load .png image names - to be loaded lazily later :path: path to folder that contains some .png images """ image_names_raw = ["{}/{}".format(path, image_name) for image_name in os.listdir(path) if ".png" in image_name] return image_names_raw def __getitem__(self, idx): image_handle = Image.open(self.image_names_raw[idx]) if self.transforms is not None: return self.transforms(image_handle) else: return image_handle def __len__(self): return len(self.image_names_raw) class Flatten(object): """ Transformation to flatten a tensor of size (CxHxW) to (Cx(H*W)) """ def __call__(self, image_tensor): image_shape = image_tensor.size() assert len(image_shape) == 3, "Expected 3D tensor but got {}".format(image_shape) return image_tensor.view((image_shape[0], -1)) transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize((100,100)), torchvision.transforms.ToTensor(), Flatten() ]) def main(): """ Test example """ civs = CellImages("../project/cell_images/Uninfected", transforms=transforms) dataloader = torch.utils.data.DataLoader(civs, batch_size=16) if __name__ == "__main__": main() <file_sep>import matplotlib.pyplot as plt import torch import torch.nn as nn import fc_autoencoder import cnn_autoencoder import dataloading import torchvision from PIL import Image import os import sys images_path = "../cell_images/Parasitized" to_PIL = torchvision.transforms.ToPILImage() def illustrate_performance(model,model_path, image_size, transforms, model_type='fc', loss=None): """ Generates images of original/reconstruction pairs, and a loss graph :loss: if not None, graph the loss history and save in the same dir """ performance_dir = model_path[:-5] if not os.path.exists(performance_dir): os.mkdir(performance_dir) cell_images = dataloading.CellImages(images_path, transforms=transforms) for img_index in range(0,10): img_orig = cell_images[img_index].view(3,image_size[0],image_size[1]) img_orig = to_PIL(img_orig) if model_type == 'cnn': img_reconst = model.forward(cell_images[img_index].view(1,3,image_size[0], image_size[1])) img_reconst = to_PIL(img_reconst.squeeze(0)) elif model_type == 'fc': img_reconst = model.forward(cell_images[img_index].view(3,image_size[0], image_size[1])) img_reconst = to_PIL(img_reconst) img_new = Image.new('RGB', (image_size[0]*2, image_size[1])) img_new.paste(img_orig,(0,0)) img_new.paste(img_reconst,(image_size[0],0)) img_new.save("{}/{}.png".format(performance_dir, img_index)) def main(): assert len(sys.argv) == 3, "python3 <script> <path/model_name> <cnn or fc>" model_path = sys.argv[1] model_type = sys.argv[2] if model_type == 'fc': model = fc_autoencoder.FCAutoencoder(image_size[0] * image_size[1]) model.load_state_dict(torch.load(model_path, map_location="cpu")) model.eval() image_size = model.image_size transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(image_size), torchvision.transforms.ToTensor(), dataloading.Flatten() ]) elif model_type == 'cnn': model = cnn_autoencoder.CNNAutoencoder() model.load_state_dict(torch.load(model_path, map_location="cpu")) model.eval() image_size = model.image_size transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(image_size), torchvision.transforms.ToTensor(), ]) illustrate_performance(model, model_path, image_size, transforms, model_type=model_type) if __name__ == "__main__": main()
62341d04366b01f5b7c2f850f25bffb9d79eb730
[ "Markdown", "Python" ]
6
Python
boykovdn/dv-code
e567bc270c05f12fd2660a256d3a6721faed3913
45c0633816703a4f439260154ff770fd8825a382
refs/heads/master
<file_sep>//small_mad_lib.cpp: This program asks the user for a number, country, animal and name and returns a string. //Name: <NAME> //Class Section: COSC-1436.900 Online // Date: 09/26/2021 #include <iostream> #include <iomanip> #include <cmath> #include <string> using namespace std; int main() { // Variables: Variables to hold all needed data int years; string country, animal, name; // Ask for a number somewhere in your program, followed by asking for a string cout << "Give me some data and I will predict your future! \n"; cout << "Enter an integer number: "; cin >> years; cin.ignore(20, '\n'); cout << "Enter the name of a country: "; // Ensuring that your program can handle a string input that may have multiple words getline(cin, country); cout << "Enter a type of animal: "; getline(cin, animal); cout << "Enter a funny name: "; getline(cin, name); // Output the story using the data provided by the user cout << "It's time to tell your future!" << endl; cout << "In "<< years <<" years, you will move to " << country << endl; cout << "You will be gifted a "<< animal <<" that you decide to name "<< name <<"." << endl; return 0; }
4860001b099fafc1412d266f477cf10054103c87
[ "C++" ]
1
C++
MacLeanLuke/assignment_3b
9fe94ea32c10a658646b640a641098092b8a8a3a
74b3e8269df5ac764f62d8e38a8eb3b3b7e8e031
refs/heads/master
<file_sep># Number Guesser ![Number Guesser](https://i.postimg.cc/6qQ13fCR/Number-Guesser.jpg) # Tools used * HTML/CSS * JavaScript * Bootstrap # What I learned * Bootstrap control * Flow control * DOM manipulation<file_sep>let randomNumber = Math.floor(Math.random() * 10) + 1; let guessing = true; let guesses = 0; document.getElementById('guess-form').addEventListener("submit", function (e) { playingTheGame(); e.preventDefault(); }) // UI Variables const guess = document.getElementById('guess'); const result = document.getElementById('results'); const submit = document.getElementById('submit'); function playingTheGame() { if (guessing === false) { guesses = 0; submit.value = "Submit"; guess.disabled = false; guess.value = ""; result.innerText = ""; guessing = true; randomNumber = Math.floor(Math.random() * 10) + 1; } else { compareGuess(); } } function compareGuess() { if (+guess.value === randomNumber) { result.innerText = randomNumber + " is correct!"; result.style.color = "green"; guess.disabled = true; submit.value = "Play Again" guessing = false; } else if (guesses === 0) { result.innerText = "Try again you have 2 guesses left"; result.style.color = "red"; guesses += 1; } else if (guesses === 1) { result.innerText = "Try again you have 1 guess left"; result.style.color = "red"; guesses += 1; } else { result.innerText = "Game over bro"; result.style.color = "red"; guess.disabled = true; submit.value = "Try Again" guessing = false; } }
dd70748ba43d44a173e22a8b78869c8e22977bfa
[ "Markdown", "JavaScript" ]
2
Markdown
hibenca/Number-Guesser
0a660c95b2857bca922242807ccc4f1a8a480f62
fa469fea11e65d4bb229c07b977f65c60f960373
refs/heads/master
<file_sep># DjangoORM `cd library` run tests ``` python manage.py makemigrations python manage.py test ``` ``` coverage run manage.py test coverage html ``` In order to execute actions correctly you need to copy file __classrom.yml into classroom.yml <file_sep># .coveragerc to control coverage.py [run] source = authentication author book customprofile order utils omit = *migrations* *apps.py* *urls.py* *__init__.py* *tests.py* *views.py* *admin.py* <file_sep>from django.db import models, DataError, IntegrityError from authentication.models import CustomUser from author.models import Author from book.models import Book import datetime class Order(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) end_at = models.DateTimeField(null=True) plated_end_at = models.DateTimeField(null=True) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=True) def __str__(self): """ Magic method is redefined to show all information about Book. :return: book id, book name, book description, book count, book authors """ end_at = f"'{self.end_at}'" if self.end_at else None return f"'id': {self.id}, 'user': {self.user.__class__.__name__}(id={self.user.id})," \ f" 'book': {self.book.__class__.__name__}(id={self.book.id}), " \ f"'created_at': '{self.created_at}', 'end_at': {end_at}, " \ f"'plated_end_at': '{self.plated_end_at}'" def __repr__(self): """ This magic method is redefined to show class and id of Book object. :return: class, id """ return f'{self.__class__.__name__}(id={self.id})' def to_dict(self): return { 'id': self.id, 'user': self.user, 'book': self.book, 'created_at': str(self.created_at), 'end_at': str(self.end_at) if self.end_at else self.end_at, 'plated_end_at': str(self.plated_end_at) } @staticmethod def create(user, book, plated_end_at): try: if book.count <= 1: raise ValueError order = Order.objects.create(user=user, book=book, plated_end_at=plated_end_at) book.count -= 1 return order except (DataError, IntegrityError, ValueError): return None @staticmethod def get_by_id(order_id): try: return Order.objects.get(id=order_id) except Order.DoesNotExist: return None def update(self, plated_end_at=None, end_at=None): if plated_end_at: self.plated_end_at = plated_end_at if end_at: self.end_at = end_at self.save() @staticmethod def get_all(): return list(Order.objects.all()) @staticmethod def get_not_returned_books(): return [order for order in Order.get_all() if order.end_at is None] @staticmethod def delete_by_id(order_id): try: return Order.objects.get(id=order_id).delete() except Order.DoesNotExist: return None
b52c02a54d95f9f3fa137837bd7dae707c3870e2
[ "Markdown", "Python", "INI" ]
3
Markdown
waldemarantypov/sprint18_django_REST
40dea1f6c72de60c03932679240d9a878afb4066
f40a7171037b39f5faa5919a4d82982e799f6eca
refs/heads/master
<repo_name>brandonIT/whackAMole<file_sep>/whackAMole/GameScene.swift // // GameScene.swift // whackAMole // // Created by xcode on 2/19/20. // Copyright © 2020 xcode. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene, SKPhysicsContactDelegate { var goodMoleSprite:SKSpriteNode? var hitMoleTexture:SKTexture? var goodMoleTexture:SKTexture? var xCoord:Int = 0 var yCoord:Int = 0 var xNumber = 0 //x can't be less than -3 or greater than 3 var yNumber = 0 //y can't be less than -5 greater than 10 var molesHit:Int = 0 var molesCount:Int = 0 var count:Int = 0 override func didMove(to view: SKView) { goodMoleSprite = self.childNode(withName: "goodMoleSprite") as? SKSpriteNode goodMoleTexture = SKTexture(imageNamed: "goodMole") hitMoleTexture = SKTexture(imageNamed: "hitMole") startGame() } func startGame() { Timer.scheduledTimer(withTimeInterval: 1.5, repeats: true) { timer in print("Timer fired!") self.count += 1 self.xNumber = Int.random(in: -3 ..< 3) self.yNumber = Int.random(in: -5 ..< 10) self.xCoord = self.xNumber self.yCoord = self.yNumber self.goodMoleSprite?.anchorPoint = CGPoint(x: self.xCoord, y: self.yCoord) if self.count == 3 { timer.invalidate() } self.molesCount += 1 self.goodMoleSprite?.texture = self.goodMoleTexture } } func didBegin(_ contact: SKPhysicsContact) { } func touchDown(atPoint pos : CGPoint) { } func touchMoved(toPoint pos : CGPoint) { } func touchUp(atPoint pos : CGPoint) { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! if (goodMoleSprite?.contains(touch.location(in: self)))! { molesHit += 1 goodMoleSprite?.texture = hitMoleTexture print("Moles hit: \(molesHit)") } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func update(_ currentTime: TimeInterval) { } }
5c6743801e184c23477e4458eef539d022de7cb4
[ "Swift" ]
1
Swift
brandonIT/whackAMole
d6f8f4b2b33282261482d673a094379de8c68ba7
27e6ee90a7d745a6894fb32c584938324287e709
refs/heads/master
<file_sep>using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; namespace BackgroundServiceSample { public class TestHostedService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine("TestHostedService.StartAsync()"); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("TestHostedService.StopAsync()"); return Task.CompletedTask; } } }
1921be2cf253c66fcfc978ca56249623f2e4f317
[ "C#" ]
1
C#
markvincze/BackgroundServiceSample
b63272bab6d3ef8a8e3a9514271dfa373ed08f4c
3a5351c1b94307eeb886cecd78e8f02be9359b81
refs/heads/master
<repo_name>choi8488kr/web<file_sep>/8-28 MVC2/src/net/tis/mvc/GuestReplyInsert.java package net.tis.mvc; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.guest.sql.ReplyDTO; import net.guest.sql.ReplySQL; import net.tis.sql.GuestDTO; import net.tis.sql.GuestSQL; @WebServlet("/greplyInsert.do") public class GuestReplyInsert extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doUser(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doUser(request, response); } public void doUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<h2>GuestReplyInsert.java</h2>"); int sabun =Integer.parseInt(request.getParameter("sabun")); String writer=request.getParameter("writer"); String content =request.getParameter("content"); ReplySQL rgs=new ReplySQL(); rgs.dbReplyInsert(writer, content, sabun); response.sendRedirect("gdetail.do?idx="+sabun); //request.setAttribute("dto", dto); // RequestDispatcher는 데이터 자원을 보낼문서를 명명 // RequestDispatcher dis = request.getRequestDispatcher("guestDetail.jsp"); // dis.forward(request, response); } } <file_sep>/8-28 MVC2/src/net/guest/sql/ReplyDTO.java package net.guest.sql; public class ReplyDTO{ //리플=Data Transfer Object private int num ; private String writer; private String content; private int sabun; //guest테이블사번필드연결 private int rrn; //댓글의 글번호 public int getRrn() { return rrn; } public void setRrn(int rrn) { this.rrn = rrn; } //오.버=>source=>Generate Getter and Setter... public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getContent() {return content; } public void setContent(String content) { this.content = content; } public int getSabun() { return sabun; } public void setSabun(int sabun) { this.sabun = sabun; } }//ReplyDTO class END <file_sep>/8-28 MVC2/src/net/tis/sql/GuestDTO.java package net.tis.sql; public class GuestDTO { private int sabun; private String name; private String title; private java.util.Date wdate; private int pay, hit; private String email; //행번호,cnt java/java연결,jsp/java연결, java/서블릿연결 private int rn,cnt; private int rcnt; public int getSabun() { return sabun;} public void setSabun(int sabun) { this.sabun = sabun; } public String getName() { return name; } public void setName(String name) {this.name = name; } public String getTitle() { return title; } public void setTitle(String title) {this.title = title; } public java.util.Date getWdate() {return wdate; } public void setWdate(java.util.Date wdate) {this.wdate = wdate;} public int getPay() { return pay; } public void setPay(int pay) { this.pay = pay; } public int getHit() { return hit;} public void setHit(int hit) { this.hit = hit; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getRn() {return rn; } public void setRn(int rn) { this.rn = rn; } public int getCnt() { return cnt; } public void setCnt(int cnt) { this.cnt = cnt; } public int getRcnt() {return rcnt;} //댓글갯수 public void setRcnt(int rcnt) {this.rcnt = rcnt;} }//class END <file_sep>/README.md # TIS 웹 프로젝트 ## 시작 <file_sep>/8-28 MVC2/src/net/guest/sql/ReplySQL.java package net.guest.sql; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import net.tis.common.DB; public class ReplySQL { Connection CN ; Statement ST ; PreparedStatement PST; CallableStatement CST; ResultSet RS ; String msg; public ReplySQL() { CN=DB.getConnection(); } public int dbReplyCount(int Rdata) { int count=0; try { msg="select count(*) as rcnt from guestreply where sabun="+Rdata; ST=CN.createStatement(); RS=ST.executeQuery(msg); if(RS.next()==true) { count=RS.getInt("rcnt");} }catch(Exception e) {System.out.println(e);} return count; } public ArrayList<ReplyDTO> dbReplySelect(int Rdata){ ArrayList<ReplyDTO> list = new ArrayList<ReplyDTO>(); try { StringBuffer sb = new StringBuffer(); sb.append("select rownum rn, g.sabun, r.num, r.writer,r.content from guest g "); sb.append("inner join guestreply r "); sb.append("on g.sabun = r.sabun "); sb.append("and r.sabun = "+Rdata); ST=CN.createStatement(); RS=ST.executeQuery(sb.toString()); while(RS.next()) { ReplyDTO rdto = new ReplyDTO(); rdto.setRrn(RS.getInt("rn")); rdto.setNum(RS.getInt("num")); rdto.setWriter(RS.getString("writer")); rdto.setContent(RS.getString("content")); rdto.setSabun(RS.getInt("sabun")); list.add(rdto); } }catch(Exception e) {System.out.println("dbreplyselect 오류"+e);} return list; } public void dbReplyInsert(String writer, String content, int sabun) { try { msg= "insert into guestreply values(guestreply_seq.nextval,?,?,?)"; PST=CN.prepareStatement(msg); PST.setString(1, writer); PST.setString(2, content); PST.setInt(3, sabun); PST.executeUpdate(); }catch(Exception e) {System.out.println("replyinsert 에러"+e);} } public void dbReplyUpdate(int num, String writer, String content, int sabun) { try { msg="update guestreply set writer=?,content=? where num="+num; PST=CN.prepareStatement(msg); PST.setString(1, writer); PST.setString(2, content); PST.executeUpdate(); }catch(Exception e) {System.out.println("dbreplyupdate 에러"+e);} } }//class END
839c69574ff2ccf314d296289e76672ceafc7d1d
[ "Markdown", "Java" ]
5
Java
choi8488kr/web
85105385026eb50ae338064d9ce81c7b288e8a6b
9079ebe075cee35d1880c594255b97e5b8300855
refs/heads/master
<file_sep>package com.jvra.pokemoncarddb; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutCompat; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.jvra.pokemoncarddb.com.jvra.pokemoncarddb.objects.EnumType; public class AddCardDetails extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private String[] pokemonTypeValues = {EnumType.GRASS.toString(), EnumType.FIRE.toString(), EnumType.WATER.toString(), EnumType.ROCK.toString()}; private int pokemonTypeImages[] = {R.drawable.grass, R.drawable.fire, R.drawable.water, R.drawable.rock}; private LinearLayout layout; private Spinner pokemonTypeSpinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_card_details); layout = (LinearLayout) findViewById(R.id.add_card_details_activity); Drawable b = getResources().getDrawable(HomeScreen.backgrounds[1]); layout.setBackground(b); pokemonTypeSpinner = (Spinner) findViewById(R.id.spinner_pokemon_type); pokemonTypeSpinner.setAdapter(new PokemonTypeSpinner(AddCardDetails.this, R.layout.spinner_pokemon_type, pokemonTypeValues)); } public class PokemonTypeSpinner extends ArrayAdapter<String> { public PokemonTypeSpinner(Context context, int resource, String[] objects) { super(context, resource, objects); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } public View getCustomView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.spinner_pokemon_type, parent, false); ImageView icon = (ImageView) row.findViewById(R.id.imageView_pokemon_type); icon.setImageResource(pokemonTypeImages[position]); return row; } } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.item_show_cards) { // Handle the camera action } else if (id == R.id.item_add_cards) { Intent intent = new Intent(this, AddCardDetails.class); startActivity(intent); } else if (id == R.id.item_search_cards) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } } <file_sep>package com.jvra.pokemoncarddb.com.jvra.pokemoncarddb.objects; import java.util.List; /** * Created by Jeroen on 25-4-2016. */ public class Card { private String cardName; private Long cardNumber; // type = trainer, energy... private EnumType cardType; private EnumType pokemonType; private int amountOfCardsOwned; private Double health; private Double level; private String team; private List<Attack> attackList; private String evolvesFrom; private Weakness weakness; private Resistance resistance; private RetreatCost retreatCost; public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } public Long getCardNumber() { return cardNumber; } public void setCardNumber(Long cardNumber) { this.cardNumber = cardNumber; } public EnumType getCardType() { return cardType; } public void setCardType(EnumType cardType) { this.cardType = cardType; } public EnumType getPokemonType() { return pokemonType; } public void setPokemonType(EnumType pokemonType) { this.pokemonType = pokemonType; } public Double getHealth() { return health; } public void setHealth(Double health) { this.health = health; } public Double getLevel() { return level; } public void setLevel(Double level) { this.level = level; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public List<Attack> getAttackList() { return attackList; } public void setAttackList(List<Attack> attackList) { this.attackList = attackList; } public Weakness getWeakness() { return weakness; } public void setWeakness(Weakness weakness) { this.weakness = weakness; } public Resistance getResistance() { return resistance; } public void setResistance(Resistance resistance) { this.resistance = resistance; } public RetreatCost getRetreatCost() { return retreatCost; } public void setRetreatCost(RetreatCost retreatCost) { this.retreatCost = retreatCost; } public String getEvolvesFrom() { return evolvesFrom; } public void setEvolvesFrom(String evolvesFrom) { this.evolvesFrom = evolvesFrom; } public int getAmountOfCardsOwned() { return amountOfCardsOwned; } public void setAmountOfCardsOwned(int amountOfCardsOwned) { this.amountOfCardsOwned = amountOfCardsOwned; } } <file_sep>package com.jvra.pokemoncarddb.com.jvra.pokemoncarddb.objects; /** * Created by Jeroen on 25-4-2016. */ public class Weakness { private EnumType enumType; private int amount; public EnumType getEnumType() { return enumType; } public void setEnumType(EnumType enumType) { this.enumType = enumType; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } }
894629337b069e0335c1d87ca7b91c222711fcb9
[ "Java" ]
3
Java
666jeroen/PokeCardDB
f8d1c45ee12774d44cec9aa2a3b09d69a7639489
5de6dda46db0a538634bfd986bc0a046a13df1cf
refs/heads/master
<repo_name>flosev/InputFormTestAngularWithoutGrunt<file_sep>/app/scripts/app.js 'use strict'; var app = angular.module('myApp', [ 'myApp.controllers' ]); app.config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/', { templateUrl: 'views/dashboard/chart.html', controller: 'DashChartCtrl', resolve: { dashboardchart: function (Main) { return Main.dashboardchart(); } } }). when('/myaccount/personal', { templateUrl: 'views/myaccount/personal.html', controller: 'MyAccPerCtrl', resolve: { getusersdata: function (Main) { return Main.getusersdata(); } } }); }]) <file_sep>/app/scripts/controllers.js 'use strict'; var ctrl = angular.module('myApp.controllers', []); ctrl.controller('MainCtrl', ['$rootScope', '$scope', function($rootScope, $scope) { $scope.urlRegex = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/; var urlArr = []; $scope.log= urlArr; console.log('fromCTRL'); $scope.submitForm = function () { var newElem=$scope.getUrl; var cutHttp = newElem.replace(/(?:((?:\/\/)|^)http[s]?:\/\/)(?=[^/]*?\.)/i, "$1"); var cutWww = cutHttp.replace(/(?:((?:\/\/)|^)www\.)(?=[^/]*?\.)/i, "$1"); var cutRight = cutWww.split("/")[0]; urlArr.unshift(cutRight); $scope.getUrl=''; } }]);
dec16f1ab7310aa4960f88e6c203d9949386e8d8
[ "JavaScript" ]
2
JavaScript
flosev/InputFormTestAngularWithoutGrunt
2498be5bec90145e5d2f32c2bb3c1cdcdc0acb07
9a9132d870e23161f8a13ad8edec11c957a94265
refs/heads/master
<repo_name>JeromeBu/05-twitter<file_sep>/server.js var express = require("express"); var app = express(); const chalk = require("chalk"); const morgan = require("morgan"); var bodyParser = require("body-parser"); var multer = require("multer"); var cloudinary = require("cloudinary"); var cloudinaryStorage = require("multer-storage-cloudinary"); var uniqid = require("uniqid"); cloudinary.config({ cloud_name: "dpmc03d5t", api_key: "441494212493983", api_secret: "<KEY>" }); var storage = cloudinaryStorage({ cloudinary: cloudinary, folder: function(req, file, cb) { cb(undefined, "twitter"); // on récupère une variable du formulaire }, allowedFormats: ["jpg", "png"], // tranformation: [{ width: 90, height: 90, crop: "thumb", gravity: "face" }], filename: function(req, file, cb) { cb(undefined, req.body.id); } }); var parser = multer({ storage: storage }); var server = require("http").createServer(app); var io = require("socket.io")(server); var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/twiter"); app .use(express.static("public")) .use(morgan("dev")) .use(bodyParser.urlencoded({ extended: true })) .set("view engine", "ejs"); var format = require("date-fns").format; // 1) Definir le schema - A faire qu'une fois var tweetSchema = new mongoose.Schema({ name: { type: String, require: true }, message: String, createdAt: { type: Date, default: Date.now }, img_id: String }); // 2) Definir le model - A faire qu'une fois var Tweet = mongoose.model("Student", tweetSchema); app.get("/", function(req, res) { Tweet.find() .sort("-createdAt") .lean() .exec(function(err, tweets) { if (!err) { tweets.forEach(tweet => { tweet.date = format(tweet.createdAt, "DD/MM/YYYY"); }); res.render("client.ejs", { tweets: tweets, id: uniqid() }); } else { res.send("An error at occured"); } }); }); io.on("connection", function(socket) { // ecoute de l'evenement d'envoi de message log("Info", "Socket connection has been established"); socket.on("message-send", function(data) { log("Connected, data :", data); var newTweet = new Tweet(data); newTweet.save(function(err, obj) { if (err) { console.log("something went wrong"); } else { console.log("we just saved tweet " + obj.message); // nous pouvons stocker des données dans l'objet client // cela peut être utile si nous souhaitonsç socket.name = data.name; socket.message = data.message; socket.img_id = data.img_id; socket.date = format(data.date, "DD/MM/YYYY"); // (6) envoyer une information à tous les clients io.emit("new_tweet", { name: socket.name, message: socket.message, date: socket.date, img_id: socket.img_id }); } }); // envoyer à tout le monde sauf au client lui-même // socket.broadcast.emit('new_connection', {name: client.name}); }); // d'autres écouteurs peuvent être créés ici `client.on(...);` }); app.post("/upload", parser.single("image", 4), function(req, res) { log("req.file", req.file); log("req.body", req.body); var image_to_upload = { version: req.file.version, public_id: req.file.public_id, mimetype: req.file.mimetype, secure_url: req.file.secure_url }; // images.push(image); res.send("upload is done"); // } // console.log(images); // res.redirect("/"); }); server.listen(3000, function() { console.log("Server started"); }); function log(string, value) { if (typeof value === "object") { var display = JSON.stringify(value); } else { var display = value; } console.log(chalk.yellow(`\n \n ${string} : \n ${display} \n`)); }
c47aaac353f8970eda15c592fb19b4f77d360e38
[ "JavaScript" ]
1
JavaScript
JeromeBu/05-twitter
f7b497b321bbc2ebfca6dd5226a3b26602fa97ba
a2a2417823dabecf2eb0c64960773cb8b1dc482e
refs/heads/master
<repo_name>ONEPIECEWBY/keras_bert_english_sequence_labeling<file_sep>/data/get_crf_data.py # -*- coding: utf-8 -*- # @Time : 2020/12/30 15:05 # @Author : Jclian91 # @File : get_crf_data.py # @Place : Yangpu, Shanghai with open("conll2003.test", "r", encoding="utf-8") as f: content = [_.strip() for _ in f.readlines()] g = open("crf_english_ner.test", "w", encoding="utf-8") for line in content: if line: char = line.split()[0] pos = line.split()[-2] tag = line.split()[-1] g.write("{}\t{}\t{}\n".format(char, pos, tag)) else: g.write("\n") g.close()<file_sep>/model_predict.py # -*- coding: utf-8 -*- # @Time : 2020/12/24 13:28 # @Author : Jclian91 # @File : model_predict.py # @Place : Yangpu, Shanghai import numpy as np from pprint import pprint from keras.models import load_model from keras_bert import get_custom_objects from keras_contrib.layers import CRF from keras_contrib.losses import crf_loss from keras_contrib.metrics import crf_accuracy from util import event_type from model_train import PreProcessInputData, id_label_dict from load_data import bert_encode # 加载训练好的模型 custom_objects = get_custom_objects() for key, value in {'CRF': CRF, 'crf_loss': crf_loss, 'crf_accuracy': crf_accuracy}.items(): custom_objects[key] = value model = load_model("%s_large_ner.h5" % event_type, custom_objects=custom_objects) # 测试句子 def get_text_predict(text): new_text = [] for word in text.split(): new_text.extend(bert_encode(word)) word_labels, seq_types = PreProcessInputData([new_text]) # 模型预测 predicted = model.predict([word_labels, seq_types]) y = np.argmax(predicted[0], axis=1) tags = [id_label_dict[_] for _ in y] # 输出预测结果 real_tag = [] i = 1 for word in text.split(): new_word = bert_encode(word) if i < len(tags): real_tag.append(tags[i]) i += len(new_word) return real_tag if __name__ == '__main__': test_text = "South Africa - 15 - <NAME> , 14 - <NAME> , 13 - <NAME> ( <NAME> , 48 mins ) 12 - <NAME> , 11 - <NAME> ; 10 - <NAME> , 9 - <NAME> ; 8 - <NAME> ( captain ) , 7 - <NAME> ( <NAME> , 75 ) , 6 - <NAME> , 5 - <NAME> ( <NAME> , 39 ) , 4 - <NAME> , 3 - <NAME> , 2 - <NAME> , 1 - <NAME> ( <NAME> , 66 ) ." print(get_text_predict(test_text)) <file_sep>/README.md 本项目采用Keras和Keras-bert实现英语序列标注,其中对BERT进行微调。 ### 维护者 - jclian91 ### 数据集 1. [Conll2003](https://www.clips.uantwerpen.be/conll2003/ner/) conll2003.train 14987条数据和conll2003.test 3466条数据,共4种标签: + [x] LOC + [x] PER + [x] ORG + [x] MISC 2. [wnut17](https://noisy-text.github.io/2017/emerging-rare-entities.html) wnut17.train 3394条数据和wnut17.test 1009条数据,共6种标签: + [x] Person + [x] Location (including GPE, facility) + [x] Corporation + [x] Consumer good (tangible goods, or well-defined services) + [x] Creative work (song, movie, book, and so on) + [x] Group (subsuming music band, sports team, and non-corporate organisations) ### 模型结构 ``` __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_1 (InputLayer) (None, None) 0 __________________________________________________________________________________________________ input_2 (InputLayer) (None, None) 0 __________________________________________________________________________________________________ model_2 (Model) multiple 108596736 input_1[0][0] input_2[0][0] __________________________________________________________________________________________________ bidirectional_1 (Bidirectional) (None, None, 200) 695200 model_2[1][0] __________________________________________________________________________________________________ crf_1 (CRF) (None, None, 9) 1908 bidirectional_1[0][0] ================================================================================================== Total params: 109,293,844 Trainable params: 109,293,844 Non-trainable params: 0 ``` ### 模型效果 - Conll2003 模型参数:uncased_L-12_H-768_A-12, MAX_SEQ_LEN=128, BATCH_SIZE=32, EPOCH=10 运行model_evaluate.py,模型评估结果如下: ``` precision recall f1-score support PER 0.9650 0.9577 0.9613 1842 ORG 0.8889 0.8770 0.8829 1341 MISC 0.8156 0.8395 0.8274 922 LOC 0.9286 0.9271 0.9278 1837 micro avg 0.9129 0.9116 0.9123 5942 macro avg 0.9134 0.9116 0.9125 5942 ``` BERT模型评估结果对比 模型参数:MAX_SEQ_LEN=128, BATCH_SIZE=32, EPOCH=10. |模型名称|P|R|F1| |---|---|---|---| |BERT-Small|0.8744|0.8859|0.8801| |BERT-Medium|0.9052|0.9031|0.9041| |BERT-Base|0.9129|0.9116|0.9123| [最新SOTA结果的F1值为94.3%.](https://github.com/sebastianruder/NLP-progress/blob/master/english/named_entity_recognition.md) - wnut17 模型参数:uncased_L-12_H-768_A-12, MAX_SEQ_LEN=128, BATCH_SIZE=20, EPOCH=10 运行model_evaluate.py,模型评估结果如下: ``` precision recall f1-score support work 0.2069 0.0571 0.0896 105 person 0.6599 0.4830 0.5577 470 product 0.3333 0.0965 0.1497 114 location 0.5070 0.4865 0.4966 74 group 0.1500 0.1538 0.1519 39 corporation 0.1935 0.1765 0.1846 34 micro avg 0.5328 0.3489 0.4217 837 macro avg 0.5016 0.3489 0.4033 837 ``` ### 代码说明 0. 将BERT英语预训练模型放在对应的文件夹下 1. 运行load_data.py,生成类别标签文件label2id.json,注意O标签为0; 2. 所需Python第三方模块参考requirements.txt文档 3. 自己需要分类的数据按照data/conll2003.train和data/conll2003.test的格式准备好 4. 调整模型参数,运行model_train.py进行模型训练 5. 运行model_evaluate.py进行模型评估 6. 运行model_predict.py对新文本进行预测
3d75455e5315a84cf00743b1ee9d9e4fc872c133
[ "Markdown", "Python" ]
3
Python
ONEPIECEWBY/keras_bert_english_sequence_labeling
caf42e5f3b03733e108d0854450836c2cd35395f
e29dcba423e028b94554b8ba85a0acee3689d627
refs/heads/master
<repo_name>KakoDaSeZove/InformativnaAgencijaApp<file_sep>/app/src/main/java/com/example/androiddevelopment/informativnaagencijaapp/db/Komentari.java package com.example.androiddevelopment.informativnaagencijaapp.db; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; /** * Created by androiddevelopment on 20.3.18.. */ @DatabaseTable(tableName = Komentari.TABLE_NAME_KOMENTARI) public class Komentari { public static final String TABLE_NAME_KOMENTARI = "komentari"; public static final String FIELD_NAME_ID = "_id"; public static final String FIELD_NAME_NAZIV = "naziv"; public static final String FIELD_NAME_OPIS = "opis"; public static final String FIELD_NAME_AUTOR = "autor"; public static final String FIELD_NAME_DATUM = "datum"; public static final String FIELD_NAME_VESTI = "vesti"; @DatabaseField(columnName = FIELD_NAME_ID, generatedId = true) private int mId; @DatabaseField(columnName = FIELD_NAME_NAZIV) private String mNaziv; @DatabaseField(columnName = FIELD_NAME_OPIS) private String mOpis; @DatabaseField(columnName = FIELD_NAME_AUTOR) private String mAutor; @DatabaseField(columnName = FIELD_NAME_DATUM) private String mDatum; @DatabaseField(columnName = FIELD_NAME_VESTI, foreign = true, foreignAutoRefresh = true) private Vesti mVesti; public Komentari() { } public int getmId() { return mId; } public void setmId(int mId) { this.mId = mId; } public String getmNaziv() { return mNaziv; } public void setmNaziv(String mNaziv) { this.mNaziv = mNaziv; } public String getmOpis() { return mOpis; } public void setmOpis(String mOpis) { this.mOpis = mOpis; } public String getmAutor() { return mAutor; } public void setmAutor(String mAutor) { this.mAutor = mAutor; } public String getmDatum() { return mDatum; } public void setmDatum(String mDatum) { this.mDatum = mDatum; } public Vesti getmVesti() { return mVesti; } public void setmVesti(Vesti mVesti) { this.mVesti = mVesti; } @Override public String toString() { return mNaziv; } } <file_sep>/app/src/main/java/com/example/androiddevelopment/informativnaagencijaapp/activities/MainActivity.java package com.example.androiddevelopment.informativnaagencijaapp.activities; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.androiddevelopment.informativnaagencijaapp.R; import com.example.androiddevelopment.informativnaagencijaapp.db.DatabaseHelper; import com.example.androiddevelopment.informativnaagencijaapp.db.Vesti; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static android.R.layout.simple_list_item_1; public class MainActivity extends AppCompatActivity { private ListView listView = null; private DrawerLayout mDrawerLayout; private List<Vesti> vesti = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_main); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_menu); AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> listView, View v, int position, long id) { Intent intent = new Intent(MainActivity.this, DetailActivity.class); //intent.putExtra(DetailActivity.EXTRA_NO, contact.get(position).getmId()); startActivity(intent); } }; listView = (ListView) findViewById(R.id.list_of_contact); listView.setOnItemClickListener(itemClickListener); mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight menuItem.setChecked(true); // close drawer when item is tapped mDrawerLayout.closeDrawers(); switch (menuItem.getItemId()) { case R.id.nav_all_news: // Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); // } return true; case R.id.nav_tools: return true; case R.id.nav_about: return true; } // Add code here to update the UI based on the item selected // For example, swap UI fragments here return true; } }); } @Override protected void onResume() { super.onResume(); DatabaseHelper helper = new DatabaseHelper(this); Dao<Vesti, Integer> vestiDao = null; try { vestiDao = helper.getVestiDao(); } catch (SQLException e) { e.printStackTrace(); } try { vesti = vestiDao.queryForAll(); } catch (SQLException e) { e.printStackTrace(); } ArrayList<String> listaVesti = new ArrayList<>(); for (Vesti v : vesti) { listaVesti.add(v.getmId() + " " + v.getmNaziv()); } ArrayAdapter<String> listAdapter = new ArrayAdapter<String>( this, simple_list_item_1, listaVesti) { }; listView.setAdapter(listAdapter); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } } <file_sep>/app/src/main/java/com/example/androiddevelopment/informativnaagencijaapp/db/Vesti.java package com.example.androiddevelopment.informativnaagencijaapp.db; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; /** * Created by androiddevelopment on 20.3.18.. */ @DatabaseTable (tableName = Vesti.TABLE_NAME_VESTI) public class Vesti { public static final String TABLE_NAME_VESTI = "vesti"; public static final String FIELD_NAME_ID = "_id"; public static final String FIELD_NAME_NAZIV = "naziv"; public static final String FIELD_NAME_OPIS = "opis"; public static final String FIELD_NAME_AUTOR = "autor"; public static final String FIELD_NAME_DATUM = "datum"; public static final String FIELD_NAME_ZADOVOLJNI_KORISNICI = "zadovoljni korisnici"; public static final String FIELD_NAME_NEZADOVOLJNI_KORISNICI = "nezadovoljni korisnici"; public static final String FIELD_NAME_SLIKA = "slika"; public static final String FIELD_NAME_KOMENTARI = "komentari"; @DatabaseField(columnName = FIELD_NAME_ID, generatedId = true) private int mId; @DatabaseField(columnName = FIELD_NAME_NAZIV) private String mNaziv; @DatabaseField(columnName = FIELD_NAME_OPIS) private String mOpis; @DatabaseField(columnName = FIELD_NAME_AUTOR) private String mAutor; @DatabaseField(columnName = FIELD_NAME_DATUM) private String mDatum; @DatabaseField(columnName = FIELD_NAME_ZADOVOLJNI_KORISNICI) private String mZadovoljni; @DatabaseField(columnName = FIELD_NAME_NEZADOVOLJNI_KORISNICI) private String mNezadovoljni; @DatabaseField(columnName = FIELD_NAME_SLIKA) private String mSlika; @ForeignCollectionField(columnName = FIELD_NAME_KOMENTARI, eager = true) private ForeignCollection<Komentari> mKomentari; public Vesti() { } public int getmId() { return mId; } public void setmId(int mId) { this.mId = mId; } public String getmNaziv() { return mNaziv; } public void setmNaziv(String mNaziv) { this.mNaziv = mNaziv; } public String getmOpis() { return mOpis; } public void setmOpis(String mOpis) { this.mOpis = mOpis; } public String getmAutor() { return mAutor; } public void setmAutor(String mAutor) { this.mAutor = mAutor; } public String getmDatum() { return mDatum; } public void setmDatum(String mDatum) { this.mDatum = mDatum; } public String getmZadovoljni() { return mZadovoljni; } public void setmZadovoljni(String mZadovoljni) { this.mZadovoljni = mZadovoljni; } public String getmNezadovoljni() { return mNezadovoljni; } public void setmNezadovoljni(String mNezadovoljni) { this.mNezadovoljni = mNezadovoljni; } public String getmSlika() { return mSlika; } public void setmSlika(String mSlika) { this.mSlika = mSlika; } public ForeignCollection<Komentari> getmKomentari() { return mKomentari; } public void setmKomentari(ForeignCollection<Komentari> mKomentari) { this.mKomentari = mKomentari; } @Override public String toString() { return mNaziv; } }
816c290dac7171e8d5a0b8b1ee3c88c51f13fc6e
[ "Java" ]
3
Java
KakoDaSeZove/InformativnaAgencijaApp
5198fbf96dc415e7ec0f45458891504f428901ef
3aa7ceb026bbc3ca00d46e16efba38b5587afedc
refs/heads/master
<file_sep>package java_code; public class BasicClass { //Instance variable String var1; int cost = 0; public BasicClass(String name_,int cost) {//constructor var1 = name_; this.cost = cost;//pass the instance of object System.out.println("its working"); } // basic function int add(int a ,int b) { if(a>b) { int larger = a;// its local cant access out side if } else { int larger = b; } return a+b; } public static void main(String []args) { BasicClass my_class = new BasicClass("sss",12); } } <file_sep>package java_code; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub char ch = 's';// however "" is not good String name = "Name"; if (ch=='s') { System.out.print("test"); } else { // todo } int number = 1; int sum = 100; for (int i = 0; i < sum; i++) { number = number + 1; } System.out.println(number); } }
7d54b03f117b419424028b6a1171cedfa3fa5e93
[ "Java" ]
2
Java
saurbkumar/java_codes
dfa0191076d0f475d661b0913a804fe4f733eadb
a3f69aacdc958f944a001328ccf6479a1705bfd1
refs/heads/master
<file_sep>import json import unittest from tests.mockito import mockito from launchkey_twisted.twisted_api import JSONResponseBodyParser class JSONResponseBodyParserTest(unittest.TestCase): def tearDown(self): mockito.unstub() super(JSONResponseBodyParserTest, self).tearDown() def setUp(self): super(JSONResponseBodyParserTest, self).setUp() self._deferred = mockito.mock() self._parser = JSONResponseBodyParser(self._deferred) def test_parser_can_receive_single_piece_of_data(self): expected = {'expected': 'value'} self._parser.dataReceived(json.dumps(expected)) self._parser.connectionLost(None) mockito.verify(self._deferred).callback(expected) def test_parser_can_receive_multiple_pieces_of_data(self): expected = {'expected': 'value'} for char in json.dumps(expected): self._parser.dataReceived(char) self._parser.connectionLost(None) mockito.verify(self._deferred).callback(expected) <file_sep>import json, launchkey from . import mockito from six.moves.urllib.parse import parse_qs from twisted.internet import defer from twisted.internet.defer import Deferred from twisted.python.failure import Failure from twisted.web.http_headers import Headers from launchkey_twisted.twisted_api import JSONResponseBodyParser, JSONToURLEncodedFormDataBodyProducer, \ RequestError, JSONBodyProducer from .api_test_base import TwistedAPITestBase class TwistedAPICreateWhiteLabelUserTest(TwistedAPITestBase): """ Tests for API authorize All tests that check final result will have to process two instances of callback as the first call will return a deferred that is waiting on the it's response, a deferred, to be called by the response body processor """ def setUp(self): super(TwistedAPICreateWhiteLabelUserTest, self).setUp() self._lk_public_key = 'Expected Public Key' self._lk_time = '2015-01-01 00:00:00' self._white_label_data = {'expected': 'white label data'} mockito.when(launchkey).decrypt_AES(mockito.any(), mockito.any(), mockito.any())\ .thenReturn(json.dumps(self._white_label_data)) mockito.when(self._api).ping() \ .thenReturn(defer.succeed({'key': self._lk_public_key, 'launchkey_time': self._lk_time})) def test_calls_request_with_post_method(self): self._api.create_whitelabel_user(None) mockito.verify(self._agent).request('POST', mockito.any(), mockito.any(), mockito.any()) def test_calls_request_with_proper_uri(self): self._api.create_whitelabel_user(None) expected = '{0}/{1}/users'.format(self._api_host, self._version) mockito.verify(self._agent).request(mockito.any(), expected, mockito.any(), mockito.any()) def test_calls_request_with_correct_headers(self): expected = Headers({ 'User-Agent': ['LaunchKey Twisted Client'], 'Accept-Type': ['application/json'], 'Content-Type': ['application/json'] }) self._api.create_whitelabel_user(None) mockito.verify(self._agent).request(mockito.any(), mockito.any(), expected, mockito.any()) def test_calls_request_with_form_data_producer(self): self._api.create_whitelabel_user(None) mockito.verify(self._agent) \ .request(mockito.any(), mockito.any(), mockito.any(), mockito.any(JSONBodyProducer)) def test_signs_data_for_secret_key(self): self._api.create_whitelabel_user(None) mockito.verify(launchkey).sign_data(mockito.any(), mockito.any()) def test_encrypts_with_lk_public_key_for_secret_key(self): self._api.create_whitelabel_user(None) mockito.verify(launchkey).encrypt_RSA(self._lk_public_key, mockito.any()) def test_encrypts_correct_data_for_secret_key(self): self._api.create_whitelabel_user(None) expected = str({'secret': self._app_secret, 'stamped': self._lk_time}) actual = mockito.getCallArgument(launchkey, 'encrypt_RSA', 2) self.assertEquals(actual, expected) def test_signs_encrypted_data_with_private_key_for_secret_key(self): self._api.create_whitelabel_user(None) mockito.verify(launchkey).sign_data(self._private_key, mockito.any()) def test_signs_encrypted_data_for_secret_key(self): self._api.create_whitelabel_user(None) mockito.verify(launchkey).sign_data(mockito.any(), self._rsa_encrypted) def test_calls_request_with_correct_form_data(self): self._api.create_whitelabel_user('Expected Identifier') expected = JSONBodyProducer({ 'identifier': 'Expected Identifier', 'app_key': 'Expected Rocket Key', 'session': 'Expected Session Value', 'signature': 'Base64 Encoded RSA Signed Value', 'secret_key': 'RSA Encrypted Value' }) actual = mockito.getCallArgument(self._agent, 'request', 4) self.assertEquals(parse_qs(actual.body), parse_qs(expected.body)) def test_returns_correct_failure_for_non_json_response(self): self._response.headers = Headers({'content-type': ['text/html']}) deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, Exception, 'Unexpected Failure value. Expected {0} but was {1}'.format( Exception.__name__, deferred.result.value.__class__.__name__)) self.assertEqual(str(deferred.result.value), 'Non JSON response from API received') def test_returns_correct_failure_for_no_response_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({}) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, KeyError, 'Unexpected Failure value. Expected {0} but was {1}'.format( KeyError.__name__, deferred.result.value.__class__.__name__)) def test_returns_correct_failure_for_no_response_cipher_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'response': {}}) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, KeyError, 'Unexpected Failure value. Expected {0} but was {1}'.format( RequestError.__name__, deferred.result.value.__class__.__name__)) def test_returns_correct_failure_for_no_response_cipher_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'response': {'data': 'Expected data'}}) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, KeyError, 'Unexpected Failure value. Expected {0} but was {1}'.format( KeyError.__name__, deferred.result.value.__class__.__name__)) def test_returns_correct_failure_for_no_response_data_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected cipher that is longer than 16 chars'}}) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, KeyError, 'Unexpected Failure value. Expected {0} but was {1}'.format( RequestError.__name__, deferred.result.value.__class__.__name__)) def test_response_has_deferred_result_before_data_is_written(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self.assertIsInstance(deferred.result, Deferred) def test_response_had_deliver_body_called_with_json_body_response_parser(self): self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) mockito.verify(self._response).deliverBody(mockito.any(JSONResponseBodyParser)) def test_response_callback_value_is_not_failure_when_error_not_returned_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) self.assertNotIsInstance(deferred.result, Failure) def test_response_callback_value_is_failure_when_error_is_returned_in_response(self): deferred = self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'status_code': 500}) self.assertIsInstance(deferred.result, Failure) def test_decrypt_rsa_is_called_with_private_key_for_cipher_data(self): self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) mockito.verify(launchkey).decrypt_RSA(self._private_key, 'Expected Cipher') def test_decrypt_aes_is_called_with_proper_key(self): mockito.when(launchkey).decrypt_RSA(mockito.any(), mockito.any()).thenReturn('keykeykeyiviviviviviviviv') self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) mockito.verify(launchkey).decrypt_AES('keykeykey', mockito.any(), mockito.any()) def test_decrypt_aes_is_called_with_proper_iv(self): mockito.when(launchkey).decrypt_RSA(mockito.any(), mockito.any()).thenReturn('keykeykeyiviviviviviviviv') self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) mockito.verify(launchkey).decrypt_AES(mockito.any(), mockito.any(), 'iviviviviviviviv') def test_decrypt_aes_is_called_with_proper_package(self): self._api.create_whitelabel_user(None) self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback( {'response': {'cipher': 'Expected Cipher', 'data': 'Expected Data'}}) mockito.verify(launchkey).decrypt_AES(mockito.any(), 'Expected Data', mockito.any()) <file_sep>CHANGELOG for LaunchKey Twisted SDK =================================== v1.0.0 ------ Initial Release<file_sep>import unittest2 from nose.tools import raises from launchkey_twisted import TwistedAPI class GetUserHashTest(unittest2.TestCase): @raises(NotImplementedError) def test_raises_unimplemented(self): api = TwistedAPI(None, None, None, None) api.get_user_hash()<file_sep>LaunchKey Twisted SDK ===================== .. image:: https://travis-ci.org/LaunchKey/launchkey-python-twisted.svg?branch=master :target: https://travis-ci.org/LaunchKey/launchkey-python-twisted Overview -------- The LaunchKey Twisted library allows for asynchronous communication with the LaunchKey Engine API via a Python library and Twisted. The public interface is the same as the `synchronous SDK <https://github.com/LaunchKey/launchkey-python>`_ with the two exceptions: 1. The first argument of the init script for launchkey_twisted.TwistedAPI is a `Twisted Web Client Agent <https://twistedmatrix.com/documents/current/api/twisted.web.client.Agent.html>`_. 2. All public methods return `Twisted Deferred <https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html>`_ objects. Installation ------------ .. code-block:: bash easy_install launchkey-twisted or .. code-block:: bash pip install launchkey-twisted The following example is a functional representation of a simple session based launch request and subsequent de-orbit if applicable. *The use of polling is not suggested for production server based implementations.* .. code-block:: python import sys from twisted.python import log from twisted.internet import task, reactor, defer from twisted.web.client import Agent from launchkey_twisted import TwistedAPI, PendingResponse # agent is needed to link the SDK to the reactor as an HTTP client agent = Agent(reactor) # app_key will be provided in the dashboard app_key = 1234567890 # app_secret will be provided in the dashboard once, or a new one may be generated app_secret = "<KEY>" # private key location will will be the path to the private key file you received from the dashboard or the # private key file you used to generate the public key you uploaded to the dashboard private_key_location = "/path/to/private.key" # Your LaunchKey username username = "myusername" # Poll interval determines the delay in seconds between poll requests poll_interval = 1.0 # Log out delay determines the delay in seconds between an accepted authentication and logout log_out_delay = 3.0 # If you are having issues, set this to true for verbose logging onthe reactor debug = False def handle_auth_response(auth_request): """ Receives the auth_request identifier and begin the polling process :param auth_request: Identifier for this authentication request returned by the LaunchKey Engine API :return: Deferred """ print("Authentication request successfully initiated with identifier: {0}".format(auth_request)) return poll_for_user_repsonse(auth_request) def poll_for_user_repsonse(auth_request): """ Schedule the next poll operation. Adds callback for success and error situations :param auth_request: Identifier for this authentication request returned by the LaunchKey Engine API :return: Deferred """ print("Poll for user response in {0} seconds".format(poll_interval)) d = task.deferLater(reactor, poll_interval, api.poll_request, auth_request) d.addCallback(handle_poll_response, auth_request) d.addErrback(handle_poll_error) return d def handle_poll_error(failure): """ Trap PendingResponse errors and schedule another poll :param failure: :return: Deferred """ failure.trap(PendingResponse) return poll_for_user_repsonse(failure.value.auth_request) def handle_poll_response(response, auth_request): """ Receive the poll response and the original auth_request to validate the poll response package and detyermine the outcome. :param response: Poll response object :param auth_request: Identifier for this authentication request returned by the LaunchKey Engine API :return: Deferred """ print("User response received, checking the response package") deferred = api.is_authorized(auth_request, response['auth']) deferred.addCallback(handle_is_authorized_response, auth_request) return deferred def handle_is_authorized_response(authorized, auth_request): """ Receive the is_authorized response and schedule the logout if authorized :param authorized: Boolean value depicting the users response to the auth_request. (True: accepted | False: declined) :param auth_request: Identifier for this authentication request returned by the LaunchKey Engine API :return: Deferred """ if authorized: print("User accepted, scheduling logout for {0} seconds from now".format(log_out_delay)) deferred = task.deferLater(reactor, log_out_delay, log_user_out, auth_request) else: print("User declined") deferred = defer.succeed(True) return deferred def log_user_out(auth_request): """ End the user session for the provided authentication request :param auth_request: Identifier for this authentication request returned by the LaunchKey Engine API :return: Deferred """ print("Logging user out") deferred = api.logout(auth_request) deferred.addCallback(done) return deferred def handle_error(failure): """ Print an error :param failure: :return: """ print("Completed with error: ", failure) return failure def done(*args): """ Stop the reactor :param args: :return: """ reactor.stop() print("Reactor stopped") agent = Agent(reactor) api = TwistedAPI( agent, app_key, app_secret, open(private_key_location, "r").read() ) print("Starting authentication request for user: {0}".format(username)) auth = api.authorize(username, True) auth.addCallback(handle_auth_response) auth.addErrback(handle_error) auth.addBoth(done) if debug: log.startLogging(sys.stderr) print("Starting reactor") reactor.run() Tests ----- Mac/Linux: .. code-block:: bash python setup.py nosetests Windows: .. code-block:: bash setup.py nosetests Contributing ------------ 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request <file_sep>import json, six from six.moves.urllib.parse import urlencode from twisted.internet.protocol import Protocol from twisted.web.http_headers import Headers from twisted.internet import defer import launchkey class TwistedAPI(launchkey.API): def __init__(self, agent, app_key, app_secret, private_key, version="v1", api_host="https://api.launchkey.com", test=False): """ :param agent: Twisted web client agent :type agent: twisted.web.client.Agent :param app_key: :param app_secret: :param private_key: :param version: :param api_host: :param test: """ self._agent = agent super(TwistedAPI, self).__init__(app_key, app_secret, private_key, version, api_host, test) def get_user_hash(self): super(TwistedAPI, self).get_user_hash() def ping(self, force=False): """ Used to retrieve the API's public key and server time The key is used to encrypt data being sent to the API and the server time is used to ensure the data being sent is recent and relevant. Instead of doing a ping each time to the server, it keeps the key and server_time stored and does a comparison from the local time to appropriately adjust the value :param success_callback: Callable to be called when the ping request succeeds :param error_callback: Callable to be called when the ping request fails :param force: Boolean. True will override the cached variables and ping LaunchKey :rtype: twisted.internet.defer.Deferred """ import datetime if force or self.api_pub_key is None or self.ping_time is None: def cache_response(response): self.api_pub_key = response['key'] self.ping_time = datetime.datetime.strptime(response['launchkey_time'], "%Y-%m-%d %H:%M:%S") self.ping_difference = self.ping_time - datetime.datetime.utcnow() return response d = self._send_request(None, 'GET', 'ping') d.addCallback(cache_response) else: self.ping_time = datetime.datetime.utcnow() + self.ping_difference d = defer.succeed({"launchkey_time": str(self.ping_time)[:-7], "key": self.api_pub_key}) return d def authorize(self, username, session=True, user_push_id=False, context=None): def process_response(response): if 'auth_request' not in response: return defer.fail(RequestError(0, 'Invalid Response - No auth_request value in response')) return response['auth_request'] data = {'username': username, 'session': session, 'user_push_id': user_push_id} if context: data['context'] = context d = self._prepare_data(data) d.addCallback(self._send_request, 'POST', 'auths') d.addCallback(process_response) return d def poll_request(self, auth_request): def handle_request_error(failure, failed_auth_request): failure.trap(RequestError) if 70403 == failure.value.code: return defer.fail(PendingResponse(failed_auth_request)) return failure d = self._prepare_data({'auth_request': auth_request}) d.addCallback(self._send_request, 'GET', 'poll') d.addErrback(handle_request_error, auth_request) return d def create_whitelabel_user(self, identifier): def process_response(response): cipher = launchkey.decrypt_RSA(self.private_key, response['response']['cipher']) data = launchkey.decrypt_AES(cipher[:-16], response['response']['data'], cipher[-16:]) return json.loads(data) d = self._prepare_data({'identifier': identifier}) d.addCallback(self._send_request, 'POST', 'users', False) d.addCallback(process_response) return d def _notify(self, action, status, auth_request): def process_response(response, status): result = status if "message" in response and response['message'] == "Successfully updated" else False return defer.succeed(result) d = self._prepare_data( {'auth_request': auth_request, 'action': action, 'status': status, 'auth_request': auth_request} ) d.addCallback(self._send_request, 'PUT', 'logs') d.addCallback(process_response, status) return d def _prepare_data(self, data={}, signature=True): """ Encrypts secret with RSA key and signs :param signature: Bool representing if a signature should be added to the response :return: Dict with RSA encrypted secret_key and signature of that value """ def _post_ping(result, my_data, signature): to_encrypt = {"secret": self.app_secret, "stamped": str(result['launchkey_time'])} encrypted_secret = launchkey.encrypt_RSA(result['key'], str(to_encrypt)) my_data['secret_key'] = encrypted_secret if signature: signature = launchkey.sign_data(self.private_key, encrypted_secret) my_data['signature'] = signature my_data['app_key'] = self.app_key return my_data d = self.ping() d.addCallback(_post_ping, data, signature) return d def _send_request(self, data, method, endpoint, form_data=True): uri = self.API_HOST + endpoint headers = { 'User-Agent': ['LaunchKey Twisted Client'], 'Accept-Type': ['application/json'] } if data is None: bodyProducer = NoneBodyProducer() elif 'GET' == method: uri = '%s?%s' % (uri, urlencode(data, doseq=True)) bodyProducer = NoneBodyProducer() elif form_data: headers['Content-Type'] = ['application/x-www-form-urlencoded'] bodyProducer = JSONToURLEncodedFormDataBodyProducer(data) else: headers['Content-Type'] = ['application/json'] bodyProducer = JSONBodyProducer(data) deferred_request = self._agent.request( six.b(method), six.b(uri), Headers(headers), bodyProducer ) def _process_response(response): content_type = response.headers.getRawHeaders('content-type') if content_type is None or not content_type.pop().startswith('application/json'): return defer.fail(Exception('Non JSON response from API received')) d = defer.Deferred() response.deliverBody(JSONResponseBodyParser(d)) return d def _check_for_error(response): status_code = int(response.get('status_code', 0)) if status_code >= 300: return defer.fail(RequestError( response.get('message_code', response.get('status_code')), response.get('message', 'Unknown request error') )) else: return response deferred_request.addCallback(_process_response) deferred_request.addCallback(_check_for_error) return deferred_request class PendingResponse(BaseException): def __init__(self, auth_request, *args, **kwargs): self.auth_request = auth_request super(PendingResponse, self).__init__(*args, **kwargs) class RequestError(BaseException): def __init__(self, code, message, *args, **kwargs): self.code = code self.message = message super(RequestError, self).__init__(*args, **kwargs) def __str__(self): return '[%s] %s' % (self.code, self.message) from zope.interface import implementer from twisted.web.iweb import IBodyProducer from twisted.internet.defer import succeed @implementer(IBodyProducer) class JSONBodyProducer(object): length = 0 def __init__(self, o): self.body = json.dumps(o) self.length = len(self.body) def startProducing(self, consumer): consumer.write(self.body) return succeed(None) def pauseProducing(self): pass def stopProducing(self): pass @implementer(IBodyProducer) class JSONToURLEncodedFormDataBodyProducer(object): def __init__(self, o): self.body = urlencode(o, doseq=True) self.length = len(self.body) def startProducing(self, consumer): consumer.write(self.body) return succeed(None) def pauseProducing(self): pass def stopProducing(self): pass @implementer(IBodyProducer) class NoneBodyProducer(object): def __init__(self): self.length = 0 def startProducing(self, consumer): return succeed(None) def pauseProducing(self): pass def stopProducing(self): pass class JSONResponseBodyParser(Protocol): def __init__(self, finished): self.finished = finished self.data = '' def dataReceived(self, bytes): self.data += bytes def connectionLost(self, reason): o = json.loads(self.data) self.finished.callback(o) <file_sep>import launchkey from . import mockito from six.moves.urllib.parse import parse_qs from twisted.internet import defer from twisted.internet.defer import Deferred from twisted.python.failure import Failure from twisted.web.http_headers import Headers from launchkey_twisted.twisted_api import JSONResponseBodyParser, JSONToURLEncodedFormDataBodyProducer, \ RequestError from .api_test_base import TwistedAPITestBase class TwistedAPIAuthorizeTest(TwistedAPITestBase): """ Tests for API authorize All tests that check final result will have to process two instances of callback as the first call will return a deferred that is waiting on the it's response, a deferred, to be called by the response body processor """ def setUp(self): super(TwistedAPIAuthorizeTest, self).setUp() self._lk_public_key = 'Expected Public Key' self._lk_time = '2015-01-01 00:00:00' mockito.when(self._api).ping() \ .thenReturn(defer.succeed({'key': self._lk_public_key, 'launchkey_time': self._lk_time})) def test_calls_request_with_post_method(self): self._api.authorize('Expected Username') mockito.verify(self._agent).request('POST', mockito.any(), mockito.any(), mockito.any()) def test_calls_request_with_proper_uri(self): self._api.authorize('Expected Username') expected = '{0}/{1}/auths'.format(self._api_host, self._version) mockito.verify(self._agent).request(mockito.any(), expected, mockito.any(), mockito.any()) def test_calls_request_with_correct_headers(self): expected = Headers({ 'User-Agent': ['LaunchKey Twisted Client'], 'Accept-Type': ['application/json'], 'Content-Type': ['application/x-www-form-urlencoded'] }) self._api.authorize('Expected Username') mockito.verify(self._agent).request(mockito.any(), mockito.any(), expected, mockito.any()) def test_calls_request_with_form_data_producer(self): self._api.authorize('Expected Username') mockito.verify(self._agent) \ .request(mockito.any(), mockito.any(), mockito.any(), mockito.any(JSONToURLEncodedFormDataBodyProducer)) def test_signs_data_for_secret_key(self): self._api.authorize('Expected Username') mockito.verify(launchkey).sign_data(mockito.any(), mockito.any()) def test_encrypts_with_lk_public_key_for_secret_key(self): self._api.authorize('Expected Username') mockito.verify(launchkey).encrypt_RSA(self._lk_public_key, mockito.any()) def test_encrypts_correct_data_for_secret_key(self): self._api.authorize('Expected Username') expected = str({'secret': self._app_secret, 'stamped': self._lk_time}) actual = mockito.getCallArgument(launchkey, 'encrypt_RSA', 2) self.assertEquals(actual, expected) def test_signs_encrypted_data_with_private_key_for_secret_key(self): self._api.authorize('Expected Username') mockito.verify(launchkey).sign_data(self._private_key, mockito.any()) def test_signs_encrypted_data_for_secret_key(self): self._api.authorize('Expected Username') mockito.verify(launchkey).sign_data(mockito.any(), self._rsa_encrypted) def test_calls_request_with_correct_form_data(self): self._api.authorize('Expected Username', 'Expected Session Value', 'Expected User Push ID Value') expected = JSONToURLEncodedFormDataBodyProducer({ 'username': 'Expected Username', 'user_push_id': 'Expected User Push ID Value', 'app_key': 'Expected Rocket Key', 'session': 'Expected Session Value', 'signature': 'Base64 Encoded RSA Signed Value', 'secret_key': 'RSA Encrypted Value' }) actual = mockito.getCallArgument(self._agent, 'request', 4) self.assertEquals(parse_qs(actual.body), parse_qs(expected.body)) def test_calls_request_with_context_in_form_data_if_priovided(self): self._api.authorize('Expected Username', 'Expected Session Value', 'Expected User Push ID Value', 'Expected Context') expected = JSONToURLEncodedFormDataBodyProducer({ 'username': 'Expected Username', 'user_push_id': 'Expected User Push ID Value', 'app_key': 'Expected Rocket Key', 'session': 'Expected Session Value', 'signature': 'Base64 Encoded RSA Signed Value', 'secret_key': 'RSA Encrypted Value', 'context': 'Expected Context' }) actual = mockito.getCallArgument(self._agent, 'request', 4) self.assertEquals(parse_qs(actual.body), parse_qs(expected.body)) def test_returns_correct_failure_for_non_json_response(self): self._response.headers = Headers({'content-type': ['text/html']}) deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, Exception, 'Unexpected Failure value. Expected Expected {0} but was {1}'.format( Exception.__name__, deferred.result.value.__class__.__name__)) self.assertEqual(str(deferred.result.value), 'Non JSON response from API received') def test_returns_correct_failure_for_no_auth_request_response(self): deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({}) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, RequestError, 'Unexpected Failure value. Expected {0} but was {1}'.format( RequestError.__name__, deferred.result.value.__class__.__name__)) self.assertEqual(str(deferred.result.value), '[0] Invalid Response - No auth_request value in response') def test_response_has_deferred_result_before_data_is_written(self): deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self.assertIsInstance(deferred.result, Deferred) def test_response_had_deliver_body_called_with_json_body_response_parser(self): self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'auth_request': 'Expected Auth Request ID'}) mockito.verify(self._response).deliverBody(mockito.any(JSONResponseBodyParser)) def test_response_callback_value_is_not_failure_when_error_not_returned_in_response(self): deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'auth_request': 'Expected Auth Request ID'}) self.assertNotIsInstance(deferred.result, Failure) def test_response_callback_value_is_failure_when_error_is_returned_in_response(self): deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'status_code': 500}) self.assertIsInstance(deferred.result, Failure) def test_final_value_is_body_parsed_value(self): expected = 'Expected Auth Request ID' deferred = self._api.authorize('Expected Username') self._agent_request_deferred.callback(self._response) self._agent_request_deferred.result.callback({'auth_request': expected}) self.assertEquals(deferred.result, expected) <file_sep>import unittest2, launchkey, launchkey_twisted from . import mockito from twisted.internet.defer import Deferred from twisted.web.http_headers import Headers class TwistedAPITestBase(unittest2.TestCase): def tearDown(self): super(TwistedAPITestBase, self).tearDown() mockito.unstub() def setUp(self): super(TwistedAPITestBase, self).setUp() self._agent = mockito.mock() self._agent_request_deferred = Deferred() mockito.when(self._agent) \ .request(mockito.any(), mockito.any(), mockito.any(), mockito.any()) \ .thenReturn(self._agent_request_deferred) self._response = mockito.mock() self._response.headers = Headers({'content-type': ['application/json']}) self._app_key = 'Expected Rocket Key' self._app_secret = 'Expected secret key' self._private_key = 'Expected private key' self._version = 'Expected version' self._api_host = 'Expected API Host' self._api = launchkey_twisted.TwistedAPI( self._agent, self._app_key, self._app_secret, self._private_key, self._version, self._api_host ) self._rsa_encrypted = 'RSA Encrypted Value' mockito.when(launchkey).encrypt_RSA(mockito.any(), mockito.any()).thenReturn(self._rsa_encrypted) self._rsa_decrypted = 'RSA Decrypted Value' mockito.when(launchkey).decrypt_RSA(mockito.any(), mockito.any()).thenReturn(self._rsa_decrypted) self._rsa_signed_and_encoded = 'Base64 Encoded RSA Signed Value' mockito.when(launchkey)\ .sign_data(mockito.any(), mockito.any())\ .thenReturn(self._rsa_signed_and_encoded) mockito.when(launchkey)\ .sign_data(mockito.any(), mockito.any(), encoded=True)\ .thenReturn(self._rsa_signed_and_encoded) mockito.when(launchkey)\ .sign_data(mockito.any(), mockito.any(), True)\ .thenReturn(self._rsa_signed_and_encoded) self._rsa_signed_and_raw = 'Raw RSA Signed Value' mockito.when(launchkey)\ .sign_data(mockito.any(), mockito.any(), False)\ .thenReturn(self._rsa_signed_and_raw) mockito.when(launchkey)\ .sign_data(mockito.any(), mockito.any(), encoded=False)\ .thenReturn(self._rsa_signed_and_raw) self._aes_decrypted = 'AES Decrypted Value' mockito.when(launchkey)\ .decrypt_AES(mockito.any(), mockito.any(), mockito.any())\ .thenReturn(self._aes_decrypted) mockito.when(launchkey)\ .verify_sign(mockito.any(), mockito.any(), mockito.any())\ .thenReturn(True) <file_sep>from . import mockito from .mockito.mock_registry import mock_registry from six.moves import filter from twisted.python import log # turn off erroneous error logging for tests log.startLogging(open('/dev/null')) def __get_call_argument(mock, method_name, param=1, invocation=1): if isinstance(mock, mockito.mock): "First parameter must be instance on mockito.mock" else: mock = mock_registry.mock_for(mock) assert isinstance(mock, mockito.mock), 'Mock parameter must be either a mock or the name of a mocked class or module' method_invocations = list(filter(lambda item: method_name == item.method_name, mock.invocations)) count = len(method_invocations) assert count > 0, 'Method {} had no invocations on this mock'.format(method_name) assert count >= invocation, 'Method {} dit not have the required {} invocation(s)'.format(method_name, invocation) invocation = method_invocations[invocation - 1] if isinstance(param, int): assert param <= len(invocation.params), 'Invocation {} of method {} was not passed at least {} unnamed aguments'\ .format(invocation, method_name, param) return invocation.params[param-1] else: assert param in invocation.named_params,\ 'Invocation {} of method {} was not poassed a named param of {}'\ .format(invocation, method_name, param) return invocation.named_params[param] mockito.getCallArgument = __get_call_argument <file_sep>import json import unittest2 from . import mockito from six.moves.urllib.parse import parse_qs from twisted.internet.defer import Deferred from launchkey_twisted.twisted_api import JSONBodyProducer, JSONToURLEncodedFormDataBodyProducer, NoneBodyProducer class ProducerTestBase(unittest2.TestCase): def tearDown(self): mockito.unstub() super(ProducerTestBase, self).tearDown() def setUp(self): super(ProducerTestBase, self).setUp() self._consumer = mockito.mock() class JSONBodyProducerTest(ProducerTestBase): def test_start_producing_writes_json_value_of_init_object(self): o = {'expected': 'value'} producer = JSONBodyProducer(o) producer.startProducing(self._consumer) mockito.verify(self._consumer).write(json.dumps(o)) def test_start_producing_returns_deferred_whos_callback_is_triggered_and_result_is_none(self): producer = JSONBodyProducer({}) deferred = producer.startProducing(self._consumer) self.assertIsInstance(deferred, Deferred) self.assertTrue(deferred.called) self.assertIsNone(deferred.result) def test_pause_producing_returns_none(self): producer = JSONBodyProducer({}) actual = producer.pauseProducing() self.assertIsNone(actual) def test_stop_producing_returns_none(self): producer = JSONBodyProducer({}) actual = producer.stopProducing() self.assertIsNone(actual) class JSONToURLEncodedFormDataBodyProducerTest(ProducerTestBase): def test_start_producing_writes_json_value_of_init_object(self): data = {'expected': 'value', 'other expected': 'value'} producer = JSONToURLEncodedFormDataBodyProducer(data) producer.startProducing(self._consumer) actual = mockito.getCallArgument(self._consumer, 'write') self.assertEquals(parse_qs(actual), {'expected': ['value'], 'other expected': ['value']}) def test_start_producing_returns_deferred_whos_callback_is_triggered_and_result_is_none(self): producer = JSONToURLEncodedFormDataBodyProducer({}) deferred = producer.startProducing(self._consumer) self.assertIsInstance(deferred, Deferred) self.assertTrue(deferred.called) self.assertIsNone(deferred.result) def test_pause_producing_returns_none(self): producer = JSONToURLEncodedFormDataBodyProducer({}) actual = producer.pauseProducing() self.assertIsNone(actual) def test_stop_producing_returns_none(self): producer = JSONToURLEncodedFormDataBodyProducer({}) actual = producer.stopProducing() self.assertIsNone(actual) class NoneBodyProducerTest(ProducerTestBase): def test_start_producing_writes_json_value_of_init_object(self): producer = NoneBodyProducer() producer.startProducing(self._consumer) mockito.verify(self._consumer, mockito.never).write(mockito.any()) def test_start_producing_returns_deferred_whos_callback_is_triggered_and_result_is_none(self): producer = NoneBodyProducer() deferred = producer.startProducing(self._consumer) self.assertIsInstance(deferred, Deferred) self.assertTrue(deferred.called) self.assertIsNone(deferred.result) def test_pause_producing_returns_none(self): producer = NoneBodyProducer() actual = producer.pauseProducing() self.assertIsNone(actual) def test_stop_producing_returns_none(self): producer = NoneBodyProducer() actual = producer.stopProducing() self.assertIsNone(actual) <file_sep>import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() def get_requires_from_txt(filename): requires = [] with open(os.path.join(here, filename)) as f: for line in f: if not line.startswith('--'): requires.append(line.replace('\n', '')) return requires setup(name='launchkey-twisted', version='1.1.0', description='LaunchKey Asynchronous SDK for Twisted', long_description=README, classifiers=[ "Programming Language :: Python", "Framework :: Twisted", "Intended Audience :: Developers", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], author='LaunchKey', author_email='<EMAIL>', url='https://launchkey.com', license='MIT', packages=find_packages(), include_package_data=False, test_suite='nose.collector', install_requires=['six', 'twisted', 'pyOpenSSL', 'service_identity', 'launchkey-python'], tests_require=['unittest2', 'nose', 'coverage'], ) <file_sep>from . import mockito from twisted.internet.defer import Deferred from twisted.python.failure import Failure from twisted.web.http_headers import Headers from launchkey_twisted.twisted_api import NoneBodyProducer, JSONResponseBodyParser from .api_test_base import TwistedAPITestBase class TwistedAPIPingTest(TwistedAPITestBase): """ Tests for API ping All tests that check fional result will have to process two instancess of callback as the first call will return a deferred that is waiting on the it's response, a deferred, to be called by the response body processor """ def test_calls_request_with_get_method(self): self._api.ping() mockito.verify(self._agent).request('GET', mockito.any(), mockito.any(), mockito.any()) def test_calls_request_with_proper_uri(self): self._api.ping() expected = '{0}/{1}/ping'.format(self._api_host, self._version) mockito.verify(self._agent).request(mockito.any(), expected, mockito.any(), mockito.any()) def test_calls_request_with_correct_headers(self): expected = Headers({ 'User-Agent': ['LaunchKey Twisted Client'], 'Accept-Type': ['application/json'] }) self._api.ping() mockito.verify(self._agent).request(mockito.any(), mockito.any(), expected, mockito.any()) def test_calls_request_with_none_producer(self): self._api.ping() mockito.verify(self._agent).request(mockito.any(), mockito.any(), mockito.any(), mockito.any(NoneBodyProducer)) def test_returns_expected_deferred(self): actual = self._api.ping() self.assertIs(actual, self._agent_request_deferred) def test_raises_correct_exception_for_non_json_response(self): self._response.headers = Headers({'content-type': ['text/html']}) deferred = self._api.ping() deferred.callback(self._response) self.assertIsInstance(deferred.result, Failure, 'Unexpected Deferred result. Expected {0} but was {1}'.format( Failure.__name__, deferred.result.__class__.__name__)) self.assertIsInstance(deferred.result.value, Exception, 'Unexpected Failure value. Expected {0} but was {1}'.format( Exception.__name__, deferred.result.value.__class__.__name__)) self.assertEqual(str(deferred.result.value), 'Non JSON response from API received') def test_response_has_deferred_result_before_data_is_written(self): deferred = self._api.ping() deferred.callback(self._response) self.assertIsInstance(deferred.result, Deferred) def test_response_had_deliver_body_called_with_json_body_response_parser_using_request_deferred_result( self): deferred = self._api.ping() deferred.callback(self._response) mockito.verify(self._response).deliverBody(mockito.any(JSONResponseBodyParser)) body_parser = mockito.getCallArgument(self._response, 'deliverBody') self.assertIs(body_parser.finished, self._agent_request_deferred.result) def test_response_callback_value_is_not_failure_when_error_not_returned_in_response(self): deferred = self._api.ping() deferred.callback(self._response) deferred.result.callback({'key': '', 'launchkey_time': '2015-01-01 00:00:00'}) self.assertNotIsInstance(deferred.result, Failure) def test_response_callback_value_is_failure_when_error_is_returned_in_response(self): deferred = self._api.ping() deferred.callback(self._response) deferred.result.callback({'status_code': 500}) self.assertIsInstance(deferred.result, Failure) def test_final_value_is_body_parsed_value(self): expected = {'key': 'expected', 'launchkey_time': '2015-01-01 00:00:00'} deferred = self._api.ping() deferred.callback(self._response) deferred.result.callback(expected) self.assertEquals(deferred.result, expected) def test_only_makes_one_agent_request_for_two_pings_with_no_force(self): expected = {'key': 'expected', 'launchkey_time': '2015-01-01 00:00:00'} deferred = self._api.ping() deferred.callback(self._response) deferred.result.callback(expected) self._api.ping() mockito.verify(self._agent).request(mockito.any(), mockito.any(), mockito.any(), mockito.any()) def test_makes_two_agent_request_for_two_pings_with_force(self): expected = {'key': 'expected', 'launchkey_time': '2015-01-01 00:00:00'} deferred = self._api.ping(True) deferred.callback(self._response) deferred.result.callback(expected) self._api.ping(True) mockito.verify(self._agent, times=2).request(mockito.any(), mockito.any(), mockito.any(), mockito.any()) def test_returns_deferred_with_result_having_same_value_on_second_call_for_two_pings_with_no_force(self): expected = {'key': 'expected', 'launchkey_time': '2015-01-01 00:00:00'} deferred = self._api.ping() deferred.callback(self._response) deferred.result.callback(expected) deferred = self._api.ping() self.assertIsInstance(deferred, Deferred) self.assertEquals(deferred.result, expected) <file_sep>from .twisted_api import TwistedAPI from .twisted_api import PendingResponse from .twisted_api import RequestError __all__ = ('TwistedAPI', 'PendingResponse', 'RequestError')
62d69913aef6091b71f794ec8916a9ed99e773ee
[ "Markdown", "Python", "reStructuredText" ]
13
Python
LaunchKey/launchkey-python-twisted
9257da50b14146a2a773a8562a415517b0b3bbbb
c7448b43ba7f71bc8514e9aa780e268a0ccd26ba
refs/heads/master
<repo_name>lumyus/todo-android<file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todoedit/EditPresenter.kt package net.xaethos.todofrontend.singleactivity.todoedit import android.support.v4.view.GravityCompat import android.view.Gravity import android.view.View import android.widget.EditText import com.jakewharton.rxbinding.widget.textChanges import net.xaethos.todofrontend.singleactivity.MainActivity import net.xaethos.todofrontend.singleactivity.NavigationPresenter import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.util.LayoutAnchor import net.xaethos.todofrontend.singleactivity.util.ViewPresenter import net.xaethos.todofrontend.singleactivity.util.bindView import net.xaethos.todofrontend.singleactivity.util.textViewText import rx.Observable import javax.inject.Inject /** * View presenter: UI controls and events */ class EditPresenter(override val root: View) : ViewPresenter, EditMediator.Presenter { @Inject lateinit var navPresenter: NavigationPresenter private val titleField: EditText by bindView(R.id.todo_title) private val detailsField: EditText by bindView(R.id.todo_detail) override var appBarTitle: CharSequence? get() = navPresenter.appBarTitle set(value) { navPresenter.appBarTitle = value } override var fabEnabled: Boolean get() = navPresenter.fabEnabled set(value) { configureFab(enabled = value) } override val fabClicks: Observable<Unit> get() { configureFab(enabled = true) return navPresenter.fabClicks } private fun configureFab(enabled: Boolean) { navPresenter.fabEnabled = enabled navPresenter.configureFab { setImageResource(R.drawable.ic_done_white_24dp) gravity = Gravity.CENTER_VERTICAL or GravityCompat.START anchor = LayoutAnchor(navPresenter.container.id, Gravity.TOP or GravityCompat.END) } } override var titleText by textViewText(titleField) override var detailsText by textViewText(detailsField) override val titleChanges: Observable<CharSequence> get() = titleField.textChanges().takeUntil(detaches) override val detailsChanges: Observable<CharSequence> get() = detailsField.textChanges().takeUntil(detaches) @Inject override lateinit var detaches: Observable<Unit> @Inject fun setUp(activity: MainActivity) { navPresenter.actionBar?.setDisplayHomeAsUpEnabled(true) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/NavigationMediator.kt package net.xaethos.todofrontend.singleactivity import android.os.Bundle import com.bluelinelabs.conductor.Conductor import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.singleactivity.tododetail.DetailController import net.xaethos.todofrontend.singleactivity.tododetail.DetailMediator import net.xaethos.todofrontend.singleactivity.todoedit.EditController import net.xaethos.todofrontend.singleactivity.todoedit.EditMediator import net.xaethos.todofrontend.singleactivity.todolist.ListController import net.xaethos.todofrontend.singleactivity.todolist.ListMediator import net.xaethos.todofrontend.singleactivity.util.pushController import javax.inject.Inject @ActivityScope class NavigationMediator @Inject constructor() : ListMediator.Navigator, DetailMediator.Navigator, EditMediator.Navigator { lateinit var router: Router fun bindPresenter(activity: MainActivity, presenter: NavigationPresenter, savedState: Bundle?) { router = Conductor.attachRouter(activity, presenter.container, savedState) if (!router.hasRootController()) { router.setRoot(RouterTransaction.with(ListController())) } } fun handleBack(): Boolean = router.handleBack() override fun pushDetailController(todo: Todo) { router.pushController(DetailController.create(todo.uri)) } override fun pushCreateController() { router.pushController(EditController.create()) } override fun pushEditController(todo: Todo) { router.pushController(EditController.create(todo.uri)) } override fun navigateBack() { router.popCurrentController() } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/tododetail/DetailController.kt package net.xaethos.todofrontend.singleactivity.tododetail import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.rxlifecycle.RxController import dagger.Subcomponent import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.component import net.xaethos.todofrontend.singleactivity.util.DataBundle import net.xaethos.todofrontend.singleactivity.util.RxControllerModule /** * Controller: lifecycle, navigation and dependency injection */ class DetailController(val args: Arguments) : RxController(args.bundle) { @Suppress("unused") constructor(bundle: Bundle) : this(Arguments(bundle)) companion object { fun create(uri: String): DetailController { val args = DetailController.Arguments(Bundle()).apply { this.uri = uri } return DetailController(args) } } init { setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View = inflater.inflate(R.layout.presenter_todo_detail, container, false) override fun onAttach(view: View) { val component = buildComponent() val presenter = component.inject(DetailPresenter(view)) component.mediator().bindPresenter(presenter, args.uri!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> router.popCurrentController() else -> return super.onOptionsItemSelected(item) } return true } fun buildComponent() = activity.component.detailComponent(RxControllerModule(this)) class Arguments(bundle: Bundle) : DataBundle(bundle) { var uri by bundleString } @ControllerScope @Subcomponent(modules = arrayOf(RxControllerModule::class)) interface Component { fun inject(viewHolder: DetailPresenter): DetailPresenter fun mediator(): DetailMediator } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/tododetail/DetailMediator.kt package net.xaethos.todofrontend.singleactivity.tododetail import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.datasource.TodoDataSource import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.util.ViewPresenter import rx.Observable import javax.inject.Inject /** * Mediator: uses business logic to binding data to views */ @ControllerScope class DetailMediator @Inject constructor(val navigator: Navigator) { @Inject lateinit var dataSource: TodoDataSource fun bindPresenter(presenter: Presenter, uri: String) { dataSource[uri].takeUntil(presenter.detaches).subscribe { todo -> presenter.titleText = todo.title presenter.detailsText = todo.details presenter.fabClicks.subscribe { navigator.pushEditController(todo) } } } interface Navigator { fun pushEditController(todo: Todo) } interface Presenter : ViewPresenter { var titleText: CharSequence? var detailsText: CharSequence? val fabClicks: Observable<Unit> } } <file_sep>/datasource/src/test/java/net/xaethos/todofrontend/datasource/test/Matchers.kt package net.xaethos.todofrontend.datasource.test import com.natpryce.hamkrest.MatchResult import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import rx.Observable import rx.observers.TestSubscriber import java.util.concurrent.TimeUnit infix fun <T> T.shouldEqual(expected: T) { assertThat(this, equalTo(expected)) } inline fun <T> Observable<T>.withTestSubscriber(body: (TestSubscriber<T>) -> Unit) { val testSubscriber = TestSubscriber<T>() subscribe(testSubscriber) body(testSubscriber) } fun <T> emits(vararg expected: T) = object : Matcher<Observable<T>> { override val description = "was observable that emits: $expected" override fun invoke(actual: Observable<T>): MatchResult { val testSubscriber = TestSubscriber<T>() actual.subscribe(testSubscriber) testSubscriber.awaitValueCount(expected.size, 300, TimeUnit.MILLISECONDS) return nextEventsMatchResult(expected, testSubscriber.onNextEvents) } } fun <T> onNextEvents(vararg expected: T): Matcher<TestSubscriber<T>> = NextEventsMatcher(expected) private class NextEventsMatcher<T>(val expected: Array<out T>) : Matcher<TestSubscriber<T>> { override val description = "was TestSubscriber with onNext events: $expected" override fun invoke(actual: TestSubscriber<T>) = nextEventsMatchResult(expected, actual.onNextEvents) } private fun <T> nextEventsMatchResult(expected: Array<out T>, actual: List<T>): MatchResult { if (expected.size != actual.size) { return MatchResult.Mismatch("${expected.size} events instead of ${actual.size}") } (0..expected.size - 1).forEach { index -> if (expected[index] != actual[index]) { return MatchResult.Mismatch("event $index was $actual") } } return MatchResult.Match } <file_sep>/app-traditional/src/main/java/net/xaethos/todofrontend/SingletonComponent.kt package net.xaethos.todofrontend import dagger.Component import net.xaethos.todofrontend.datasource.DataModule import javax.inject.Singleton @Singleton @Component(modules = arrayOf(DataModule::class)) interface SingletonComponent { fun inject(activity: TodoListActivity) fun inject(fragment: TodoDetailFragment) } val singletonComponent: SingletonComponent = DaggerSingletonComponent.create() <file_sep>/app-traditional/src/main/java/net/xaethos/todofrontend/ToDoDetailFragment.kt package net.xaethos.todofrontend import android.os.Bundle import android.support.design.widget.CollapsingToolbarLayout import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import net.xaethos.todofrontend.datasource.TodoDataSource import rx.subscriptions.Subscriptions import javax.inject.Inject /** * A fragment representing a single to do detail screen. * This fragment is either contained in a [TodoListActivity] * in two-pane mode (on tablets) or a [TodoDetailActivity] * on handsets. */ class TodoDetailFragment : Fragment() { @Inject lateinit var dataSource: TodoDataSource private var appBarLayout: CollapsingToolbarLayout? = null private var subscription = Subscriptions.unsubscribed() private val itemId: String? get() = arguments.getString(ARG_ITEM_ID) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) appBarLayout = activity.findViewById(R.id.toolbar_layout) as CollapsingToolbarLayout? singletonComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.todo_detail, container, false) itemId?.let { itemId -> subscription = dataSource[itemId].subscribe { item -> appBarLayout?.title = item.title // Show the dummy content as text in a TextView. val detailView = rootView.findViewById(R.id.todo_detail) as TextView detailView.text = item?.details } } return rootView } override fun onDestroyView() { subscription.unsubscribe() super.onDestroyView() } companion object { /** * The fragment argument representing the item ID that this fragment * represents. */ val ARG_ITEM_ID = "item_id" } } <file_sep>/datasource/src/main/java/net/xaethos/todofrontend/datasource/DataModule.kt package net.xaethos.todofrontend.datasource import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DataModule { @Provides @Singleton fun dataSource(): TodoDataSource = LocalSource() } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/DependencyInjection.kt package net.xaethos.todofrontend.singleactivity import android.app.Activity import dagger.Component import net.xaethos.todofrontend.datasource.DataModule import javax.inject.Scope import javax.inject.Singleton import kotlin.annotation.AnnotationRetention.RUNTIME @Scope @Retention(RUNTIME) annotation class ActivityScope @Scope @Retention(RUNTIME) annotation class ControllerScope @Singleton @Component(modules = arrayOf(DataModule::class)) interface SingletonComponent { fun activityComponent(module: MainActivity.Module): MainActivity.Component } val singletonComponent: SingletonComponent = DaggerSingletonComponent.create() val Activity.component: MainActivity.Component get() = if (this is MainActivity) dependencySource else throw IllegalStateException("Somebody set us up the bomb") <file_sep>/app-singleactivity/src/androidTest/java/net/xaethos/todofrontend/singleactivity/features/HappyPathFeature.kt package net.xaethos.todofrontend.singleactivity.features import android.support.test.espresso.Espresso.onView import android.support.test.espresso.Espresso.pressBack import android.support.test.espresso.action.ViewActions import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.action.ViewActions.typeText import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.contrib.RecyclerViewActions import android.support.test.espresso.matcher.ViewMatchers.hasDescendant import android.support.test.espresso.matcher.ViewMatchers.hasSibling import android.support.test.espresso.matcher.ViewMatchers.isDisplayed import android.support.test.espresso.matcher.ViewMatchers.isNotChecked import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.espresso.matcher.ViewMatchers.withText import android.support.test.runner.AndroidJUnit4 import android.support.v7.widget.RecyclerView import android.test.suitebuilder.annotation.LargeTest import net.xaethos.todofrontend.singleactivity.MainActivity import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.test.activityTestRule import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.containsString import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class HappyPathFeature { @get:Rule var activityRule = activityTestRule<MainActivity>() @Test fun seeTodoDetails() { // Scroll down list and tap on to do onView(withId(R.id.todo_list)) .perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(1)) onView(withText("Do stuff")).perform(click()) // Check that the details are shown. onView(withText("I have stuff to do")).check(matches(isDisplayed())) // Go back to the list pressBack() onView(withId(R.id.todo_list)).check(matches(isDisplayed())) } @Test fun createTodo() { // Fabulous tap onView(withId(R.id.fab)).perform(click()) // Check that the create view is shown. // onView(withText("New todo")).check(matches(isDisplayed())) // Fill in form and submit onView(withId(R.id.todo_title)).perform(typeText("Test creating todo")) onView(withId(R.id.todo_detail)).perform(typeText("And then we're peachy")) onView(withId(R.id.fab)).perform(click()) // We should be back in the list, with our new to do displayed onView(withId(R.id.todo_list)).check(matches(isDisplayed())) onView(withText("Test creating todo")).check(matches(isDisplayed())) // Since we tested creating a to do, mark it as done onView(allOf(isNotChecked(), hasSibling(hasDescendant(withText("Test creating todo"))))) .perform(click()) } @Test fun editTodo() { // Scroll down list and tap on to do onView(withId(R.id.todo_list)) .perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(1)) onView(withText("Do stuff")).perform(click()) // Check that the details are shown. onView(withText(containsString("I have stuff to do"))).check(matches(isDisplayed())) // Fabulous tap onView(withId(R.id.fab)).perform(click()) // Check that the edit view is shown. // onView(withText("Edit todo")).check(matches(isDisplayed())) // Fill in form and submit onView(withId(R.id.todo_detail)).perform(ViewActions.replaceText("I have stuff to test")) onView(withId(R.id.fab)).perform(click()) // We should be back in the detail view, with our updates onView(withText("I have stuff to test")).check(matches(isDisplayed())) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/ViewPresenters.kt package net.xaethos.todofrontend.singleactivity.util import android.support.v7.widget.RecyclerView import android.view.View import rx.Observable import rx.lang.kotlin.PublishSubject interface ViewPresenter { val root: View val detaches: Observable<Unit> } abstract class ViewHolderPresenter(override val root: View) : RecyclerView.ViewHolder(root), ViewPresenter { abstract val controllerDetaches: Observable<Unit> override val detaches: Observable<Unit> get() = controllerDetaches.mergeWith(recycleSubject.asObservable()).first() private val recycleSubject = PublishSubject<Unit>() fun onRecycle() = recycleSubject.onNext(Unit) } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/DataBundle.kt package net.xaethos.todofrontend.singleactivity.util import android.os.Bundle import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty abstract class DataBundle(val bundle: Bundle) { companion object { val bundleString = object : ReadWriteProperty<DataBundle, String?> { override fun getValue(thisRef: DataBundle, property: KProperty<*>): String? { return thisRef.bundle.getString(property.name) } override fun setValue(thisRef: DataBundle, property: KProperty<*>, value: String?) { thisRef.bundle.putString(property.name, value) } } } } <file_sep>/app-traditional/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { compileSdkVersion dep.compileSdk buildToolsVersion dep.buildTools defaultConfig { applicationId "net.xaethos.todofrontend.traditional" minSdkVersion dep.minSdk targetSdkVersion dep.targetSdk versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } kapt { generateStubs = true } dependencies { compile project(':datasource') compile "org.jetbrains.kotlin:kotlin-stdlib:$dep.kotlin" // Android Support compile("com.android.support:appcompat-v7:$dep.support", "com.android.support:support-v4:$dep.support", "com.android.support:recyclerview-v7:$dep.support", "com.android.support:design:$dep.support") // Dagger provided 'javax.annotation:jsr250-api:1.0' kapt "com.google.dagger:dagger-compiler:$dep.dagger" compile "com.google.dagger:dagger:$dep.dagger" testCompile "junit:junit:$dep.junit" // Instrumentation androidTestCompile("com.android.support:appcompat-v7:$dep.support", "com.android.support:support-v4:$dep.support", "com.android.support:recyclerview-v7:$dep.support", "com.android.support:design:$dep.support") androidTestCompile "com.android.support:support-annotations:$dep.support" androidTestCompile "com.android.support.test:runner:$dep.supportTest" androidTestCompile "com.android.support.test:rules:$dep.supportTest" androidTestCompile "com.android.support.test.espresso:espresso-core:$dep.espresso" androidTestCompile "com.android.support.test.espresso:espresso-contrib:$dep.espresso" androidTestCompile "com.android.support.test.espresso:espresso-idling-resource:$dep.espresso" androidTestCompile 'org.hamcrest:hamcrest-library:1.3' } <file_sep>/settings.gradle include ':app-traditional', ':datasource', ':app-singleactivity' <file_sep>/datasource/src/main/java/net/xaethos/todofrontend/datasource/Todo.kt package net.xaethos.todofrontend.datasource data class Todo( val uri: String, val title: String, val details: String? = null, val completed: Boolean = false) <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todolist/ListPresenter.kt package net.xaethos.todofrontend.singleactivity.todolist import android.graphics.Paint import android.support.v4.view.GravityCompat import android.support.v7.widget.RecyclerView import android.view.Gravity import android.view.View import android.widget.CheckBox import android.widget.TextView import com.jakewharton.rxbinding.view.clicks import com.jakewharton.rxbinding.widget.checkedChanges import net.xaethos.todofrontend.singleactivity.MainActivity import net.xaethos.todofrontend.singleactivity.NavigationPresenter import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.util.* import rx.Observable import javax.inject.Inject /** * A presenter handling a `RecyclerView` of to do items. * * Presenters manipulate a subtree of the view hierarchy. They conform to an interface * provided by the mediator, and forward commands and queries to the appropriate views. * They also forward user interaction events to the mediator. In this case, they do so * via RxJava [Observable]s. * * We keep our bound views together in the presenter, so we can drop all the * references at once. If we were to use [bindView] directly on the controller, * a second call to [Controller.onCreateView] wouldn't reinitialize the bindings. */ class ListPresenter(override val root: View) : ViewPresenter, ListMediator.ListPresenter { @Inject lateinit var navPresenter: NavigationPresenter private val listView by bindView<RecyclerView>(R.id.todo_list) override val fabClicks: Observable<Unit> get() { navPresenter.configureFab { setImageResource(R.drawable.ic_add_white_24dp) enabled = true gravity = Gravity.BOTTOM or GravityCompat.END anchor = LayoutAnchor.NONE } return navPresenter.fabClicks.takeUntil(detaches) } @Inject lateinit var adapter: ListController.Adapter @Inject override lateinit var detaches: Observable<Unit> @Inject fun setUp(activity: MainActivity) { navPresenter.actionBar?.setDisplayHomeAsUpEnabled(false) navPresenter.appBarTitle = activity.title listView.adapter = adapter } override fun notifyDataSetChanged() = adapter.notifyDataSetChanged() class ItemHolder(view: View) : ViewHolderPresenter(view), ListMediator.ItemPresenter { private val titleView: TextView by bindView(R.id.text_title) private val uriView: TextView by bindView(R.id.text_uri) private val completedView: CheckBox by bindView(R.id.chk_completed) override var titleText by textViewText(titleView) override var urlText by textViewText(uriView) override var isChecked: Boolean get() = completedView.isChecked set(value) { completedView.isChecked = value if (value) { titleView.paintFlags = titleView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG } else { titleView.paintFlags = titleView.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() } } override val clicks: Observable<Unit> get() = root.clicks().takeUntil(detaches) override val checkedChanges: Observable<Boolean> get() = completedView.checkedChanges().takeUntil(detaches) @Inject override lateinit var controllerDetaches: Observable<Unit> } } <file_sep>/app-singleactivity/src/test/java/net/xaethos/todofrontend/singleactivity/test/Mocking.kt package net.xaethos.todofrontend.singleactivity.test import org.mockito.Mockito import org.mockito.stubbing.OngoingStubbing import rx.Observable import rx.subjects.Subject import kotlin.test.assertTrue inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java) inline fun <reified T : Any> mock(initialization: T.() -> Unit): T = Mockito.mock(T::class.java).apply(initialization) fun <T> stub(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall) inline fun <R> OngoingStubbing<R>.with(crossinline answer: () -> R): OngoingStubbing<R> = then { invocation -> answer() } inline fun <reified P0 : Any, R> OngoingStubbing<R>.with(crossinline answer: (P0) -> R): OngoingStubbing<R> = then { invocation -> assertTrue("invocation has enough parameters") { invocation.arguments.size >= 1 } answer( invocation.getArgumentAt(0, P0::class.java) ) } fun <T> OngoingStubbing<Observable<T>>.withSubject(subject: Subject<T, T>): Subject<T, T> { thenReturn(subject.asObservable()) return subject } <file_sep>/build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.dep = [ compileSdk : 25, minSdk : 16, targetSdk : 25, buildTools : "25.0.2", rxJava : "1.1.7", rxKotlin : "0.60.0", support : '25.0.0', supportTest: '0.5', kotlin : '1.1.0', dagger : '2.9', espresso : '2.2.2', junit : '4.12' ] repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$dep.kotlin" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/Toaster.kt package net.xaethos.todofrontend.singleactivity.util import android.content.Context import android.widget.Toast import javax.inject.Inject class Toaster @Inject constructor(private val context: Context) { fun short(text: CharSequence) = Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } <file_sep>/app-traditional/src/main/java/net/xaethos/todofrontend/ToDoListActivity.kt package net.xaethos.todofrontend import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.datasource.TodoDataSource import javax.inject.Inject /** * An activity representing a list of to dos. This activity * has different presentations for handset and tablet-size devices. On * handsets, the activity presents a list of items, which when touched, * lead to a [TodoDetailActivity] representing * item details. On tablets, the activity presents the list of items and * item details side-by-side using two vertical panes. */ class TodoListActivity : AppCompatActivity() { @Inject lateinit var dataSource: TodoDataSource /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private var twoPane = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_todo_list) singletonComponent.inject(this) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) toolbar.title = title val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show() } setupRecyclerView(findViewById(R.id.todo_list) as RecyclerView) if (findViewById(R.id.todo_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-w900dp). // If this view is present, then the // activity should be in two-pane mode. twoPane = true } } private fun setupRecyclerView(recyclerView: RecyclerView) { val adapter = SimpleItemRecyclerViewAdapter() recyclerView.adapter = adapter dataSource.all.subscribe { adapter.values = it } } inner class SimpleItemRecyclerViewAdapter : RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder>() { var values: List<Todo> = emptyList() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) return ViewHolder(inflater.inflate(R.layout.todo_list_content, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.idView.text = item.uri holder.contentView.text = item.title holder.itemView.setOnClickListener { v -> if (twoPane) { val fragment = TodoDetailFragment() fragment.arguments = Bundle().apply { putString(TodoDetailFragment.ARG_ITEM_ID, item.uri) } supportFragmentManager.beginTransaction() .replace(R.id.todo_detail_container, fragment) .commit() } else { val context = v.context val intent = Intent(context, TodoDetailActivity::class.java) intent.putExtra(TodoDetailFragment.ARG_ITEM_ID, item.uri) context.startActivity(intent) } } } override fun getItemCount() = values.size inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val idView: TextView val contentView: TextView init { idView = view.findViewById(R.id.id) as TextView contentView = view.findViewById(R.id.content) as TextView } override fun toString() = super.toString() + " '" + contentView.text + "'" } } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/tododetail/DetailPresenter.kt package net.xaethos.todofrontend.singleactivity.tododetail import android.support.v4.view.GravityCompat import android.view.Gravity import android.view.View import android.widget.TextView import net.xaethos.todofrontend.singleactivity.MainActivity import net.xaethos.todofrontend.singleactivity.NavigationPresenter import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.util.LayoutAnchor import net.xaethos.todofrontend.singleactivity.util.ViewPresenter import net.xaethos.todofrontend.singleactivity.util.bindView import net.xaethos.todofrontend.singleactivity.util.textViewText import rx.Observable import javax.inject.Inject /** * View presenter: UI controls and events */ class DetailPresenter(override val root: View) : ViewPresenter, DetailMediator.Presenter { @Inject lateinit var navPresenter: NavigationPresenter private val detailView: TextView by bindView(R.id.todo_detail) override var titleText: CharSequence? get() = navPresenter.appBarTitle set(value) { navPresenter.appBarTitle = value } override var detailsText by textViewText(detailView) override val fabClicks: Observable<Unit> get() { navPresenter.configureFab { setImageResource(R.drawable.ic_edit_white_24dp) enabled = true gravity = Gravity.CENTER_VERTICAL or GravityCompat.START anchor = LayoutAnchor(navPresenter.container.id, Gravity.TOP or GravityCompat.END) } return navPresenter.fabClicks.takeUntil(detaches) } @Inject override lateinit var detaches: Observable<Unit> @Inject fun setUp(activity: MainActivity) { navPresenter.actionBar?.setDisplayHomeAsUpEnabled(true) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/Logger.kt package net.xaethos.todofrontend.singleactivity.util import android.util.Log import javax.inject.Inject import javax.inject.Singleton @Singleton class Logger(val tag: String) { @Inject constructor() : this("XAE") fun warn(throwable: Throwable) { Log.w(tag, throwable.message) } fun d(message: String) { Log.d(tag, message) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todoedit/EditController.kt package net.xaethos.todofrontend.singleactivity.todoedit import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.rxlifecycle.RxController import dagger.Subcomponent import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.component import net.xaethos.todofrontend.singleactivity.util.DataBundle import net.xaethos.todofrontend.singleactivity.util.RxControllerModule /** * Controller: lifecycle, navigation and dependency injection */ class EditController(val args: Arguments) : RxController(args.bundle) { @Suppress("unused") constructor(bundle: Bundle) : this(Arguments(bundle)) companion object { fun create(uri: String? = null): EditController { val args = EditController.Arguments(Bundle()).apply { this.uri = uri } return EditController(args) } } init { setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View = inflater.inflate(R.layout.presenter_todo_edit, container, false) override fun onAttach(view: View) { val component = buildComponent() val presenter = component.inject(EditPresenter(view)) component.mediator().bindPresenter(presenter, args.uri) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> router.popCurrentController() else -> return super.onOptionsItemSelected(item) } return true } fun buildComponent() = activity.component.editComponent(RxControllerModule(this)) class Arguments(bundle: Bundle) : DataBundle(bundle) { var uri by bundleString } @ControllerScope @Subcomponent(modules = arrayOf(RxControllerModule::class)) interface Component { fun inject(viewHolder: EditPresenter): EditPresenter fun mediator(): EditMediator } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/NavigationPresenter.kt package net.xaethos.todofrontend.singleactivity import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.CoordinatorLayout import android.support.design.widget.FloatingActionButton import android.support.v7.app.ActionBar import android.support.v7.widget.Toolbar import android.view.ViewGroup import com.jakewharton.rxbinding.view.clicks import net.xaethos.todofrontend.singleactivity.util.* import rx.Observable import javax.inject.Inject class NavigationPresenter( override val root: CoordinatorLayout, override val detaches: Observable<Unit>) : ViewPresenter { private val appBarLayout: CollapsingToolbarLayout by bindView(R.id.toolbar_layout) private val toolbar: Toolbar by bindView(R.id.toolbar) private val fab: FloatingActionButton by bindView(R.id.fab) private val fabPresenter = presenter(fab) var actionBar: ActionBar? = null var appBarTitle: CharSequence? get() = appBarLayout.title set(value) { appBarLayout.title = value } val container by bindView<ViewGroup>(R.id.content_container) var fabEnabled by viewEnabled(fab) val fabClicks: Observable<Unit> get() = fab.clicks().takeUntil(detaches) fun configureFab(configure: FabPresenter.() -> Unit) { fab.hide(object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton) { fabPresenter.configure() fab.show() } }) } @Inject fun setUp(activity: MainActivity) { activity.setSupportActionBar(toolbar) actionBar = activity.supportActionBar } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/MainActivity.kt package net.xaethos.todofrontend.singleactivity import android.content.Context import android.os.Bundle import android.support.design.widget.CoordinatorLayout import android.support.v7.app.AppCompatActivity import dagger.Provides import dagger.Subcomponent import net.xaethos.todofrontend.singleactivity.tododetail.DetailController import net.xaethos.todofrontend.singleactivity.tododetail.DetailMediator import net.xaethos.todofrontend.singleactivity.todoedit.EditController import net.xaethos.todofrontend.singleactivity.todoedit.EditMediator import net.xaethos.todofrontend.singleactivity.todolist.ListController import net.xaethos.todofrontend.singleactivity.todolist.ListMediator import net.xaethos.todofrontend.singleactivity.util.RxControllerModule import net.xaethos.todofrontend.singleactivity.util.bindView import rx.lang.kotlin.PublishSubject class MainActivity : AppCompatActivity() { val coordinatorLayout by bindView<CoordinatorLayout>(R.id.coordinator) lateinit var dependencySource: Component private val destroys = PublishSubject<Unit>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val presenter = NavigationPresenter(coordinatorLayout, destroys.asObservable()) dependencySource = singletonComponent.activityComponent(Module(presenter)) dependencySource.mediator().bindPresenter(this, presenter, savedInstanceState) } override fun onDestroy() { destroys.onNext(Unit) super.onDestroy() } override fun onBackPressed() { if (!dependencySource.mediator().handleBack()) super.onBackPressed() } @ActivityScope @Subcomponent(modules = arrayOf(Module::class)) interface Component { fun mediator(): NavigationMediator fun listComponent(module: RxControllerModule): ListController.Component fun detailComponent(module: RxControllerModule): DetailController.Component fun editComponent(module: RxControllerModule): EditController.Component } @dagger.Module inner class Module(val presenter: NavigationPresenter) { @Provides @ActivityScope fun context(): Context = this@MainActivity @Provides @ActivityScope fun activity(): MainActivity = this@MainActivity @Provides fun navigationPresenter() = presenter @Provides fun listNavigator(mediator: NavigationMediator): ListMediator.Navigator = mediator @Provides fun detailNavigator(mediator: NavigationMediator): DetailMediator.Navigator = mediator @Provides fun editNavigator(mediator: NavigationMediator): EditMediator.Navigator = mediator } } <file_sep>/app-traditional/src/androidTest/java/net/xaethos/todofrontend/test/Rules.kt package net.xaethos.todofrontend.test import android.app.Activity import android.support.test.rule.ActivityTestRule inline fun <reified T : Activity> activityTestRule(): ActivityTestRule<T> = ActivityTestRule(T::class.java) <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todoedit/EditMediator.kt package net.xaethos.todofrontend.singleactivity.todoedit import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.datasource.TodoDataSource import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.util.ViewPresenter import rx.Observable import rx.lang.kotlin.subscribeWith import javax.inject.Inject /** * Mediator: uses business logic to binding data to views */ @ControllerScope class EditMediator @Inject constructor(val navigator: Navigator) { @Inject lateinit var dataSource: TodoDataSource var titleValue: String = "" var detailsValue: String = "" fun bindPresenter(presenter: Presenter, uri: String?) = if (uri == null) bindForCreate(presenter) else bindForEdit(presenter, uri) private fun bindForCreate(presenter: Presenter) { presenter.appBarTitle = "New todo" bindFields(presenter, null) } private fun bindForEdit(presenter: Presenter, uri: String) { presenter.appBarTitle = "Edit todo" dataSource[uri].takeUntil(presenter.detaches).first().subscribeWith { onNext { todo -> presenter.titleText = todo.title presenter.detailsText = todo.details bindFields(presenter, todo) } } } private fun bindFields(presenter: Presenter, originalTodo: Todo?) { presenter.fabClicks .doOnNext { presenter.fabEnabled = false } .subscribe { submit(originalTodo, titleValue, detailsValue) } presenter.titleChanges .map { it.toString() } .subscribe { titleValue = it } presenter.titleChanges .map(CharSequence?::isNullOrBlank) .distinctUntilChanged() .subscribe { isBlank -> presenter.fabEnabled = !isBlank } presenter.detailsChanges .map { it.toString() } .subscribe { detailsValue = it } } private fun submit(originalTodo: Todo?, titleValue: String, detailsValue: String) { if (titleValue.isBlank()) return if (originalTodo == null) { dataSource.create(titleValue, detailsValue) } else { dataSource.put(originalTodo.copy(title = titleValue, details = detailsValue)) } navigator.navigateBack() } interface Navigator { fun navigateBack() } interface Presenter : ViewPresenter { var appBarTitle: CharSequence? var titleText: CharSequence? var detailsText: CharSequence? var fabEnabled: Boolean val titleChanges: Observable<CharSequence> val detailsChanges: Observable<CharSequence> val fabClicks: Observable<Unit> } } <file_sep>/app-singleactivity/src/test/java/net/xaethos/todofrontend/singleactivity/todolist/ListMediatorTest.kt package net.xaethos.todofrontend.singleactivity.todolist import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.should.shouldMatch import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.datasource.TodoDataSource import net.xaethos.todofrontend.singleactivity.test.mock import net.xaethos.todofrontend.singleactivity.test.stub import net.xaethos.todofrontend.singleactivity.test.withSubject import org.junit.Before import org.junit.Test import org.mockito.Mockito.verify import rx.lang.kotlin.BehaviorSubject import rx.lang.kotlin.PublishSubject import kotlin.test.assertEquals class ListMediatorTest { val data = listOf( todo(0), todo(1), todo(2), todo(3) ) val fabClickSubject = PublishSubject<Unit>() val clickSubject = PublishSubject<Unit>() val checkedSubject = PublishSubject<Boolean>() val navigator: ListMediator.Navigator = mock() val dataSource: TodoDataSource = mock { stub(all).withSubject(BehaviorSubject(data)) } val listPresenter: ListMediator.ListPresenter = mock { stub(fabClicks).withSubject(fabClickSubject) stub(detaches).withSubject(PublishSubject<Unit>()) } val itemPresenter: ListMediator.ItemPresenter = mock { stub(clicks).withSubject(clickSubject) stub(checkedChanges).withSubject(checkedSubject) stub(detaches).withSubject(PublishSubject<Unit>()) } val mediator = ListMediator(navigator) @Before fun setUp() { mediator.dataSource = dataSource } @Test fun bindListPresenter() { mediator.bindListPresenter(listPresenter) verify(listPresenter).notifyDataSetChanged() mediator.todoList shouldMatch equalTo(data) } @Test fun bindItemPresenter() { mediator.todoList = listOf( Todo("todo/10", "title", completed = true), Todo("todo/1", "To Do 1") ) mediator.bindItemPresenter(itemPresenter, 0) verify(itemPresenter).titleText = "title" verify(itemPresenter).urlText = "todo/10" verify(itemPresenter).isChecked = true mediator.bindItemPresenter(itemPresenter, 1) verify(itemPresenter).titleText = "To Do 1" verify(itemPresenter).urlText = "todo/1" verify(itemPresenter).isChecked = false } @Test fun onItemClick_showDetails() { mediator.todoList = data mediator.bindItemPresenter(itemPresenter, 2) clickSubject.onNext(Unit) verify(navigator).pushDetailController(data[2]) } @Test fun onItemChecked_updateData() { val item = Todo("todo/13", "doable") mediator.todoList = listOf(item) mediator.bindItemPresenter(itemPresenter, 0) checkedSubject.onNext(true) verify(dataSource).put(item.copy(completed = true)) } @Test fun onFabClick_showCreate() { mediator.bindListPresenter(listPresenter) fabClickSubject.onNext(Unit) verify(navigator).pushCreateController() } @Test fun itemCount() { mediator.todoList = data assertEquals(4, mediator.itemCount) } @Test fun itemId() { mediator.todoList = data assertEquals(data[2].uri.hashCode().toLong(), mediator.itemId(2)) } } private fun todo(id: Int) = Todo("http://example.com/todo/$id", "To Do $id") <file_sep>/datasource/build.gradle apply plugin: 'com.android.library' apply plugin: 'kotlin-android' android { compileSdkVersion dep.compileSdk buildToolsVersion dep.buildTools defaultConfig { minSdkVersion dep.minSdk targetSdkVersion dep.targetSdk versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } kapt { generateStubs = true } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$dep.kotlin" // Dagger provided 'javax.annotation:jsr250-api:1.0' kapt "com.google.dagger:dagger-compiler:$dep.dagger" compile "com.google.dagger:dagger:$dep.dagger" // Rx compile "io.reactivex:rxjava:$dep.rxJava" compile "io.reactivex:rxkotlin:$dep.rxKotlin" testCompile "junit:junit:$dep.junit" testCompile "org.jetbrains.kotlin:kotlin-test:$dep.kotlin" testCompile 'com.natpryce:hamkrest:1.2.1.0' } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/Delegates.kt package net.xaethos.todofrontend.singleactivity.util import android.view.View import android.widget.CompoundButton import android.widget.TextView import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KFunction1 import kotlin.reflect.KFunction2 import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 fun textViewText(textView: TextView): ReadWriteProperty<Any?, CharSequence?> = mapping<TextView, CharSequence?>(textView, TextView::getText, TextView::setText) fun compoundButtonChecked(button: CompoundButton): ReadWriteProperty<Any?, Boolean> = mapping(button, CompoundButton::isChecked, CompoundButton::setChecked) fun viewEnabled(view: View): ReadWriteProperty<Any?, Boolean> = mapping(view, View::isEnabled, View::setEnabled) fun <T, V> forwarding(target: T, kProperty: KProperty1<T, V>) = object : ReadOnlyProperty<Any?, V> { override fun getValue(thisRef: Any?, property: KProperty<*>) = kProperty.getter(target) } fun <T, V> forwarding(target: T, kProperty: KMutableProperty1<T, V>) = object : ReadWriteProperty<Any?, V> { override fun getValue(thisRef: Any?, property: KProperty<*>) = kProperty.getter(target) override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) { kProperty.setter(target, value) } } fun <T, V> mapping(target: T, getter: KFunction1<T, V>, setter: KFunction2<T, V, Unit>) = object : ReadWriteProperty<Any?, V> { override fun getValue(thisRef: Any?, property: KProperty<*>): V = getter(target) override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) { setter(target, value) } } <file_sep>/datasource/src/main/java/net/xaethos/todofrontend/datasource/ToDoDataSource.kt package net.xaethos.todofrontend.datasource import rx.Observable import rx.lang.kotlin.BehaviorSubject import rx.lang.kotlin.emptyObservable import rx.subjects.BehaviorSubject import java.util.* interface TodoDataSource { /** * A list of all to do items. */ val all: Observable<List<Todo>> /** * Get item by index */ operator fun get(index: Int): Observable<Todo> /** * Find item by URI */ operator fun get(uri: String): Observable<Todo> /** * Create a new item */ fun create(title: String, details: String? = null): Observable<Todo> /** * Insert or update an item */ fun put(item: Todo): Observable<Todo> /** * Remove an item. Is a no-op if item is not present. */ fun delete(uri: String) } internal class LocalSource : TodoDataSource { private val items = ArrayList<Todo>() private val itemMap = HashMap<String, BehaviorSubject<Todo>>() private val listSubject = BehaviorSubject<List<Todo>>() override val all: Observable<List<Todo>> = listSubject.asObservable() init { insertItemUnsafe(Todo("todo/0", "Write To Do app", completed = true)) insertItemUnsafe(Todo("todo/1", "Give a talk on To Do app")) insertItemUnsafe(Todo("todo/2", "Do stuff", details = "I have stuff to do")) } override fun get(index: Int) = get(items[index].uri) override fun get(uri: String): Observable<Todo> = itemMap[uri]?.asObservable() ?: emptyObservable() override fun create(title: String, details: String?): Observable<Todo> = synchronized(this) { val id = System.nanoTime() val item = Todo("todo/$id", title, details) put(item) } override fun put(item: Todo): Observable<Todo> = synchronized(this) { if (itemMap.contains(item.uri)) { updateItemUnsafe(item) } else { insertItemUnsafe(item) } } override fun delete(uri: String) = synchronized(this) { if (itemMap.contains(uri)) { items.removeAt(findIndex(uri)) itemMap.remove(uri)?.onCompleted() listSubject.onNext(items.toList()) } } /** * Insert a new item in correct position. Assumes item is not in source. Not thread safe. */ private fun insertItemUnsafe(item: Todo): Observable<Todo> { val itemSubject = BehaviorSubject(item) itemMap.put(item.uri, itemSubject) if (item.completed) { items.add(item) } else { items.add(findCompletedIndex(), item) } listSubject.onNext(items.toList()) return itemSubject } /** * Update an existing item. Assumes item is already in source. Not thread safe. */ private fun updateItemUnsafe(item: Todo): Observable<Todo> { val key = item.uri val itemSubject = itemMap[key] ?: throw IllegalArgumentException("Item missing: $item") val currentItem = itemSubject.value if (item != currentItem) { val currentIndex = findIndex(key) if (item.completed == currentItem.completed) { items[currentIndex] = item } else { items.removeAt(currentIndex) items.add(findCompletedIndex(), item) } itemSubject.onNext(item) listSubject.onNext(items.toList()) } return itemSubject.asObservable() } private fun findIndex(uri: String): Int { return items.indexOfFirst { it.uri == uri } } /** * Find the index where completed items would start */ private fun findCompletedIndex(): Int { val index = items.indexOfFirst { it.completed } return if (index < 0) items.size else index } } <file_sep>/app-singleactivity/src/test/java/net/xaethos/todofrontend/singleactivity/tododetail/DetailMediatorTest.kt package net.xaethos.todofrontend.singleactivity.tododetail import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.singleactivity.test.mock import net.xaethos.todofrontend.singleactivity.test.stub import net.xaethos.todofrontend.singleactivity.test.withSubject import org.junit.Before import org.junit.Test import org.mockito.Mockito.verify import rx.Observable import rx.lang.kotlin.BehaviorSubject import rx.lang.kotlin.PublishSubject class DetailMediatorTest { val uri = "http://example.com/todo/13" val todo = Todo(uri, "Title", "Details") val fabClickSubject = PublishSubject<Unit>() val presenter = mock<DetailMediator.Presenter> { stub(fabClicks).withSubject(fabClickSubject) stub(detaches).thenReturn(Observable.never()) } val navigator = mock<DetailMediator.Navigator>() val mediator = DetailMediator(navigator) @Before fun setUp() { mediator.dataSource = mock { stub(get(uri)).withSubject(BehaviorSubject(todo)) } } @Test fun bindPresenter() { mediator.bindPresenter(presenter, uri) verify(presenter).titleText = "Title" verify(presenter).detailsText = "Details" } @Test fun onFabClick_editTodo() { mediator.bindPresenter(presenter, uri) fabClickSubject.onNext(Unit) verify(navigator).pushEditController(todo) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/CoordinatorLayouts.kt package net.xaethos.todofrontend.singleactivity.util import android.support.annotation.IdRes import android.support.design.widget.CoordinatorLayout import android.view.Gravity import android.view.View data class LayoutAnchor(@IdRes val viewId: Int, val gravity: Int) { companion object { val NONE = LayoutAnchor(View.NO_ID, Gravity.NO_GRAVITY) } } var CoordinatorLayout.LayoutParams.anchor: LayoutAnchor get() = LayoutAnchor(anchorId, anchorGravity) set(value) { anchorId = value.viewId anchorGravity = value.gravity } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/ConductorUtils.kt package net.xaethos.todofrontend.singleactivity.util import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.rxlifecycle.ControllerEvent import com.bluelinelabs.conductor.rxlifecycle.RxController import dagger.Module import dagger.Provides import rx.Observable @Module open class RxControllerModule(val controller: RxController) { @Provides fun controllerDetachesObservable(): Observable<Unit> { return controller.lifecycle() .filter { it == ControllerEvent.DETACH } .map { Unit } } } fun Router.pushController(controller: Controller) { pushController(RouterTransaction.with(controller)) } inline fun Router.pushController(controller: Controller, init: RouterTransaction.() -> Unit) { val transaction = RouterTransaction.with(controller) transaction.init() pushController(transaction) } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todolist/ListController.kt package net.xaethos.todofrontend.singleactivity.todolist import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.rxlifecycle.RxController import dagger.MembersInjector import dagger.Subcomponent import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.R import net.xaethos.todofrontend.singleactivity.component import net.xaethos.todofrontend.singleactivity.util.RxControllerModule import javax.inject.Inject /** * A controller for displaying a list of to do items. * * Controllers live on nodes in the view hierarchy. They are akin to fragments, but with a * simpler lifecycle. They will instantiate mediators and presenters to do the actual view * manipulation. * * While presenters manipulate views, controllers choose what type of view and presenter * will be used. Controllers are also in charge of navigation, pushing and popping new * controllers onto the router as the mediator requests. * * Finally, controllers handle dependency injection for mediators and presenters. */ class ListController() : RxController() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View = inflater.inflate(R.layout.presenter_todo_list, container, false) override fun onAttach(view: View) { /* This component holds a reference to the activity, and the controller sometimes outlives the activity, so we create a new one every time. */ val component = buildComponent() val presenter = component.inject(ListPresenter(view)) component.mediator().bindListPresenter(presenter) } private fun buildComponent() = activity.component.listComponent(RxControllerModule(this)) @ControllerScope class Adapter @Inject constructor( private val mediator: ListMediator, private var viewHolderInjector: MembersInjector<ListPresenter.ItemHolder>) : RecyclerView.Adapter<ListPresenter.ItemHolder>() { init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListPresenter.ItemHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.presenter_todo_list_item, parent, false) val viewHolder = ListPresenter.ItemHolder(view) viewHolderInjector.injectMembers(viewHolder) return viewHolder } override fun onBindViewHolder(holder: ListPresenter.ItemHolder, position: Int) = mediator.bindItemPresenter(holder, position) override fun onViewRecycled(holder: ListPresenter.ItemHolder) = holder.onRecycle() override fun getItemCount() = mediator.itemCount override fun getItemId(position: Int): Long = mediator.itemId(position) } /** * The Dagger component providing dependencies for this controller's views. * * Its lifecycle should match the _view's_ lifecycle: we should create a new * [Component] instance on each [onCreateView]. */ @ControllerScope @Subcomponent(modules = arrayOf(RxControllerModule::class)) interface Component { fun inject(presenter: ListPresenter): ListPresenter fun mediator(): ListMediator } } <file_sep>/app-traditional/src/androidTest/java/net/xaethos/todofrontend/features/HappyPathFeature.kt package net.xaethos.todofrontend.features import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.contrib.RecyclerViewActions import android.support.test.espresso.matcher.ViewMatchers.isDisplayed import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.espresso.matcher.ViewMatchers.withText import android.support.test.filters.LargeTest import android.support.test.runner.AndroidJUnit4 import android.support.v7.widget.RecyclerView import net.xaethos.todofrontend.R import net.xaethos.todofrontend.TodoListActivity import net.xaethos.todofrontend.test.activityTestRule import org.hamcrest.Matchers.containsString import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class HappyPathFeature { @get:Rule var activityRule = activityTestRule<TodoListActivity>() @Test fun seeTodoDetails() { // Scroll down list and tap on to do onView(withId(R.id.todo_list)) .perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(1)) onView(withText("Do stuff")).perform(click()) // Check that the details are shown. onView(withText(containsString("I have stuff to do"))).check(matches(isDisplayed())) } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/todolist/ListMediator.kt package net.xaethos.todofrontend.singleactivity.todolist import android.support.annotation.VisibleForTesting import net.xaethos.todofrontend.datasource.Todo import net.xaethos.todofrontend.datasource.TodoDataSource import net.xaethos.todofrontend.singleactivity.ControllerScope import net.xaethos.todofrontend.singleactivity.util.Logger import net.xaethos.todofrontend.singleactivity.util.ViewPresenter import rx.Observable import rx.lang.kotlin.subscribeWith import javax.inject.Inject /** * Mediator: All business logic goes here */ @ControllerScope class ListMediator @Inject constructor(val navigator: Navigator) { @Inject lateinit var dataSource: TodoDataSource @Inject lateinit var logger: Logger @VisibleForTesting var todoList: List<Todo> = emptyList() val itemCount: Int get() = todoList.size fun itemId(index: Int): Long = todoList[index].uri.hashCode().toLong() fun bindListPresenter(presenter: ListPresenter) { dataSource.all.takeUntil(presenter.detaches).subscribe { newItems -> todoList = newItems presenter.notifyDataSetChanged() } presenter.fabClicks.subscribe { navigator.pushCreateController() } } fun bindItemPresenter(presenter: ItemPresenter, position: Int) { // First get the data to bind to val todo = todoList[position] // We now set the state of the presenter to reflect its position presenter.titleText = todo.title presenter.urlText = todo.uri presenter.isChecked = todo.completed // Finally, we subscribe to UI events presenter.clicks.subscribeWith { onNext { navigator.pushDetailController(todo) } onError { logger.warn(it) } } presenter.checkedChanges.takeUntil(presenter.detaches).subscribe { checked -> dataSource.put(todo.copy(completed = checked)) } } /** * The navigator interfaces are how the mediator requests for a change in the app flow. * It'll almost certainly be implemented by a Controller, since it has access to the router, * but the exact way the flow changes may be different depending on the current app * configuration. i.e. a phone may push a new controller on top, while a tablet may place it on * a detail view. */ interface Navigator { fun pushDetailController(todo: Todo) fun pushCreateController() } interface ListPresenter : ViewPresenter { fun notifyDataSetChanged() val fabClicks: Observable<Unit> } /** * The presenter interfaces are what the mediator needs to control and react to the UI. The * exact view structure is not important as long as these methods are available. */ interface ItemPresenter : ViewPresenter { /* These are the presenters "controls." They let us check and modify its state. */ var titleText: CharSequence? var urlText: CharSequence? var isChecked: Boolean /* These are the presenters event emitters. */ val clicks: Observable<Unit> val checkedChanges: Observable<Boolean> } } <file_sep>/datasource/src/test/java/net/xaethos/todofrontend/datasource/ModuleDataSourceTest.kt package net.xaethos.todofrontend.datasource import com.natpryce.hamkrest.isEmpty import com.natpryce.hamkrest.should.shouldMatch import net.xaethos.todofrontend.datasource.test.emits import net.xaethos.todofrontend.datasource.test.onNextEvents import net.xaethos.todofrontend.datasource.test.shouldEqual import net.xaethos.todofrontend.datasource.test.withTestSubscriber import org.junit.Test import kotlin.test.assertNotEquals class ModuleDataSourceTest { val seededItems = listOf( Todo(uri = "todo/1", title = "Give a talk on To Do app"), Todo(uri = "todo/2", title = "Do stuff", details = "I have stuff to do"), Todo(uri = "todo/0", title = "Write To Do app", completed = true) ) val dataSource = DataModule().dataSource() @Test fun initialItems() { dataSource.all shouldMatch emits(seededItems) } @Test fun observeAll() { dataSource.all.withTestSubscriber { subscriber -> subscriber shouldMatch onNextEvents(seededItems) subscriber.assertNotCompleted() } } @Test fun getByIndex() { dataSource[1].withTestSubscriber { subscriber -> subscriber shouldMatch onNextEvents(seededItems[1]) subscriber.assertNotCompleted() } } @Test fun getByUri() { dataSource["todo/0"].withTestSubscriber { subscriber -> subscriber shouldMatch onNextEvents(seededItems[2]) subscriber.assertNotCompleted() } } @Test fun getByUri_completesIfMissingUri() { dataSource["does not exist"].withTestSubscriber { subscriber -> subscriber.onNextEvents shouldMatch isEmpty subscriber.assertCompleted() } } @Test fun create() { dataSource.create("new title", "details").withTestSubscriber { subscriber -> subscriber.assertNotCompleted() val createdItem = subscriber.onNextEvents.single() createdItem shouldEqual Todo(createdItem.uri, "new title", "details", completed = false) } } @Test fun create_emitsListUpdate() { val createdItem = dataSource.create("new title", "details").toBlocking().first() dataSource.all shouldMatch emits(listOf( seededItems[0], seededItems[1], createdItem, seededItems[2] )) } @Test fun create_generatesDifferingUris() { val fooItem = dataSource.create("title").toBlocking().first() val barItem = dataSource.create("title").toBlocking().first() assertNotEquals(fooItem.uri, barItem.uri) } @Test fun put_whenExistingUri_updatesItemInPlace() { val updatedItem = Todo(uri = "todo/1", title = "Give a talk on application testing") dataSource.put(updatedItem) dataSource.all shouldMatch emits(listOf( updatedItem, seededItems[1], seededItems[2] )) } @Test fun put_whenExistingUri_emitsUpdatedItem() { val originalItem = seededItems[0] val updatedItem = originalItem.copy(title = "new title") dataSource[originalItem.uri].withTestSubscriber { subscriber -> dataSource.put(updatedItem) subscriber shouldMatch onNextEvents(originalItem, updatedItem) } } @Test fun put_noOpWhenNoChange() { dataSource.all.withTestSubscriber { subscriber -> dataSource.put(seededItems[0]) subscriber shouldMatch onNextEvents(seededItems) } } @Test fun put_whenCompletionChanges_updatesPosition() { val completedItem = seededItems[0].copy(completed = true) val uncompletedItem = seededItems[2].copy(completed = false) dataSource.all.withTestSubscriber { subscriber -> dataSource.put(completedItem) dataSource.put(uncompletedItem) subscriber shouldMatch onNextEvents( listOf(seededItems[0], seededItems[1], seededItems[2]), listOf(seededItems[1], completedItem, seededItems[2]), listOf(seededItems[1], uncompletedItem, completedItem) ) } } @Test fun put_whenNewUri_insertsBeforeCompleted() { val newItem = Todo(uri = "todo/new", title = "another to do") dataSource.put(newItem) dataSource.all shouldMatch emits(listOf( seededItems[0], seededItems[1], newItem, seededItems[2] )) } @Test fun put_whenNewUri_andCompleted_insertsAtEnd() { val newItem = Todo(uri = "todo/new", title = "completed to do", completed = true) dataSource.put(newItem) dataSource.all shouldMatch emits(listOf( seededItems[0], seededItems[1], seededItems[2], newItem )) } @Test fun delete() { dataSource.delete(seededItems[2].uri) dataSource.all shouldMatch emits(listOf( seededItems[0], seededItems[1] )) } @Test fun delete_completesItemObservable() { dataSource["todo/0"].withTestSubscriber { subscriber -> dataSource.delete("todo/0") subscriber shouldMatch onNextEvents(seededItems[2]) subscriber.assertCompleted() } } @Test fun delete_noOpOnMissingUri() { dataSource.all.withTestSubscriber { subscriber -> dataSource.delete("non-existent") subscriber shouldMatch onNextEvents(seededItems) } } } <file_sep>/app-singleactivity/src/main/java/net/xaethos/todofrontend/singleactivity/util/FabPresenter.kt package net.xaethos.todofrontend.singleactivity.util import android.content.res.ColorStateList import android.graphics.Color import android.support.annotation.DrawableRes import android.support.design.widget.CoordinatorLayout import android.support.design.widget.FloatingActionButton import android.util.TypedValue import android.view.Gravity import net.xaethos.todofrontend.singleactivity.R interface FabPresenter { var enabled: Boolean var gravity: Int var anchor: LayoutAnchor fun setImageResource(@DrawableRes drawableRes: Int) } fun presenter(fab: FloatingActionButton): FabPresenter = FabPresenterImpl(fab) private class FabPresenterImpl(val fab: FloatingActionButton) : FabPresenter { override var enabled: Boolean get() = fab.isEnabled set(enabled) { fab.isEnabled = enabled fab.backgroundTintList = if (enabled) colorEnabled else colorDisabled } override var gravity: Int get() = layoutParams?.gravity ?: Gravity.NO_GRAVITY set(value) { layoutParams?.gravity = value } override var anchor: LayoutAnchor get() = layoutParams?.anchor ?: LayoutAnchor.NONE set(value) { layoutParams?.anchor = value } override fun setImageResource(drawableRes: Int) = fab.setImageResource(drawableRes) private val layoutParams: CoordinatorLayout.LayoutParams? get() = fab.layoutParams as? CoordinatorLayout.LayoutParams private val colorEnabled: ColorStateList by lazy { val typedValue = TypedValue() val a = fab.context.obtainStyledAttributes(typedValue.data, intArrayOf(R.attr.colorAccent)) val color = a.getColor(0, 0) a.recycle() ColorStateList.valueOf(color) } private val colorDisabled = ColorStateList.valueOf(Color.GRAY) }
76dd77cd6d1c59166a41a8710776ec204a106562
[ "Kotlin", "Gradle" ]
39
Kotlin
lumyus/todo-android
4ea9b84f1833735249f094fc8b7b013cbe1a3c82
23997994eabb66e3b1befd4fdc55d66c1ef8a7a1
refs/heads/master
<repo_name>rosynirvana/ZeroJudge<file_sep>/a414.cpp #include <cstdio> int main() { int n; while(scanf("%d", &n) == 1 && n != 0){ int ary[40]; int pos = 0; while(n > 0){ ary[pos++] = n % 2; n /= 2; } int upper = pos-1; pos = 0; int sum; if(ary[pos] == 0) sum = 0; else{ sum = 1; ++pos; bool carry = true; for(; pos <= upper; ++pos){ if(carry == false || ary[pos] == 0) break; else ++sum; } } printf("%d\n", sum); } return 0; } <file_sep>/d074.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int n; std::cin >> n; int max = -1; for(int i=0; i<n; ++i){ int temp; std::cin >> temp; if(temp > max) max = temp; } std::cout << max << "\n"; return 0; }<file_sep>/d051.cpp #include <iostream> #include <ios> #include <iomanip> int main() { std::ios_base::sync_with_stdio(false); std::cout << std::fixed << std::setprecision(3); int f; while(std::cin >> f){ double c; c = (f-32)/9.0*5; std::cout << c; } return 0; }<file_sep>/b238.cpp /* works but cannot get ACed */ #include <iostream> int main() { int n; std::cin >> n; for(int i=0; i!=n; ++i){ long long a,b,c,d,M; int day; std::cin >> a >> b >> c >> d >> day >> M; long long h = 1, t = 1; for(int j = 1; j <= day; ++j){ long long lh = h, lt = t; t = (a * lt + b * lh) % M; h = (c * lt + d * lh) % M; } //std::cout << t << " " << h; if(t == h) std::cout << "Normal\n"; else if(t > h) std::cout << "Tsundere\n"; else std::cout << "Haraguroi\n"; } return 0; }<file_sep>/a734d.cpp #include <map> #include <iostream> #include <ios> #include <string> #include <utility> #include <cctype> #include <cstdlib> #include <vector> void parseInput(const std::string& comp, std::vector< std::pair< std::string, int > >& buf); int main() { std::ios::sync_with_stdio(false); int M, N; while(std::cin >> M >> N){ std::map< std::string, int > table; for(int i=0; i != M; ++i){ std::string tstring; int temp; std::cin >> tstring >> temp; table[tstring] = temp; } for(int i=0; i != N; ++i){ std::string comp; std::cin >> comp; std::vector< std::pair< std::string, int > > buf; parseInput(comp, buf); int sum = 0; for(size_t j=0; j!=buf.size(); ++j) sum += table[buf[j].first] * buf[j].second; std::cout << sum << "\n"; } } return 0; } void parseInput(const std::string& comp, std::vector< std::pair< std::string, int > >& buf) { size_t left = 0, right = 0; std::vector< std::string > minibuf; while(right != comp.size()){ if(isupper(comp[right])){ minibuf.push_back(comp.substr(left, right - left)); left = right; ++right; } else ++right; } minibuf.push_back(comp.substr(left, right - left)); for(size_t i=0; i != minibuf.size(); ++i){ if(isdigit(minibuf[i][minibuf[i].size()-1])) { if(isdigit(minibuf[i][1])){ int num = atoi(minibuf[i].substr(1).c_str()); buf.push_back(make_pair(minibuf[i].substr(0,1), num)); } else{ int num = atoi(minibuf[i].substr(2).c_str()); buf.push_back(std::make_pair(minibuf[i].substr(0,2), num)); } } else buf.push_back(std::make_pair(minibuf[i], 1)); } }<file_sep>/a121.cpp #include <cstdio> #include <vector> #include <algorithm> using std::binary_search; using std::vector; bool isPrime(int n, vector<int>&); int main() { int n, m; vector<int> prime_table; int temp[46369]; for(int i=1; i<=46368; ++i) temp[i] = i; temp[0] = 0; temp[1] = 0; int upper = 216; while(true){ int i = 2; while(true){ if(temp[i] != 0) break; else ++i; } if(temp[i] > upper) break; prime_table.push_back(temp[i]); for(int j = i; j < 46369; j += i) temp[j] = 0; } for(int i=0; i<46369; ++i) if(temp[i] != 0) prime_table.push_back(i); while(scanf("%d %d", &n, &m) == 2){ int sum = 0; for(; n<=m; ++n) if(isPrime(n, prime_table)) ++sum; printf("%d\n", sum); } return 0; } bool isPrime(int n, vector<int>& prime_table) { if(n <= prime_table.back()){ if(binary_search(prime_table.begin(), prime_table.end(), n)) return true; else return false; } else{ for(vector<int>::const_iterator iter = prime_table.begin(); iter != prime_table.end() && *iter * *iter <= n; ++iter) if(n % *iter == 0) return false; } return true; }<file_sep>/d066.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int hh, mm; while(std::cin >> hh >> mm){ bool atSchool = true; if(hh < 7) atSchool = false; else if(hh > 16) atSchool = false; else if(hh == 7 && mm < 30) atSchool = false; if(atSchool) std::cout << "At School\n"; else std::cout << "Off School\n"; } return 0; }<file_sep>/a059.cpp #include <cstdio> #include <cmath> int main() { int t; scanf("%d", &t); for(int i=0; i<t; ++i){ int a, b; scanf("%d %d", &a, &b); int lower = static_cast<int>(ceil(sqrt(a))); int upper = static_cast<int>(floor(sqrt(b))); int sum = 0; for(; lower<=upper; ++lower) sum += lower * lower; printf("Case %d: %d\n", i+1, sum); } return 0; }<file_sep>/a053.cpp #include <iostream> int main() { int n; while(std::cin >> n){ int score; if(n<=10) score = 6*n; else if(n<=20) score = 60 + (n-10)*2; else if(n<=40) score = 80 + n - 20; else score = 100; std::cout << score << "\n"; } return 0; }<file_sep>/a225.cpp #include <iostream> #include <algorithm> #include <vector> bool comp(int i, int j); int main() { int n; while(std::cin >> n){ std::vector<int> buf; for(int i=0; i!=n; ++i){ int temp; std::cin >> temp; buf.push_back(temp); } std::sort(buf.begin(), buf.end(), comp); for(std::vector<int>::const_iterator iter = buf.begin(); iter != buf.end(); ++iter) std::cout << *iter << " "; std::cout << "\n"; } return 0; } bool comp(int i, int j) { if(i % 10 < j % 10) return true; if(i % 10 > j % 10) return false; if(i / 10 > j / 10) return true; return false; }<file_sep>/d899.cpp #include <iostream> #include <ios> #include <cstdio> int count2(int); int main() { std::ios_base::sync_with_stdio(false); int L, R; while(std::cin >> L >> R){ int count = 0; for(; L<=R; ++L) count += count2(L); std::cout << count << "\n"; } return 0; } int count2(int num) { int result = 0; char buf[10]; sprintf(buf, "%d", num); for(int i=0; buf[i] != '\0'; ++i) if(buf[i] == '2') ++result; return result; }<file_sep>/a020.cpp #include <iostream> #include <string> using std::cin; using std::cout; using std::string; int convert(char); int main() { string str; while(cin >> str){ int p2 = convert(str[0]) % 10 * 9 + convert(str[0]) / 10; int p3 = 0; for(size_t i=1; i <= 8; ++i) p3 += (str[i] - '0')* (9-i); int p4 = p2 + p3 + str[str.size() - 1] - '0'; if(p4 % 10 == 0) cout << "real\n"; else cout << "fake\n"; } return 0; } int convert(char c) { if(c == 'I') return 34; if(c == 'O') return 35; if(c == 'W') return 32; if(c == 'Z') return 33; if(c >= 'A' && c <= 'H') return c-'A'+10; if(c >= 'J' && c <= 'N') return c-'J'+18; if(c >= 'P' && c <= 'V') return c-'P'+23; if(c >= 'X') return c-'X'+30; } <file_sep>/a040.cpp /*WARNING : MAY NOT GET THE CORRECT ANSWER UNDER mingw *If you want to fix it manually, see comments in cmath */ #include <iostream> #include <vector> #include <cmath> bool cal(int, int); int main() { //std::cout << static_cast<int>(pow(5,3)); //std::cout << cal(153,3) <<"\n"; int upper, lower; while(std::cin >> lower){ std::cin >> upper; std::vector<int> buf; int n = 0, temp = lower; while(temp > 0){ ++n; temp /= 10; } while(lower < upper){ if(cal(lower, n)) buf.push_back(lower); ++lower; if(lower == 10 || lower == 100 || lower == 1000 || lower == 10000 || lower == 100000 || lower == 1000000) ++n; } if(buf.size() == 0) std::cout << "none" << "\n"; else{ for(std::vector<int>::const_iterator iter = buf.begin(); iter != buf.end(); ++iter) std::cout << *iter << " "; std::cout << "\n"; } } return 0; } bool cal(int num, int n) { int sum = 0, temp = num; while(temp > 0){ //std::cout << (pow(temp%10, n)) << "\n"; sum += (pow(temp%10, n)); //std::cout << sum << "\n"; temp /= 10; } //std::cout << "sum: " << sum << " num: " << num ; if(sum == num) return true; return false; }<file_sep>/d065.cpp #include <iostream> int main() { int a, b, c; while(std::cin >> a >> b >> c){ int max = (a > b ? a : b); std::cout << (max > c ? max : c) << "\n"; } return 0; }<file_sep>/a044.cpp #include <iostream> int main() { int n; while(std::cin >> n){ std::cout << (n*n*n + 5 * n + 6) / 6 << "\n"; } return 0; }<file_sep>/d010.cpp #include <cstdio> #include <vector> #include <cmath> using std::vector; int main() { int n; while(scanf("%d", &n) == 1){ if(n == 1) printf("虧數\n"); else{ vector<int> buf; buf.push_back(1); int upper = static_cast<int>(sqrt(n)); for(int i=2; i<upper; ++i) if(n % i == 0){ buf.push_back(n/i); buf.push_back(i); } if(n % upper == 0){ buf.push_back(upper); if(n / upper != upper) buf.push_back(n / upper); } for(vector<int>::const_iterator iter = buf.begin(); iter != buf.end(); ++iter){ n -= *iter; if(n < 0) break; } if(n > 0) printf("虧數\n"); else if(n == 0) printf("完全數\n"); else printf("盈數\n"); } } return 0; }<file_sep>/a244.cpp #include <iostream> int main() { int N; std::cin >> N; for(int i=0; i<N; ++i){ long long int a, b, c; long long int d; std::cin >> a >> b >> c; switch(a){ case 1: d = b + c; break; case 2: d = b - c; break; case 3: d = b * c; break; case 4: d = b / c; break; } std::cout << d << "\n"; } return 0; }<file_sep>/a216.cpp #include <iostream> long long int f[30000] = {1}; long long int g[30000] = {1}; int main() { for(int i=1; i<30000; ++i){ f[i] = i + 1 + f[i-1]; g[i] = f[i] + g[i-1]; } int n; while(std::cin >> n){ std::cout << f[n-1] << " " << g[n-1] << "\n"; } return 0; }<file_sep>/a738.cpp #include <cstdio> int gcd(long long, long long); int main() { long long a ,b; while(scanf("%lld %lld", &a, &b) == 2) printf("%d\n", gcd(a, b)); } int gcd(long long a, long long b) { while(a!=0 && b!=0){ if(a >= b) a = a % b; else b = b % a; } if(a == 0) return (int)b; return (int)a; }<file_sep>/d016.cpp #include <iostream> #include <ios> #include <stack> #include <sstream> #include <string> #include <cctype> #include <cstdlib> int main() { std::string input; while(std::getline(std::cin, input) && input.size() != 0){ std::stringstream buf(input); std::string temp; std::stack<int> pool; while(buf >> temp){ if(isdigit(temp.c_str()[0])) pool.push(atoi(temp.c_str())); else{ int a = pool.top(); pool.pop(); int b = pool.top(); pool.pop(); char c = temp.c_str()[0]; int result; switch(c){ case '+': result = a+b; break; case '-': result = b-a; break; case '*': result = a*b; break; case '/': result = b/a; break; case '%': result = b%a; break; } pool.push(result); } } std::cout << pool.top() << "\n"; } return 0; }<file_sep>/a058.cpp #include <cstdio> int main() { int n; while(scanf("%d", &n) == 1){ int result[3] = {0}; for(int i=0; i<n; ++i){ int temp; scanf("%d", &temp); ++result[temp%3]; } printf("%d %d %d\n", result[0], result[1], result[2]); } return 0; }<file_sep>/d050.cpp #include <iostream> int main() { int h; while(std::cin >> h){ if(h >= 15) std::cout << h - 15 << "\n"; else std::cout << h + 9 << "\n"; } return 0; }<file_sep>/a104.cpp #include <iostream> #include <algorithm> int main() { int n; while(std::cin >> n){ int a[1000]; for(int i=0; i<n; ++i) std::cin >> a[i]; std::sort(&a[0], (a+n)); for(int i=0; i<n; ++i) std::cout << a[i] << " "; std::cout << "\n"; } return 0; }<file_sep>/d299.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); std::cout << "29786 + 850 + 850 = 31486"; return 0; }<file_sep>/d114.cpp #include <iostream> #include <string> using std::string; string ary[100] = {"1", "2", "6", "24", "120", "720", "5040", "40320", "362880", "3628800"}; string times(const string&, int num); void times_two(string &); void plus(string&, string&) int main() { for(int i=10; 1!=100; ++i) ary[i] = ary[i-1] * (i+1); std::cout << ary[99] << "\n"; return 0; } string times(const string& ori, int num) { string result = ori; string a; while(num > 0){ if(num & 1){ plus(a, result); times_two(result); num /= 2; } else{ times_two(result); num /= 2; } } plus(result, a); return result; } void plus(string& a, string& b) { <file_sep>/d018.cpp #include <vector> #include <utility> #include <sstream> #include <iostream> #include <string> int main() { std::string input; while(std::getline(std::cin, input) && input.size() != 0){ std::stringstream buf(input); std::vector< std::pair<int, double> > pool; int seq; char sep; double num; while(buf >> seq >> sep >> num){ //std::cout << seq << " " << num << "\n"; pool.push_back(std::make_pair(seq, num)); } double sum = 0; for(size_t i=0; i!=pool.size(); ++i) if(pool[i].first % 2 == 0) sum -= pool[i].second; else sum += pool[i].second; std::cout << sum <<"\n"; } return 0; }<file_sep>/a736f.cpp #include <iostream> #include <ios> #include <cstdlib> int main() { int T; std::ios_base::sync_with_stdio(false); std::cin >> T; for(int i=0; i!=T; ++i){ int N; std::cin >> N; //std::cout << N << "\n"; int t_left = 0, t_right = 0; int current_pos = 0; for(int j=0; j!=N; ++j){ int temp; int next_pos; std::cin >> temp; //std::cout << temp << "\n"; next_pos = current_pos + temp; if(next_pos >= 0 && current_pos >= 0) t_right += abs(temp); else if(next_pos <= 0 && current_pos <= 0) t_left += abs(temp); else if(current_pos < 0 && next_pos > 0){ t_left -= current_pos; t_right += next_pos; } else if(current_pos > 0 && next_pos < 0){ t_right += current_pos; t_left -= next_pos; } current_pos = next_pos; //std::cout << t_left << " " << t_right << "\n"; } if(t_left == t_right) std::cout << "Both okay\n"; else if(t_left < t_right) std::cout << "Go right\n"; else std::cout << "Go left\n"; } return 0; }<file_sep>/a273.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int n, k; while(std::cin >> n >> k){ bool c = true; if(n != 0){ if(k > n) c = false; else if(k == 0) c = false; else if(n % k != 0) c = false; } if(c) std::cout << "Ok!\n"; else std::cout << "Impossib1e!\n"; } return 0; }<file_sep>/d881.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int buf[50] = {1}; int d; while(std::cin >> d){ int t = d; d = 1; for(int i=1; i!=50; ++i, d += t) buf[i] = buf[i-1] + d; int sum = 0; for(int i=0; i!=50; ++i) sum += buf[i]; std::cout << sum << "\n"; } return 0; }<file_sep>/a021.cpp #include <iostream> #include <string> #include <algorithm> using std::cin; using std::cout; using std::string; using std::reverse; string my_plus(const string&, const string&); string my_minus(const string&, const string&); string mul(const string&, const string&); string div(const string&, const string&); static string base_minus(const string&, const string&); static string base_mul(const string&, int a); int main() { string input; while(getline(cin, input)){ if(input.size() == 0) break; size_t first_blank = input.find(' '); size_t second_blank = first_blank + 2; char op = input[first_blank + 1]; string num1 = input.substr(0, first_blank - 0); string num2 = input.substr(second_blank + 1, input.size() - second_blank - 1); switch(op){ case '+': cout << my_plus(num1, num2) << "\n"; break; case '-': cout << my_minus(num1, num2) << "\n"; break; case '*': cout << mul(num1, num2) << "\n"; break; case '/': cout << div(num1, num2) << "\n"; break; } input.clear(); } return 0; } string my_plus(const string& num1, const string& num2) { string r; int i = num1.size() - 1; int j = num2.size() - 1; bool carry = false; for(; i>=0 && j>=0; --i, --j){ r.push_back((num1[i] - '0' + num2[j] - '0' + (carry ? 1 : 0)) % 10 + '0' ); num1[i] - '0' + num2[j] - '0' + (carry ? 1 : 0) >= 10 ? carry = true : carry = false; } if(i >= 0) for(; i>=0; --i){ r.push_back((num1[i] - '0' + (carry ? 1 : 0)) % 10 + '0'); if(num1[i] == '9' && carry) carry = true; else carry = false; } else if(j >= 0) for(; j>=0; --j){ r.push_back((num2[j] - '0' + (carry ? 1 : 0)) % 10 + '0'); if(num2[j] == '9' && carry) carry = true; else carry = false; } reverse(r.begin(), r.end()); return r; } string my_minus(const string& num1, const string& num2) { bool neg; int temp = num1.compare(num2); if(temp == 0) return "0"; if(temp > 0) neg = false; else neg = true; string r; if(temp > 0) r = base_minus(num1, num2); else r = base_minus(num2, num1); if(neg) r.push_back('-'); reverse(r.begin(), r.end()); return r; } string base_minus(const string& num1, const string& num2) { string r; bool carry; int i = num1.size() - 1; int j = num2.size() - 1; for(; i>=0 && j >=0; --i, --j){ if(num1[i] >= num2[j]){ r.push_back(num1[i] - num2[j] + '0'); carry = false; } else{ r.push_back(num1[i] + 10 - num2[j] +'0'); carry = true; } } for(; i>=0; --i){ if(carry && num1[i] > '0'){ r.push_back(num1[i] - 1); carry = false; } else if(carry && num1[i] == '0') r.push_back('9'); else if(!carry) r.push_back(num1[i]); } reverse(r.begin(), r.end()); return r; } string mul(const string& num1, const string& num2) { int i = num2.size() - 1; string r = "0"; for(; i>=0; --i){ string temp = base_mul(num1, num2[i] - '0'); temp.append(string(num2.size()-1-i,'0')); r = my_plus(r, temp); } return r; } string div(const string& num1, const string& num2) { if(num1.compare(num2) < 0) return "0"; string r; string num1_c = num1; while(num1_c.compare(num2)){ string sub = num1_c.substr(0,num2.size()); if(sub.compare(num2) == 1){ int i; bool equal = false; string temp = num2; for(i = 1; i < 10; ++i){ if (sub.compare(temp) < 0){equal = false; break;} else if(sub.compare(temp) == 0){ equal = true; break; } else{ temp = my_plus(temp, num2); } } r.push_back(i-1+'0' + (equal?1:0)); } else if(sub.compare(num2) == 0) r.push_back('1'); else r.push_back('0'); num1_c = my_minus(num1_c, num2); } size_t not_zero = 0; for(; not_zero != r.size(); ++not_zero) if(r[not_zero] != '0') break; return r.substr(not_zero, r.size() - not_zero); } string base_mul(const string& num, int a) { string r; int i = num.size() - 1; int carry = 0; for(; i>=0; --i){ int temp = (num[i] - '0') * a + carry; r.push_back(temp % 10 + '0'); carry = temp / 10; } if(carry != 0) r.push_back(carry + '0'); reverse(r.begin(), r.end()); return r; } <file_sep>/d092.cpp #include <iostream> #include <ios> #include <algorithm> #include <vector> #include <utility> using std::cin; using std::cout; using std::vector; using std::sort; using std::pair; using std::make_pair; bool comp(const pair<char, int>& p1, const pair<char, int>& p2) { if(p1.second < p2.second) return false; if(p1.second == p2.second){ if(p1.first == '>') return true; if(p2.first == '>') return false; if(p1.first == '=') return true; if(p2.first == '=') return false; } return true; } int main() { int n; while(cin >> n && n != 0){ long long int a, b; vector< pair<char, long long int> > buf; for(int i=0; i!=n; ++i){ cin >> a >> b; long long int c = a + b; if(a > b) buf.push_back(make_pair('>', c)); else if(a == b) buf.push_back(make_pair('=', c)); else buf.push_back(make_pair('<', c)); } sort(buf.begin(), buf.end(), comp); for(size_t i=0; i != buf.size(); ++i) std::cout << buf[i].first << buf[i].second << " "; std::cout << "\n"; } return 0; }<file_sep>/d533.cpp /* This is not correct perhaps. * * == and != is defined for a complex number a+bi (b != 0) * * > and < are not defined * * Here comes the question: a==1, b==1, c==1, d==1 * * It's OK to print "No" because > and < are undefined * * and it's also OK to print '=' because the two comples number equal */ #include <cstdio> int main() { int count; scanf("%d", &count); for(int i=0; i!=count; ++i){ double a,b,c,d; scanf("%lf %lf %lf %lf", &a, &b, &c, &d); if(b == d && d == 0){ if(a > c) printf(">\n"); else if(a == c) printf("=\n"); else printf("<\n"); } else printf("No\n"); } return 0; } <file_sep>/d356.cpp #include <iostream> #include <ios> int main() { double k; while(std::cin >> k){ double sum = 1; double i = 2; while(sum <= k){ sum += 1/i; ++i; } std::cout << static_cast<int>(i-1) << "\n"; } return 0; }<file_sep>/d827.cpp #include <iostream> #include <ios> int main() { int n; while(std::cin >> n){ std::cout << (n/12*50 + n%12*5); } return 0; }<file_sep>/a147.cpp #include <iostream> int main() { int n; while(std::cin >> n){ if(n == 0) break; for(int i=0; i<n; ++i) if(i%7 != 0) std::cout << i << " "; std::cout << "\n"; } }<file_sep>/a224.cpp #include <iostream> #include <cctype> #include <string> #include <map> using std::cin; using std::cout; using std::string; using std::map; int main() { string input; while(std::cin >> input){ map<char, int> temp; string::const_iterator iter; for(iter = input.begin(); iter != input.end(); ++iter) if(isalpha(*iter)){ if(temp.find(toupper(*iter)) == temp.end()) temp[toupper(*iter)] = 1; else ++temp[toupper(*iter)]; } int odd = 0; for(map<char, int> :: const_iterator miter = temp.begin(); miter != temp.end(); ++miter){ if((miter ->second) % 2 != 0) ++odd; if(odd > 1) break; } if(odd > 1) cout << "no...\n"; else cout << "yes !\n"; } return 0; }<file_sep>/a272.cpp /* This works but cannot get ACed */ #include <iostream> int main() { int buf[50000]; buf[0] = 1, buf[1] = 2; for(int i=2; i != 50000; ++i) buf[i] = (buf[i-1] + buf[i-2]) % 10007; int n; while(std::cin >> n){ if(n <= 50000) std::cout << buf[n-1] <<"\n"; else{ int a, b, c, k; a = buf[49998]; b = buf[49999]; k = 50001; while(k <= n){ c = a; a = (a + b + 1) % 10007; b = c; ++k; } std::cout << a << "\n"; } } return 0; }<file_sep>/d069.cpp #include <iostream> int main() { int x; std::cin >> x; for(int i=1; i<=x; ++i){ int y; std::cin >> y; if((y%400 == 0) || ((y%4==0) && (y%100 != 0))) std::cout << "a leap year\n"; else std::cout << "a normal year\n"; } return 0; }<file_sep>/a694.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int n, m; int food[500][500]; while(std::cin >> n >> m){ for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) std::cin >> food[i][j]; for(int i=1; i<n; ++i) food[0][i] += food[0][i-1]; for(int i=1; i<n; ++i) food[i][0] += food[i-1][0]; for(int i=1; i<n; ++i) for(int j=1; j<n; ++j) food[i][j] = food[i][j] + food[i-1][j] + food[i][j-1] - food[i-1][j-1]; for(int i=0; i!=m; ++i){ int x1, y1, x2, y2; std::cin >> x1 >> y1 >> x2 >> y2; int sum = 0; if(x1 == 1 && y1 == 1) sum = food[x2-1][y2-1]; else if(x1 == 1) sum = food[x2-1][y2-1] - food[x2-1][y1-2]; else if(y1 == 1) sum = food[x2-1][y2-1] - food[x1-2][y2-1]; else sum = food[x2-1][y2-1] + food[x1-2][y1-2] - food[x1-2][y2-1] - food[x2-1][y1-2]; std::cout << sum << "\n"; } } return 0; }<file_sep>/a271.cpp #include <iostream> #include <cstdio> /*for getchar() to consume a '\n'*/ #include <sstream> int main() { int n; std::cin >> n; for(int i=0; i!=n; ++i){ int x, y, z, w, n, m; std::cin >> x >> y >> z >> w >> n >> m; int poison_level = 0; getchar(); /* consume the '\n' */ std::string input; std::getline(std::cin, input); if(input.size() != 0){ std::stringstream buf; buf << input; int temp; while(buf >> temp){ //std::cout << temp << " "; m -= poison_level * n; if(m <= 0) break; if(temp == 1) m += x; else if(temp == 2) m += y; else if(temp == 3) m -= z; else if(temp == 4){ m -= w; poison_level += 1; } //std::cout << m << " "; if(m <= 0) break; } } if(m > 0) std::cout << m <<"g\n"; else std::cout << "bye~Rabbit\n"; } return 0; }<file_sep>/a702.cpp #include <iostream> #include <ios> #include <vector> using std::vector; using std::cin; using std::cout; int temp[20000000]; int main() { vector<int> prime_table; for(int i=1; i<=20000000; ++i) temp[i] = i; temp[0] = 0; temp[1] = 0; int upper = 4473; while(true){ int i = 2; while(true){ if(temp[i] != 0) break; else ++i; } if(temp[i] > upper) break; prime_table.push_back(temp[i]); for(int j = i; j < 20000000; j += i) temp[j] = 0; } for(int i=0; i<20000000; ++i) if(temp[i] != 0) prime_table.push_back(i); /* for(int i=prime_table.back(); prime_table.back() <= 20000000; i+=2){ bool isP = true; for(size_t j=0; j != prime_table.size() && prime_table[j] * prime_table[j] <= i; ++j) if(i % prime_table[j] == 0){ isP = false; break; } if(isP) prime_table.push_back(i); } */ vector<int> result; for(size_t i=0; result.size() <= 100000; ++i) if(prime_table[i+2] - prime_table[i] == 4 || prime_table[i+1] - prime_table[i] == 4) result.push_back(prime_table[i]); int S; while(std::cin >> S){ std::cout << "(" << result[S-1] << ", " << result[S-1] + 4 << ")\n"; } return 0; }<file_sep>/a742.cpp #include <cstdio> #include <queue> #include <utility> #include <cstring> using namespace std; #define enqueue push int map[2005][2005]; int dist[2005][2005]; void visit(int, int, queue< pair<int, int> >&); int main() { int N, M, x0, y0, x1, y1, K; while(scanf("%d %d %d %d %d %d %d", &N, &M, &x0, &y0, &x1, &y1, &K) == 7){ for(int i=0; i<N; ++i){ for(int j=0; j<M; ++j){ map[i][j] = 0; if(j != 0) map[i][j] += 1; if(j != M-1) map[i][j] += 10; if(i != 0) map[i][j] += 100; if(i != N-1) map[i][j] += 1000; } } for(int i=1; i <=K; ++i){ int x2, y2, x3, y3; scanf("%d %d %d %d", &x2, &y2, &x3, &y3); if(x2 == x3){ map[x2][y2] -= 10; map[x3][y3] -= 1; int a = y2+1; int b = y3-1; while(a<=b){ map[x2][a] -= 11; ++a; } } if(y2 == y3){ map[x2][y2] -= 1000; map[x3][y3] -= 100; int a = x2+1; int b = x3-1; while(a<=b){ map[a][y2] -= 1100; ++a; } } } memset(dist, 0, sizeof(dist)); dist[x0][y0] = 0; queue< pair<int, int> > q; q.enqueue(make_pair(x0, y0)); while(!q.empty()){ pair<int, int> point = q.front(); if(point.first == x1 && point.second == y1) break; q.pop(); visit(point.first, point.second, q); } if(dist[x1][y1] == 0) printf("%d\n", 10080); else printf("%d\n", dist[x1][y1]); } } void visit(int y, int x, queue< pair<int, int> >& q) { if(map[y][x] < 10000){ int temp = map[y][x]; map[y][x] += 10000; if(temp % 10 == 1){ q.enqueue(make_pair(y, x-1)); dist[y][x-1] = dist[y][x]+1; } temp /= 10; if(temp % 10 == 1){ q.enqueue(make_pair(y, x+1)); dist[y][x+1] = dist[y][x]+1; } temp /= 10; if(temp % 10 == 1){ q.enqueue(make_pair(y-1, x)); dist[y-1][x] = dist[y][x]+1; } temp /= 10; if(temp == 1){ q.enqueue(make_pair(y+1, x)); dist[y+1][x] = dist[y][x]+1; } } }<file_sep>/b130.cpp #include <cstdio> #include <bitset> using std::bitset; int main() { int M; while(scanf("%d", &M) == 1){ bitset<1000> buf; int min = 1001; int max = -1; int count = 0; for(int i=0; i!=M; ++i){ int temp; scanf("%d", &temp); if(buf[temp-1] != 1){ buf[temp-1] = 1; ++count; } if(temp < min) min = temp-1; if(temp > max) max = temp-1; } printf("%d\n", count); for(; min<=max; ++min) if(buf[min] == 1) printf("%d ", min+1); printf("\n"); } return 0; }<file_sep>/a215.cpp #include <cstdio> int main() { int a, b; while(scanf("%d %d", &a, &b) == 2){ int sum = 0; int a0 = a; for(; ; ++a){ sum += a; if(sum > b) break; } printf("%d\n", a - a0 + 1); } return 0; }<file_sep>/d086.cpp #include <iostream> #include <string> #include <cctype> int main() { std::string input; while(std::cin >> input && input.compare("0") != 0){ int sum = 0; for(size_t i=0; i!=input.size(); ++i){ if(isalpha(input[i])) sum += (toupper(input[i]) - 'A' + 1); else{ sum = -1; break; } } if(sum != -1) std::cout << sum << "\n"; else std::cout << "Fail\n"; } return 0; }<file_sep>/a006.cpp #include <iostream> #include <cmath> int main() { double a, b, c; while(std::cin >> a){ std::cin >> b >> c; double j = b*b - 4*a*c; if(j > 0){ double x1 = (sqrt(j) - b)/2/a; double x2 = (-sqrt(j) - b)/2/a; if(x1 == -0) x1 = 0; if(x2 == -0) x2 = 0; std::cout << "Two different roots x1=" << x1 << " , x2=" << x2 << "\n"; } else if(j == 0){ double x = b/2/a/(-1); if(x == -0) x = 0; std::cout << "Two same roots x=" << x << "\n"; } else std::cout << "No real root\n"; } return 0; } <file_sep>/a065.cpp #include <iostream> #include <string> int main() { std::string input; while(std::cin >> input){ for(int i=1; i!=7; ++i) std::cout << (input[i] > input[i-1] ? input[i] - input[i-1] : input[i-1] - input[i]); std::cout << "\n"; } return 0; }<file_sep>/d323.cpp #include <iostream> #include <ios> #include <vector> #include <algorithm> int main() { int n; while(std::cin >> n){ std::vector<int> buf; for(int i=0; i!=n; ++i){ int temp; std::cin >> temp; buf.push_back(temp); } std::sort(buf.begin(), buf.end()); for(std::vector<int>::const_iterator iter = buf.begin(); iter != buf.end(); ++iter) std::cout << *iter << " "; std::cout << "\n"; } return 0; }<file_sep>/d929.cpp #include <cstdio> #include <cstring> int main() { int n; while(scanf("%d", &n) == 1){ for(int i=0; i!=n; ++i){ char buf[110]; scanf("%s", buf); int last = strlen(buf) - 1; bool is_par = true; for(int j=0; j<=last; ++j, --last) if(buf[j] != buf[last]){ is_par = false; break; } if(is_par) printf("yes\n"); else printf("no\n"); } } return 0; }<file_sep>/d574/d574.cpp /* reading the whole input and then process is a two-pass method * but read and process could involve more I/O so optimization calls * for profiling. This two-pass method got AC within 0.2 seconds and * eaten up 14.8MB RAM anyway. */ #include <iostream> #include <ios> #include <string> #include <cstdio> using std::cin; using std::cout; using std::string; int main() { std::ios_base::sync_with_stdio(false); unsigned int length; string input, result; char buf[10]; while(cin >> length >> input){ bool shorter = true; char currentChar = input[0]; int num_currentChar = 1; for(size_t i=1; i!=length; ++i){ if(input[i] != currentChar){ sprintf(buf, "%d", num_currentChar); result.append(buf).push_back(currentChar); currentChar = input[i]; num_currentChar = 1; if(result.size() >= length){ shorter = false; break; } } else ++num_currentChar; } if(shorter){ sprintf(buf, "%d", num_currentChar); result.append(buf).push_back(currentChar); if(result.size() >= length) shorter = false; } if(shorter) cout << result << "\n\n"; else cout << input << "\n\n"; } return 0; }<file_sep>/a218.cpp #include <iostream> #include <ios> #include <utility> #include <algorithm> #include <vector> #include <cstring> bool comp(const std::pair<int, int>& p1, const std::pair<int, int>& p2) { if(p1.second > p2.second) return true; if(p1.second == p2.second && p1.first < p2.first) return true; return false; } int main() { int n; int count_pool[10]; while(std::cin >> n){ memset(count_pool, 0, sizeof(count_pool)); for(int i=1; i<=n; ++i){ int temp; std::cin >> temp; count_pool[temp] += 1; } std::vector< std::pair<int, int> > result_pool; for(int i=0; i!=10; ++i) if(count_pool[i] != 0) result_pool.push_back(std::make_pair(i, count_pool[i])); std::sort(result_pool.begin(), result_pool.end(), comp); for(size_t i=0; i!=result_pool.size(); ++i) std::cout << result_pool[i].first << " "; std::cout << "\n"; } }<file_sep>/a263.cpp #include <iostream> #include <ios> #include <cstdlib> inline bool isLeapYear(int); inline int daysPassed(int, int ,int); int month[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int main() { std::ios_base::sync_with_stdio(false); int y1, m1, d1; while(std::cin >> y1 >> m1 >> d1){ int y2, m2, d2; std::cin >> y2 >> m2 >> d2; int sum = 0; if(y1 < y2){ for(int y=y1; y<y2; ++y){ sum += (isLeapYear(y) ? 366 : 365); } sum += (daysPassed(y2, m2, d2) - daysPassed(y1, m1, d1)); } else if(y1 > y2){ for(int y=y2; y<y1; ++y){ sum += (isLeapYear(y) ? 366 : 365); } sum += (daysPassed(y1, m1, d1) - daysPassed(y2, m2, d2)); } else{ //std::cout << daysPassed(y1, m1, d1) << "\n"; //std::cout << daysPassed(y2, m2, d2) << "\n"; sum = abs(daysPassed(y1, m1, d1) - daysPassed(y2, m2, d2)); } std::cout << sum << "\n"; } } bool isLeapYear(int year) { if(year % 400 == 0) return true; if(year % 4 == 0 && year % 100 != 0) return true; return false; } int daysPassed(int y, int m, int d) { int days = 0; for(int i=0; i<m-1; ++i) days += month[i]; if(isLeapYear(y) && m >= 3) days += 1; return days+d; }<file_sep>/a272_2.cpp #include <iostream> #include <cstring> void cal(int, int*, int (*)[3]); void dump_pool(const int (*result_pool)[3]) { for(int i=0; i!=3; ++i){ for(int j=0; j!=3; ++j) std::cout << result_pool[i][j] << " "; std::cout << "\n"; } std::cout << "\n"; } const int base_pool[3][3] = {{0,1,0}, {1,1,0}, {0,0,0}}; int main() { int n; while(std::cin >> n){ if(n == 1){ std::cout << 1 << "\n"; continue; } if(n == 2){ std::cout << 2 << "\n"; continue; } int buf[32]; int pos = 0; n = n - 2; //std::cout << n << "\n"; while(n > 1){ if(n % 2 == 0) buf[pos] = 0; else buf[pos] = 1; ++pos; n /= 2; } //std::cout << pos << "\n"; int result_pool[3][3]; cal(pos, buf, result_pool); std::cout << (1*result_pool[1][0] + 2*result_pool[1][1]) % 10007 <<"\n"; } } void cal(int pos, int* buf, int (*result_pool)[3]) { int old_pool[3][3]; memcpy(old_pool, base_pool, sizeof(base_pool)); /* int temp = pos - 1; for(; temp >= 0; --temp) std::cout << buf[temp] << " "; std::cout << std::endl; */ int new_pool[3][3]; for(pos = pos - 1; pos >= 0; --pos){ if(buf[pos] == 1){ for(int i=0; i!=3; ++i) for(int j=0; j!=3; ++j){ new_pool[i][j] = 0; for(int k=0; k!=3; ++k) new_pool[i][j] += old_pool[i][k] * old_pool[k][j] % 10007; } memcpy(old_pool, new_pool, sizeof(old_pool)); for(int i=0; i!=3; ++i) for(int j=0; j!=3; ++j) for(int k=0; k!=3; ++k){ new_pool[i][j] = 0; for(int k=0; k!=3; ++k) new_pool[i][j] += old_pool[i][k] * base_pool[k][j] % 10007; } memcpy(old_pool, new_pool, sizeof(old_pool)); } else{ for(int i=0; i!=3; ++i) for(int j=0; j!=3; ++j) for(int k=0; k!=3; ++k){ new_pool[i][j] = 0; for(int k=0; k!=3; ++k) new_pool[i][j] += old_pool[i][k] * old_pool[k][j] % 10007; } memcpy(old_pool, new_pool, sizeof(old_pool)); } } memcpy(result_pool, old_pool, sizeof(old_pool)); //dump_pool(result_pool); }<file_sep>/a693.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int n, m; int food[100000]; while(std::cin >> n >> m){ for(int i=0; i<n; ++i) std::cin >> food[i]; for(int i=1; i<n; ++i) food[i] += food[i-1]; for(int i=0; i<m; ++i){ int sum = 0; int begin, end; std::cin >> begin >> end; if(begin == 1) sum = food[end-1]; else sum = food[end-1] - food[begin-2]; std::cout << sum << "\n"; } } return 0; }<file_sep>/d984.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); long long int a, b, c; char result; while(std::cin >> a >> b >> c){ if(a > b && b >= c){ if(b + c > a) result = 'B'; else result = 'A'; } else if(a > c && c >= b){ if(b + c > a) result = 'C'; else result = 'A'; } else if(b > a && a >= c){ if(a + c > b) result = 'A'; else result = 'B'; } else if(b > c && c >= a){ if(a + c > b) result = 'C'; else result = 'B'; } else if(c > b && b >= a){ if(b + a > c) result = 'B'; else result = 'C'; } else if(c > a && a >= b){ if(b + a > c) result = 'A'; else result = 'C'; } std::cout << result << "\n"; } return 0; }<file_sep>/d058.cpp #include <iostream> int main() { int x; while(std::cin >> x){ if(x > 0) std::cout << 1 << "\n"; else if(x == 0) std::cout << 0 << "\n"; else std::cout << -1; } return 0; }<file_sep>/d681.cpp #include <iostream> #include <sstream> #include <string> #include <ios> void cal(std::string&, const std::string&, bool); int main() { std::string input; std::ios_base::sync_with_stdio(false); while(std::getline(std::cin, input)){ std::stringstream buf(input); std::string result; buf >> result; std::string temp; bool isNum = false; bool opIsAnd = true; std::cout << result; while(buf >> temp){ if(isNum){ std::cout << temp; if(opIsAnd) cal(result, temp, true); else cal(result, temp, false); isNum = false; } else{ if(temp.compare("or") == 0){ std::cout << "||"; opIsAnd = false; } else if(temp.compare("and") == 0){ std::cout << "&&"; opIsAnd = true; } isNum = true; } } std::cout << " = " << result << "\n"; } return 0; } void cal(std::string& result, const std::string& temp, bool opIsAnd) { if(opIsAnd) for(size_t i=0; i!=5; ++i) result[i] = ((result[i] - '0') & (temp[i] - '0')) + '0'; else for(size_t i=0; i!=5; ++i) result[i] = ((result[i] - '0') | (temp[i] - '0')) + '0'; }<file_sep>/a721a.cpp #include <iostream> #include <ios> #include <algorithm> #include <vector> int main(int argc, char const *argv[]) { int T; std::ios::sync_with_stdio(false); std::cin >> T; for(int i=0; i!=T; ++i){ int M, N; std::cin >> M >> N; std::vector<int> buf; for(int j=0; j!=M; ++j){ int temp; std::cin >> temp; buf.push_back(temp); } std::sort(buf.begin(), buf.end()); if(N > buf.back()) std::cout << "not yet\n"; else{ size_t z; size_t limit = buf.size(); for(z=0; z!=limit; ++z) if(buf[z] >= N) break; std::cout << (z+1)*50 << "\n"; } } return 0; }<file_sep>/d060.cpp #include <iostream> int main() { int m; while(std::cin >> m){ if(25 - m >= 0) std::cout << 25 - m << "\n"; else std::cout << 85 - m << "\n"; } return 0; }<file_sep>/a054.cpp #include <iostream> #include <ios> int main() { int alpha[] = {10, 11, 12, 13, 14, 15 ,16, 17, 34, 18, 19, 20, 21, 22, 35, 23, 24, 25, 26, 27, 28, 29, 32, 30, 31, 33}; std::ios_base::sync_with_stdio(false); for(int i=0; i != 26; ++i) alpha[i] = alpha[i] / 10 + alpha[i] % 10 * 9; std::string input; while(std::cin >> input){ int num = 0; for(int i=0; i != 8; ++i){ num += (8-i) * (input[i] - '0'); //std::cout << num << '\n'; } num += (input[8] - '0'); //std::cout <<"\n" << num << '\n'; for(int i=0; i!=26; ++i) if((alpha[i] + num) % 10 == 0) std::cout << static_cast<char>(i+'A'); std::cout << "\n"; } return 0; }<file_sep>/d460.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int age; while(std::cin >> age){ int price; if(age < 6) price = 0; else if(age < 12) price = 590; else if(age < 18) price = 790; else if(age < 60) price = 890; else price = 399; std::cout << price << "\n"; } return 0; }<file_sep>/d068.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int w; while(std::cin >> w){ if(w > 50) w -= 1; std::cout << w << "\n"; } return 0; }<file_sep>/d098.cpp #include <iostream> #include <ios> #include <sstream> #include <string> #include <cstdlib> int main() { std::string input; while(std::getline(std::cin, input) && input.size() != 0){ std::stringstream buf(input); int sum = 0; std::string temp; while(buf >> temp){ bool isNum = true; for(size_t i=0; i!=temp.size(); ++i) if(!isdigit(temp[i])){ isNum = false; break; } if(isNum) sum += atoi(temp.c_str()); } std::cout << sum << "\n"; } return 0; }<file_sep>/a740.cpp #include <cstdio> #include <vector> using std::vector; int main() { int n; vector<int> prime_table; int temp[46369]; for(int i=1; i<=46368; ++i) temp[i] = i; temp[0] = 0; temp[1] = 0; int upper = 216; while(true){ int i = 2; while(true){ if(temp[i] != 0) break; else ++i; } if(temp[i] > upper) break; prime_table.push_back(temp[i]); for(int j = i; j < 46369; j += i) temp[j] = 0; } for(int i=0; i<46369; ++i) if(temp[i] != 0) prime_table.push_back(i); while(scanf("%d", &n) == 1){ vector<int> result; while(n > 1){ bool premature = false; for(vector<int>::const_iterator iter = prime_table.begin(); iter != prime_table.end() && *iter * *iter <= n; ++iter) if(n % *iter == 0){ result.push_back(*iter); n /= *iter; premature = true; break; } if(!premature){ result.push_back(n); n = 1; } } int sum = 0; for(vector<int>::const_iterator iter = result.begin(); iter != result.end(); ++iter) sum += *iter; printf("%d\n", sum); } return 0; }<file_sep>/b238_2.cpp #include <iostream> #include <cstring> void normalize(long long int (*result_pool)[2], int M) { for(int i=0; i!=2; ++i) for(int j=0; j!=2; ++j) result_pool[i][j] = (result_pool[i][j] + M) % M; } void dump_pool(long long int (*result_pool)[2]) { for(int i=0; i!=2; ++i){ for(int j=0; j!=2; ++j) std::cout << result_pool[i][j] << " "; std::cout << "\n"; } std::cout << "\n"; } void cal(int, int*, long long int (*)[2], long long int (*)[2], int); int main() { int n; std::cin >> n; for(int i=0; i!=n; ++i){ long long a,b,c,d,M; int day; std::cin >> a >> b >> c >> d >> day >> M; if(day != 0){ long long int base_pool[2][2] = {{a, b}, {c, d}}; //dump_pool(base_pool); int buf[32]; int pos = 0; while(day > 1){ if(day % 2 == 0) buf[pos++] = 0; else buf[pos++] = 1; day /= 2; } long long int result_pool[2][2]; cal(pos, buf, result_pool, base_pool, M); if((a + b) % M == (c + d) % M) std::cout << "Normal\n"; else if((a + b) % M > (c + d) % M) std::cout << "Tsundere\n"; else std::cout << "Haraguroi\n"; } else std::cout << "Normal\n"; } return 0; } void cal(int pos, int* buf, long long int (*result_pool)[2], long long int (*base_pool)[2], int M) { long long int old_pool[2][2]; memcpy(old_pool, base_pool, sizeof(base_pool)); /* int temp = pos - 1; for(; temp >= 0; --temp) std::cout << buf[temp] << " "; std::cout << std::endl; */ long long int new_pool[2][2]; for(pos = pos - 1; pos >= 0; --pos){ if(buf[pos] == 1){ for(int i=0; i!=2; ++i) for(int j=0; j!=2; ++j){ new_pool[i][j] = 0; for(int k=0; k!=2; ++k) new_pool[i][j] += (old_pool[i][k] * old_pool[k][j]) % M; } normalize(new_pool, M); memcpy(old_pool, new_pool, sizeof(old_pool)); for(int i=0; i!=2; ++i) for(int j=0; j!=2; ++j){ new_pool[i][j] = 0; for(int k=0; k!=2; ++k) new_pool[i][j] += (old_pool[i][k] * base_pool[k][j]) % M; } normalize(new_pool, M); memcpy(old_pool, new_pool, sizeof(old_pool)); } else{ for(int i=0; i!=2; ++i) for(int j=0; j!=2; ++j){ new_pool[i][j] = 0; for(int k=0; k!=2; ++k) new_pool[i][j] += (old_pool[i][k] * old_pool[k][j]) % M; } normalize(new_pool, M); memcpy(old_pool, new_pool, sizeof(old_pool)); } } memcpy(result_pool, old_pool, sizeof(old_pool)); dump_pool(result_pool); }<file_sep>/d835.cpp #include <cstdio> #include <vector> #include <cstdlib> using std::vector; int main() { vector<int> r11, r21; int w11 = 0, w21 = 0, l11 = 0, l21 = 0; int c; while((c = getchar()) && c != 'E'){ if(c == 'W'){ ++w11; ++w21; } else if(c == 'L'){ ++l11; ++l21; } if((w11 >= 11 || l11 >= 11) && abs(w11 - l11) >= 2){ r11.push_back(w11); r11.push_back(l11); w11 = 0; l11 = 0; } if((w21 >= 21 || l21 >= 21) && abs(w21 - l21) >= 2){ r21.push_back(w21); r21.push_back(l21); w21 = 0; l21 = 0; } } r11.push_back(w11); r11.push_back(l11); r21.push_back(w21); r21.push_back(l21); size_t i = 0; while(i!=r11.size()){ printf("%d:%d\n", r11[i],r11[i+1]); i += 2; } printf("\n"); i = 0; while(i!=r21.size()){ printf("%d:%d\n", r21[i], r21[i+1]); i += 2; } return 0; } <file_sep>/a095.cpp #include <iostream> int main() { int N, M; while(std::cin >> N){ std::cin >> M; if(M != N) std::cout << M+1 << "\n"; else std::cout << M << "\n"; } return 0; }<file_sep>/d071.cpp #include <iostream> int main() { int y; while(std::cin >> y){ if((y%400 == 0) || ((y%4==0) && (y%100 != 0))) std::cout << "a leap year\n"; else std::cout << "a normal year\n"; } return 0; }<file_sep>/d985/d985.cpp #include <iostream> #include <ios> int main() { std::ios_base::sync_with_stdio(false); int N; std::cin >> N; for(int i=1; i<=N; ++i){ int M; std::cin >> M; int sum = 0, min = 99999; for(int j=0; j!=M; ++j){ int m, s; std::cin >> m >> s; s += m * 60; sum += s; if(s < min) min = s; } std::cout << "Track " << i << ":\n"; std::cout << "Best Lap: " << min/60 << " minute(s) " << min%60 << " second(s).\n"; std::cout << "Average: " << sum/M/60 << " minute(s) " << sum/M%60 << " second(s).\n\n"; } return 0; }<file_sep>/d059.cpp #include <iostream> #include <cmath> #include <iomanip> #include <cstdlib> #include <ctime> int main() { int a, b; while(std::cin >> a >> b){ std::cout << static_cast<int>(pow(a, b)) << "\n"; std::cin >> a; std::cout << std::setprecision(3) << std::fixed; std::cout << sqrt(a) << "\n"; std::cin >> a; std::cout << abs(a) << "\n"; std::cin >> a >> b; srand(time(0)); std::cout << rand() %(b-a) + a << "\n"; } return 0; }<file_sep>/d073.cpp #include <iostream> int main() { int n; while(std::cin >> n){ if(n % 3 == 0) std::cout << n/3 << "\n"; else std::cout << n/3+1 << "\n"; } return 0; }
d850e50d2cb97b85c524802201efb624889fe132
[ "C++" ]
71
C++
rosynirvana/ZeroJudge
c48e7daf99da3f8c5928d20b51510c4ddbdea161
347e8bd5b18adb20d8c39efa700056696c720f6c
refs/heads/master
<file_sep>let dark = false; $(document).on("click", "#btn_lampu", function () { let img = $("#btn_lampu").find("img")[0]; if (dark) { dark = false; $("body").css("color", "black"); // $("h2").css("color", "white"); // $("h3").css("color", "white"); // $("h4").css("color", "white"); // $("h5").css("color", "white"); // $("h6").css("color", "white"); $(".card").removeClass("bg-dark text-light"); $("body").removeClass("bg-dark"); $(img).attr("src", "images/lamp_dark.svg"); } else { $("body").css("color", "white"); dark = true; $(".card").css("border-color", "white"); $(".card").addClass("bg-dark text-light"); $("body").addClass("bg-dark"); $(img).attr("src", "images/lamp_light.svg"); } }); let size = 1; $(document).on("click", "#btn_font_inc", function () { if (size < 3) { size++; var fontSize = parseInt($("body").css("font-size")); fontSize = fontSize + 15 + "px"; $("body").css({ "font-size": fontSize }); var fontSize = parseInt($("h5").css("font-size")); fontSize = fontSize + 15 + "px"; $("h5").css({ "font-size": fontSize }); } $.fn.fullpage.reBuild(); }); $(document).on("click", "#btn_font_dec", function () { if (size > 1) { size--; var fontSize = parseInt($("body").css("font-size")); fontSize = fontSize + -15 + "px"; $("body").css({ "font-size": fontSize }); var fontSize = parseInt($("h5").css("font-size")); fontSize = fontSize + -15 + "px"; $("h5").css({ "font-size": fontSize }); } $.fn.fullpage.reBuild(); }); let width = 1; $(document).on("click", "#btn_text_width_i", function () { if (width < 10) { width++; var textWidth = parseInt($("body").css("letter-spacing")); textWidth = textWidth + 1 + "px"; $("body").css({ "letter-spacing": textWidth }); } $.fn.fullpage.reBuild(); }); $(document).on("click", "#btn_text_width_d", function () { if (width > 1) { width--; var textWidth = parseInt($("body").css("letter-spacing")); textWidth = textWidth + -1 + "px"; $("body").css({ "letter-spacing": textWidth }); } $.fn.fullpage.reBuild(); }); let font = true; $(document).on("click", "#btn_disleksia", function () { if (font) { font = false; $("body").css("font-family", "Open-Dyslexic"); } else { font = true; $("body").css("font-family", "Sans-serif"); } }); <file_sep>$(document).ready(function () { let url = "https://services5.arcgis.com/VS6HdKS0VfIhv8Ct/arcgis/rest/services/COVID19_Indonesia_per_Provinsi/FeatureServer/0/query?where=1%3D1&outFields=Provinsi,Kasus_Posi,Kasus_Semb,Kasus_Meni&outSR=4326&f=json"; fetch(url) .then((response) => response.json()) .then((data) => { dataCovid = data.features; for (let i = 0; i < dataCovid.length; i++) { idxProv.push(dataCovid[i].attributes.Provinsi); } }) .catch((err) => { console.log(err); }); goToLanding(); }); function goToLanding() { isInLan = true; fetch("pages/landing.html") .then((response) => response.text()) .then((data) => { $("body").html(data); $(".se-pre-con").fadeOut("slow"); }) .catch((err) => { console.log(err); }); } $(document).on("click", ".btn-home", goToLanding); function goToNonTunanetra() { fetch("pages/nontunanetra.html") .then((response) => response.text()) .then((data) => { $("body").html(data); let el; for (let i = 0; i < dataCovid.length; i++) { let el = ` <div class="col-md-4 voiceable"> <div class="card mb-3"> <div class="card-header"> <h5 class="card-title">Provinsi ${dataCovid[i].attributes.Provinsi}</h5> </div> <div class="card-body"> <p class="card-text">Positif ${dataCovid[i].attributes.Kasus_Posi}</p> <p class="card-text">Sembuh ${dataCovid[i].attributes.Kasus_Semb}</p> <p class="card-text">Meninggal ${dataCovid[i].attributes.Kasus_Meni}</p> </div> </div> </div> `; $("#content").html($("#content").html() + el); } $(".se-pre-con").fadeOut("slow"); }) .catch((err) => { console.log(err); }); } function goToTunanetra() { // msg.text = "halaman sedang di muat, silahkan tunggu!"; // window.speechSynthesis.speak(msg); fetch("pages/tunanetra.html") .then((response) => response.text()) .then((data) => { $("body").html(data); $(".se-pre-con").fadeOut("slow"); }) .then(() => { // msg.text = // "halaman berhasil dimuat.silahkan tekan dan tahan tombol disekitaran tengah layar untuk mengaktifkan mikrofon dan sebutkan nama provinsi."; // window.speechSynthesis.speak(msg); }) .catch((err) => { console.log(err); }); }
1792fa4486be4dfcb99f0302c49a339f78613c06
[ "JavaScript" ]
2
JavaScript
ihzaa/Si-David
697d884226a65e0359013de7c652dd420ab2a4ce
1ce60e3594b9386aac4d01267ea93ebf42683111
refs/heads/master
<repo_name>leostein1234/leostein1234<file_sep>/Rosilind prob/stronghold/Computing GC Content.py def gc_Count (seq): nucleotide= {"A": 0, "C": 0, "T": 0, "G": 0} for nuc in seq: if nuc in nucleotide: nucleotide[nuc] += 1 percent_gc = 100* (nucleotide["G"] + nucleotide["C"]) / (nucleotide["G"] + nucleotide["C"] + nucleotide["A"] + nucleotide["T"]) return round(percent_gc, 10) file = open("rosalind_gc.txt", 'r') lines = file.readlines() dnaDict = {} for line in lines: if ">" in line: name = line.replace(">", "").replace("\n", "") dnaDict[name] = '' else: dnaDict[name] +=line for key in dnaDict: seq = dnaDict[key] dnaDict[key] = gc_Count(seq) for key, value in dnaDict.items(): print (key,value)<file_sep>/bioinformatics/Matplotlib/random lineplot pyplot.py import random as r from matplotlib import pyplot as plt print(plt.style.available) plt.style.use('fivethirtyeight') list_x = [0] list_y = [0] for x in range(100): list_x.append(r.randint(1, 100) - r.randint(1, 50)) list_y.append(1+list_y[x]) plt.plot(list_y, list_x, color = 'b', linestyle='--',label = 'first rand', linewidth = .9) plt.xlabel('x label') plt.ylabel('y label') plt.title('random graph') for x in range(100): list_x[x] = (r.randint(1, 100)) list_y[x] = (1 + list_y[x]) print(list_y) plt.plot(list_y, list_x, color = 'g', linestyle = '-',label='second rand', linewidth = .9) plt.show() <file_sep>/bioinformatics/DNAToolKit.py import collections nucliotides = ["A", "C", "G", "T"] reverseCom = {"A": "T", "C":"G", "G":"C", "T":"A"} DNA_Codons = { # 'M' - START, '_' - STOP "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A", "TGT": "C", "TGC": "C", "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E", "TTT": "F", "TTC": "F", "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G", "CAT": "H", "CAC": "H", "ATA": "I", "ATT": "I", "ATC": "I", "AAA": "K", "AAG": "K", "TTA": "L", "TTG": "L", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "ATG": "M", "AAT": "N", "AAC": "N", "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P", "CAA": "Q", "CAG": "Q", "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R", "AGA": "R", "AGG": "R", "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S", "AGT": "S", "AGC": "S", "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T", "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V", "TGG": "W", "TAT": "Y", "TAC": "Y", "TAA": "_", "TAG": "_", "TGA": "_" } def validateSeq(dnaSeq): tempSeq = dnaSeq.upper() for nuc in tempSeq: if nuc not in nucliotides: print("not valid") return False return tempSeq def countNucFrequency(seq): tempSeqDict = {"A": 0, "C": 0, "T": 0, "G": 0} for nuc in seq: tempSeqDict [nuc] += 1 return tempSeqDict #return dict(collections.Counter(seq)) easier way to do what is done in countNucFrewuency def dnaToRna(seq): return seq.replace("T", "U") def reverseComplement (seq): string2 = '' for nuc in seq: string = reverseCom[nuc] string2 +=string return string2[::-1] #return ''.join([reverseCom[nuc] for nuc in seq]) [::-1]) def gc_Count (seq): nucleotide: {"A": 0, "C": 0, "T": 0, "G": 0} for nuc in seq: if nuc in nucleotide: nucleotide[nuc] += 1 percent_gc = (nucleotide["G"] + nucleotide["C"]) / (nucleotide["G"] + nucleotide["C"] +nucleotide["A"] + nucleotide["T"]) return nucleotide def transRNAtoProtein(seq): seq = seq.replace("U","T") length = len(seq) string = '' protein = '' for x in range(int(length/3)): for y in range(3): string += seq[x*3 + y] string = DNA_Codons[string] protein += string string = '' print (protein) def RNAtoProtein(seq, init_pos=0): #simpilar code of transRNAtoProtein seq = seq.replace("U","T") return [DNA_Codons[seq[pos:pos + 3]] for pos in range(init_pos, len(seq) -2, 3)] def readingFrames(seq): reverseSeq = seq[::-1] frames = [] reverseFrames = [] for x in range(0,3): frames.append(RNAtoProtein(seq, x)) reverseFrames.append(RNAtoProtein(seq, x)) return frames, reverseFrames def proteinInReadingFrame(AA_sequence): proteins = [] oneProtein = '' for i in range(len(AA_sequence)): oneProtein += AA_sequence[i] if AA_sequence[i] == '_': proteins.append(oneProtein.replace(' ', '')) oneProtein = '' elif oneProtein[0] == 'M': oneProtein += AA_sequence[i] if AA_sequence[i] == 'M': oneProtein += AA_sequence[i] return proteins <file_sep>/Rosilind prob/stronghold/Mendel's First Law.py def percentDomAllele(x,y,z): total = x + y + z zz = (z/total) * ((z-1)/(total-1)) rh = (z/total) * (y/(total -1)) + (y/total) * (z/(total -1)) hh = (y/total) * ((y-1)/(total-1)) probDom = 1- (zz + hh/4 + rh/2) return probDom print(percentDomAllele(18,28,20)) <file_sep>/Rosilind prob/algorithmic Heights/Fibonacci numbers.py def fibNum(num): new = 1 old = 1 for x in range(num - 1): temp = new new = old old = old + temp return new print(fibNum(20))
73ba080a0e26dbc2b08a99f05171bb0bdb9c23c2
[ "Python" ]
5
Python
leostein1234/leostein1234
6b0cdcac1dc17fbf0b6a6b483847ef31e0a8dadc
548a013dec07c3b1a2cc3e8dd67e4353eb15a9cb
refs/heads/master
<file_sep>rootProject.name='Ourchat' include ':app' include ':login' include ':chat' include ':my' include ':contacts' include ':commond' <file_sep>package com.lpm_wxl.chat.debug; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.lpm_wxl.chat.R; public class Chat_Debug_MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_debug_activity_main); } } <file_sep>package com.lpm_wxl.commond; public class a { } <file_sep>package com.lpm_wxl.my.debug; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.lpm_wxl.my.R; public class My_Debug_MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_debug_activity_main); } }
9eebf60338bbc96f801db9251983289e2ff0ba03
[ "Java", "Gradle" ]
4
Gradle
laipanmeng/Ourchat
ed0e71f0a319a0e554566154f91805e8526a1cfa
3010c88a56aa9e596c44990c067d0b45143bafe4
refs/heads/main
<repo_name>SwaXTech/CursoDjango<file_sep>/platzigram/views.py from django.http import HttpResponse from datetime import datetime import json def hello_world(request): return HttpResponse("Hello, world!") def time(request): now = datetime.now().strftime('%b %dth, %Y - %H:%M hs') return HttpResponse("Que onda!. La hora es: {}".format(str(now))) def hi(request): #import pdb # Add a debugger for request #pdb.set_trace() return HttpResponse("Hola!!") def sort_numbers(request): numbers = list(eval(request.GET['numbers'])) numbers.sort() data = { 'status': 'ok', 'numbers': numbers, 'message': 'Integer sorted successfully' } return HttpResponse(json.dumps(data, indent = 2), content_type = 'application/json') def hello(request, name, age): if age < 18: message = "Sorry {}, you are not allowed here".format(name) else: message = 'Hello {}!, Welcome to Platzigram!'.format(name) return HttpResponse(message) <file_sep>/posts/views.py from django.shortcuts import render from datetime import datetime posts = [ { 'title': 'Mont Blac', 'user': { 'name': "<NAME>", 'picture': 'https://picsum.photos/60/60/?image=1027' }, 'timestamp': datetime.now().strftime('%b %dth, %Y - %H:%M hs'), 'picture': 'https://picsum.photos/800/600/?image=1036' }, { 'title': 'Vía Lactea', 'user': { 'name': "<NAME>", 'picture': 'https://picsum.photos/60/60/?image=1005' }, 'timestamp': datetime.now().strftime('%b %dth, %Y - %H:%M hs'), 'picture': 'https://picsum.photos/800/600/?image=903' }, { 'title': 'Nuevo Auditorio', 'user': { 'name': "Uriel (thespianartist)", 'picture': 'https://picsum.photos/60/60/?image=883' }, 'timestamp': datetime.now().strftime('%b %dth, %Y - %H:%M hs'), 'picture': 'https://picsum.photos/800/600/?image=1076' } ] def list_posts(request): return render(request, 'feed.html', { 'posts': posts }) <file_sep>/startProject.sh echo "Executing: django-admin startproject platzigram ." django-admin startproject platzigram . <file_sep>/users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): """Proxy model that extends the base data with other information""" user = models.OneToOneField(User, on_delete = models.CASCADE) website = models.URLField(max_length = 100, blank = True) biography = models.TextField(blank = True) phone_number = models.CharField(max_length = 20, blank = True) picture = models.ImageField(upload_to = 'users/pictures', blank = True, null = True) created = models.DateTimeField(auto_now_add= True) modified = models.DateTimeField(auto_now = True) def __str__(self): return self.user.username <file_sep>/requirements.txt asgiref==3.3.1 certifi==2020.12.5 Django==3.1.6 django-extensions==3.1.1 Pillow==8.1.0 pytz==2021.1 sqlparse==0.4.1 <file_sep>/startApp.sh python manage.py startapp posts
f8f5b7412353b11d2ef25d1756f143911c96be46
[ "Python", "Text", "Shell" ]
6
Python
SwaXTech/CursoDjango
03056e710a09a8d2d2c29a3edc7caede92116793
4d47e9f6664d4f77a3525853e8a5bf3d1e584f4a
refs/heads/master
<repo_name>joebadmus/serenity-js<file_sep>/packages/core/src/reporting/serenity_bdd_reporter.ts import * as _ from 'lodash'; import * as path from 'path'; import StackTrace = require('stacktrace-js'); import { StackFrame } from 'stacktrace-js'; import { Md5 } from 'ts-md5/dist/md5'; import { serenity } from '../'; import { DomainEvent, Photo, RecordedScene, Result, SceneFinished, Tag } from '../domain'; import { FileSystem, JSONObject } from '../io'; import { Stage, StageCrewMember } from '../stage'; import { ActivityPeriod, RehearsalPeriod, ReportExporter, ScenePeriod } from './index'; import { RehearsalReport } from './rehearsal_report'; import { ActivityReport, ErrorReport, ErrorReportStackFrame, FullReport, SceneReport, ScreenshotReport, TagReport, } from './serenity_bdd_report'; export function serenityBDDReporter(pathToReports: string = serenity.config.outputDirectory): StageCrewMember { return new SerenityBDDReporter(new FileSystem(pathToReports)); } export class SerenityBDDReporter implements StageCrewMember { private static Events_of_Interest = [ SceneFinished ]; private stage: Stage; constructor(private fs: FileSystem) { } assignTo(stage: Stage) { this.stage = stage; this.stage.manager.registerInterestIn(SerenityBDDReporter.Events_of_Interest, this); } notifyOf(event: DomainEvent<any>): void { switch (event.constructor) { // tslint:disable-line:switch-default - ignore other events case SceneFinished: return this.persistReport(); } } private persistReport() { this.stage.manager.informOfWorkInProgress( RehearsalReport.from(this.stage.manager.readNewJournalEntriesAs('SerenityBDDReporter')) .exportedUsing(new SerenityBDDReportExporter()) .then((fullReport: FullReport) => Promise.all( fullReport.scenes.map( (scene: SceneReport) => this.fs.store(reportFileNameFor(scene), JSON.stringify(scene)), ), )), ); } } function reportFileNameFor(scene: SceneReport): string { const id = scene.id, tags = scene.tags.map(t => `${t.type}:${t.name}`).join('-'); return Md5.hashStr(`${id}-${tags}`) + '.json'; } /** * Transforms the tree structure of the RehearsalPeriod to a format acceptable by Protractor */ export class SerenityBDDReportExporter implements ReportExporter<JSONObject> { private errorExporter = new ErrorExporter(); private photoExporter = new PhotoExporter(); exportRehearsal(node: RehearsalPeriod): PromiseLike<FullReport> { return Promise.all(node.children.map(child => child.exportedUsing(this))) .then(children => ({ scenes: children, })); } exportScene(node: ScenePeriod): PromiseLike<SceneReport> { return Promise.all(node.children.map(child => child.exportedUsing(this))) .then((children: ActivityReport[]) => this.errorExporter.tryToExport(node.outcome.error).then(error => { return node.promisedTags().then(tags => ({ id: `${this.dashified(node.value.category)};${this.dashified(node.value.name)}`, title: node.value.name, name: node.value.name, context: tags.filter(tag => tag.type === 'context').map(tag => tag.value).pop(), description: '', startTime: node.startedAt, duration: node.duration(), testSource: 'cucumber', // todo: provide the correct test source manual: false, result: Result[ node.outcome.result ], userStory: { id: this.dashified(node.value.category), path: path.relative(process.cwd(), node.value.location.path), storyName: node.value.category, type: 'feature', }, tags: this.serialisedTags(tags.concat(node.value.tags).concat(this.featureTags(node.value))), issues: this.issuesCoveredBy(node.value), testSteps: children, annotatedResult: Result[ node.outcome.result ], testFailureCause: error, })); })); } exportActivity(node: ActivityPeriod): PromiseLike<ActivityReport> { return Promise.all(node.children.map(child => child.exportedUsing(this))) .then((children: ActivityReport[]) => Promise.all([ node.photos(), this.errorExporter.tryToExport(node.outcome.error)]).then( r => ({ description: node.value.name, duration: node.duration(), startTime: node.startedAt, screenshots: this.photoExporter.tryToExport(r[0]), result: Result[node.outcome.result], children, exception: r[1], // this.errorExporter.tryToExport(node.outcome.error), }))); } private dashified = (name: string) => name .replace(/([a-z])([A-Z])/g, '$1-$2') .replace(/[ \t\W]/g, '-') .replace(/^-+|-+$/g, '') .toLowerCase(); private issuesCoveredBy(scene: RecordedScene): string[] { const onlyIssueTags = this.isAnIssue, toIssueIds = (tag: Tag): string[] => tag.values; return _.chain(scene.tags).filter(onlyIssueTags).map(toIssueIds).flatten().uniq().value() as string[]; } // todo: add the capability tag? private featureTags(scene: RecordedScene) { return [ new Tag('feature', [scene.category]), ]; } private serialisedTags(tags: Tag[]): TagReport[] { const isAnIssue = this.isAnIssue; function serialise(tag: Tag) { const noValue = (t: Tag) => ({ name: t.type, type: 'tag' }), withValue = (t: Tag) => ({ name: t.values.join(','), type: t.type }); return tag.values.length === 0 ? noValue(tag) : withValue(tag); } function breakDownIssues(tag: Tag) { return isAnIssue(tag) ? tag.values.map(issueId => new Tag('issue', [ issueId ])) : tag; } return _.chain(tags) .map(breakDownIssues) .flatten() .map(serialise) .uniqBy('name') .value(); } private isAnIssue = (tag: Tag): boolean => !! ~['issue', 'issues'].indexOf(tag.type); } class PhotoExporter { tryToExport(photos: Photo[]): ScreenshotReport[] { return this.ifNotEmpty(photos.map(photo => ({ screenshot: path.basename(photo.path) }))); } private ifNotEmpty = <T>(list: T[]): T[] => !! list.length ? list : undefined; } class ErrorExporter { tryToExport(error: Error): PromiseLike<ErrorReport> { if (! error) { return Promise.resolve(undefined); // an undefined JSON field does not get serialised and that's what Serenity BDD expects } return this.stackTraceOf(error).then(frames => ({ errorType: error.name, message: error.message, stackTrace: frames, })); } private stackTraceOf(error: Error): PromiseLike<ErrorReportStackFrame[]> { return !! error.stack ? this.parsedStackTraceOf(error) : Promise.resolve([]); } private parsedStackTraceOf(error: Error): PromiseLike<ErrorReportStackFrame[]> { const serenityCode = /node_modules[\\/]serenity/, onlyIfFound = index => !! ~index ? index : undefined, firstSerenityStackFrame = (stack: StackFrame[]): number => onlyIfFound(stack.findIndex(frame => !! serenityCode.exec(frame.fileName))), stack = StackTrace.fromError(error); return stack.then(frames => frames.slice(0, firstSerenityStackFrame(frames)).map(frame => { return { declaringClass: '', methodName: `${ frame.functionName }(${ (frame.args || []).join(', ') })`, fileName: frame.fileName, lineNumber: frame.lineNumber, }; })); } }
92444801601d1615a35f626da790247933303bb8
[ "TypeScript" ]
1
TypeScript
joebadmus/serenity-js
53e35812cda942ab7156f56f55c7c731576c7629
0423fc3b8912fba040ebff0d8f2d9a0f1007f6b9
refs/heads/master
<repo_name>DarrelDent/P412-Assignment-2<file_sep>/corrgram_script.R corrgram(tmsalary, upper.panel = panel.conf, lower.panel = panel.shade)<file_sep>/boxplot_carat_script.R boxplot(tmsalary$carat, notch=TRUE, col=28, horizontal=TRUE, main="Carat", ylim=c(0,2.5))<file_sep>/Recode store.R store_num <- recode(tmsalary$store, "'Ashford'=1; 'Ausmans'=2; '<NAME>'=3; 'Chalmers'=4; 'Danford'=5; '<NAME>'=6; 'Goodmans'=7; 'Kay'=8; '<NAME>'=9; 'Riddles'=10; 'University'=11; 'Zales'=12;", as.factor.result=FALSE)<file_sep>/Figure 2- Histogram.R library(Hmisc) hist(tmsalary)<file_sep>/scatterplot_model1.train vs model1fb.train.R plot(fitted(model1.train) ~ fitted(model1fb.train), xlab = "Model with All Variables", ylab = "Model with forward/backward-selected Variables") abline(0, 1) cor(fitted(model.orig.variables), fitted(model1b.naive))<file_sep>/tree_fit_script.R tree.fit <- rpart(price ~ carat + color + clarity + cut + channel + store, data = tmsalary) plot(tree.fit) text(tree.fit)<file_sep>/model1b2_naive_script.R model1b2.naive <- step(model1b.naive)<file_sep>/Recode factor variables.R cut_num <- recode(tmsalary$cut, "'Ideal'=1; 'Not Ideal'=2;", as.factor.result=FALSE) cha_num <- recode(tmsalary$channel, "'Independent'=1; 'Internet'=2; 'Mall'=3;", as.factor.result=FALSE) store_num <- recode(tmsalary$store, "'Ashford'=1; 'Ausmans'=2; '<NAME>'=3; 'Chalmers'=4; 'Danford'=5; '<NAME>'=6; 'Goodmans'=7; 'Kay'=8; '<NAME>'=9; 'Riddles'=10; 'University'=11; 'Zales'=12;", as.factor.result=FALSE) tmsalary.matrix2 <- cbind(tmsalary.matrix, cut_num, cha_num, store_num)<file_sep>/scatterplot_model_orig_var_vs_model1b_naive_script.R plot(fitted(model.orig.variables) ~ fitted(model1b.naive)) abline(0, 1) cor(fitted(model.orig.variables), fitted(model1b.naive))<file_sep>/scatterplotMatrix.R scatterplotMatrix(~ price + carat + color + clarity + store, span = 0.7, data = tmsalary, lwd = 2, col = palette()[c(4,2,1)])<file_sep>/scatterplot_price_store_script.R scatterplot(tmsalary$sto_num, tmsalary$price, boxplots=FALSE, xlab="Store", ylab="Price", main="Price vs Store")<file_sep>/scatterplot_price_carat_script.R scatterplot(tmsalary$carat, tmsalary$price, boxplots=FALSE, xlab="Carat", ylab="Price", main="Price vs Carat Size")<file_sep>/tree_fit_train_script.R tree.fit.train <- rpart(price ~ carat + color + clarity + cut + channel + store, data = train.tmsalary) plot(tree.fit.train) text(tree.fit.train)<file_sep>/hist_color_script.R with(tmsalary, { hist(color, freq=TRUE, ylab="Frequency", col=28) lines(density(color), lwd=2) rug(color) box() })<file_sep>/tree_fit_test_script.R tree.fit.test <- rpart(price ~ carat + color + clarity + cut + channel + store, data = test.tmsalary) plot(tree.fit.test) text(tree.fit.test)<file_sep>/hist_clarity_script.R with(tmsalary, { hist(clarity, freq=TRUE, ylab="Frequency", col=28) lines(density(price), lwd=2) rug(price) box() })<file_sep>/dataset split script (training vs test).R # Sample Indexes indexes <- sample(1:nrow(tmsalary), size = 0.3 * nrow(tmsalary)) test.tmsalary <- tmsalary[indexes,] train.tmsalary <- tmsalary[-indexes,]<file_sep>/boxplot_color_script.R boxplot(tmsalary$color, notch=TRUE, col=28, horizontal=TRUE, main="Color", ylim=c(0,10))<file_sep>/scatterplot_price_clarity_script.R scatterplot(tmsalary$clarity, tmsalary$price, boxplots=FALSE, xlab="Clarity", ylab="Price", main="Price vs Clarity")<file_sep>/model_best_subsets.R model.best.subsets <- regsubsets(price ~ carat + color + clarity + cut + channel + store, data = train.tmsalary, nbest = 1, nvmax = 10, method = "exhaustive")<file_sep>/model_ran_forest_script.R model.ran.forest <- randomForest(price ~ carat + color + clarity + cut + channel + store, data = test.tmsalary) print(model.ran.forest) importance(model.ran.forest)<file_sep>/build_lm_model_script.R build.lm.model <- lm(price ~ carat + color + clarity + cut + channel + store, data = train.tmsalary)<file_sep>/boxplot_clarity_script.R boxplot(tmsalary$clarity, notch=TRUE, col=28, horizontal=TRUE, main="Clarity")<file_sep>/scatterplot_price_color_script.R scatterplot(tmsalary$color, tmsalary$price, boxplots=FALSE, xlab="Color", ylab="Price", main="Price vs Color")<file_sep>/Bonacossa_Assignment2.R setwd("C:\\Users\\abo586\\Documents\\Dropbox\\PREDICT\\PREDICT 412\\Assignment 2") diamond=read.csv("two_months_salary.csv", header=TRUE) library(xtable) library(psych) library(pastecs) library(Hmisc) library(MMST) library(car) library(corrplot) library(ellipse) library(PerformanceAnalytics) library(caret) library(car) ### CREATE A TRAIN AND TEST SET set.seed(3456) trainindex=sample(1:nrow(diamond), 298) train=diamond[trainindex,] test=diamond[-trainindex,] head(train) head(test) ##################################### ### DESCRIPTIVES and QUALITY CHECK### ##################################### head(diamond, 5) dim(diamond) names(diamond) #summary(diamond[,-c(4:6)]) #describe(diamond[,-c(4:6)]) xtable(stat.desc(diamond[,-c(4:6)], basic=TRUE, desc=TRUE, norm=TRUE)) #xtabs(~store+channel+cut, data=diamond) #xtable(xtabs(~store+channel, data=diamond)) sapply(diamond,class) sapply(diamond, function(x) sum(is.na(x))) #xtable(table(diamond$store)) #xtable(table(diamond$channel)) #xtable(table(diamond$channel)) #descriptive table of price by channel and store #library(doBy) #xtable(summaryBy(price ~ channel+store, diamond)) ##Frequency for store, channel and cut par(mfrow=c(1,3)) bar charts for categorical variables ds <- rbind(summary(diamond$store)) ord <- order(ds[1,], decreasing=TRUE) bp <- barplot(ds[,ord], beside=TRUE, ylab="Frequency", las=3, ylim=c(0, 250), col=colorspace::rainbow_hcl(1)) text(bp, ds[,ord]+6, ds[,ord]) title(main="Distribution of store") ds <- rbind(summary(diamond$channel)) ord <- order(ds[1,], decreasing=TRUE) bp <- barplot(ds[,ord], beside=TRUE, ylab="Frequency", xlab="channel", ylim=c(0, 400), col=colorspace::rainbow_hcl(1)) text(bp, ds[,ord]+9, ds[,ord]) title(main="Distribution of channel") ds <- rbind(summary(diamond$cut)) ord <- order(ds[1,], decreasing=TRUE) bp <- barplot(ds[,ord], beside=TRUE, ylab="Frequency", xlab="cut", ylim=c(0, 400), col=colorspace::rainbow_hcl(1)) text(bp, ds[,ord]+8, ds[,ord]) title(main="Distribution of cut") #histogram and QQplots for continuous variables par(mfrow=c(2,2), cex=0.6) hist(carat, main="Carat") with(diamond, { hist(carat, breaks="FD", freq=FALSE, ylab="Density") lines(density(carat), lwd=2) lines(density(carat, adjust=0.5), lwd=1) rug(carat) box() }) #plot20<-Boxplot(diamond$carat, id.n=5, notch=TRUE, ylab="Carat", cex.axis=0.85, col=c("turquoise3")) qqPlot(diamond$carat, labels=row.names(diamond), id.n=3) hist(color, main="Color") with(diamond, { hist(color, breaks="FD", freq=FALSE, ylab="Density") lines(density(color), lwd=2) lines(density(color, adjust=0.5), lwd=1) rug(color) box() }) #plot21<-Boxplot(diamond$color, id.n=5, notch=TRUE, ylab="Color", cex.axis=0.85, col=c("turquoise3")) qqPlot(diamond$color, labels=row.names(diamond), id.n=3) hist(clarity, main="Clarity") with(diamond, { hist(clarity, breaks="FD", freq=FALSE, ylab="Density") lines(density(clarity), lwd=2) lines(density(clarity, adjust=0.5), lwd=1) rug(clarity) box() }) #plot21<-Boxplot(diamond$clarity, id.n=5, notch=TRUE, ylab="Clarity", cex.axis=0.85, col=c("turquoise3")) qqPlot(diamond$clarity, labels=row.names(diamond), id.n=3) hist(price, main="Price") with(diamond, { hist(price, breaks="FD", freq=FALSE, ylab="Density") lines(density(price), lwd=2) lines(density(price, adjust=0.5), lwd=1) rug(price) box() }) #plot21<-Boxplot(diamond$price, id.n=5, notch=TRUE, ylab="Price", cex.axis=0.85, col=c("turquoise3")) qqPlot(diamond$price, labels=row.names(diamond), id.n=3) ############ ### EDA #### ############ #correlation diamond.matrix<-data.matrix(diamond, rownames.force = NA) cor(diamond.matrix) cor_diamond=cor(diamond.matrix, use="complete.obs") xtable(corstarsl(cor_diamond)) ##SCATTERPLOTS AND OUTLIERS library(car) scatterplotMatrix(diamond[-c(4:6)], id.n=4)#### PLOT THIS ONE INSTEAD OF CORRELATIONS #approach 3 -- correlation function ### EDA TREE library(tree) tree.data=tree(diamond$price~., diamond) summary(tree.data) plot(tree.data) text(tree.data, pretty=0, cex=0.8) ################ ### MODELING ### ################ ## 1 naive regression model with backwards variable selection library(MASS) model1 <- lm(train$price~.,data=train) summary(model1) cbind(Estimate=coef(model1), confint(model1)) model1back<- step(model1, direction="backward") summary(model1back) par(mfrow=c(2,2)) plot(model1back) mean((train$price-predict(model1,test))^2) #comment on RSE, R2, F ##compare AIC models models= list(model1, model1back) aic= unlist(lapply(models, AIC)) aic #outlier test library(car) par(mfrow=c(2,2)) outlierTest(model1) #Influence influenceIndexPlot(model1, vars=c("Cook", "hat"), id.n=3) influencePlot(model1, id.n=3) #<NAME> for autocorrelation of residuals library(lmtest) dwtest(model1) #variance inflation factor for multicollinearity vif(model1back) ##boxcox power transformation response bc=boxcox(model1) which.max(bc$y)#largest log likelihood for y lambda=bc$x[which.max(bc$y)]## value of lambda lambda #transform price #library(car) #pricetrain <- yjPower(train$price, lambda) #pricetest <- yjPower(test$price, lambda) #transform store library(plyr) store2 <- revalue(diamond$store, c("Blue Nile"="Blue Nile", "Ashford"="Ashford", "Ausmans"="Other", "Chalmers"="Other", "Danford"="Other", "<NAME>"="Other", "Goodmans"="Other", "Kay"="Other", "R. Holland"="Other", "Riddles"="Other", "University"="Other", "Zales"="Other")) storetrain<- revalue(train$store, c("Blue Nile"="Blue Nile", "Ashford"="Ashford", "Ausmans"="Other", "Chalmers"="Other", "Danford"="Other", "<NAME>"="Other", "Goodmans"="Other", "Kay"="Other", "R. Holland"="Other", "Riddles"="Other", "University"="Other", "Zales"="Other")) storetest<- revalue(test$store, c("Blue Nile"="Blue Nile", "Ashford"="Ashford", "Ausmans"="Other", "Chalmers"="Other", "Danford"="Other", "<NAME>"="Other", "Goodmans"="Other", "Kay"="Other", "R. Holland"="Other", "Riddles"="Other", "University"="Other", "Zales"="Other")) ##bestregsubsets with leaps library(leaps) bestreg=regsubsets(price~., data=train, nvmax=15) # xxx depends on the number of variables available. include all test.mat=model.matrix(price~., data=test) val.errors=rep(NA,8) #xxx is the number of variables for (i in 1:8) { coefi=coef(bestreg, id=i) pred=test.mat[,names(coefi)]%*%coefi val.errors[i]=mean((test$price-pred)^2) }##model with 8 is best bestreg=regsubsets(price~., data=train, nvmax=) coef(bestregfull, ) #use to remove observations #modelbis=update(model, subset=-c(xxx,xxx)) ################# ## CORRELATION ## ################# #approach1 #diamond.matrix<-data.matrix(diamond, rownames.force = NA) #cor(diamond.matrix) #cor_diamond=cor(diamond.matrix, use="complete.obs") #colramp = colorRampPalette(c("white", blues9)) #colors = colramp(100) #my.plotcorr(cor_diamond, col=colors[((cor_diamond + 1)/2) * 100], diag='ellipse', # upper.panel="number", mar=c(0,2,0,0)) #approach2 #library(PerformanceAnalytics) #chart.Correlation(cor_diamond) <file_sep>/hist_carat_script.R with(tmsalary, { hist(carat, freq=TRUE, ylab="Frequency", col=28) lines(density(carat), lwd=2) rug(carat) box() })<file_sep>/boxplot_price_script.R boxplot(tmsalary$price, notch=TRUE, col=28, horizontal=TRUE, main="Price", ylim=c(0,30000))<file_sep>/build_lm_model_inter_script.R build.lm.model.inter <- lm(price ~ carat + color + clarity + cut + channel + store + store:clarity, data = train.tmsalary)<file_sep>/travis - assign2.R diamond<-read.csv("~/Desktop/two_months_salary.csv", header=TRUE,stringsAsFactor=T) require('caret') require('nloptr') require(ggplot2) #SPLIT INTO TRAIN & TEST SETS smp_size <- floor(0.70 * nrow(diamond)) set.seed(2013) train_ind <- sample(seq_len(nrow(diamond)), size = smp_size) train <- diamond[train_ind, ] test <- diamond[-train_ind, ] dim(train) names(train) train<-as.data.frame(train) test<-as.data.frame(test) logprice<-log(test$price) test<-cbind(test,logprice) #REDEFINE CATEGORICAL VARIABLES mall<-as.matrix(train$channel=="Mall") internet<-as.matrix(train$channel=="Internet") indepedent<-as.matrix(train$channel=="Independent") mall.test<-as.matrix(test$channel=="Mall") internet.test<-as.matrix(test$channel=="Internet") indepedent.test<-as.matrix(test$channel=="Independent") not.ideal<-as.matrix(train$cut=="Not Ideal") ideal<-as.matrix(train$cut=="Ideal") not.ideal.test<-as.matrix(test$cut=="Not Ideal") ideal.test<-as.matrix(test$cut=="Ideal") goodmans<-as.matrix(train$store=="Goodmans") chalmers<-as.matrix(train$store=="Chalmers") fred<-as.matrix(train$store=="<NAME>er") R.holland<-as.matrix(train$store=="R. Holland") ausmans<-as.matrix(train$store=="Ausmans") university<-as.matrix(train$store=="University") kay<-as.matrix(train$store=="Kay") zales<-as.matrix(train$store=="Zales") danford<-as.matrix(train$store=="Danford") bluenile<-as.matrix(train$store=="Blue Nile") ashford<-as.matrix(train$store=="Ashford") riddles<-as.matrix(train$store=="Riddles") goodmans.test<-as.matrix(test$store=="Goodmans") chalmers.test<-as.matrix(test$store=="Chalmers") fred.test<-as.matrix(test$store=="<NAME>er") R.holland.test<-as.matrix(test$store=="R. Holland") ausmans.test<-as.matrix(test$store=="Ausmans") university.test<-as.matrix(test$store=="University") kay.test<-as.matrix(test$store=="Kay") zales.test<-as.matrix(test$store=="Zales") danford.test<-as.matrix(test$store=="Danford") bluenile.test<-as.matrix(test$store=="Blue Nile") ashford.test<-as.matrix(test$store=="Ashford") riddles.test<-as.matrix(test$store=="Riddles") #DESCRIPTIVE STATISTICS require(pastecs) stat.desc(train) #FACTOR TRAIN CATEGORICAL VARIABLESD train$cut<-factor(train$cut,c("Ideal","Not Ideal")) train$channel<-factor(train$channel,c("Independent","Mall","Internet")) train$store<-factor(train$store,c("Ashford","Ausmans","Blue Nile","Chalmers","Danford","<NAME>","Goodmans","Kay","R. Holland","Riddles","University","Zales")) #FACTOR TEST CATEGORICAL VARIABLES test$cut<-factor(test$cut,c("Ideal","Not Ideal")) test$channel<-factor(test$channel,c("Independent","Mall","Internet")) test$store<-factor(test$store,c("Ashford","Ausmans","Blue Nile","Chalmers","Danford","<NAME>","Goodmans","Kay","R. Holland","Riddles","University","Zales")) #HISTORGRAMS require(lattice) hist(train$carat,prob=T) curve(dnorm(x,mean=mean(train$carat),sd=sd(train$carat)),add=T,col="blue") abline(v=mean(train$carat),col="red") hist(train$color,prob=T) curve(dnorm(x,mean=mean(train$color),sd=sd(train$color)),add=T,col="blue") abline(v=mean(train$color),col="red") hist(train$clarity,prob=T) curve(dnorm(x,mean=mean(train$clarity),sd=sd(train$clarity)),add=T,col="blue") abline(v=mean(train$clarity),col="red") hist(train$price,prob=T) curve(dnorm(x,mean=mean(train$price),sd=sd(train$price)),add=T,col="blue") abline(v=mean(train$price),col="red") barplot(prop.table(table(train$cut)),main="Frequency of Cut") barplot(prop.table(table(train$channel)),main="Frequency of Channel") barplot(prop.table(table(train$store)),main="Frequency of Store") #Q-Q PLOT MATHS n.carat=length(train$carat) probabilities.carat=(1:n.carat)/(n.carat+1) normal.quantiles.carat=qnorm(probabilities.carat,mean(train$carat,na.rm=T),sd(train$carat,na.rm=T)) n.price=length(train$price) probabilities.price=(1:n.price)/(n.price+1) normal.quantiles.price=qnorm(probabilities.price,mean(train$price,na.rm=T),sd(train$price,na.rm=T)) #Q-Q PLOTS plot(sort(normal.quantiles.carat),sort(train$carat),xlab='Theoretical Quantiles from Normal Distribution',ylab='Sample Quantiles from Carat',main='Q-Q Plot Carat') abline(0,1) plot(sort(normal.quantiles.price),sort(train$price),xlab='Theoretical Quantiles from Normal Distribution',ylab='Sample Quantiles from Price',main='Q-Q Plot Price') abline(0,1) #HISTOGRAM OF LOGPRICE logprice<-log(train$price) n.logprice=length(logprice) probabilities.logprice=(1:n.logprice)/(n.logprice+1) normal.quantiles.logprice=qnorm(probabilities.logprice,mean(logprice,na.rm=T),sd(logprice,na.rm=T)) plot(sort(normal.quantiles.logprice),sort(logprice),xlab='Theoretical Quantiles from Normal Distribution',ylab='Sample Quantiles from Log Price',main='Q-Q Plot Log Price') abline(0,1) hist(logprice,prob=T) curve(dnorm(x,mean=mean(logprice),sd=sd(logprice)),add=T,col="blue") abline(v=mean(logprice),col="red") #BOXPLOTS OF CONTINUOUS VARIABLES plot1<-boxplot(train$carat,notch=F,outline=T,plot=T,col="green",ylab="Carat",xlab="Diamond Size",main="Diamond Carat Boxplot") plot2<-boxplot(train$price,notch=F,outline=T,plot=T,col="blue",ylab="Price",xlab="Diamond Price",main="Diamond Price Boxplot") plot3<-boxplot(logprice,notch=F,outline=T,plot=T,col="red",ylab="Log Price",xlab="Log of Diamond Price",main="Log of Diamond Price Boxplot") #CORRELATIONS cor(train[sapply(train,is.numeric)],use="complete.obs") require(corrplot) corrplot(cor(train[sapply(train,is.numeric)],use="complete.obs"),type="lower",method="ellipse") require(psych) corr.test(train[sapply(train,is.numeric)],use="complete.obs") #INITIAL TREE MODEL require(tree) tree.data<-tree(train$price~.,train) summary(tree.data) plot(tree.data) text(tree.data,pretty=2,cex=0.8,col="red") #NAIVE MODEL FOR TRAIN$PRICE, TRAIN$PRICE -COLOR, LOGPRICE naive.model<-lm(train$price~.,data=train) summary(naive.model) extractAIC(naive.model) plot(resid(naive.model),ylab="Residuals",main="Naive Model") abline(0,0,col="red") yhat.nm=predict(naive.model,newdata=test) nm.test=test[,"price"] mean((yhat.nm-nm.test)^2) dat.nm<-data.frame(x=nm.test,y=yhat.nm) res.nm<-stack(data.frame(Observed=dat.nm$x,Predicted=yhat.nm)) res.nm<-cbind(res.nm,x=dat.nm$x,2) require(lattice) xyplot(values~x,data=res.nm,group=ind,auto.key=FALSE,main="Naive: Predicted v. Observed") naive.model1<-lm(train$price~carat+clarity+channel+store, data=train) summary(naive.model1) extractAIC(naive.model1) plot(resid(naive.model1),ylab="Residuals",main="Naive Model (-Color)") abline(0,0,col="red") yhat.nm1=predict(naive.model1,newdata=test) nm.test1=test[,"price"] mean((yhat.nm1-nm.test1)^2) dat.nm1<-data.frame(x=nm.test1,y=yhat.nm1) res.nm1<-stack(data.frame(Observed=dat.nm1$x,Predicted=yhat.nm1)) res.nm1<-cbind(res.nm1,x=dat.nm1$x,2) require(lattice) xyplot(values~x,data=res.nm1,group=ind,auto.key=FALSE,main="Naive (-Color): Predicted v. Observed") naive.model1<-lm(train$price~tcarat+clarity+channel+store, data=train) summary(naive.model1) extractAIC(naive.model1) plot(resid(naive.model1),ylab="Residuals",main="Naive Model (-Color)") abline(0,0,col="red") yhat.nm1=predict(naive.model1,newdata=test) nm.test1=test[,"price"] mean((yhat.nm1-nm.test1)^2) dat.nm1<-data.frame(x=nm.test1,y=yhat.nm1) res.nm1<-stack(data.frame(Observed=dat.nm1$x,Predicted=yhat.nm1)) res.nm1<-cbind(res.nm1,x=dat.nm1$x,2) require(lattice) xyplot(values~x,data=res.nm1,group=ind,auto.key=FALSE,main="Naive (-Color): Predicted v. Observed") naive.model2<-lm(logprice~carat+color+clarity+channel+store+cut,data=train) summary(naive.model2) extractAIC(naive.model2) plot(resid(naive.model2),ylab="Residuals",main="Naive Model (logprice)") abline(0,0, col="red") yhat.nm2=predict(naive.model2,newdata=test) nm.test2=test[,"logprice"] mean((yhat.nm2-nm.test2)^2) dat.nm2<-data.frame(x=nm.test2,y=yhat.nm2) res.nm2<-stack(data.frame(Observed=dat.nm2$x,Predicted=yhat.nm2)) res.nm2<-cbind(res.nm2,x=dat.nm2$x,2) require(lattice) xyplot(values~x,data=res.nm2,group=ind,auto.key=FALSE,main="Naive (Log Price): Predicted v. Observed") #FORWARD BACKWARD AND STEPWISE FOR TRAIN$PRICE require(MASS) forward<-lm(price~carat+color+clarity+mall+internet+ideal+not.ideal+goodmans+chalmers+fred+R.holland+ausmans+university+kay+zales+danford+bluenile+ashford+riddles,data=train) forward.null<-lm(price~1,data=train) forward<-step(forward.null,scope=list(lower=forward.null,upper=forward),direction="forward") step(forward,data=train,direction="backward") step(forward.null, scope=list(upper=forward), data=train,direction="both") #FORWARD BACKWARD AND STEPWISE FOR LOGPRICE forward.log<-lm(logprice~carat+color+clarity+channel+store+cut,data=train) forward.log.null<-lm(logprice~1,data=train) step(forward.log.null,scope=list(lower=forward.log.null,upper=forward.log),direction="forward") step(forward.log,data=train,direction="backward") step(forward.log.null, scope=list(upper=forward.log), data=train,direction="both") yhat.for=predict(step(forward.log.null,scope=list(lower=forward.log.null,upper=forward.log),direction="forward"),newdata=test) for.test=test[,"logprice"] mean((yhat.for-for.test)^2) dat.for<-data.frame(x=for.test,y=yhat.for) res.for<-stack(data.frame(Observed=dat.for$x,Predicted=yhat.for)) res.for<-cbind(res.for,x=dat.for$x,2) require(lattice) xyplot(values~x,data=res.for,group=ind,auto.key=FALSE,main="Forward (Log Price): Predicted v. Observed") yhat.bac=predict(step(forward.log,data=train,direction="backward"),newdata=test) bac.test=test[,"logprice"] mean((yhat.bac-bac.test)^2) dat.bac<-data.frame(x=bac.test,y=yhat.bac) res.bac<-stack(data.frame(Observed=dat.bac$x,Predicted=yhat.bac)) res.bac<-cbind(res.bac,x=dat.bac$x,2) require(lattice) xyplot(values~x,data=res.bac,group=ind,auto.key=FALSE,main="Backward (Log Price): Predicted v. Observed") yhat.step=predict(step(forward.log.null, scope=list(upper=forward.log), data=train,direction="both"),newdata=test) step.test=test[,"logprice"] mean((yhat.step-step.test)^2) dat.step<-data.frame(x=step.test,y=yhat.step) res.step<-stack(data.frame(Observed=dat.step$x,Predicted=yhat.step)) res.step<-cbind(res.step,x=dat.step$x,2) require(lattice) xyplot(values~x,data=res.step,group=ind,auto.key=FALSE,main="Stepwise (Log Price): Predicted v. Observed") require(leaps) leaps<-regsubsets(train$price~.,data=train,nbest=10) leaps plot(leaps,scale="adjr2") plot(leaps,scale="bic") leaps.model<-leaps.model<-lm(price~carat+color+clarity+not.ideal+mall+fred+goodmans+R.holland,data=train) summary(leaps.model) plot(resid(leaps.model),ylab="Residuals",main="Leaps Model") abline(0,0, col="red") extractAIC(leaps.model) leaps.model.test<-lm(price~carat+color+clarity+not.ideal.test+mall.test+fred.test+goodmans.test+R.holland.test, data=test) yhat.leaps=predict(leaps.model.test,newdata=test) leaps.test2=test[,"price"] mean((yhat.leaps-leaps.test2)^2) dat.leaps<-data.frame(x=leaps.test2,y=yhat.leaps) res.leaps<-stack(data.frame(Observed=dat.leaps$x,Predicted=yhat.leaps)) res.leaps<-cbind(res.leaps,x=dat.leaps$x,2) require(lattice) xyplot(values~x,data=res.leaps,group=ind,auto.key=FALSE,main="Leaps: Predicted v. Observed") #LASSO MODEL require(glmnet) x<-model.matrix(price~.,train)[,-1] y<-train$price grid<-10^seq(10,-2,length=25) lasso.mod=glmnet(x,y,alpha=1,lambda=grid) lasso.train=sample(1:nrow(x),nrow(x)/2) lasso.test=(-train) cv.out=cv.glmnet(x,y,alpha=1) plot(cv.out) bestlam=cv.out$lambda.min out=glmnet(x,y,alpha=1,lambda=grid) lasso.coef=predict(out,type="coefficients",s=bestlam)[1:18,] lasso.coef lasso.coef[lasso.coef!=0] #LINEAR MODEL FOR TRAIN$PRICE AND LOGPRICE linear.model<-lm(train$price~train$carat+train$color+train$clarity+mall++ideal+goodmans+fred+R.holland,data=train) summary(linear.model) extractAIC(linear.model) BIC(linear.model) linear.model.test<-lm(price~carat+color+clarity+mall.test++ideal.test+goodmans.test+fred.test+R.holland.test,data=test) yhat.lin=predict(linear.model.test,newdata=test) lin.test2=test[,"price"] mean((yhat.lin-lin.test2)^2) dat.lin<-data.frame(x=lin.test2,y=yhat.lin) res.lin<-stack(data.frame(Observed=dat.lin$x,Predicted=yhat.lin)) res.lin<-cbind(res.lin,x=dat.lin$x,2) require(lattice) xyplot(values~x,data=res.lin,group=ind,auto.key=FALSE,main="Analyst Linear: Predicted v. Observed") linear.logmodel<-lm(logprice~train$carat+train$color+train$clarity+goodmans+R.holland+kay+zales,data=train) summary(linear.logmodel) extractAIC(linear.logmodel) BIC(linear.logmodel) linear.logmodel.test<-lm(logprice~carat+color+clarity+mall.test++ideal.test+goodmans.test+fred.test+R.holland.test,data=test) yhat.log=predict(linear.logmodel.test,newdata=test) log.test2=test[,"logprice"] mean((yhat.log-log.test2)^2) dat.log<-data.frame(x=log.test2,y=yhat.log) res.log<-stack(data.frame(Observed=dat.log$x,Predicted=yhat.log)) res.log<-cbind(res.log,x=dat.log$x,2) require(lattice) xyplot(values~x,data=res.log,group=ind,auto.key=FALSE,main="Analyst Linear (Log Price): Predicted v. Observed") #LINEAR PLUS INTERACTION FOR TRAIN$PRICE AND LOGPRICE linear.plus<-lm(train$price~train$carat+mall+goodmans+kay+train$cut+train$carat:train$color+train$carat:train$clarity,data=train) summary(linear.plus) extractAIC(linear.plus) BIC(linear.plus) linear.plus.test<-lm(price~carat+mall.test+goodmans.test+kay.test+cut+carat:color+carat:clarity,data=test) yhat.lp=predict(linear.plus.test,newdata=test) lp.test2=test[,"price"] mean((yhat.lp-lp.test2)^2) dat.lp<-data.frame(x=lp.test2,y=yhat.lp) res.lp<-stack(data.frame(Observed=dat.lp$x,Predicted=yhat.lp)) res.lp<-cbind(res.lp,x=dat.lp$x,2) require(lattice) xyplot(values~x,data=res.lp,group=ind,auto.key=FALSE,main="Analyst Linear+Interaction Price: Predicted v. Observed") linear.logplus<-lm(logprice~train$carat+mall+goodmans+train$carat:train$color+train$carat:train$clarity,data=train) summary(linear.logplus) extractAIC(linear.logplus) BIC(linear.logplus) linear.pluslog.test<-lm(logprice~carat+mall.test+goodmans.test+kay.test+cut+carat:color+carat:clarity,data=test) yhat.lpp=predict(linear.pluslog.test,newdata=test) lpp.test2=test[,"logprice"] mean((yhat.lpp-lpp.test2)^2) dat.lpp<-data.frame(x=lpp.test2,y=yhat.lpp) res.lpp<-stack(data.frame(Observed=dat.lpp$x,Predicted=yhat.lpp)) res.lpp<-cbind(res.lpp,x=dat.lpp$x,2) require(lattice) xyplot(values~x,data=res.lpp,group=ind,auto.key=FALSE,main="Analyst Linear+Interaction (Log Price): Predicted v. Observed") #TREE MODEL tree.model<-tree(train$price~train$carat+train$color+train$clarity+mall+internet+goodmans+chalmers+fred+R.holland+ausmans+university+kay+zales+danford+bluenile+ashford+riddles,data=train) summary(tree.model) plot(tree.model) text(tree.model,pretty=2,cex=0.8,col="red") tree.model.test<-tree(price~carat+color+clarity+mall.test+internet.test+goodmans.test+chalmers.test+fred.test+R.holland.test+ausmans.test+university.test+kay.test+zales.test+danford.test+bluenile.test+ashford.test+riddles.test,data=test) yhat.tree=predict(tree.model.test,newdata=test) tree.test2=test[,"price"] mean((yhat.tree-tree.test2)^2) #RANDOM FOREST CODE require(randomForest) smp_size.r <- floor(0.50 * nrow(train)) set.seed(2013) train.r <- sample(seq_len(nrow(train)), size = smp_size.r) ran.train <- train[train.r, ] ran.test<-train[-train.r,] ran.train$cut<-as.numeric(ran.train$cut) ran.train$store<-as.numeric(ran.train$store) ran.train$channel<-as.numeric(ran.train$channel) ran.test$cut<-as.numeric(ran.test$cut) ran.test$store<-as.numeric(ran.test$store) ran.test$channel<-as.numeric(ran.test$channel) rf.train<-randomForest(ran.train$price~.,data=ran.train,mtry=6,importance=T) yhat.rf=predict(rf.train,newdata=ran.test) tree.test=ran.test[,"price"] mean((yhat.rf-tree.test)^2) varImpPlot(rf.train) <file_sep>/Recode cut.R cut_num <- recode(tmsalary$cut, "'Ideal'=1; 'Not Ideal'=2;", as.factor.result=FALSE)<file_sep>/models.R # 1st model tried: price by carat + store (strongest correlations, pos & neg) model.carat.store <- lm(tmx$price ~ tmx$carat + tmx$store_num) # Take a step back and model all variables to see what it looks like model.all.variables <- lm(tmx$price ~ tmx$carat + tmx$color + tmx$clarity + tmx$cut_num + tmx$cha_num + tmx$store_num)
1c57031111d410e91c0eae97b6067f2db9f0943c
[ "R" ]
31
R
DarrelDent/P412-Assignment-2
2e42783bc01887583099a67d32ee9b747f3c81b4
93f713c2f42d04014dff1194f619b3be8aad1627
refs/heads/master
<file_sep>import LY from 'lvyii-engine' import {blockFunc} from './blocks' LY.Cloud.define('cloudTest', function (request) { let {text} = request.params return text?text:'hello lvyii' }) LY.Cloud.define('getInfo', blockFunc.getInfo)<file_sep>import Eos from 'eosjs' const eos = Eos({httpEndpoint: process.env.HTTP_END_POINT, chainId: process.env.CHAIN_ID}) async function getInfo() { let info = await eos.getInfo({}); return info; } export const blockFunc = { getInfo, }
abb2485b8b34b74079822856a01ca8a435df603a
[ "JavaScript" ]
2
JavaScript
eosmonitor/EOSMonitorCloud
bdb6d80224809898e9c2fbdc030f79efc45e1be6
e82fe58546449b39b2d922b82d4b2d3bac106242
refs/heads/master
<file_sep>import cv2 import numpy as np #from cv2 import ellipse as cvellipse from find_staff import rectify def pix(np_array): return tuple(np.round(np_array).astype(int)) def fit_note(note_h): canvas_h = 2 * note_h canvas_w = 3 * note_h p = 0.63 angle = 65 theta = angle * np.pi / 180.0 pos = np.array((canvas_w/2.0, canvas_h/2.0)) min_b = note_h max_b = 2 * note_h itt = 0 debug = False ret = None while itt < 100: curr_h = (min_b + max_b) / 2.0 ma = curr_h MA = curr_h * p ellipse = (pos, (MA, ma), angle) img = np.zeros((canvas_h, canvas_w), dtype='uint8') cv2.ellipse(img, ellipse, color=(255), thickness=-1) cnts, h = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) note_contour = max(cnts, key=lambda c: cv2.contourArea(c)) rect = cv2.boundingRect(note_contour) bx, by, bw, bh = rect if debug: vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawContours(vis, [note_contour], -1, (255, 0, 255), 8) x, y = pos pt1 = np.array((x, y - note_h/2.0)) pt2 = np.array((x, y + note_h/2.0)) cv2.line(vis, pix(pt1), pix(pt2), color=(255, 255, 0), thickness=8) cv2.rectangle(vis, (bx, by), (bx+bw, by+bh), color=(0,255,0), thickness=1) cv2.imshow('note', vis) k = cv2.waitKey() print(note_h, bh, curr_h, itt) if note_h == bh: ret = img[by:by + bh, bx:bx + bw] break elif note_h < bh: max_b = curr_h else: min_b = curr_h itt += 1 # img = np.zeros((bh, bw), dtype='uint8') # pos = np.array((bw/2.0, bh/2.0)) # ma = curr_h # MA = curr_h * p # ellipse = (pos, (MA, ma), angle) # cv2.ellipse(img, ellipse, color=(255), thickness=-1) return ret def draw_note(img, pos, h): #p = 0.63 #angle = 65 p = 0.2 angle = 80 theta = angle * np.pi / 180.0 use_h = h * 0.95 h2 = use_h * use_h p2 = p * p sin = np.sin(theta) sin2 = sin*sin d = (sin2 + 1) * p2 + 1 b = 2.0 * np.sqrt(h2 / d) a = p * b MA = a ma = b ellipse = (pos, (MA, ma), angle) cv2.ellipse(img, ellipse, color=(255, 0, 255), thickness=1) x, y = pos pt1 = np.array((x, y - h/2.0)) pt2 = np.array((x, y + h/2.0)) cv2.line(vis, pix(pt1), pix(pt2),color = (255, 255, 0), thickness=1) cv2.line(vis, (0, 0), (0, h), color = (255, 255, 0), thickness=1) def fit_from_img(): img = cv2.imread('res/note.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, ret = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) cnts, h = cv2.findContours(ret, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) note_contour = max(cnts, key=lambda c: cv2.contourArea(c)) vis = img.copy() cv2.drawContours(vis, [note_contour], -1, (255, 0, 255), 1) #(x, y), (MA, ma), angle = cv2.fitEllipse(note_contour) ellipse = cv2.fitEllipse(note_contour) (x, y), (MA, ma), angle = ellipse print("x, y", x, y) print("M, m", MA, ma) print("angle", angle) print("prop", MA / ma) #center = (int(x), int(y)) #axes = (int(MA), int(ma)) #cvellipse(vis, center, axes, angle, startAngle=0, endAngle=360, color=(0, 255, 0)) cv2.ellipse(vis, ellipse, thickness=1, color=(0, 255, 0)) theta = angle * np.pi / 180.0 #a = MA #b = ma a = MA b = ma a2 = a*a b2 = b*b cos2 = np.cos(theta) * np.cos(theta) sin2 = np.sin(theta) * np.sin(theta) eH = np.sqrt(2 * (a2 + b2 - (a2 - b2) * cos2))/2.0 eh = np.sqrt(2 * (a2 + b2 - (b2 - a2) * sin2))/2.0 #pt1 = np.array((x - h/2.0, y)) #pt2 = np.array((x + h/2.0, y)) pt1 = np.array((x, y - eh/2.0)) pt2 = np.array((x, y + eh/2.0)) cv2.line(vis, pix(pt1), pix(pt2),color = (0, 255, 255), thickness=2) pt3 = np.array((x - eH/2.0, y)) pt4 = np.array((x + eH/2.0, y)) cv2.line(vis, pix(pt3), pix(pt4),color = (255, 255, 0), thickness=2) w, h = img.shape[1], img.shape[0] note_pos = (w/2.0, h/2.0) note_h = 88 draw_note(vis, note_pos, note_h) cv2.namedWindow('note', cv2.WINDOW_NORMAL) cv2.imshow('note', vis) cv2.waitKey() #vis = img.copy() #cv2.drawContours(vis, cnts, -1, (0, 255, 0), -1) #cv2.imshow('note', vis) #cv2.waitKey() #vis = img.copy() #for i in range(len(cnts)): # cv2.drawContours(vis, cnts, i, (0, 255, 0), -1) #(x, y), (MA, ma), angle = cv2.fitEllipse(cnts[i]) #center = (int(x), int(y)) #axes = (int(MA), int(ma)) #cvellipse(vis, center, axes, angle, startAngle=0, endAngle=360, color=(0, 255, 0)) # cv2.imshow('note', vis) # cv2.waitKey() img, ns = cv2.imread('samples/cotton_fields_0.jpg'), 13 #img, ns = cv2.imread('samples/torcida.jpg'), 9 img = rectify(img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, edges = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV) note_img= fit_note(ns) note_w, note_h = note_img.shape[1], note_img.shape[0] #filtered = cv2.filter2D(edges, -1, note_img) #cv2.TM_CCOEFF_NORMED result = cv2.matchTemplate(edges, note_img, cv2.TM_CCOEFF_NORMED) max = np.max(result) poss = np.argwhere(result >= 0.75 * max) vis = img.copy() for pos in poss: note_pos = np.array((pos[1] + note_w/2.0, pos[0] + note_h/2.0)) cv2.circle(vis, pix(note_pos), 3, (0,255,0), 1) cv2.namedWindow("note", cv2.WINDOW_NORMAL) cv2.imshow("note", note_img) cv2.imshow("image", edges) cv2.imshow("filt", result) cv2.imshow("found", vis) cv2.waitKey()<file_sep>import glob import cv2 import numpy as np from matplotlib import pyplot as plt #from hough import hough_lines from hough import hough_lines_, hough_lines_2 def draw_line(img, line, color=(255, 0, 0)): h, w = img.shape[0], img.shape[1] rho = line[0] theta = line[1] sinT = np.sin(theta) cosT = np.cos(theta) if abs(sinT) < 0.5: # vertical ish line y1 = 0 x1 = int((rho - y1 * sinT) / cosT) y2 = h x2 = int((rho - y2 * sinT) / cosT) else: # horizontal ish line x1 = 0 y1 = int((rho - x1 * cosT) / sinT) x2 = w y2 = int((rho - x2 * cosT) / sinT) cv2.line(img, (x1, y1), (x2, y2), color, 2) def draw_lines(img, lines, color=(255, 0, 0)): for line in lines: draw_line(img, line, color) def degrees_to_radians(angle): """ """ return (angle * np.pi / 180.0) def radians_to_degrees(angle): """ """ return (angle * 180.0 / np.pi) def find_lines(edges, angle, tolerance, min_votes): rho_resolution = 1 theta_resolution = 0.5 * (np.pi / 180) #theta_resolution = (np.pi / 180) #theta_resolution = np.pi / 180 * 2 #min_votes = 30 min_theta = degrees_to_radians(angle - tolerance) max_theta = degrees_to_radians(angle + tolerance) # lines = cv2.HoughLines( # edges, # rho_resolution, # theta_resolution, # threshold=min_votes # ) lines = cv2.HoughLines( edges, rho_resolution, theta_resolution, threshold=min_votes, min_theta=min_theta, max_theta=max_theta ) lines = np.reshape(lines, (-1, 2)) return lines def filter_outliers(lines): thetas = lines[:, 1] mu = np.median(thetas) var = np.var(thetas) thresh = 0.5 * var lines = [line for line in lines if abs(line[1] - mu) <= thresh] return lines, mu def find_staves(img, lines): w, h = img.shape[1], img.shape[0] lines = np.sort(lines, axis=0) rhos = lines[:, 0] # sort lines by rho #lines = sorted(lines, key=lambda line: line[0]) #rhos = lines[:, 0] #rhos.sort() seq0 = np.insert(rhos, 0, 0) seq1 = np.insert(rhos, len(rhos), h) diff = seq1 - seq0 #n_bins = int(h/10) #n_bins = h #bins = range(0, int(h/2), 3) bins = range(0, h) hist, bins = np.histogram(diff, bins=bins) # width = 0.7 * (bins[1] - bins[0]) # center = (bins[:-1] + bins[1:]) / 2 # plt.bar(center, hist, align='center', width=width) # plt.show() max_bin = np.argmax(hist) max = bins[max_bin] staves = [] staff = [] for i in range(len(lines) - 1): line1 = lines[i] line2 = lines[i+1] rho1 = line1[0] rho2 = line2[0] rhoDiff = np.abs(rho2 - rho1) if (rhoDiff - max) < 2: if len(staff) < 3: staff.append(line1) else: staff.append(line1) staff.append(line2) staves.append(staff) staff = [] else: staff = [] return staves, max def rectify(img): w, h = img.shape[1], img.shape[0] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 1) negative threshold of image _, edges = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV) # 2) finds horizontal lines hough_thresh = int(0.5 * w) h_lines = find_lines(edges, angle=90, tolerance=5, min_votes=hough_thresh) # 3) obtains page rotation (mu) _, mu = filter_outliers(h_lines) # 4) de-rotates image angle = radians_to_degrees(mu) angle = (90 - angle) R = cv2.getRotationMatrix2D((0, 0), -angle, 1.0) dsize = (img.shape[1], img.shape[0]) rot = cv2.warpAffine(img, R, dsize, borderValue=(255,255,255)) return rot def map_line_func(img, line, func): w, h = img.shape[1], img.shape[0] rho = line[0] theta = line[1] sinT = np.sin(theta) cosT = np.cos(theta) # horizontal ish line y1 = int((rho - 0 * cosT) / sinT) y2 = int((rho - w * cosT) / sinT) return func(y1, y2) def process_staves(img, staves): #i = 0 #vis = img.copy() #for staff in staves: # if i % 2 == 0: # color = (255, 0, 0) # else: # color = (0, 0, 255) # draw_lines(vis, staff, color=color) # i+= 1 # cv2.imshow('staff', vis) w, h = img.shape[1], img.shape[0] for staff in staves: top = staff[0] bottom = staff[-1] y_from = map_line_func(img, top, min) y_to = map_line_func(img, bottom, max) sub = img[y_from:y_to, 0:w] sub = cv2.cvtColor(sub, cv2.COLOR_BGR2GRAY) hough_thresh = int(0.97 * sub.shape[0]) _, edges = cv2.threshold(sub, 200, 255, cv2.THRESH_BINARY_INV) #cv2.imshow('sub', edges) #cv2.waitKey() v_lines = find_lines(edges, angle=0, tolerance=1, min_votes=hough_thresh) vis = cv2.cvtColor(sub, cv2.COLOR_GRAY2BGR) draw_lines(vis, v_lines, color=(0, 0, 255)) cv2.imshow('vlines', vis) cv2.imshow('sub', sub) cv2.waitKey() def process(file): img = cv2.imread(file) print("file: ", file, " shape:", img.shape) #img = imutils.resize(img, width=1024) # 1) Rectifies the music sheet img = rectify(img) #cv2.imshow('rect', img) #cv2.waitKey() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #edges = cv2.Canny(gray,50,150,apertureSize = 3) _, edges = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV) w, h = img.shape[1], img.shape[0] hough_thresh = int(0.5 * w) h_lines = find_lines(edges, angle=90, tolerance=1, min_votes=hough_thresh) h_lines, mu = filter_outliers(h_lines) staves, note_si = find_staves(img, h_lines) print("note size:", note_si) process_staves(img, staves) vis = img.copy() draw_lines(vis, h_lines) cv2.imshow('filtered', vis) cv2.waitKey() # plt.imshow(img) # plt.xticks([]), plt.yticks([]) # plt.show() def test(): base_path = 'samples/' files = [f for f in glob.glob(base_path + "/*.jpg", recursive=False)] for file in files: process(file) cv2.waitKey() #file = 'samples/cotton_fields_0.jpg' #file = 'samples/cotton_fields_1.jpg' #file = 'samples/cotton_fields_2.jpg' #file = 'samples/capture.jpg' file = 'samples/torcida.jpg' #file = 'samples/capture2.jpg' #file = 'samples/capture3.jpg' process(file) cv2.waitKey() # def test2(): # file = 'samples/cotton_fields_0.jpg' # # file = 'samples/capture.jpg' # #file = 'samples/torcida.jpg' # # file = 'samples/capture2.jpg' # # file = 'samples/capture3.jpg' # img = cv2.imread(file) # # print("file: ", file, " shape:", img.shape) # #w, h = img.shape[1], img.shape[0] # #new_w = 320 # #new_h = int(h * (new_w / w)) # #img = cv2.resize(img, (new_w, new_h)) # # w, h = img.shape[1], img.shape[0] # # # Pipeline Idea # # 0. Gray, Thresholding (img -> edges)    # # 0.0 test using vertical Sobel? # # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # # edges = cv2.Canny(gray,50,150,apertureSize = 3) # _, edges = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV) # # cv2.imshow('edges', edges) # # # 1. Hough -> lines      # # 1.1 adaptive thresh # # #hough_thresh = int(w / 2.0) # # lines = hough_lines(img) # #lines = cv2.HoughLines(edges, rho=1, theta=0.5 * np.pi / 180, threshold=hough_thresh) # lines = cv2.HoughLinesP(edges, rho=1, theta=0.5 * np.pi/180, threshold=500, minLineLength=1, maxLineGap=2) # #h = hough_lines_(edges) # #h = np.array(255 * h / np.max(h), dtype='uint8') # # #h = h.T # #res = cv2.resize(h, (1920, 480)) # #cv2.imshow('spectrum', res) # #cv2.waitKey() # plt.imshow(h) # plt.xticks([]), plt.yticks([]) # plt.show() if __name__ == "__main__": test()<file_sep>import time import numpy as np from scipy.sparse import csr_matrix def hough_lines_2(img): h, w = img.shape[0], img.shape[1] q = np.ceil( np.sqrt(h*h + w*w) ) n_rho = int(2 * q - 1) #thetas = np.linspace(-90, 89, 180) thetas = np.linspace(-5, 5, 16) n_theta = len(thetas) ts = thetas * np.pi / 180 cos = np.cos(ts).reshape(-1, 1) sin = np.sin(ts).reshape(-1, 1) H = np.zeros((n_rho, n_theta), dtype='int') r = np.where(img) xs, ys = r[0], r[1] xs = xs.reshape(-1, 1) ys = ys.reshape(-1, 1) t0 = time.time() #i = 0 rhos = xs * cos.T + ys * sin.T #sparse = csr_matrix((data, (rhos_idx, thetas_idx)), (nRho, nTheta)) #for x, y in zip(xs, ys): # i += 1 # pass # #print(x, y, time.time()) # #for t in thetas: # # rho = x * np.cos(t) + y * np.sin(t) t1 = time.time() print('elapsed', t1 - t0) return H def hough_lines_(img): iH, iW = img.shape[0], img.shape[1] #a0, af, an = (88, 92, 5) a0, af, an = (-3, 3, 9) #a0, af, an = (-90, 89, 180) theta = np.linspace(a0, af, an) nTheta = len(theta) d = np.sqrt(iH*iH + iW*iW) q = int(np.ceil(d)) #n_rho = int(2 * q - 1) #rho = np.linspace(-q, q, nRho) #slope = (n_rho - 1) / (q + q) n_rho = q rho = np.linspace(0, q, n_rho) slope = (n_rho - 1) / q #h = np.zeros((nRho, nTheta)) h = csr_matrix((n_rho, nTheta)) r = np.where(img) x, y = r[0], r[1] val = img[x, y] #take = 50000 take = 5000 totK = int(np.ceil(len(val) / take)) ts = theta * np.pi / 180 cos = np.cos(ts).reshape(-1, 1) sin = np.sin(ts).reshape(-1, 1) #totK = 1 for k in range(totK): print(time.time(), "start") first = k * take last = min(first + take, len(x)) xs = x[first:last].reshape(-1, 1) ys = y[first:last].reshape(-1, 1) print(time.time(), "rhos") rhos = xs * cos.T + ys * sin.T slope = (n_rho - 1) / (rho[-1] - rho[0]) norm_rho = rhos - rho[0] #rho_bin_index = np.round(slope * (norm_rho) + 1) rho_bin_index = (slope * (norm_rho) + 1).astype(int) print(time.time(), "bin idx") num = last-first theta_bin_index = np.tile(range(nTheta), (num, 1)) data = np.ones(num * nTheta).reshape(-1) rhos_idx = rho_bin_index.reshape(-1) thetas_idx = theta_bin_index.reshape(-1) print(time.time(), "sparse") sparse = csr_matrix((data, (rhos_idx, thetas_idx)), (n_rho, nTheta)) #h = h + sparse.toarray() print(time.time(), "sum") h += sparse return h.toarray() def hough_lines(img): iH, iW = img.shape[0], img.shape[1] theta = np.linspace(-90, 89, 180) nTheta = len(theta) d = np.sqrt((iH - 1) ^ 2 + (iW - 1) ^ 2) q = np.ceil(d) nRho = int(2 * q - 1) rho = np.linspace(-q, q, nRho) slope = (nRho - 1) / (q + q) h = np.zeros((nRho, nTheta)) r = np.where(img) x, y = r[0], r[1] val = img[x, y] take = 5000 totK = int(np.ceil(len(val) / take)) for k in range(1, totK): first = (k - 1) * take last = min(first + take, len(x)) x_matrix = np.tile(x[first:last], (1, nTheta)) y_matrix = np.tile(y[first:last], (1, nTheta)) val_matrix = np.tile(val[first:last], (1, nTheta)) tsize = x_matrix.shape[0] # size(x_matrix, 1) theta_matrix = np.tile(theta, (tsize, 1)) * np.pi / 180 rho_matrix = x_matrix * np.cos(theta_matrix) + y_matrix * np.sin(theta_matrix) slope = (nRho - 1) / (rho[-1] - rho[0]) rho_bin_index = round(slope * (rho_matrix - rho[0]) + 1) theta_bin_index = np.tile(range(1, nTheta), (tsize, 1)) sparse = csr_matrix(val_matrix[:], (rho_bin_index[:], theta_bin_index[:]), (nRho, nTheta)) h = h + np.full(sparse) <file_sep>import cv2 import imutils import numpy as np #from matplotlib import pyplot as plt template = cv2.imread('res/bass_clef.jpg') #template = cv2.imread('res/treble_clef.jpg') template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) #image = cv2.imread('samples/capture.jpg') #image = cv2.imread('samples/capture2.jpg') #image = cv2.imread('samples/capture3.jpg') #image = cv2.imread('samples/torcida.jpg') image = cv2.imread('samples/cotton_fields_0.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) found = None visualize = False # detect edges in the resized, grayscale image and apply template # matching to find the template in the image #edged = cv2.Canny(gray, 50, 200) #cv2.imshow('edged', edged) # loop over the scales of the image scales = np.linspace(0.1, 1.0, 20)[::-1] for scale in scales: scaled = imutils.resize(template, width=int(template.shape[1] * scale)) scaled_template = cv2.Canny(scaled, 50, 200) (tH, tW) = scaled_template.shape[:2] # # resize the image according to the scale, and keep track # # of the ratio of the resizing # #resized = resize(gray, width=int(gray.shape[1] * scale)) r = template.shape[1] / float(scaled_template.shape[1]) # # # if the resized image is smaller than the template, then break # # from the loop if scaled_template.shape[0] < tH or gray.shape[1] < tW: print("Scale skipped:", scale) continue #result = cv2.matchTemplate(edged, scaled_template, cv2.TM_CCOEFF) result = cv2.matchTemplate(gray, scaled, cv2.TM_CCOEFF_NORMED) (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result) threshold = 0.6 if maxVal < threshold: continue loc = np.where(result >= threshold) score = np.median(result[loc]) # check to see if the iteration should be visualized if visualize: #print("size:", tH, tW, maxVal, maxLoc, r) #cv2.imshow('template', scaled_template) # draw a bounding box around the detected region clone = np.copy(gray) #x_offset = y_offset = 0 #clone[y_offset:y_offset + scaled.shape[0], x_offset:x_offset + scaled.shape[1]] = scaled clone = cv2.cvtColor(clone, cv2.COLOR_GRAY2BGR) for maxLoc in zip(*loc[::-1]): cv2.rectangle(clone, maxLoc, (maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2) #cv2.rectangle(clone, (maxLoc[0], maxLoc[1]), # (maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2) cv2.imshow("Visualize", clone) cv2.waitKey(0) # if we have found a new maximum correlation value, then update # the bookkeeping variable if found is None or score > found[0]: found = (score, loc, scale) # unpack the bookkeeping variable and compute the (x, y) coordinates # of the bounding box based on the resized ratio (_, loc, scale) = found print(found) #startX = maxLoc[0] #startY = maxLoc[1] #endX = maxLoc[0] + int(template.shape[1] * scale) #endY = maxLoc[1] + int(template.shape[0] * scale) # draw a bounding box around the detected result and display the image #cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2) tW = int(template.shape[1] * scale) tH = int(template.shape[0] * scale) for maxLoc in zip(*loc[::-1]): cv2.rectangle(image, maxLoc, (maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2) cv2.namedWindow('Image', cv2.WINDOW_NORMAL) cv2.imshow("Image", image) cv2.resizeWindow("Image", 1024, 768) cv2.waitKey(0) #template = cv2.resize(template, (256, 437)) #template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) #w, h = template.shape[::-1] # res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) # threshold = 0.8 # loc = np.where( res >= threshold ) # for pt in zip(*loc[::-1]): # cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) #cv2.imshow('template', template) #cv2.imshow('res', img_rgb) #cv2.waitKey() <file_sep>import cv2 import numpy as np # For windows: # 1. Download zip file with Poppler's latest binaries/dlls from http://blog.alivate.com.au/poppler-windows/ and unzip to a new folder in your program files folder. For example: "C:\Program Files (x86)\Poppler". # 2. Add "C:\Program Files (x86)\Poppler\poppler-0.68.0\bin" to your SYSTEM PATH environment variable. from pdf2image import convert_from_path def pil2cv(pil_image): #pil_image = PIL.Image.open('Image.jpg').convert('RGB') cv_image = np.array(pil_image) # Convert RGB to BGR cv_image = cv_image[:, :, ::-1].copy() return cv_image def convert_using_pdf2image(): #file = "cotton_fields" file = "chega_de_saudade" full_name = "samples/" + file + ".pdf" pages = convert_from_path(full_name, 200, poppler_path='C:/Program Files (x86)/Poopler/poppler-0.68.0/bin') # Saving pages in jpeg format for i, page in enumerate(pages): cv_page = pil2cv(page) page_name = "samples/" + file + "_" + str(i) + ".jpg" cv2.imwrite(page_name, cv_page) cv2.imshow("page", cv_page) #page.save('out.jpg', 'JPEG') cv2.waitKey() convert_using_pdf2image()<file_sep># Music Sheet Scanner The main goal for this project is to convert an image of a music score to actual sound, that plays that score, using computer vision algorithms.
84f651cc3ef5cc63c2f781f1b1fcdfcd797118ed
[ "Markdown", "Python" ]
6
Python
estebanuri/sheet_scan
cb63c18bb6eab83c61f5ca2944e83bb1c4d349e6
e807fc0cc2c549b7a3fa1514520e6dfc5b7ff3a0
refs/heads/master
<file_sep>#!/usr/bin/env node const expect = require('chai').expect const CliTest = require('command-line-test') /* global describe:true */ /* global it:true */ /* eslint no-undef: "error" */ describe('Environment variable test', () => { it('should print error if no both variables are not set', async () => { const cliTest = new CliTest() delete process.env.JTL_USERNAME delete process.env.JTL_PASS const result = await cliTest.exec('./jtl.js') expect(result.stdout).to.be.equal('Please supply your Jira username and password in the JTL_USERNAME and JTL_PASS environment variables.') }) it('should print error if only JTL_USERNAME is set', async () => { const cliTest = new CliTest() delete process.env.JTL_PASS process.env.JTL_USERNAME = 'super.secret' const result = await cliTest.exec('./jtl.js') expect(result.stdout).to.be.equal('Please supply your Jira username and password in the JTL_USERNAME and JTL_PASS environment variables.') }) it('should print error if only JTL_PASS is set', async () => { const cliTest = new CliTest() delete process.env.JTL_USERNAME process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js') expect(result.stdout).to.be.equal('Please supply your Jira username and password in the JTL_USERNAME and JTL_PASS environment variables.') }) }) describe('log command', () => { it('should error if no args are passed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js log') expect('' + result.error).to.contain('\n error: missing required argument `issueId\'\n') }) it('should error if only issueId is passed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js log INT-1234567') expect('' + result.error).to.contain('\n error: missing required argument `time\'\n') }) it('should error if text is passsed as a date', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js log --date=tomorrow INT-1234567 1h') expect(result.stdout).to.be.equal('Please use a correct date in the form of YYYY-MM-DD') }) it('should error if impossible date is passsed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js log --date=2018-09-40 INT-1234567 1h') expect(result.stdout).to.be.equal('Please use a correct date in the form of YYYY-MM-DD') }) }) describe('logs command', () => { it('should error if no args are passed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js logs') expect('' + result.error).to.contain('\n error: missing required argument `date\'\n') }) it('should error if text is passsed as a date', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js logs today') expect(result.stdout).to.be.equal('Please use a correct date in the form of YYYY-MM-DD') }) it('should error if impossible date is passsed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js logs 2018-09-40') expect(result.stdout).to.be.equal('Please use a correct date in the form of YYYY-MM-DD') }) it('should error if no project is passed with --project flag', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js logs --project 2018-09-40') expect('' + result.error).to.contain('\n error: missing required argument `date\'\n') }) it('should error if no project is passed with -p flag', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js logs --project 2018-09-40') expect('' + result.error).to.contain('\n error: missing required argument `date\'\n') }) }) describe('logs command', () => { it('should error if no args are passed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js rm') expect('' + result.error).to.contain('\n error: missing required argument `issueId\'\n') }) it('should error if only issueId is passed', async () => { const cliTest = new CliTest() process.env.JTL_USERNAME = 'super.secret' process.env.JTL_PASS = '<PASSWORD>' const result = await cliTest.exec('./jtl.js rm INT-123456') expect('' + result.error).to.contain('\n error: missing required argument `worklogId\'\n') }) }) <file_sep># Build a binary for just the current platform all: node_modules/.bin/pkg jtl.js -o bin/jtl # Build binaries for all different platforms release: node_modules/.bin/pkg -t node10-linux,node10-win,node10-macos jtl.js -o bin/jtl # Delete all the built binaries clean: rm bin/jtl*
8b9830b01e68a1c51b7746f65c746a366828e183
[ "JavaScript", "Makefile" ]
2
JavaScript
hjarrell/jira-timelog
e9926b4541a45c4978d8e598fecf51b954f200fa
e61f78ad3294310c853543daef9cff096b1b1255
refs/heads/master
<file_sep># Android sensor bridge for ROS Publish sensor data from your phone (connected via WiFi or USB) to ROS. ## Overview [![Android sensor bridge for ROS ](http://img.youtube.com/vi/K4_FIi-hl-w/0.jpg)](http://www.youtube.com/watch?v=K4_FIi-hl-w) A collection of python scripts that publish sensor data from your phone (connected via WiFi or USB) to ROS. Supports a small variety of data logging apps (no dedicated Android app required): * `ip_webcam_bridge.py`: Connects to [IP Webcam](https://play.google.com/store/apps/details?id=com.pas.webcam) and publishes camera images as `sensor_msgs/CompressedImage`. Launch `http://<phone_ip>:<port>` in the browser to configure or use service calls als follows - use service `<node>/<setting>/<get>` to retrieve the current value of a setting (e.g. `$ rosservice call /ip_webcam_bridge/video_size/get` returns `720x480`) - use service `<node>/<setting>/<options>` to list all available options for a setting (e.g `$ rosservice call /ip_webcam_bridge/video_size/options` returns `1920x1080; 1440x1080; 1088x1088; 1280x720; 1056x704; 1024x768; 960x720; 800x450; 720x720; 720x480; 640x480; 352x288; 320x240; 256x144; 176x144`) - use service `<node>/<setting>/<set>` to change a setting (e.g. `$ rosservice call /ip_webcam_bridge/video_size/set "value: {data: '720x480'}"`) * `sensrec_bridge.py`: Connects to [Sensors Record](https://play.google.com/store/apps/details?id=pl.mrwojtek.sensrec.app) and publishes: - `sensor_msgs/Imu` inertial measurement based on phone's rotation vector, linear acceleration and gyroscope - `sensor_msgs/MagneticField` magnetic field based on phone's magnetometer - `nmea_msgs/Sentence` low-level GPS NMEA sentecnes for processing with 3rd party tools (e.g. `nmea_navsat_driver`) - `sensor_msgs/NavSatFix` location based on phone's location API - `geometry_msgs/TwistStamped` velocity based on phones location API - battery info - pressure - ambient light intensity Check the [Android Sensor Types](https://source.android.com/devices/sensors/sensor-types) documentation for detais! ## Related projects * [android_sensors_driver](https://github.com/ros-android/android_sensors_driver) relies on a dedicated Android app <file_sep>#!/usr/bin/env python # <NAME> # https://github.com/robbeofficial # check this: https://source.android.com/devices/sensors/sensor-types # TODO create class # TODO check parse errors # TODO include system time stamps in header # TODO add http://docs.ros.org/api/sensor_msgs/html/msg/TimeReference.html message # TODO use http://docs.ros.org/jade/api/sensor_msgs/html/msg/BatteryState.html for battery # TODO check what of message generation stuff is actually important import socket, traceback from sensor_msgs.msg import Imu, MagneticField, NavSatFix from geometry_msgs.msg import TwistStamped from std_msgs.msg import Float64 from nmea_msgs.msg import Sentence as NmeaSentence import rospy rospy.init_node('sensrec_bridge') # pubs pub_imu = rospy.Publisher('~imu/data', Imu, queue_size=1) pub_mag = rospy.Publisher('~imu/mag', MagneticField, queue_size=1) pub_nmea = rospy.Publisher('~gps/nmea', NmeaSentence, queue_size=1) #pub_nmea = rospy.Publisher('nmea_sentence', NmeaSentence, queue_size=1) pub_fix = rospy.Publisher('~gps/fix', NavSatFix, queue_size=1) pub_vel = rospy.Publisher('~gps/vel', TwistStamped, queue_size=1) pub_pressure = rospy.Publisher('~pressure', Float64, queue_size=1) pub_light = rospy.Publisher('~light', Float64, queue_size=1) pub_bat_level = rospy.Publisher('~battery/level', Float64, queue_size=1) pub_bat_voltage = rospy.Publisher('~battery/voltage', Float64, queue_size=1) pub_bat_temp = rospy.Publisher('~battery/temperature', Float64, queue_size=1) # params host = rospy.get_param('~host', '') port = rospy.get_param('~port', 44335) socket_bufsize = rospy.get_param('~socket_bufsize', 4096) # UDP socket connection sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind((host, port)) # holds latest message for each sensor type vals = {} def messages(sock, bufsize=4096): "reads newline-separated messages from socket" buf = sock.recv(bufsize) buffering = True while buffering: if "\n" in buf: (line, buf) = buf.split('\n', 1) yield line else: more = sock.recv(bufsize) if not more: buffering = False else: buf += more if buf: yield buf while not rospy.is_shutdown(): try: for message in messages(sock, socket_bufsize): fields = message.strip().split('\t') # message fields are tab-separated sensor = fields[0] vals[sensor] = fields # check https://github.com/mrwojtek/sens-rec/blob/b0d34aad1e827720cb6eb11b512ad9eff021a1e5/lib/src/main/java/pl/mrwojtek/sensrec/SensorRecorder.java#L121 # For Android Sensors: type_id ms ns length values[] if sensor not in ['rotv_0', 'lacc_0', 'gyro_0', 'magn_0', 'press_0', 'light_0', 'gps', 'nmea', 'bat']: rospy.logerr("Unknwon message: '{}'".format(message)) # publish an Imu message for each received rotation vector if sensor == 'rotv_0': rotv = fields imu_msg = Imu() imu_msg.header.frame_id = 'android' imu_msg.orientation.x = float(rotv[4]) imu_msg.orientation.y = float(rotv[5]) imu_msg.orientation.z = float(rotv[6]) imu_msg.orientation.w = float(rotv[7]) if 'lacc_0' in vals: lacc = vals['lacc_0'] imu_msg.linear_acceleration.x = float(lacc[4]) imu_msg.linear_acceleration.y = float(lacc[5]) imu_msg.linear_acceleration.z = float(lacc[6]) if 'gyro_0' in vals: gyro = vals['gyro_0'] imu_msg.angular_velocity.x = float(gyro[4]) imu_msg.angular_velocity.y = float(gyro[5]) imu_msg.angular_velocity.z = float(gyro[6]) pub_imu.publish(imu_msg) # publish magnetic field elif sensor == 'magn_0': magn = fields mag_msg = MagneticField() mag_msg.header.frame_id = 'android' mag_msg.magnetic_field.x = float(magn[4]) mag_msg.magnetic_field.y = float(magn[5]) mag_msg.magnetic_field.z = float(magn[6]) pub_mag.publish(mag_msg) # publish pressure elif sensor == 'press_0': msg_press = Float64() msg_press.data = float(fields[4]) pub_pressure.publish(msg_press) # publish light elif sensor == "light_0": msg_light = Float64() msg_light.data = float(fields[4]) pub_light.publish(msg_light) # publish NMEA setence elif sensor == "nmea": msg_nmea = NmeaSentence() msg_nmea.header.frame_id = 'android' msg_nmea.header.stamp = rospy.Time.from_sec(float(fields[2]) / 1000) msg_nmea.sentence = fields[3] pub_nmea.publish(msg_nmea) # publish fix and vel from device location # check https://github.com/mrwojtek/sens-rec/blob/b0d34aad1e827720cb6eb11b512ad9eff021a1e5/lib/src/main/java/pl/mrwojtek/sensrec/LocationRecorder.java#L113 # check https://developer.android.com/reference/android/location/Location.html#getAccuracy() # gps 48021735 52.51782937923822 13.447371576740874 82.6810805981322 0.0 9.953303E-4 12.0 1496696180000 # type ms lat lon alt bearing[deg] speed[m/s] accuracy[m] time[s] # horizontal accuracy of this location, radial, in meters # bearing is the horizontal direction of travel of this device (0.0, 360.0], 0.0 = no bearing [deg] elif sensor == 'gps': stamp = rospy.Time.from_sec(float(fields[8]) / 1000) # publish fix msg_fix = NavSatFix() msg_fix.header.frame_id = 'android' msg_fix.header.stamp = stamp msg_fix.latitude = float(fields[2]) msg_fix.longitude = float(fields[3]) msg_fix.altitude = float(fields[4]) var = float(fields[7]) msg_fix.position_covariance = [var*var, 0, 0, 0, var*var, 0, 0, 0, var*var] msg_fix.position_covariance_type = NavSatFix.COVARIANCE_TYPE_APPROXIMATED pub_fix.publish(msg_fix) # publish velicity msg_vel = TwistStamped() msg_vel.header.frame_id = 'android' msg_vel.header.stamp = stamp msg_vel.twist.linear.x = float(fields[6]) pub_vel.publish(msg_vel) # publish battery info # check https://github.com/mrwojtek/sens-rec/blob/b0d34aad1e827720cb6eb11b512ad9eff021a1e5/lib/src/main/java/pl/mrwojtek/sensrec/BatteryRecorder.java#L110 # bat 49820907 0.51 3826 299 # type ms percentage voltage[mV] temperature[delsius*10] elif sensor == 'bat': pub_bat_level.publish(float(fields[2])) pub_bat_voltage.publish(float(fields[3]) / 1000) pub_bat_temp.publish(float(fields[4]) / 10) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc()<file_sep>#!/usr/bin/env python # <NAME> # https://github.com/robbeofficial # todo create class from enum import Enum import socket, traceback import math from sensor_msgs.msg import Imu, MagneticField from std_msgs.msg import Float32 import rospy rospy.init_node('sensorstreamgps_bridge') pub_imu = rospy.Publisher('imu/data_raw', Imu, queue_size=1) pub_mag = rospy.Publisher('imu/mag', MagneticField, queue_size=1) host = rospy.get_param('~host', '') port = rospy.get_param('~port', 5555) # TODO check why they are different from https://developer.android.com/reference/android/hardware/Sensor.html ACCELEROMETER = 3 # [m/s^2] GRAVITY = 83 # [m/s^2] LINEAR_ACCELERATION = 82 # ACCELEROMETER - GRAVITY [m/s^2] GYROSCOPE = 4 # [rad/s] MAGNETIC_FIELD = 5 # [uT] ORIENTATION = 81 # legacy - azimuth, pitch, yaw [deg] ROTATION_VECTOR = 84 # roation angle theta around axis <x,y,z>: <x*sin(theta/2), y*sin(theta/2), z*sin(theta/2)> TEMPERATURE = 86 # [celsius] PRESSURE = 85 # [hPa] # unknown sensor: 1 - [' 52.517632', ' 13.447430', ' 83.2', ' 3', ' 5.801', '-13.746', '-28.710', ' 4', ' 11.797', ' 0.481', ' -3.857', ' 6', ' 3782828.967', ' 904506.791', ' 5038124.782', ' 7', ' -0.253', '-0.131', ' 0.212', ' 8', ' 1496608842000', ' 86', ' 32'] GPS = 1 vals = {} # TODO publish sensor_msgs/Imu s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) def pop_front(lst, n=1, cast=float): if n == 1: return cast(lst.pop(0)) else: vals = lst[:n] del lst[:n] return [cast(s) for s in vals] while not rospy.is_shutdown(): try: message, address = s.recvfrom(8192) #print(message) arr = message.split(',') time_stamp = pop_front(arr) while len(arr) > 0: sensor = pop_front(arr, 1, int) if sensor in [ACCELEROMETER, GYROSCOPE, MAGNETIC_FIELD, ORIENTATION, LINEAR_ACCELERATION, GRAVITY, ROTATION_VECTOR, GPS]: sensor_vals = pop_front(arr, 3) vals[sensor] = (time_stamp, sensor_vals) elif sensor in [TEMPERATURE, PRESSURE]: sensor_vals = pop_front(arr, 1) vals[sensor] = (time_stamp, sensor_vals) else: print "unknown sensor: {} - {}".format(sensor, arr) break # publish IMU imu_msg = Imu() imu_msg.header.frame_id = 'android' rv = vals[ROTATION_VECTOR][1] imu_msg.orientation.x = rv[0] imu_msg.orientation.y = rv[1] imu_msg.orientation.z = rv[2] w = 1 - rv[0]*rv[0] - rv[1]*rv[1] - rv[2]*rv[2] if w > 0: w = math.sqrt(w) else: w = 0 imu_msg.orientation.w = w imu_msg.orientation_covariance[0] = -1 # cov unknown imu_msg.angular_velocity.x = vals[GYROSCOPE][1][0] imu_msg.angular_velocity.y = vals[GYROSCOPE][1][1] imu_msg.angular_velocity.z = vals[GYROSCOPE][1][2] imu_msg.angular_velocity_covariance[0] = -1 # cov unknown imu_msg.linear_acceleration.x = vals[LINEAR_ACCELERATION][1][0] imu_msg.linear_acceleration.y = vals[LINEAR_ACCELERATION][1][1] imu_msg.linear_acceleration.z = vals[LINEAR_ACCELERATION][1][2] imu_msg.linear_acceleration_covariance[0] = -1 # cov unknown pub_imu.publish(imu_msg) # publish magfield mag_msg = MagneticField() mag_msg.header.frame_id = 'android' mag_msg.magnetic_field.x = vals[MAGNETIC_FIELD][1][0] mag_msg.magnetic_field.x = vals[MAGNETIC_FIELD][1][1] mag_msg.magnetic_field.z = vals[MAGNETIC_FIELD][1][2] pub_mag.publish(mag_msg) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc()<file_sep>#!/usr/bin/env python # <NAME> # https://github.com/robbeofficial # Run IP Webcam on your android phone # https://play.google.com/store/apps/details?id=com.pas.webcam&hl=de # use it's browser interface (or ROS service calls) to configure # TODO create class # TODO doc: did not use dynreconf because too static # TODO check if it's okay to use msg.String instead of srv.GetStringResponse # TODO add success flag or similar to service calls import urllib2 import requests #import cv2 #import numpy as np import rospy import std_msgs.msg import sensor_msgs.msg import android_sensor_bridge.srv def setting_get(setting): status = requests.get(hoststr + '/status.json').json() return std_msgs.msg.String(status['curvals'][setting]) def setting_options(setting): status = requests.get(hoststr + '/status.json', params = {'show_avail': 1}).json() return std_msgs.msg.String('; '.join(status['avail'][setting])) def setting_set(setting, req): # torch: /enabletorch /disabletorch # focus: /focus /nofocus # video_size: /settings/video_size?set=352x288 value = req.value.data # create a list of possible entry points entry_points = [hoststr + '/settings/' + setting + "?set=" + value] if value in ['on', 'off']: entry_points.append(hoststr + ('enable' if value == 'on' else 'disable') + setting) entry_points.append(hoststr + ('' if value == 'on' else 'no') + setting) # try calling them for entry_point in entry_points: rospy.loginfo('querying ' + entry_point) http = requests.get(entry_point) if http.status_code == 200: break return android_sensor_bridge.srv.SetStringResponse() def add_settings_services(): status = requests.get(hoststr + '/status.json', params = {'show_avail': 1}).json() curvals = status['curvals'].keys() avail = status['avail'].keys() for setting in curvals: if setting != " ": # TODO more generic? rospy.loginfo('Adding setting ' + setting) rospy.Service("~" + setting + "/get", android_sensor_bridge.srv.GetString, lambda req, setting=setting : setting_get(setting)) rospy.Service("~" + setting + "/set", android_sensor_bridge.srv.SetString, lambda req, setting=setting : setting_set(setting, req)) if setting in avail: rospy.Service("~" + setting + "/options", android_sensor_bridge.srv.GetString, lambda req, setting=setting : setting_options(setting)) if __name__ == '__main__': rospy.init_node('ip_webcam_bridge') # params host = rospy.get_param('~host', '192.168.43.1') port = rospy.get_param('~port', 8080) hoststr = 'http://{}:{}'.format(host, port) # pubs pub_image = rospy.Publisher('~image/compressed', sensor_msgs.msg.CompressedImage, queue_size=1) # services add_settings_services() rospy.loginfo('Streaming ' + hoststr + '/video') stream = urllib2.urlopen(hoststr + '/video') buffer = '' while not rospy.is_shutdown(): buffer += stream.read(1024) a = buffer.find('\xff\xd8') b = buffer.find('\xff\xd9') if a != -1 and b != -1: jpg = buffer[a:b+2] buffer = buffer[b+2:] # create and send CompressedImage message img_msg = sensor_msgs.msg.CompressedImage() img_msg.data = jpg img_msg.format = 'jpeg' pub_image.publish(img_msg) rospy.logdebug('published image') # decode and show image #img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR) # openCV < 3 #img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR) # openCV >= 3 #cv2.imshow(hoststr, img) #if cv2.waitKey(1) == 27: # exit(0)
b04e27d4dd36dffe3efff5f5ea3ab31dcdc73aa5
[ "Markdown", "Python" ]
4
Markdown
robbeofficial/android_sensor_bridge
02d5cbe1eb96e9172ede88bed18b1785ae394b28
3f16250282ff2f98df6a94bc066e3ebc8fb939bb
refs/heads/master
<repo_name>javiss/weather-app<file_sep>/playground/promisesss.js let asyncAdd = (a, b) => { return new Promise((resolve, reject) => { setTimeout(() => { if (typeof a === 'number' && typeof b === 'number') { resolve(a + b); } else { reject('not numbers'); } }, 300); }); }; asyncAdd(2, '3').then((res) => { console.log('res --> ' + res); return asyncAdd(res, '33'); }).then((res) => { console.log('res2 --> ' + res); }).catch((err) => { console.log('catch --> ' + err); });<file_sep>/playground/callbacks.js function getUser(id, callback) { let user = { id: id, name: 'Javi' }; setTimeout(() => { callback(user); }, 500); } getUser(31, (user) => { console.log(user); }); <file_sep>/geocode/geoCode.js const _request = require('request'); function geocodeAddress(address) { return new Promise((resolve, reject) => { _request({ url: `http://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}`, json: true }, (error, response, body) => { if (error) { console.log(error); reject('Cant connect'); } else if (body.status === 'ZERO_RESULTS') { console.log(body); reject('No results found'); } else if (body.status === 'OK') { console.log(body); resolve({ address: body.results[0].formatted_address, lat: body.results[0].geometry.location.lat, lng: body.results[0].geometry.location.lng }); } }); }); } module.exports = { geocodeAddress };
ae43f0eed536a99ff20cfdadaf6dd68db3ed29f5
[ "JavaScript" ]
3
JavaScript
javiss/weather-app
232208ccf983333346788fbfa829cbf401c2b74e
e7e4d6198554fa2cdf68a08dd30c73293e64fc68
refs/heads/master
<repo_name>dorantor/php-vast<file_sep>/src/Ad/InLine.php <?php namespace Sokil\Vast\Ad; use Sokil\Vast\Creative\AbstractLinearCreative; use Sokil\Vast\Creative\InLine\Linear; class InLine extends AbstractAdNode { /** * Set Ad title * * @param string $value * * @return \Sokil\Vast\Ad\InLine */ public function setAdTitle($value) { $this->setScalarNodeCdata('AdTitle', $value); return $this; } /** * @inheritdoc */ protected function buildCreativeClassName($type) { return '\\Sokil\\Vast\\Creative\\InLine\\' . $type; } /** * Create Linear creative * * @throws \Exception * @return AbstractLinearCreative */ public function createLinearCreative() { return $this->buildCreative('Linear'); } } <file_sep>/tests/AbstractTestCase.php <?php namespace Sokil\Vast; use Sokil\Vast\Document; abstract class AbstractTestCase extends \PHPUnit\Framework\TestCase { /** * @param string $expectedXml * @param Document $actualVastDocument */ protected function assertVastXmlEquals($expectedXml, Document $actualVastDocument) { $actualXml = str_replace( array("\r", "\n"), '', (string) $actualVastDocument ); self::assertEquals($expectedXml, $actualXml); } /** * Minify XML * * @param string $xml * @return string */ protected function minifyXml($xml) { $document = new \DOMDocument(); $document->preserveWhiteSpace = false; $document->loadXML($xml); return $document->saveXML(); } /** * Get minified xml string using file from data/ dir * * @param $filename * @return string */ protected function minifiedXmlFromData($filename) { $xml = file_get_contents(__DIR__ . '/data/' . $filename); return $this->minifyXml($xml); } /** * Assert xml equals between file from data/ dir and given Document * * @param string $filename * @param Document $document */ protected function assertFileVsDocument($filename, Document $document) { self::assertEquals( $this->minifiedXmlFromData($filename), (string) $document ); } } <file_sep>/src/Creative/InLine/Linear/AdParameters.php <?php namespace Sokil\Vast\Creative\InLine\Linear; class AdParameters { private $domElement; public function __construct(\DomElement $domElement) { $this->domElement = $domElement; } public function setParams($params) { if (is_array($params)) { $params = json_encode($params); } $cdata = $this->domElement->ownerDocument->createCDATASection($params); // update CData if ($this->domElement->hasChildNodes()) { $this->domElement->replaceChild($cdata, $this->domElement->firstChild); } // insert CData else { $this->domElement->appendChild($cdata); } return $this; } }
68d0a783275c0ec1cadced9279ca14c7fd800875
[ "PHP" ]
3
PHP
dorantor/php-vast
ef3b8215170461f40c003d063167f2942c54b798
6d4685a2ff2edbd5f5875a94d8f34944652102c1
refs/heads/master
<file_sep>[RemoteSSH] Host = 1.2.3.4 User = user RemotePort = 443 LocalPort = 2222 [RemoteWeb] Host = my.c2.com FileName = cmd.txt [Local] Upgrade = yes DistUpgrade = no SetupVNC = no AdditionalPackages = tree jq <file_sep>from setuptools import setup setup( name='ptb', version='0.1.0', packages=['ptb'], entry_points={ 'console_scripts': ['ptb=ptb.ptb:main'] } ) <file_sep>from pathlib import Path from typing import Dict, List, Tuple WEBCMD_PATH = '/opt/ptb' WEBCMD_APP = 'webcmd.py' WEBCMD_CRON = '*/2 * * * * root /opt/ptb/webcmd.py' CONFIG_SECTIONS: Dict[str, List[Tuple]] = { 'RemoteSSH': [ ('Host', 'IP of remote SSH server:', ''), ('RemotePort', 'Port of remote SSH server:', 443), ('LocalPort', 'Local port on remote SSH server for forwarding:', 2200), ('User', 'Username on remote SSH Server', '') ], 'RemoteWeb': [ ('Host', 'Hostname or IP of remote web server for commands ' '(e.g. example.com):', ''), ('FileName', 'Name of hosted file containing the commands to execute:', 'cmd.txt') ], 'Local': [ ('Upgrade', 'Run apt-get upgrade?', 'yes'), ('DistUpgrade', 'Run apt-get dist-upgrade?', 'yes'), ('SetupVNC', 'Should a VNC server be set up on the pentest box? ' '(won\'t start automatically)', 'no'), ('AdditionalPackages', 'Add additional apt packages to be installed (space separated)', 'none') ] } REQUIRED_PACKAGES = ['autossh', 'openssh-server', 'sshpass'] VNC_PACKAGES = ['novnc', 'x11vnc'] HOME_PATH = Path().home() SSH_KEY_PATH = HOME_PATH / '.ssh/dropbox' SSH_SERVICE_TEMPLATE = """[Unit] Description=AutoSSH to remote server after network comes online After=network-online.target [Service] Environment="AUTOSSH_GATETIME=0" ExecStart=/usr/bin/autossh -M 0 -o "ExitOnForwardFailure=yes" -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -R {{remote_forward_port}}:127.0.0.1:22 {{user}}@{{host}} -i {{key_path}} -p {{port}} [Install] WantedBy=multi-user.target """ WEBCMD_SCRIPT_TEMPLATE = """#!/bin/python3 import os import hashlib import urllib.request FILE = '/opt/ptb/lastcmd' with urllib.request.urlopen('https://{{host}}/{{filename}}') as cmd: commands = cmd.read().strip() hashed = hashlib.sha1(commands).hexdigest() mode = 'r+' if os.path.exists(FILE) else 'w+' with open(FILE, mode) as f: last = f.read() f.seek(0) if last != hashed: for command in commands.decode('utf-8').split('\\n'): os.system(command) f.write(hashed) """ <file_sep>from pkg_resources import get_distribution __version__ = get_distribution('ptb').version <file_sep>from .ptb import main main() <file_sep>import logging import configparser from typing import Optional, Tuple from pathlib import Path from ptb.const import CONFIG_SECTIONS class Config: def __init__(self, config_file: Optional[Path]): self.config_file = config_file self.parser = configparser.ConfigParser() def load(self) -> bool: """Loads config and makes sure all values are set Loads from config file, if set, and/or prompts user for any missing config values """ key_config: Tuple if self.config_file: if self.config_file.exists(): self._load_from_file() else: logging.warning(('Configfile file %s given, but does not ' 'exist.' % self.config_file)) return False for section in CONFIG_SECTIONS: if section not in self.parser.sections(): self.parser[section] = {} for key in CONFIG_SECTIONS[section]: try: value = self.parser[section][key[0]] except KeyError: # ask for config value help_text = key[1] help_text += f' (default: {key[2]})' if key[2] else '' value = input(f'> {help_text} ') if not value: # set default if nothing was given value = key[2] if not value: logging.info( 'No value given for "%s" in section "%s"', key[0], section) logging.info('Cancelling...') return False logging.info( 'Config value for "%s" in section "%s": %s', key[0], section, value) return True def _load_from_file(self) -> None: try: self.parser.read(self.config_file) except configparser.Error: logging.warning('Failed to read config file %s' % self.config_file) return logging.info(('Loaded config file with sections: %s' % self.parser.sections())) <file_sep>class PtbException(Exception): """Base exception.""" class PtbProcessException(PtbException): """Raised when external process fails.""" <file_sep># PTB - Pentest Box This is a small app for setting up connectivity on a pentest dropbox. It will install packages, configure an autossh service (systemd), and set up a cronjob that checks for remote commands from a webserver for troubleshooting in case the SSH connection drops. IPs, hostnames, packages, etc. can be configured in a config file (see `config.sample.ini`). If no config file is found, the app will ask for the values it needs. I made this just now for experimentation and to have a quicker setup. Please test thoroughly if it fits *your* case before using it in a real assessment. ## Install & Usage `ptb` must be run as root to install necessary components. ``` git clone git@github.com:davidhamann/ptb.git cd ptb python3 -m venv venv source venv/bin/activate pip install . ptb my-config.ini ``` You will see issued commands as it goes. After the script ran, you should be able to connect to the box via a proxy jump: ``` ssh -o ProxyCommand="ssh -i ~/.ssh/<key-to-remote> -W %h:%p -p <remote-port> <remote-user>@<remote-ip>" -p <local-port> pentestbox-user@127.0.0.1 # Add -D 1080, if you would like to run a SOCKS proxy on your local box for local tools. ``` Commands from the webserver are checked and executed every two minutes. If the last published commands have already been executed, they won't be executed a second time. ## Notes The app won't do anything to secure or otherwise set up your pentest box. Make sure to configure your host firewall/iptables, encrypted volumes, ip config, etc. yourself. `ptb` is only a helper for the connection setup plus a few extras. More importantly, make sure that your remote SSH server and webserver are secure. Otherwise, once *they* are pwned, your dropbox is basically rooted as well :-) ## Requirements You need a remote SSH server (with a static IP) to be used as proxy and a webserver to fetch commands from (simple text file). Tested on Kali Linux, but should run on any Debian based Linux. <file_sep>import os import re import time import sys import logging import subprocess from getpass import getpass from typing import Optional, List, TextIO from pathlib import Path from ptb.config import Config from ptb.exceptions import PtbProcessException from ptb.const import ( REQUIRED_PACKAGES, VNC_PACKAGES, SSH_KEY_PATH, HOME_PATH, SSH_SERVICE_TEMPLATE, WEBCMD_PATH, WEBCMD_APP, WEBCMD_SCRIPT_TEMPLATE, WEBCMD_CRON) class Ptb: def __init__(self, config: Config, verbose=False): self.config = config self.verbose = verbose def exec(self, command: List[str], stdout: Optional[TextIO] = None) -> int: """Wrapper for executing external commands.""" assert isinstance(command, List) joined = ' '.join(command) logging.info('Running %s' % joined) if stdout: # use given file handle for redirection try: exit = subprocess.run( command, check=True, stdout=stdout).returncode except subprocess.CalledProcessError as error: raise PtbProcessException( 'Command "%s" failed with return %d' % (joined, error.returncode)) else: try: proc = subprocess.Popen(command, stdout=subprocess.PIPE) except FileNotFoundError: raise PtbProcessException('%s cannot be found' % command[0]) # print stdout until process exits while True: out = proc.stdout.readline() if proc.poll() is not None and out == b'': break if self.verbose and out: logging.info(out.decode('utf-8').strip()) time.sleep(0.1) exit = proc.poll() if exit != 0: raise PtbProcessException('Command "%s" failed. Return code: %d', ' '.join(command), exit) return exit def install_packages(self) -> None: """Install required and optional packages, optionally upgrade dist.""" self.exec(['apt-get', 'update']) if self.config.parser['Local'].getboolean('Upgrade'): self.exec(['apt-get', 'upgrade', '-y']) if self.config.parser['Local'].getboolean('DistUpgrade'): self.exec(['apt-get', 'dist-upgrade', '-y']) self.exec(['apt-get', 'install', '-y'] + REQUIRED_PACKAGES) if self.config.parser['Local'].getboolean('SetupVNC'): self.exec(['apt-get', 'install', '-y'] + VNC_PACKAGES) add_packages = self.config.parser['Local']['AdditionalPackages'] if add_packages != '' and add_packages != 'none': package_list = add_packages.split(' ') self.exec(['apt-get', 'install', '-y'] + package_list) def configure_ssh(self) -> None: """Enable local SSH server, then set up keys for remote communication.""" ssh_user = self.config.parser['RemoteSSH']['User'] ssh_host = self.config.parser['RemoteSSH']['Host'] ssh_port = self.config.parser['RemoteSSH']['RemotePort'] # enable openssh server on pentest box self.exec(['systemctl', 'enable', 'ssh']) # delete previous key if existing self.exec(['rm', '-f', str(SSH_KEY_PATH)]) # generate keypair for remote server self.exec(['ssh-keygen', '-f', str(SSH_KEY_PATH), '-N', '']) # clean known_hosts and re-add remote server self.exec(['touch', str(HOME_PATH / '.ssh/known_hosts')]) self.exec(['ssh-keygen', '-R', ssh_host + ':' + ssh_port]) with open(HOME_PATH / '.ssh/known_hosts', 'a') as known_hosts: self.exec(['ssh-keyscan', '-H', '-p', ssh_port, ssh_host], stdout=known_hosts) # prompt for one-time remote login pass and upload key to remote server os.environ['SSHPASS'] = getpass( f'Enter the password for the user {ssh_user} ' f'at {ssh_host} (for key upload): ') self.exec(['sshpass', '-e', 'ssh-copy-id', '-i', str(SSH_KEY_PATH), '-p', ssh_port, f'{ssh_user}@{ssh_host}']) # test login logging.info('Testing login...') self.exec(['ssh', '-q', '-o', 'BatchMode=yes', '-i', str(SSH_KEY_PATH), f'{ssh_user}@{ssh_host}', '-p', ssh_port, 'true']) logging.info('Login with key works!') def install_service(self) -> None: """Install service to keep SSH alive.""" ssh_user = self.config.parser['RemoteSSH']['User'] ssh_host = self.config.parser['RemoteSSH']['Host'] with open('/etc/systemd/system/ptb-ssh.service', 'w') as service: replacements = { '{{remote_forward_port}}': self.config.parser['RemoteSSH']['LocalPort'], '{{port}}': self.config.parser['RemoteSSH']['RemotePort'], '{{user}}': ssh_user, '{{host}}': ssh_host, '{{key_path}}': str(SSH_KEY_PATH) } replacements = dict( (re.escape(k), v) for k, v in replacements.items()) pattern = re.compile("|".join(replacements.keys())) service_config = pattern.sub( lambda x: replacements[re.escape(x.group(0))], SSH_SERVICE_TEMPLATE) service.write(service_config) def install_cron(self) -> None: """Write-out webcmd script and set up cron to call it.""" self.exec(['mkdir', '-p', WEBCMD_PATH]) with open(WEBCMD_PATH + '/' + WEBCMD_APP, 'w') as f: f.write( WEBCMD_SCRIPT_TEMPLATE .replace('{{host}}', self.config.parser['RemoteWeb']['Host']) .replace('{{filename}}', self.config.parser['RemoteWeb']['FileName'])) self.exec(['chmod', '+x', WEBCMD_PATH + '/' + WEBCMD_APP]) with open('/etc/cron.d/ptb-webcmd', 'w') as cron: cron.write(WEBCMD_CRON + '\n') def enable_services(self) -> None: logging.info('Enabling openssh-server') self.exec(['systemctl', 'enable', 'ssh']) logging.info('Starting openssh-server') self.exec(['systemctl', 'start', 'ssh']) logging.info('Enabling autossh service') self.exec(['systemctl', 'enable', 'ptb-ssh.service']) logging.info('Starting autossh service') self.exec(['systemctl', 'start', 'ptb-ssh.service']) def set_up(self) -> bool: logging.info('Starting to set up pentest box') try: # update, upgrade and install packages logging.info('Starting with package install') self.install_packages() # set up openssh server and set up key pair for remote logging.info('Setting up local SSH and keypair for remote access') self.configure_ssh() # add autossh service logging.info('Installing service for keeping SSH alive') self.install_service() logging.info('Starting services') self.enable_services() logging.info('Setting up cron for fetching web commands') self.install_cron() except PtbProcessException as exc: logging.error(exc) return False print('Setup done. You should now be able to connect to the pentest ' 'box from anywhere via a proxy jump (you will likely use a ' 'different key than the one we generated here):\n') print('ssh -o ProxyCommand="ssh -i ~/.ssh/key-to-remote -W %h:%p -p ' f'{self.config.parser["RemoteSSH"]["RemotePort"]} remote-user@' f'remote-ip" -p {self.config.parser["RemoteSSH"]["LocalPort"]} ' 'pentestbox-user@127.0.0.1\n\n(Add -D 1080, if you would like ' 'to run a SOCKS proxy on your local box for local tools.)') return True def main(): '''CLI entry point''' result: bool = True logging.basicConfig( format='[%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout)], level=logging.DEBUG) config_file = Path(sys.argv[1]) if len(sys.argv) > 1 else None if not os.geteuid() == 0: logging.error('Please run as root') sys.exit(1) confirm = input('Configure this box? [Y/n]: ') if confirm in ['', 'Y', 'y']: config = Config(config_file) if config.load(): ptb = Ptb(config, verbose=False) result = ptb.set_up() else: print('Cancelling...') sys.exit(0) if result else sys.exit(1)
65078347c1ec87af5e0281bb4c1fa0801b5403ae
[ "Markdown", "Python", "INI" ]
9
INI
davidhamann/ptb
7c13014d0f9a0b399055b6005ce2d8c2590896b3
f332f7bf425ff2bfc9b3e1e3f85aaf9e178d3eda
refs/heads/main
<file_sep>import pandas as pd import numpy as np import streamlit as st import requests import yfinance as yf import plotly.express as px import plotly.graph_objects as go import io st.sidebar.title("Options") option = st.sidebar.selectbox("Which Dashboard?", ("Chart", "Portfolio", "Crypto", "Total Portfolio Holding Calculator", "Ishares Etf Position Explorer", "Symbol", "ARK Invest Portfolio", ), 2) @st.cache def get_ticker_data(symbol, years=3): period=f"{years}y" ticker = yf.Ticker(symbol) infos = ticker.info hist_data = ticker.history(period) return ticker, infos, hist_data @st.cache def plot_data(hist_data): fig = go.Figure(data=[ go.Candlestick(x=hist_data.index.date.tolist(), open=hist_data["Open"], high=hist_data["High"], low=hist_data["Low"], close=hist_data["Close"], name=symbol) ] ) fig.update_xaxes(type='category') fig.update_layout(height=800, width=1000) return fig def plot_and_infos(symbol, isEtf=False): ticker, infos, hist_data = get_ticker_data(symbol) c1, c2 = st.beta_columns((1, 4)) try: c1.image(infos["logo_url"]) except: c1.subheader(symbol) with c2: c2.header(infos["longName"]) c2.subheader("Basic Info:") if not isEtf: f""" **Country:** {infos["country"]} **Sector:** {infos["industry"]} **Dividend:** {infos["dividendRate"]} % **Website:** {infos["website"]} --- """ st.image(f'https://finviz.com/chart.ashx?t={symbol}') try: fig = plot_data(hist_data) st.plotly_chart(fig, use_container_width=True) #st.write(hist_data) except: st.write("No Plot Data available right now...") if option == "Crypto": st.image("https://alternative.me/crypto/fear-and-greed-index.png", caption="Fear & Greed Index") #st.title(option) if option == "Total Portfolio Holding Calculator": holdings_columns = ["Ticker","Weight","Url"] text_csv = st.text_area(f"Your Etf Positions in Format: {holdings_columns}") if st.button('Run'): if text_csv != None: portfolio_holdings_df = pd.read_csv(io.StringIO(text_csv), sep=";", names=holdings_columns) else: st.write("Please Enter your holdings") '----' with st.spinner("Loading Data..."): #info_ticker = st.selectbox("Holdings Info", holdings_df["Ticker"]) #plot_and_infos(u'{}'.format(info_ticker), isEtf=True) def conv_str_to_float(df, conv_cols): df_conv = df.copy() for col in conv_cols: df_conv[col] = [float(i.replace('.', '').replace(',', '.')) for i in df_conv[col]] return df_conv def scan_ishares_etf_holdings(url): drop_cols = ["Anlageklasse", "Nominale", "Nominalwert", "Börse", "Marktwährung"] rename_cols = {"Gewichtung (%)":"Gewichtung"} conv_cols = ["Gewichtung", "Kurs", "Marktwert"] df = pd.read_csv(url, skiprows=2, ) df = df.drop(columns=drop_cols) df = df.rename(columns=rename_cols) df = df[:-1] df = conv_str_to_float(df, conv_cols) df = df.loc[df.Gewichtung > 0.01] return df hold_positions = [] for index, hold in portfolio_holdings_df.iterrows(): hold_positions_df = scan_ishares_etf_holdings(hold["Url"]) hold_positions_df.Gewichtung = hold_positions_df.Gewichtung / 100 hold_positions_df["Gewichtung"] = hold.Weight * hold_positions_df.Gewichtung hold_positions.append(hold_positions_df) portfolioDf = pd.concat(hold_positions).sort_values("Gewichtung", ascending=False).reset_index(drop=True) st.header("Portfolio Holdings") st.write(portfolioDf) st.balloons() if option == "Chart": symbol = st.sidebar.text_input(label="Symbol:", value="ASML",) years = st.sidebar.slider("Years:", 1, 6, value=3) plot_and_infos(symbol) # akt_name = infos["name"] # isin = infos["isin"] # aktionär_url = f"https://www.deraktionaer.de/aktien/kurse/{akt_name}-{isin}.html" with st.beta_expander("Links:"): c1, c2 = st.beta_columns((1,3)) c2.markdown(f'[![Der Aktionär](https://www.deraktionaer.de/assets/images/svg/logo-deraktionaer.svg)](https://www.deraktionaer.de/)') if option == "Portfolio": headcol, chartcol = st.beta_columns((1.5, 3)) headcol.header("My Portfolio") chartcol.image(f'https://finviz.com/chart.ashx?t={"PLTR"}') bcol = st.beta_columns((3,1,1,1,1)) bcol[1].button(label="Day") bcol[2].button(label="1Wk") bcol[3].button(label="1Mo") bcol[4].button(label="Max") st.subheader("Performance:") perfcol = st.beta_columns((1, 1, 1)) perfcol[0].button(label="Performance: +500€") perfcol[1].button(label="Monthly Performance: +500€") perfcol[2].button(label="Yearly Performance: +500€") if option == "Symbol": symbol = st.sidebar.text_input(label="Symbol:", value="ASML",) st.subheader(f'Chart:') <EMAIL> st.image(f'https://finviz.com/chart.ashx?t={symbol}') st.markdown("---") st.header(f'Stocktwits for {symbol}:') stocktwits_symbol_url = "https://api.stocktwits.com/api/2/streams/symbol/{}.json".format(symbol) r = requests.get(stocktwits_symbol_url) data = r.json() st.subheader(f'Stocktwits for: {data["symbol"]["title"]}') for message in data["messages"]: st.image(message["user"]["avatar_url"]) st.write(message["user"]["username"]) st.write(message["created_at"]) st.write(message["body"]) st.markdown("---") st.write(data) if option == "Ishares Etf Position Explorer": st.subheader("Get all Positions of an ETF in a Table") @st.cache def read_ishares_data(url): df = pd.read_csv(url, skiprows=2) return df # #holdings > div.holdings.fund-component-data-export > a url2 = st.text_area("ETF Url", value="", height=None, max_chars=None, key=None) if url2 == "": st.write("No Url Input.") else: df = read_ishares_data(url2) st.dataframe(df) if option == "ARK Invest Portfolio": st.write(option) st.markdown("[Ark Invest Fond Holdings](https://cathiesark.com/ark-funds-combined/complete-holdings)") <file_sep># StockApp Simple functions for dealing with stocks and visual representation as a streamlit app <file_sep>streamlit pandas plotly numpy yfinance requests requests-html html5lib
c6bff8dbe02368e61d0e032d05cf90710fcfec8e
[ "Markdown", "Python", "Text" ]
3
Python
michih8/StockApp
6275894c2797848e18a0d4bb40ef09be75f9304b
93fb7564cf129fe82745a709c7d4c50b1d9dc3db
refs/heads/master
<file_sep>package com.miracle.camel.service; import org.apache.camel.Exchange; import org.apache.camel.Message; import com.miracle.itx.utility.ITXInvoker; public class ITXService { @SuppressWarnings("static-access") public String process(Exchange exchange) { Message msg = exchange.getIn(); String mapName = (String) msg.getHeader("mapName"); String endpoint = (String) msg.getHeader("endpoint"); ITXInvoker itxInvoker = new ITXInvoker(); msg.setBody(itxInvoker.transform(msg.getBody().toString(),mapName)); System.out.println(msg.getBody().toString()); System.out.println(mapName); return endpoint; } }
3d2710544dceddb4d578fefa6d80234ba64e378d
[ "Java" ]
1
Java
csnmiraclesoft/Camel-API
a09c19b6ab84d6e521555e0e108981a8ba4ba4ab
46272265bd52b7c1513400a6f429d1e2644ce6ae
refs/heads/main
<repo_name>frodo10messi/ios-form<file_sep>/Sources/Views/ToggleInputCell/ToggleInputCell.swift // // ToggleInputCell.swift // iOSForm // // Created by <NAME> on 30/03/2021. // import UIKit protocol ToggleInputCellDelegate: AnyObject { func cell(_ cell: ToggleInputCell, didChangeValue value: Bool) } final class ToggleInputCell: UITableViewCell { private let titleLabel = UILabel() private let valueSwitch = UISwitch() weak var delegate: ToggleInputCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { selectionStyle = .none contentView.addSubview(titleLabel) contentView.addSubview(valueSwitch) titleLabel.snp.makeConstraints { $0.leading.equalToSuperview().inset(16.0) $0.centerY.equalToSuperview() } valueSwitch.snp.makeConstraints { $0.trailing.equalToSuperview().inset(16.0) $0.centerY.equalToSuperview() } valueSwitch.addTarget(self, action: #selector(valueSwitchDidChange), for: .valueChanged) } @objc private func valueSwitchDidChange() { delegate?.cell(self, didChangeValue: valueSwitch.isOn) } } // MARK: - Configure extension ToggleInputCell { func configure(_ viewModel: ToggleInputViewModel) { titleLabel.text = viewModel.title valueSwitch.isOn = viewModel.value } } <file_sep>/Sources/Modules/Select/OpenSelectRouterInput.swift // // OpenSelectRouterInput.swift // iOSForm // // Created by <NAME> on 26/03/2021. // import UIKit protocol OpenSelectRouterInput: AnyObject { var viewController: UIViewController? { get } func showSelectScreen(output: SelectModuleOutput?) } extension OpenSelectRouterInput { func showSelectScreen(output: SelectModuleOutput?) { let module = SelectModule() module.output = output viewController?.navigationController?.pushViewController(module.view, animated: true) } } <file_sep>/Sources/Utilities/Form/FormSection.swift // // FormSection.swift // iOSForm // // Created by <NAME> on 24/03/2021. // final class FormSection { var key: String var header: FormHeader? var fields: [FormField] init(key: String, header: FormHeader? = nil, fields: [FormField]) { self.key = key self.header = header self.fields = fields } } <file_sep>/Sources/Modules/Select/SelectableItem.swift // // SelectableItem.swift // iOSForm // // Created by <NAME> on 26/03/2021. // protocol SelectableItem: AnyObject, Equatable { var title: String { get set } } extension SelectableItem { static func == (lhs: Self, rhs: Self) -> Bool { lhs.title == rhs.title } } <file_sep>/Sources/Modules/Form/FormDemoViewController.swift // // FormDemoViewController.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol FormDemoViewInput: FormViewInput { var dataSource: FormDataSource { get } func configure() } protocol FormDemoViewOutput: AnyObject { func viewDidLoad() func didTapSaveButton() } final class FormDemoViewController: FormViewController { var output: FormDemoViewOutput? override func viewDidLoad() { super.viewDidLoad() output?.viewDidLoad() } } // MARK: - Private extension FormDemoViewController { private func setUpLayout() {} private func setUpViews() { navigationItem.title = "Registration Form" view.backgroundColor = .white navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Save", style: .done, target: self, action: #selector(didTapSaveButton) ) tableView.keyboardDismissMode = .onDrag } @objc private func didTapSaveButton() { output?.didTapSaveButton() } } // MARK: - FormDemoViewInput extension FormDemoViewController: FormDemoViewInput { func configure() { setUpLayout() setUpViews() } } <file_sep>/Sources/Views/TextInputCell/TextInputCell.swift // // TextInputCell.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol TextInputCellDelegate: AnyObject { func cell(_ cell: TextInputCell, didChangeValue value: String?) } final class TextInputCell: UITableViewCell { private let titleLabel = UILabel() private let textField = UITextField() weak var delegate: TextInputCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { selectionStyle = .none contentView.addSubview(titleLabel) contentView.addSubview(textField) titleLabel.snp.makeConstraints { $0.leading.equalToSuperview().inset(16.0) $0.centerY.equalToSuperview() } textField.snp.makeConstraints { $0.leading.equalTo(titleLabel.snp.trailing).offset(16.0) $0.trailing.equalToSuperview().inset(16.0) $0.top.bottom.equalToSuperview() } titleLabel.setContentCompressionResistancePriority(.defaultHigh + 1.0, for: .horizontal) titleLabel.setContentHuggingPriority(.required, for: .horizontal) } @objc private func textFieldEditingChanged(_ textField: UITextField) { delegate?.cell(self, didChangeValue: textField.text) } } // MARK: - Configure extension TextInputCell { func configure(_ viewModel: TextInputViewModel) { titleLabel.text = viewModel.title textField.placeholder = viewModel.title textField.text = viewModel.value textField.isSecureTextEntry = viewModel.isSecure textField.textAlignment = .right textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged) } } <file_sep>/Sources/Views/ToggleInputCell/ToggleInputViewModel.swift // // ToggleInputViewModel.swift // iOSForm // // Created by <NAME> on 30/03/2021. // struct ToggleInputViewModel { var title: String var value: Bool init(title: String, value: Bool = false) { self.title = title self.value = value } } <file_sep>/Sources/Modules/Form/FormDemoViewModel.swift // // FormDemoViewModel.swift // iOSForm // // Created by <NAME> on 24/03/2021. // final class FormDemoViewModel { let router: FormDemoRouter weak var view: FormDemoViewInput? init(router: FormDemoRouter) { self.router = router } private func configureProvinceAfterSelectCountry() { guard let view = view else { return } guard let country = view.dataSource.getValue( of: SelectInputFormField<Country>.self, byKey: FormFieldKey.country() ) else { return } if country.title == "Thailand" { view.dataSource.updateDataSource( for: SelectInputFormField<Province>.self, with: Province.thaiProvinces, byKey: FormFieldKey.province() ) } else { view.dataSource.updateDataSource( for: SelectInputFormField<Province>.self, with: Province.vietProvinces, byKey: FormFieldKey.province() ) } view.dataSource.updateValue( for: SelectInputFormField<Province>.self, with: nil, byKey: FormFieldKey.province() ) } private func handleEnabled2FA() { guard let view = view else { return } let enabled2FA = view.dataSource.getValue( of: ToggleInputFormField.self, byKey: FormFieldKey.enabled2FA() ) if enabled2FA { if !view.dataSource.fields.contains(where: { $0.key == FormFieldKey.twoFA() }) { let fields = view.dataSource.fields(ofSection: FormSectionKey.profile()) view.dataSource.insertField( TextInputFormField(key: FormFieldKey.twoFA(), viewModel: .init(title: "2FA Code")), at: fields.count, ofSection: FormSectionKey.profile() ) } } else { if view.dataSource.fields.contains(where: { $0.key == FormFieldKey.twoFA() }) { view.dataSource.removeField(FormFieldKey.twoFA()) } } } private func handleEnabledAddress() { guard let view = view else { return } let enabledAddress = view.dataSource.getValue( of: ToggleInputFormField.self, byKey: FormFieldKey.enabledAddress() ) if enabledAddress { let addressSection = FormSection( key: FormSectionKey.address(), fields: [ SelectInputFormField<Country>( key: FormFieldKey.country(), viewModel: .init(title: "Country"), dataSource: Country.list, router: router ), SelectInputFormField<Province>( key: FormFieldKey.province(), viewModel: .init(title: "Province"), router: router ) ] ) addressSection.fields.forEach { $0.delegate = self } view.dataSource.insertSection(addressSection, at: view.dataSource.sections.count) } else { view.dataSource.removeSection(withKey: FormSectionKey.address()) } } } // MARK: - FormDemoViewOutput extension FormDemoViewModel: FormDemoViewOutput { func viewDidLoad() { view?.configure() let sections: [FormSection] = [ .init( key: FormSectionKey.profile(), header: TitleFormHeader(key: "Profile", viewModel: .init(title: "PROFILE")), fields: [ TextInputFormField( key: FormFieldKey.fullName(), viewModel: .init(title: "Full Name", value: "Admin") ), TextInputFormField(key: FormFieldKey.username(), viewModel: .init(title: "Username")), TextInputFormField( key: FormFieldKey.password(), viewModel: .init(title: "Password", isSecure: true) ), DateInputFormField(key: FormFieldKey.birthday(), viewModel: .init(title: "Birthday")), ToggleInputFormField(key: FormFieldKey.enabled2FA(), viewModel: .init(title: "Enabled 2FA")) ] ), .init( key: FormSectionKey.enabledAddress(), fields: [ ToggleInputFormField(key: FormFieldKey.enabledAddress(), viewModel: .init(title: "Enabled Address")) ] ) ] view?.dataSource.updateSections(sections) view?.dataSource.fields.forEach { $0.delegate = self } } func didTapSaveButton() { guard let view = view else { return } var message = "" let fullName = view.dataSource.getValue(of: TextInputFormField.self, byKey: FormFieldKey.fullName()) message += "fullName: \(fullName)\n" let username = view.dataSource.getValue(of: TextInputFormField.self, byKey: FormFieldKey.username()) message += "username: \(username)\n" let password = view.dataSource.getValue(of: TextInputFormField.self, byKey: FormFieldKey.password()) message += "password: \(password)\n" if let birthday = view.dataSource.getValue(of: DateInputFormField.self, byKey: FormFieldKey.birthday()) { message += "birthday: \(birthday)\n" } let enabled2FA = view.dataSource.getValue(of: ToggleInputFormField.self, byKey: FormFieldKey.enabled2FA()) message += "enabled2FA: \(enabled2FA)\n" if enabled2FA { let twoFA = view.dataSource.getValue(of: TextInputFormField.self, byKey: FormFieldKey.twoFA()) message += "2FA: \(twoFA)\n" } let enabledAddress = view.dataSource.getValue( of: ToggleInputFormField.self, byKey: FormFieldKey.enabledAddress() ) message += "enabledAddress: \(enabledAddress)\n" if enabledAddress { if let country = view.dataSource.getValue( of: SelectInputFormField<Country>.self, byKey: FormFieldKey.country() ) { message += "country: \(country.title)\n" } if let province = view.dataSource.getValue( of: SelectInputFormField<Province>.self, byKey: FormFieldKey.province() ) { message += "province: \(province.title)\n" } } router.presentAlert(with: message) } } extension FormDemoViewModel: FormFieldDelegate { func fieldDidChangeValue(_ field: FormField) { switch field.key { case FormFieldKey.country.rawValue: configureProvinceAfterSelectCountry() case FormFieldKey.enabled2FA.rawValue: handleEnabled2FA() case FormFieldKey.enabledAddress.rawValue: handleEnabledAddress() default: break } } } // MARK: - Form Keys extension FormDemoViewModel { enum FormSectionKey: String { case profile case enabledAddress case address func callAsFunction() -> String { rawValue } } enum FormFieldKey: String { case fullName case username case password case birthday case enabled2FA case twoFA case enabledAddress case country case province func callAsFunction() -> String { rawValue } } } <file_sep>/Sources/Views/DateInputCell/DateInputCell.swift // // DateInputCell.swift // iOSForm // // Created by <NAME> on 01/04/2021. // import UIKit protocol DateInputCellDelegate: AnyObject { func cell(_ cell: DateInputCell, didChangeValue value: Date) } final class DateInputCell: UITableViewCell { private let titleLabel = UILabel() private let textField = UITextField() private let datePicker = UIDatePicker() private let toolbar = UIToolbar(frame: .init(x: 0.0, y: 0.0, width: 100.0, height: 100.0)) weak var delegate: DateInputCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { selectionStyle = .none contentView.addSubview(titleLabel) contentView.addSubview(textField) titleLabel.snp.makeConstraints { $0.leading.equalToSuperview().inset(16.0) $0.centerY.equalToSuperview() } textField.snp.makeConstraints { $0.leading.equalTo(titleLabel.snp.trailing).offset(16.0) $0.trailing.equalToSuperview().inset(16.0) $0.top.bottom.equalToSuperview() } titleLabel.setContentCompressionResistancePriority(.defaultHigh + 1.0, for: .horizontal) titleLabel.setContentHuggingPriority(.required, for: .horizontal) if #available(iOS 13.4, *) { datePicker.preferredDatePickerStyle = .wheels } datePicker.datePickerMode = .date textField.textAlignment = .right textField.inputView = datePicker configureToolbar() } private func configureToolbar() { let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(didTapDoneButton)) let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbar.setItems([spaceButton, doneButton], animated: false) toolbar.sizeToFit() textField.inputAccessoryView = toolbar } @objc private func didTapDoneButton() { delegate?.cell(self, didChangeValue: datePicker.date) endEditing(true) } } // MARK: - Configure extension DateInputCell { func configure(_ viewModel: DateInputViewModel) { titleLabel.text = viewModel.title textField.placeholder = viewModel.title textField.text = viewModel.valueString } } <file_sep>/Sources/Views/ToggleInputCell/ToggleInputFormField.swift // // ToggleInputFormField.swift // iOSForm // // Created by <NAME> on 30/03/2021. // import UIKit final class ToggleInputFormField { let key: String var viewModel: ToggleInputViewModel weak var delegate: FormFieldDelegate? init(key: String, viewModel: ToggleInputViewModel) { self.key = key self.viewModel = viewModel } } // MARK: - FormField extension ToggleInputFormField: FormField { var height: CGFloat { 44.0 } func register(for tableView: UITableView) { tableView.register(ToggleInputCell.self, forCellReuseIdentifier: "ToggleInputCell") } func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable:next force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "ToggleInputCell", for: indexPath) as! ToggleInputCell cell.configure(viewModel) cell.delegate = self return cell } } // MARK: - FieldDataSource extension ToggleInputFormField: FieldDataSource { var value: Bool { get { viewModel.value } set { viewModel.value = newValue } } } // MARK: - ToggleInputCellDelegate extension ToggleInputFormField: ToggleInputCellDelegate { func cell(_ cell: ToggleInputCell, didChangeValue value: Bool) { viewModel.value = value delegate?.fieldDidChangeValue(self) } } <file_sep>/Sources/Modules/Select/SelectViewController.swift // // SelectViewController.swift // iOSForm // // Created by <NAME> on 26/03/2021. // import UIKit protocol SelectViewInput: AnyObject { func configure() func setTitle(_ title: String?) func reloadTableView() } protocol SelectViewOutput: AnyObject { var list: [String] { get } func viewDidLoad() func didSelectItem(at index: Int) } final class SelectViewController: UIViewController { private let tableView = UITableView(frame: .zero, style: .grouped) var output: SelectViewOutput? override func viewDidLoad() { super.viewDidLoad() output?.viewDidLoad() } } // MARK: - Configure extension SelectViewController { private func setUpLayout() { view.addSubview(tableView) tableView.snp.makeConstraints { $0.edges.equalToSuperview() } } private func setUpViews() { tableView.backgroundColor = .systemGroupedBackground tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell.default") } } // MARK: - SelectViewInput extension SelectViewController: SelectViewInput { func configure() { setUpLayout() setUpViews() } func setTitle(_ title: String?) { navigationItem.title = title } func reloadTableView() { tableView.reloadData() } } // MARK: - UITableViewDataSource extension SelectViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { output?.list.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell.default") cell.textLabel?.text = output?.list[indexPath.row] ?? "" return cell } } // MARK: - UITableViewDelegate extension SelectViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 44.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) CATransaction.begin() CATransaction.setCompletionBlock { self.output?.didSelectItem(at: indexPath.row) } navigationController?.popViewController(animated: true) CATransaction.commit() } } <file_sep>/Sources/Views/TitleHeader/TitleHeaderFooterView.swift // // TitleHeaderFooterView.swift // iOSForm // // Created by <NAME> on 25/03/2021. // import UIKit struct TitleHeaderFooterViewModel { let title: String } final class TitleHeaderFooterView: UITableViewHeaderFooterView { private let titleLabel = UILabel() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setUpView() } required init?(coder: NSCoder) { super.init(coder: coder) setUpView() } func configure(with viewModel: TitleHeaderFooterViewModel) { titleLabel.text = viewModel.title } } // MARK: - Private helper extension TitleHeaderFooterView { private func setUpView() { contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { $0.leading.trailing.equalToSuperview().inset(16.0) $0.bottom.equalToSuperview().inset(8.0) } titleLabel.textColor = .systemGray titleLabel.font = UIFont.systemFont(ofSize: 12.0) } } <file_sep>/Sources/Modules/Form/FormDemoRouter.swift // // FormDemoRouter.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol FormDemoRouterInput: AnyObject { func show(on window: UIWindow) } final class FormDemoRouter { weak var view: FormDemoViewInput? var viewController: UIViewController? { view as? UIViewController } } // MARK: - FormDemoRouterInput extension FormDemoRouter: FormDemoRouterInput { func show(on window: UIWindow) { guard let viewController = viewController else { return } let navigationController = UINavigationController(rootViewController: viewController) window.rootViewController = navigationController } func presentAlert(with message: String) { let alert = UIAlertController(title: "iOSForm", message: message, preferredStyle: .alert) alert.addAction(.init(title: "OK", style: .default, handler: nil)) viewController?.present(alert, animated: true, completion: nil) } } // MARK: - OpenSelectRouterInput extension FormDemoRouter: OpenSelectRouterInput {} <file_sep>/Sources/Models/Country.swift // // Country.swift // iOSForm // // Created by <NAME> on 26/03/2021. // final class Country: SelectableItem { var title: String init(title: String) { self.title = title } } extension Country { static let list: [Country] = { [.init(title: "Vietnam"), .init(title: "Thailand")] }() } <file_sep>/Sources/Views/DateInputCell/DateInputFormField.swift // // DateInputFormField.swift // iOSForm // // Created by <NAME> on 01/04/2021. // import UIKit final class DateInputFormField { let key: String var viewModel: DateInputViewModel weak var delegate: FormFieldDelegate? init(key: String, viewModel: DateInputViewModel) { self.key = key self.viewModel = viewModel } } // MARK: - FormField extension DateInputFormField: FormField { var height: CGFloat { 44.0 } func register(for tableView: UITableView) { tableView.register(DateInputCell.self, forCellReuseIdentifier: "DateInputCell") } func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable:next force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "DateInputCell", for: indexPath) as! DateInputCell cell.configure(viewModel) cell.delegate = self return cell } } // MARK: - FieldDataSource extension DateInputFormField: FieldDataSource { var value: Date? { get { viewModel.value } set { viewModel.value = newValue } } } // MARK: - ToggleInputCellDelegate extension DateInputFormField: DateInputCellDelegate { func cell(_ cell: DateInputCell, didChangeValue value: Date) { viewModel.value = value cell.configure(viewModel) } } <file_sep>/Sources/Modules/Select/SelectViewModel.swift // // SelectViewModel.swift // iOSForm // // Created by <NAME> on 26/03/2021. // final class SelectViewModel { weak var view: SelectViewInput? weak var output: SelectModuleOutput? private(set) var list: [String] = [] } // MARK: - SelectViewOutput extension SelectViewModel: SelectViewOutput { func viewDidLoad() { view?.configure() view?.setTitle(output?.title) list = output?.list ?? [] view?.reloadTableView() } func didSelectItem(at index: Int) { output?.didSelectItem(at: index) } } <file_sep>/Sources/Utilities/Form/FormField.swift // // FormField.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol FormFieldDelegate: AnyObject { func fieldDidChangeValue(_ field: FormField) } protocol FormField: AnyObject { var key: String { get } var height: CGFloat { get } var delegate: FormFieldDelegate? { get set } func register(for tableView: UITableView) func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) } extension FormField { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {} } <file_sep>/Sources/Modules/Form/FormDemoModule.swift // // FormDemoModule.swift // iOSForm // // Created by <NAME> on 24/03/2021. // final class FormDemoModule { let view: FormDemoViewController let viewModel: FormDemoViewModel let router: FormDemoRouter init() { view = FormDemoViewController() router = FormDemoRouter() viewModel = FormDemoViewModel(router: router) view.output = viewModel viewModel.view = view router.view = view } } <file_sep>/Sources/Views/TextInputCell/TextInputViewModel.swift // // TextInputViewModel.swift // iOSForm // // Created by <NAME> on 25/03/2021. // struct TextInputViewModel { var title: String var value: String? var isSecure: Bool init(title: String, value: String? = nil, isSecure: Bool = false) { self.title = title self.value = value self.isSecure = isSecure } } <file_sep>/README.md # iOS Form | Form Demo | New Contact | | ----------------------------------- | ----------------------------------- | | ![Form demo](/images/form-demo.png) | ![New Contact](/images/contact.png) | ## Implement iOS Form with UITableView ### Create a base controller Base class `FormViewController` with - A table view - A data source to handle data - Implement table view's data source and delegate ```swift class FormViewController: UIViewController { let tableView = UITableView(frame: .zero, style: .grouped) let dataSource = FormDataSource() override func viewDidLoad() { super.viewDidLoad() configure() } } // MARK: - UITableViewDataSource extension FormViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { dataSource.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { dataSource.sections[section].fields.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let field = dataSource.sections[indexPath.section].fields[indexPath.row] return field.dequeue(for: tableView, at: indexPath) } } // MARK: - UITableViewDelegate extension FormViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let field = dataSource.sections[indexPath.section].fields[indexPath.row] return field.height } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { dataSource.sections[section].header?.dequeue(for: tableView, in: section) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let header = dataSource.sections[section].header else { return .zero } return header.height } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let field = dataSource.sections[indexPath.section].fields[indexPath.row] field.tableView(tableView, didSelectRowAt: indexPath) } } ``` ### Detail about FormDataSource The class `FormDataSource` contains data that is used for the form. ```swift final class FormDataSource { private(set) var sections: [FormSection] = [] } ``` #### FormSection `FormSection` contains data for each section on the table view. ```swift final class FormSection { var key: String var header: FormHeader? var fields: [FormField] init(key: String, header: FormHeader? = nil, fields: [FormField]) { self.key = key self.header = header self.fields = fields } } ``` #### FormHeader A object conform to `FormHeader` protocol, it will contains only the configuration of a header. `FormHeader` makes it easy to create and maintain a header in a `FormSection`. ```swift import UIKit protocol FormHeader: AnyObject { var key: String { get } var height: CGFloat { get } func register(for tableView: UITableView) func dequeue(for tableView: UITableView, in section: Int) -> UIView? } ``` How the implementation might look: ```swift final class TitleFormHeader { let key: String let viewModel: TitleHeaderFooterViewModel init(key: String, viewModel: TitleHeaderFooterViewModel) { self.key = key self.viewModel = viewModel } } extension TitleFormHeader: FormHeader { var height: CGFloat { 60.0 } func register(for tableView: UITableView) { tableView.register(TitleHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "TitleHeaderFooterView") } func dequeue(for tableView: UITableView, in section: Int) -> UIView? { let view = tableView.dequeueReusableHeaderFooterView( withIdentifier: "TitleHeaderFooterView" ) as? TitleHeaderFooterView view?.configure(with: viewModel) return view } } ``` #### FormField `FormField` is the most important protocol. For cells in table view, we will have field objects that carry the logic configuration of a view. We will create fields that conform `FormField` for all the cells we want to display in a table view. ```swift protocol FormField: AnyObject { var key: String { get } var height: CGFloat { get } var delegate: FormFieldDelegate? { get set } func register(for tableView: UITableView) func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) } ``` Here is an example about an implementation of `FormField` ```swift final class TextInputFormField { let key: String var viewModel: TextInputViewModel weak var delegate: FormFieldDelegate? init(key: String, viewModel: TextInputViewModel) { self.key = key self.viewModel = viewModel } } // MARK: - FormField extension TextInputFormField: FormField { var height: CGFloat { 44.0 } func register(for tableView: UITableView) { tableView.register(TextInputCell.self, forCellReuseIdentifier: "TextInputCell") } func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell", for: indexPath) as! TextInputCell cell.delegate = self cell.configure(viewModel) return cell } } ``` ## Form Demo Check out the demo for more detail about different types of cell. ```bash git clone git@github.com:nimblehq/ios-form.git pod install ``` ## License This project is Copyright (c) 2014 and onwards. It is free software, and may be redistributed under the terms specified in the [LICENSE] file. [LICENSE]: /LICENSE ## About ![Nimble](https://assets.nimblehq.co/logo/dark/logo-dark-text-160.png) This project is maintained and funded by Nimble. We love open source and do our part in sharing our work with the community! See [our other projects][community] or [hire our team][hire] to help build your product. [community]: https://github.com/nimblehq [hire]: https://nimblehq.co/<file_sep>/Sources/Utilities/Form/DataSource/FormDataSource.swift // // FormDataSource.swift // iOSForm // // Created by <NAME> on 25/03/2021. // import Foundation protocol FormDataSourceDelegate: AnyObject { func dataSourceDidChangeSections(_ dataSource: FormDataSource) func dataSourceDidReloadTableView(_ dataSource: FormDataSource) func dataSource(_ dataSource: FormDataSource, didUpdateAt indexPaths: [IndexPath]) func dataSource(_ dataSource: FormDataSource, didInsertAt indexPaths: [IndexPath]) func dataSource(_ dataSource: FormDataSource, didRemoveAt indexPaths: [IndexPath]) func dataSource(_ dataSource: FormDataSource, didInsertSectionAt sections: IndexSet) func dataSource(_ dataSource: FormDataSource, didRemoveSectionAt sections: IndexSet) } final class FormDataSource { private(set) var sections: [FormSection] = [] { didSet { delegate?.dataSourceDidChangeSections(self) } } var fields: [FormField] { Array(sections.compactMap { $0.fields }.joined()) } weak var delegate: FormDataSourceDelegate? func updateSections(_ sections: [FormSection]) { self.sections = sections delegate?.dataSourceDidReloadTableView(self) } func updateValue<Field: FieldDataSource>(for formField: Field.Type, with value: Field.Value, byKey key: String) { guard let indexPath = indexPath(of: key), let field = sections[indexPath.section].fields[indexPath.row] as? Field else { return } field.value = value if let field = field as? FormField { sections[indexPath.section].fields[indexPath.row] = field reloadField(by: key) } } func getValue<Field: FieldDataSource>(of formField: Field.Type, byKey key: String) -> Field.Value { guard let field = fields.first(where: { $0.key == key }) as? Field else { fatalError("\(formField) not found with key: \(key)") } return field.value } func updateDataSource<Field: InputDataSource>(for formField: Field.Type, with dataSource: [Field.Item], byKey key: String) { guard let indexPath = indexPath(of: key), let field = sections[indexPath.section].fields[indexPath.row] as? Field else { return } field.dataSource = dataSource if let field = field as? FormField { sections[indexPath.section].fields[indexPath.row] = field } } func fields(ofSection key: String) -> [FormField] { guard let section = sections.first(where: { $0.key == key }) else { return [] } return section.fields } func insertField(_ field: FormField, at index: Int, ofSection key: String) { guard let section = sections.firstIndex(where: { $0.key == key }) else { return } sections[section].fields.insert(field, at: index) let indexPath = IndexPath(row: index, section: section) delegate?.dataSource(self, didInsertAt: [indexPath]) } func removeField(_ key: String) { guard let indexPath = self.indexPath(of: key) else { return } sections[indexPath.section].fields.remove(at: indexPath.row) delegate?.dataSource(self, didRemoveAt: [indexPath]) } func insertSection(_ section: FormSection, at index: Int) { sections.insert(section, at: index) delegate?.dataSource(self, didInsertSectionAt: IndexSet(integer: index)) } func removeSection(withKey key: String) { if let index = sections.firstIndex(where: { $0.key == key }) { sections.remove(at: index) delegate?.dataSource(self, didRemoveSectionAt: .init(integer: index)) } } private func reloadField(by key: String) { guard let indexPath = indexPath(of: key) else { return } delegate?.dataSource(self, didUpdateAt: [indexPath]) } private func indexPath(of key: String) -> IndexPath? { var indexPath: IndexPath? for (index, section) in sections.enumerated() { if let firstIndex = section.fields.firstIndex(where: { $0.key == key }) { indexPath = IndexPath(row: firstIndex, section: index) break } } return indexPath } } <file_sep>/Sources/Utilities/Form/FormHeader.swift // // FormHeader.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol FormHeader: AnyObject { var key: String { get } var height: CGFloat { get } func register(for tableView: UITableView) func dequeue(for tableView: UITableView, in section: Int) -> UIView? } <file_sep>/Sources/Utilities/Form/FormViewController.swift // // FormViewController.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit protocol FormViewInput: AnyObject { func reloadTableView(at indexPaths: [IndexPath]) } class FormViewController: UIViewController { let tableView = UITableView(frame: .zero, style: .grouped) let dataSource = FormDataSource() override func viewDidLoad() { super.viewDidLoad() configure() } } // MARK: - Configure extension FormViewController { private func configure() { setUpLayout() setUpViews() } private func setUpLayout() { view.addSubview(tableView) tableView.snp.makeConstraints { $0.edges.equalToSuperview() } } private func setUpViews() { tableView.backgroundColor = .systemGroupedBackground tableView.delegate = self tableView.dataSource = self dataSource.delegate = self } } // MARK: - FormDataSourceDelegate extension FormViewController: FormDataSourceDelegate { func dataSourceDidChangeSections(_ dataSource: FormDataSource) { for section in dataSource.sections { section.header?.register(for: tableView) for field in section.fields { field.register(for: tableView) } } } func dataSourceDidReloadTableView(_ dataSource: FormDataSource) { tableView.reloadData() } func dataSource(_ dataSource: FormDataSource, didUpdateAt indexPaths: [IndexPath]) { tableView.reloadRows(at: indexPaths, with: .automatic) } func dataSource(_ dataSource: FormDataSource, didInsertAt indexPaths: [IndexPath]) { tableView.insertRows(at: indexPaths, with: .automatic) } func dataSource(_ dataSource: FormDataSource, didRemoveAt indexPaths: [IndexPath]) { tableView.deleteRows(at: indexPaths, with: .automatic) } func dataSource(_ dataSource: FormDataSource, didInsertSectionAt sections: IndexSet) { tableView.performBatchUpdates { tableView.insertSections(sections, with: .fade) } } func dataSource(_ dataSource: FormDataSource, didRemoveSectionAt sections: IndexSet) { tableView.deleteSections(sections, with: .fade) } } // MARK: - FormViewInput extension FormViewController: FormViewInput { func reloadTableView(at indexPaths: [IndexPath]) { tableView.reloadRows(at: indexPaths, with: .automatic) } } // MARK: - UITableViewDataSource extension FormViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { dataSource.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { dataSource.sections[section].fields.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let field = dataSource.sections[indexPath.section].fields[indexPath.row] return field.dequeue(for: tableView, at: indexPath) } } // MARK: - UITableViewDelegate extension FormViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let field = dataSource.sections[indexPath.section].fields[indexPath.row] return field.height } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { dataSource.sections[section].header?.dequeue(for: tableView, in: section) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let header = dataSource.sections[section].header else { return .zero } return header.height } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let field = dataSource.sections[indexPath.section].fields[indexPath.row] field.tableView(tableView, didSelectRowAt: indexPath) } } <file_sep>/Sources/Views/SelectInputCell/SelectInputCell.swift // // SelectInputCell.swift // iOSForm // // Created by <NAME> on 26/03/2021. // import UIKit final class SelectInputCell: UITableViewCell { private let titleLabel = UILabel() private let valueLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { selectionStyle = .none contentView.addSubview(titleLabel) contentView.addSubview(valueLabel) titleLabel.snp.makeConstraints { $0.leading.equalToSuperview().inset(16.0) $0.centerY.equalToSuperview() } valueLabel.snp.makeConstraints { $0.leading.equalTo(titleLabel.snp.trailing).offset(16.0) $0.trailing.equalToSuperview().inset(16.0) $0.top.bottom.equalToSuperview() } titleLabel.setContentCompressionResistancePriority(.defaultHigh + 1.0, for: .horizontal) titleLabel.setContentHuggingPriority(.required, for: .horizontal) valueLabel.textAlignment = .right accessoryType = .disclosureIndicator } } // MARK: - Configure extension SelectInputCell { func configure(_ viewModel: SelectInputViewModel) { titleLabel.text = viewModel.title valueLabel.text = viewModel.value } } <file_sep>/Sources/Views/TitleHeader/TitleFormHeader.swift // // TitleFormHeader.swift // iOSForm // // Created by <NAME> on 25/03/2021. // import UIKit final class TitleFormHeader { let key: String let viewModel: TitleHeaderFooterViewModel init(key: String, viewModel: TitleHeaderFooterViewModel) { self.key = key self.viewModel = viewModel } } extension TitleFormHeader: FormHeader { var height: CGFloat { 60.0 } func register(for tableView: UITableView) { tableView.register(TitleHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "TitleHeaderFooterView") } func dequeue(for tableView: UITableView, in section: Int) -> UIView? { let view = tableView.dequeueReusableHeaderFooterView( withIdentifier: "TitleHeaderFooterView" ) as? TitleHeaderFooterView view?.configure(with: viewModel) return view } } <file_sep>/Sources/Views/TextInputCell/TextInputFormField.swift // // TextInputFormField.swift // iOSForm // // Created by <NAME> on 24/03/2021. // import UIKit final class TextInputFormField { let key: String var viewModel: TextInputViewModel weak var delegate: FormFieldDelegate? init(key: String, viewModel: TextInputViewModel) { self.key = key self.viewModel = viewModel } } // MARK: - FormField extension TextInputFormField: FormField { var height: CGFloat { 44.0 } func register(for tableView: UITableView) { tableView.register(TextInputCell.self, forCellReuseIdentifier: "TextInputCell") } func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable:next force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell", for: indexPath) as! TextInputCell cell.delegate = self cell.configure(viewModel) return cell } } // MARK: - FieldDataSource extension TextInputFormField: FieldDataSource { var value: String { get { viewModel.value ?? "" } set { viewModel.value = newValue } } } // MARK: - TextInputCellDelegate extension TextInputFormField: TextInputCellDelegate { func cell(_ cell: TextInputCell, didChangeValue value: String?) { viewModel.value = value } } <file_sep>/Sources/Views/SelectInputCell/SelectInputFormField.swift // // SelectInputFormField.swift // iOSForm // // Created by <NAME> on 26/03/2021. // // import UIKit final class SelectInputFormField<Value: SelectableItem> { let key: String var viewModel: SelectInputViewModel var dataSource: [Value] weak var cell: SelectInputCell? weak var delegate: FormFieldDelegate? weak var router: OpenSelectRouterInput? private var selectedIndex: Int? init(key: String, viewModel: SelectInputViewModel, dataSource: [Value] = [], router: OpenSelectRouterInput?) { self.key = key self.viewModel = viewModel self.dataSource = dataSource self.router = router } } // MARK: - FormField extension SelectInputFormField: FormField { var height: CGFloat { 44.0 } func register(for tableView: UITableView) { tableView.register(SelectInputCell.self, forCellReuseIdentifier: "SelectInputCell") } func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable:next force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "SelectInputCell", for: indexPath) as! SelectInputCell cell.configure(viewModel) self.cell = cell return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if dataSource.isEmpty { return } router?.showSelectScreen(output: self) } } // MARK: - FieldDataSource extension SelectInputFormField: FieldDataSource { var value: Value? { get { guard let selectedIndex = selectedIndex else { return nil } return dataSource[selectedIndex] } set { if let value = newValue { let index = dataSource.firstIndex(of: value) selectedIndex = index viewModel.value = value.title } else { selectedIndex = nil viewModel.value = nil } delegate?.fieldDidChangeValue(self) } } } // MARK: - InputDataSource extension SelectInputFormField: InputDataSource {} // MARK: - SelectModuleOutput extension SelectInputFormField: SelectModuleOutput { var title: String { "Select Item" } var list: [String] { dataSource.map { $0.title } } func didSelectItem(at index: Int) { value = dataSource[index] cell?.configure(viewModel) } } <file_sep>/Sources/Models/Province.swift // // Province.swift // iOSForm // // Created by <NAME> on 26/03/2021. // final class Province: SelectableItem { var title: String init(title: String) { self.title = title } } extension Province { static let vietProvinces: [Province] = { [.init(title: "Hanoi"), .init(title: "Hanoi 1")] }() static let thaiProvinces: [Province] = { [.init(title: "Bangkok"), .init(title: "Bangkok 1")] }() } <file_sep>/Tests/UnitTests/IOSFormTests.swift // // IOSFormTests.swift // iOSFormTests // // Created by <NAME> on 24/03/2021. // import XCTest @testable import iOSForm final class IOSFormTests: XCTestCase { } <file_sep>/Sources/Utilities/Form/DataSource/FieldDataSource.swift // // FieldDataSource.swift // iOSForm // // Created by <NAME> on 25/03/2021. // protocol FieldDataSource: AnyObject { associatedtype Value associatedtype ViewModel var viewModel: ViewModel { get set } var value: Value { get set } } <file_sep>/Sources/Modules/Select/SelectModule.swift // // SelectModule.swift // iOSForm // // Created by <NAME> on 26/03/2021. // protocol SelectModuleOutput: AnyObject { var title: String { get } var list: [String] { get } func didSelectItem(at index: Int) } final class SelectModule { let view: SelectViewController let viewModel: SelectViewModel var output: SelectModuleOutput? { get { viewModel.output } set { viewModel.output = newValue } } init() { view = SelectViewController() viewModel = SelectViewModel() view.output = viewModel viewModel.view = view } } <file_sep>/Sources/Utilities/Form/DataSource/InputDataSource.swift // // InputDataSource.swift // iOSForm // // Created by <NAME> on 26/03/2021. // protocol InputDataSource: AnyObject { associatedtype Item var dataSource: [Item] { get set } } <file_sep>/Sources/Views/SelectInputCell/SelectInputViewModel.swift // // SelectInputViewModel.swift // iOSForm // // Created by <NAME> on 26/03/2021. // struct SelectInputViewModel { var title: String var value: String? init(title: String, value: String? = nil) { self.title = title self.value = value } } <file_sep>/Sources/Views/DateInputCell/DateInputViewModel.swift // // DateInputViewModel.swift // iOSForm // // Created by <NAME> on 01/04/2021. // import Foundation struct DateInputViewModel { let title: String var value: Date? var valueString: String? { value?.string(with: .date) } init(title: String, value: Date? = nil) { self.title = title self.value = value } } extension DateFormatter { static let date: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy" return formatter }() } extension Date { func string(with formatter: DateFormatter) -> String { return formatter.string(from: self) } } <file_sep>/Tests/UITests/IOSFormUITests.swift // // IOSFormUITests.swift // iOSFormUITests // // Created by <NAME> on 24/03/2021. // import XCTest final class IOSFormUITests: XCTestCase { }
a02619d0e0fac9ab3f9676a6ce70c10f5ca4beb0
[ "Swift", "Markdown" ]
35
Swift
frodo10messi/ios-form
52f82c7dc0a9333fb33e58f61ee453d15a8a9968
2ce98d1e1e03082acf6a2e2936de43965c3708e0
refs/heads/master
<repo_name>yashjainaj/restaurant-site-using-html-css-php<file_sep>/cart/datecheck.php <?php $dat = $_POST['date']; date_default_timezone_set("Asia/Kolkata"); $d= date("Y-m-d"); $d2= strtotime($d); $d1= strtotime($dat); if($d1 < $d2 ){ function died(){ echo'<script type="text/javascript"> alert('date must be grater than today')</script> die(); } } ?><file_sep>/payment.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $name = $_POST['name']; $cardno = $_POST['cardno']; $month = $_POST['month']; $year = $_POST['year']; $cvv = $_POST['cvv']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "INSERT INTO payment(name,cardno,month,year,cvv) VALUES('$name','$cardno','$month','$year','$cvv')"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: index.html"); exit; ?><file_sep>/checkout.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $name = $_POST['name']; $mobile = $_POST['mobileno']; $email = $_POST['email']; $address = $_POST['address']; $pincode = $_POST['pincode']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "INSERT INTO checkout(name,mobile,email,address,pincode) VALUES('$name','$mobile','$email','$address','$pincode')"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: payment.html"); exit; ?><file_sep>/admindetail1.php <!DOCTYPE html> <html> <head> <title>Admin Seat Reservation table</title> <style type="text/css"> nav ul{ display: inline; float: left; padding: 0px; } nav ul li{ display: inline-block; list-style-type: none; color: black; float: left; margin-left: 32px; } nav ul li a{ color: black; text-decoration: none; } #datapages{ font-family:montserrat; } .homered{ background-color: red; padding: 13px 11px 13px 11px; } .homeblack:hover{ background-color: red; padding: 13px 11px 13px 11px; } table{ border-collapse: collapse; width:100%; color: #588c7e; font-family: monospace; font-size: 25px; text-align: left; } th{ background-color: #588c7e; color: white; } </style> </head> <body> <div> <nav> <ul id="datapages"> <li><a class="homeblack" href="nsp.html">HOME</a></li> <li><a class="homered" href="loginpage.html">LOGIN</a></li> <li><a class="homeblack" href="signup.html">REGISTRATION</a></li> <li><a class="homeblack" href="aboutus.html">ABOUT US</a></li> <li><a class="homeblack" href="news.html">EVENTS</a></li> </ul> </nav> </div> <table> <tr> <th>Name</th> <th>Person</th> <th>Mobile no</th> <th>Date</th> <th>Time</th> </tr> <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $conn = mysqli_connect($servername,$username,$password,$dbname); if($conn-> connect_error){ die("connection faild". $conn-> connect_error); } $sql = "SELECT name, person, mobile, date, time from reservation"; $result = mysqli_query($conn,$sql); if($result-> num_rows > 0){ While($row = $result-> fetch_assoc()){ echo "<tr><td>". $row["name"] ."</td><td>". $row["person"] ."</td><td>". $row["mobile"] ."</td><td>". $row["date"] ."</td><td>". $row["time"] ."</td></tr>"; } echo "</table>"; } else{ echo " 0 result"; } $conn-> close(); ?> </table> </body> </html><file_sep>/order.php <?php session_start(); $product_ids = array(); $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $conn = mysqli_connect($servername,$username,$password,$dbname); if(filter_input(INPUT_POST, 'add_to_cart')) { if(isset($_SESSION['shopping_cart'])) { $count = count($_SESSION['shopping_cart']); $product_ids=array_column($_SESSION['shopping_cart'], 'id'); if(!in_array(filter_input(INPUT_GET, 'id'), $product_ids)) { $_SESSION['shopping_cart'][$count] = array ( 'id' => filter_input(INPUT_GET, 'id'), 'name' => filter_input(INPUT_POST, 'name'), 'price' => filter_input(INPUT_POST, 'price'), 'quantity' => filter_input(INPUT_POST, 'quantity'), ); } else { for ($i = 0; $i < count($product_ids); $i++) { if ($product_ids[$i] == filter_input(INPUT_GET, 'id')) { $_SESSION['shopping_cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity'); } } } } else { $_SESSION['shopping_cart'][0] = array ( 'id' => filter_input(INPUT_GET, 'id'), 'name' => filter_input(INPUT_POST, 'name'), 'price' => filter_input(INPUT_POST, 'price'), 'quantity' => filter_input(INPUT_POST, 'quantity'), ); } } if (filter_input(INPUT_GET, 'action')) { if (filter_input(INPUT_GET, 'action') == 'delete') { foreach ($_SESSION['shopping_cart'] as $key => $product) { if($product['id'] == filter_input(INPUT_GET, 'id')) { unset($_SESSION['shopping_cart'][$key]); } } $_SESSION['shopping_cart'] = array_values($_SESSION['shopping_cart']); } } function pre_r($array) { echo '<pre>'; print_r($array); echo '</pre>'; } ?> <!DOCTYPE HTML> <html> <head> <title>menu</title> <link rel="stylesheet" href="https://maxcdn.bootstarpcdn.com/bootstarp/3.3.6/css/bootstarp.min.css" /> <link rel="stylesheet" href="cart.css"/> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet"> <!-- Animate.css --> <link rel="stylesheet" href="css/animate.css"> <!-- Icomoon Icon Fonts--> <link rel="stylesheet" href="css/icomoon.css"> <!-- Themify Icons--> <link rel="stylesheet" href="css/themify-icons.css"> <!-- Bootstrap --> <link rel="stylesheet" href="css/bootstrap.css"> <!-- Magnific Popup --> <link rel="stylesheet" href="css/magnific-popup.css"> <!-- Bootstrap DateTimePicker --> <link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css"> <!-- Owl Carousel --> <link rel="stylesheet" href="css/owl.carousel.min.css"> <link rel="stylesheet" href="css/owl.theme.default.min.css"> <!-- Theme style --> <link rel="stylesheet" href="css/style.css"> <!-- Modernizr JS --> <script src="js/modernizr-2.6.2.min.js"></script> <!-- FOR IE9 below --> <!--[if lt IE 9]> <script src="js/respond.min.js"></script> <![endif]--> </head> <body> <div class="gtco-loader"></div> <div id="page"> <!-- <div class="page-inner"> --> <nav class="gtco-nav" role="navigation"> <div class="gtco-container"> <div class="row"> <div class="col-sm-4 col-xs-12"> <div id="gtco-logo"><a href="index.html">fun&food <em>.</em></a></div> </div> <div class="col-xs-8 text-right menu-1"> <ul> <li><a href="index.html">Home</a></li> <li><a href="menu.html">Menu</a></li> <li class="has-dropdown"> <a href="services.html">Services</a> <ul class="dropdown"> <li><a href="contact.html">Food Catering</a></li> <li><a href="contact.html">Wedding Celebration</a></li> <li><a href="contact.html">Birthday's Celebration</a></li> </ul> </li> <li class="active"><a href="order.php">Order</a></li> <li><a href="contact.html">Contact</a></li> <li class="btn-cta"><a href="index.html"><span>Reservation</span></a></li> </ul> </div> </div> </div> </nav> <header id="gtco-header" class="gtco-cover gtco-cover-sm" role="banner" style="background-image: url(images/img_bg_1.jpg)" data-stellar-background-ratio="0.5"> <div class="overlay"></div> <div class="gtco-container"> <div class="row"> <div class="col-md-12 col-md-offset-0 text-center"> <div class="row row-mt-15em"> <div class="col-md-12 mt-text animate-box" data-animate-effect="fadeInUp"> <span class="intro-text-small">key of taste is <a href="index.html" target="_blank">f&f</a></span> <h1 class="cursive-font">Taste all our menu!</h1> </div> </div> </div> </div> </div> </header> <br /> <div class="container"> <div class="row"> <?php $query = 'SELECT * FROM products ORDER by id ASC'; $result = mysqli_query($conn, $query); if($result): if(mysqli_num_rows($result)>0): while($product = mysqli_fetch_array($result)): //print_r($product) ?> <div class="col-sm-4 col-md-3"> <form method="post" action="order.php?action=add&id=<?php echo $product['id'];?>"> <div class="products"> <img src="<?php echo $product['image']; ?>" class="img-responsive"/><br/> <h4 class="text-info"><?php echo $product['name']; ?></h4> <h4>Rs. <?php echo $product['price']; ?></h4> <input type="text" name="quantity" class="form-control" value="1"/> <input type="hidden" name="name" value="<?php echo $product['name']; ?>"/> <input type="hidden" name="price" value="<?php echo $product['price']; ?>"/> <input type="submit" name="add_to_cart" style="margin-top: 5px;" class="btn btn-info" value="Add to Cart"/> </div> </form> </div> <?php endwhile; endif; endif; ?> </div> <div style="clear:both"></div> <br /> <div class="table-responsive"> <table class="table"> <tr><th colspan="5"><h3>Order Details</h3></th></tr> <tr> <th width="40%">Product Name</th> <th width="10%">Quantity</th> <th width="20%">Price</th> <th width="15%">Total</th> <th width="5%">Action</th> </tr> <?php if(!empty($_SESSION['shopping_cart'])): $total = 0; foreach ($_SESSION['shopping_cart'] as $key => $product): ?> <tr> <td align="left"><?php echo $product['name']; ?></td> <td align="left"><?php echo $product['quantity']; ?></td> <td align="left">Rs. <?php echo $product['price']; ?></td> <td align="left">Rs. <?php echo number_format($product['quantity'] * $product['price'], 2); ?></td> <td> <a href="order.php?action=delete&id=<?php echo $product['id']; ?>"> <div class="btnremove">Remove</div> </a> </td> </tr> <?php $total = $total + ($product['quantity'] * $product['price']); endforeach; ?> <tr> <br> <br> <td colspan="3" align="right" class="totalcls">Total</td> <td align="right" class="totalcls">Rs. <?php echo number_format($total, 2); ?></td> <td></td> </tr> <tr> <td colspan="5"> <?php if (isset($_SESSION['shopping_cart'])): if (count($_SESSION['shopping_cart']) > 0): ?> <a href="checkout.html" class="button">Checkout</a> <?php endif; endif; ?> </td> </tr> <?php endif; ?> </table> </div> </div> <footer id="gtco-footer" role="contentinfo" style="background-image: url(images/img_bg_1.jpg)" data-stellar-background-ratio="0.5"> <div class="overlay"></div> <div class="gtco-container"> <div class="row row-pb-md"> <div class="col-md-12 text-center"> <div class="gtco-widget"> <h3>Get In Touch</h3> <ul class="gtco-quick-contact"> <li><a href="#"><i class="icon-phone"></i> +91 838 505 3703</a></li> <li><a href="#"><i class="icon-mail2"></i> <EMAIL></a></li> <li><a href="#"><i class="icon-chat"></i> Live Chat</a></li> </ul> </div> <div class="gtco-widget"> <h3>Get Social</h3> <ul class="gtco-social-icons"> <li><a href="www.twitter.com"><i class="icon-twitter"></i></a></li> <li><a href="www.facebook.com"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> </ul> </div> </div> </div> </div> </footer> <!-- </div> --> </div> <!-- jQuery --> <script src="js/jquery.min.js"></script> <!-- jQuery Easing --> <script src="js/jquery.easing.1.3.js"></script> <!-- Bootstrap --> <script src="js/bootstrap.min.js"></script> <!-- Waypoints --> <script src="js/jquery.waypoints.min.js"></script> <!-- Carousel --> <script src="js/owl.carousel.min.js"></script> <!-- countTo --> <script src="js/jquery.countTo.js"></script> <!-- Stellar Parallax --> <script src="js/jquery.stellar.min.js"></script> <!-- Magnific Popup --> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/magnific-popup-options.js"></script> <script src="js/moment.min.js"></script> <script src="js/bootstrap-datetimepicker.min.js"></script> <!-- Main --> <script src="js/main.js"></script> </body> </html> <file_sep>/admindeletedetail1.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $imgid = $_POST['imgid']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "DELETE FROM products WHERE id = $imgid"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: admindeletedetail.php"); exit; ?><file_sep>/admincheckout.php <!DOCTYPE HTML> <html> <head> <title>Seat reserve detail</title> <style type="text/css"> nav ul{ display: inline; float: left; padding: 0px; } nav ul li{ display: inline-block; list-style-type: none; color: black; float: left; margin-left: 32px; } nav ul li a{ color: black; text-decoration: none; } #datapages{ font-family:montserrat; } .homered{ background-color: red; padding: 13px 20px 15px 15px; } .homeblack:hover{ background-color: red; padding: 13px 20px 15px 15px; } table{ border-collapse: collapse; width:100%; color: #d96459; font-family: monospace; font-size: 25px; text-align: left; } th{ background-color: #d96459; color: white; } </style> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet"> <!-- Animate.css --> <link rel="stylesheet" href="css/animate.css"> <!-- Icomoon Icon Fonts--> <link rel="stylesheet" href="css/icomoon.css"> <!-- Themify Icons--> <link rel="stylesheet" href="css/themify-icons.css"> <!-- Bootstrap --> <link rel="stylesheet" href="css/bootstrap.css"> <!-- Magnific Popup --> <link rel="stylesheet" href="css/magnific-popup.css"> <!-- Bootstrap DateTimePicker --> <link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css"> <!-- Owl Carousel --> <link rel="stylesheet" href="css/owl.carousel.min.css"> <link rel="stylesheet" href="css/owl.theme.default.min.css"> <!-- Theme style --> <link rel="stylesheet" href="css/style.css"> <!-- Modernizr JS --> <script src="js/modernizr-2.6.2.min.js"></script> <!-- FOR IE9 below --> <!--[if lt IE 9]> <script src="js/respond.min.js"></script> <![endif]--> </head> <body> <div class="gtco-loader"></div> <div id="page"> <!-- <div class="page-inner"> --> <nav class="gtco-nav" role="navigation"> <div class="gtco-container"> <div class="row"> <div class="col-sm-4 col-xs-12"> <div id="gtco-logo"><a href="index.html">fun&food <em>.</em></a></div> </div> <div class="col-xs-8 text-right menu-1"> <ul> <li><a href="index.html">Home</a></li> <li><a href="menu.html">Menu</a></li> <li class="has-dropdown"> <a href="services.html">Services</a> <ul class="dropdown"> <li><a href="contact.html">Food Catering</a></li> <li><a href="contact.html">Wedding Celebration</a></li> <li><a href="contact.html">Birthday's Celebration</a></li> </ul> </li> <li><a href="order.php">Order</a></li> <li><a href="contact.html">Contact</a></li> <li class="active"><a href="seatreservedetail.php">Admin</a></li> <li class="btn-cta"><a href="index.html"><span>Reservation</span></a></li> </ul> </div> </div> </div> </nav> <header id="gtco-header" class="gtco-cover gtco-cover-sm" role="banner" style="background-image: url(images/img_bg_1.jpg)"> <div class="overlay"></div> <div class="gtco-container"> <div class="row"> <div class="col-md-12 col-md-offset-0 text-center"> <div class="row row-mt-15em"> <div class="col-md-12 mt-text animate-box" data-animate-effect="fadeInUp"> <span class="intro-text-small">key of taste is<a href="index.html" target="_blank">f&f</a></span> <h1 class="cursive-font">Say hello!</h1> </div> </div> </div> </div> </div> </header> <div> <nav> <ul id="datapages"> <li><a class="homeblack" href="nsp.html">Seat Reservation</a></li> <li><a class="homeblack" href="admincontactus.php">Contact us</a></li> <li><a class="homered" href="admincheckout.php">Checkout</a></li> <li><a class="homeblack" href="adminpayment.php">Payment</a></li> <li><a class="homeblack" href="adminorder.php">Menu</a></li> </ul> </nav> </div> <table> <tr><th>S.No.</th> <th>Name</th> <th>Mobile No.</th> <th>Email</th> <th>Address</th> <th>Pincode</th> </tr> <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $conn = mysqli_connect($servername,$username,$password,$dbname); if($conn-> connect_error){ die("connection faild". $conn-> connect_error); } $sql = "SELECT sno,name,mobile,email,address,pincode from checkout"; $result = mysqli_query($conn,$sql); if($result-> num_rows > 0){ While($row = $result-> fetch_assoc()){ echo "<tr><td>". $row["sno"] ."</td><td>". $row["name"] ."</td><td>". $row["mobile"] ."</td><td>". $row["email"] ."</td><td>". $row["address"] ."</td><td>". $row["pincode"] ."</td></tr>"; } echo "</table>"; } else{ echo " 0 result"; } $conn-> close(); ?> </table> <footer id="gtco-footer" role="contentinfo" style="background-image: url(images/img_bg_1.jpg)" data-stellar-background-ratio="0.5"> <div class="overlay"></div> <div class="gtco-container"> <div class="row row-pb-md"> <div class="col-md-12 text-center"> <div class="gtco-widget"> <h3>Get In Touch</h3> <ul class="gtco-quick-contact"> <li><a href="#"><i class="icon-phone"></i> +91 838 505 3703</a></li> <li><a href="#"><i class="icon-mail2"></i> <EMAIL></a></li> <li><a href="#"><i class="icon-chat"></i> Live Chat</a></li> </ul> </div> <div class="gtco-widget"> <h3>Get Social</h3> <ul class="gtco-social-icons"> <li><a href="www.twitter.com"><i class="icon-twitter"></i></a></li> <li><a href="www.facebook.com"><i class="icon-facebook"></i></a></li> <li><a href="#"><i class="icon-dribbble"></i></a></li> </ul> </div> </div> </div> </div> </footer> <!-- </div> --> </div> <!-- jQuery --> <script src="js/jquery.min.js"></script> <!-- jQuery Easing --> <script src="js/jquery.easing.1.3.js"></script> <!-- Bootstrap --> <script src="js/bootstrap.min.js"></script> <!-- Waypoints --> <script src="js/jquery.waypoints.min.js"></script> <!-- Carousel --> <script src="js/owl.carousel.min.js"></script> <!-- countTo --> <script src="js/jquery.countTo.js"></script> <!-- Stellar Parallax --> <script src="js/jquery.stellar.min.js"></script> <!-- Magnific Popup --> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/magnific-popup-options.js"></script> <script src="js/moment.min.js"></script> <script src="js/bootstrap-datetimepicker.min.js"></script> <!-- Main --> <script src="js/main.js"></script> </body> </html> <file_sep>/contact.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "INSERT INTO contact(name,email,message) VALUES('$name','$email','$message')"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: contact.html"); exit; ?><file_sep>/login.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $name = $_POST['name']; $person = $_POST['Person']; $mobile = $_POST['mobileno']; $date = $_POST['date']; $time = $_POST['time']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "INSERT INTO reservation(name,person,mobile,date,time) VALUES('$name','$person','$mobile','$date','$time')"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: index.html"); exit; ?><file_sep>/adminorder1.php <?php $servername="localhost"; $username=" id5432391_root"; $password="<PASSWORD>"; $dbname="id5432391_cart"; $name = $_POST['name']; $imgid = $_POST['imgid']; $desimg = $_POST['desimg']; $price = $_POST['price']; $conn = mysqli_connect($servername,$username,$password,$dbname); $sql= "INSERT INTO products(id,name,image,price) VALUES('$imgid','$name','$desimg','$price')"; $result = mysqli_query($conn,$sql); mysqli_close($conn); header("Location: adminorder.php"); exit; ?>
f7a1962702f73231a9dcb22c53858775d57afb01
[ "PHP" ]
10
PHP
yashjainaj/restaurant-site-using-html-css-php
6f00fccc35aac2c422280574ff2c285fdd3a0c6d
a955c9e78d969ebb3eb9537c2b7dfcf4ff063f72
refs/heads/master
<file_sep>const express = require('express'); const app = express(); const mongoose = require("mongoose") const bcrypt = require("bcrypt") const jwt = require("jsonwebtoken") // connect to mongo db with all this strange options // so you do not get all these annyoing warnings on connecting mongoose.connect('mongodb://localhost/users_db', { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }, (err) => { if (!err) { console.log('MongoDB Connection succeeded') } else { console.log('Error on DB connection: ' + err) } }); // Create Todo Model const Todo = mongoose.model("Todo", new mongoose.Schema({ title: {type: String, required: true}, status : {type: String , enum: ["OPEN", "IN PROCESS", "DONE", "ON HOLD", "CANCELED"], default: "OPEN"}, User: { type: mongoose.Schema.Types.ObjectId, ref: "User" } } )) // Create User Model const User = mongoose.model('User', new mongoose.Schema({ email: { type: String, required: true }, password: { type: String, required: true }, roles: [String], })); User.findById("<PASSWORD>") .then(user =>{ console.log(user) }) // parse incoming JSON data (from fetch or browser client) app.use(express.json()); app.get('/', (req, res) => { res.send('Hello World!'); }); app.get('/users/seed', (req, res) => { // array of users to create let users = [ {email: "<EMAIL>", password: "<PASSWORD>", roles: ['Admin']}, {email: "<EMAIL>", password: "pw1", roles: ['Guest']}, {email: "<EMAIL>", password: "pw2", roles: ['Reader', 'Editor']}, ] let Todo = [ { title: "coding", status: "OPEN", User: user._id}, { title: "dancing", status: "DONE", User: user._id }, { title: "panting",status:"DONE",User: user._id } ] // hash password for each user (using bcrypt) let usersHashed = users.map(user => { user.password = bcrypt.hashSync(user.password, 10) return user }) // insert users into MongoDB User.insertMany(usersHashed) .then(usersNew => res.send(usersNew)) }) app.get('/user/:id/todos/seed', (req, res) => { let userId = req.params.id User.findById(userId).then(user => { if (user) { Todo.insertMany([ { title: "ToDo 1", user: user._id }, { title: "ToDo 2", status: "ON HOLD", user: user._id }, { title: "ToDo 3", status: "DONE", user: user._id }, ]).then(todos => res.send(todos)) } else { next("User does not exist") } }).catch(err => next(err)) }) // handle incoming LOGIN requests here.... app.post('/login', (req, res, next) => { // find user User.findOne({email: req.body.email}).then(user => { // user with this email not found? => error if(!user) { return next(`Authentication failed`) } // compare passwords using bcrypt.compare() function bcrypt.compare(req.body.password, user.password) .then(success => { // user password does not match password from login form? => error if(!success) { return next(`Authentication failed`) } // create JWT token by signing let secret = "jwt-master-secret" let token = jwt.sign( {id: user.id, email: user.email}, // WHAT data to sign secret, // signing key { expiresIn: "1h" } // expiry time ) // return token res.send({ token }) // => same as: { "token": token } }) }) .catch(err => next(err)) }) let port = 3000 app.listen(port, () => { console.log(`Server listening on port ${port}!`); }); //Run app, then load http://localhost:port in a browser to see the output. <file_sep># Mongoose Workshop - Exercise #2 - ToDo refs Now we want to manage ToDos for users and store them in our MongoDB database. Therefore we have to create a ToDo model. And set it into a relationship with the user. ## Task: Create Data Model * Setup a ToDo model with the following fields * title (String), required * status (enum: "OPEN", "IN PROCESS", "DONE", "ON HOLD", "CANCELED"), default: "OPEN" * Define the relationship between users & todos: * Clarify & fill in the "?" in the following two lines to get the right relationship type: * 1 user - ? todos * 1 todo - ? users * Connect user schema and todo schema * Create a relationship either by nesting or reference * Consider the factors "relationship tightness", "update frequency" and growing potential" ### Bonus Task - Seed user todos * Create a seed GET route /user/:id/todos/seed * Get the user ID from the url param (req.params.id) * Check if a user with that ID exists in the database * If so: Seed three todos here for this user * Return the todos to the browser * Testing: * Look into your list of users in Compass and grab a valid user ID * Call your seed route with that ID (replace :id in the URL with the users real ID)
280c52f8e2d1b8e7297183c018ce8b6406250b5f
[ "JavaScript", "Markdown" ]
2
JavaScript
mojvaf/Mongoose-Workshop2
4204f7ff6234cf8f261b8df1b07d7577ada6409d
55accf4a26f13f65243881057e1b64b76e631e33
refs/heads/master
<file_sep>#!/bin/bash VENV="venv" if [[ ! -d "$VENV" ]]; then python -m venv "$VENV" "$VENV"/bin/python -m pip install -r requirements.txt fi "$VENV"/bin/python project-euler-offline.py <file_sep># Project Euler Offline This is a quick program I threw together before getting on a plane so I would be able to solve PE problems and check solutions without having internet access. The program decrypts an encrypted file that contains the solutions, so there are no spoilers in plain text. ## Usage Just run `python project-euler-offline.py` or first `chmod +x` it and then use `./project-euler-offline.py`. Whatever floats your boat. ## Getting the problems offline 1. Register and login to PE 2. Go to <http://projecteuler.net/show=all> 3. Save the page to your computer
0d24a1df9dd44d2d97f25f328e554b18e81fb43a
[ "Markdown", "Shell" ]
2
Shell
csu/project-euler-offline
9a3c5d6c12f743ef44d12224e0ce8963430af4b8
ccb4b1967a1b90e0c226905d1c58383cfbcc4d69
refs/heads/master
<file_sep>from flask import Flask, request, render_template import json import requests import re import omdb import wikipedia app = Flask(__name__) app.debug = True @app.route('/') def hello_world(): return 'Hello World!' #Route 1 / FORM that sends data to be used in next view function @app.route('/form') def artist_form(): return render_template('form1.html') #Route 2 // view function @app.route('/formresults', methods=["POST", "GET"]) def getting_results(): if request.method == 'GET': result = request.args user_query = result.get('movie_title') user_query += ' (film)' movie_data = wikipedia.search(user_query) wiki_page = wikipedia.WikipediaPage(movie_data[0]) wiki_summary = wiki_page.summary return render_template('datamanip.html', result=wiki_summary) if __name__ == '__main__': app.run(debug=True) <file_sep>## SI 364 ## Fall 2017 ## HW 3 ## This homework has 2 parts. This file is the basis for HW 3 part 1. ## Add view functions to this Flask application code below so that the routes described in the README exist and render the templates they are supposed to (all templates provided inside the HW3Part1/templates directory). from flask import Flask, request, render_template import json import requests app = Flask(__name__) app.debug = True @app.route('/') def hello_world(): return 'Hello World!' @app.route('/user/<name>') def hello_user(name): return '<h1>Hello {0}<h1>'.format(name) @app.route('/artistform') def artist_form(): return render_template('artistform.html') @app.route('/artistinfo', methods=['POST', 'GET']) def artist_i(): if request.method == 'GET': result = request.args params = {} params['term'] = result.get('artist') resp = requests.get('https://itunes.apple.com/search?', params = params) data = json.loads(resp.text) dumping = json.dumps(data, indent=3) print(dumping) return render_template('artist_info.html', objects=data['results']) @app.route('/artistlinks') def artist_l(): return render_template('artist_links.html') @app.route('/specific/song/<artist_name>') def artist_n(artist_name): if request.method == 'GET': result = request.args params = {} params['term'] = artist_name resp = requests.get('https://itunes.apple.com/search?', params = params) data = json.loads(resp.text) dumping = json.dumps(data, indent=3) print(dumping) return render_template('specific_artist.html', results=data['results']) if __name__ == '__main__': app.run(debug=True)
aa0ea8512b6b30870158fdff2c42a682395ba7f2
[ "Python" ]
2
Python
dbcolber/HW3
dabf3e1707abf19fe3cf2d6da8ead21503fd846f
0f46f7f3d0112d8abf05d0697b95221edc3d2955
refs/heads/main
<repo_name>hondaminori/sample_app<file_sep>/docker-compose.yml version: "3.9" services: rails: build: . container_name: rails command: ash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - .:/sample_app ports: - "3000:3000" env_file: - .env depends_on: - db db: image: mysql:8.0.27 container_name: db environment: TZ: Asia/Tokyo MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} ports: - "3306:3306" volumes: - db:/var/lib/mysql volumes: db: <file_sep>/config/routes.rb Rails.application.routes.draw do # get 'lists/new' # # get 'lists/edit' # get 'top' => "homes#top" # post 'lists' => 'lists#create' # get 'lists' => 'lists#index' # # .../lists/1 や .../lists/3 に該当する # get 'lists/:id' => 'lists#show', as: 'list' # get 'lists/:id/edit' => 'lists#edit', as: 'edit_list' # patch 'lists/:id' => 'lists#update', as: 'update_list' # delete 'lists/:id' => 'lists#destroy', as: 'destroy_list' get 'top' => "homes#top" resources :lists end <file_sep>/README.md # README DMM WEBCAMP アプリケーションを完成させよう テキスト <file_sep>/Dockerfile FROM ruby:alpine3.13 RUN apk update \ && apk add --no-cache gcc make libc-dev g++ mariadb-dev tzdata nodejs~=14 yarn mysql-client WORKDIR /sample_app COPY Gemfile . COPY Gemfile.lock . RUN bundle install --jobs=2 COPY . /sample_app COPY entrypoint.sh /usr/bin/ RUN chmod +x /usr/bin/entrypoint.sh ENTRYPOINT ["entrypoint.sh"] EXPOSE 3000 CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
668348fa980e7114691786833ed1ec054cb56f21
[ "Markdown", "Ruby", "YAML", "Dockerfile" ]
4
YAML
hondaminori/sample_app
17538fcfea4718df7a1a38db681117d0e45bf8d7
1f081a42cfc0aa487776f03cc5a72666eed4ec4a
refs/heads/master
<file_sep>'use strict'; var browserify = require('browserify'), browserSync = require('browser-sync'), buffer = require('vinyl-buffer'), config = require('../config'), gulp = require('gulp'), gulpif = require('gulp-if'), gutil = require('gulp-util'), handleErrors = require('../util/handleErrors'), source = require('vinyl-source-stream'), sourcemaps = require('gulp-sourcemaps'), streamify = require('gulp-streamify'), uglify = require('gulp-uglify'), insert = require('gulp-insert'), watchify = require('watchify'); /* ------------------------------------------------------------------------- :: WATCHIFY IS WATCHING ------------------------------------------------------------------------- */ var isWatch = false; /* ------------------------------------------------------------------------- :: EXTERNALS ------------------------------------------------------------------------- */ var externals = [].concat(config.browserify.libs); /* ------------------------------------------------------------------------- :: FILES ------------------------------------------------------------------------- */ var files = [{ input: config.browserify.libs, output: config.browserify.libName, destination: config.browserify.dest, require: true, debug:false }, { input: config.browserify.libs, output: config.browserify.libName, destination: config.browserify.dest, require: true, debug:true }, { input: config.browserify.entries, output: config.browserify.bundleName, destination: config.browserify.dest, debug: true }, { input: config.browserify.entries, output: config.browserify.bundleName, destination: config.browserify.dest, debug: false }]; /* ------------------------------------------------------------------------- :: Defer object to handle task ending. ------------------------------------------------------------------------- */ /** * When bundling is complete, it will execute callback so that other task can wait until the task ends.*/ var Defer = function(max, callback) { this.max = max; this.count = 0; this.callback = callback; this.exec = function() { if (this.max === ++this.count) { this.callback(); } }; }; /* ------------------------------------------------------------------------- :: Bundle given file. ------------------------------------------------------------------------- */ var bundle = function(bundler, options) { var stream = bundler.bundle(), createSourcemap = config.browserify.sourcemap, startTime = new Date().getTime(), outputFile = options.output, destination = (!options.debug) ? options.destination : options.destination + "/dev"; return stream.on('error', handleErrors) .pipe(source(outputFile)) .pipe(insert.prepend("(function($, jQuery){")) .pipe(insert.append("})(window.CONTIKI.$, window.CONTIKI.$);")) .pipe(buffer()) .pipe(gulpif(createSourcemap && !options.debug , sourcemaps.init())) .pipe(gulpif(!options.debug, streamify(uglify({ compress: { drop_console: false } })))) .pipe(gulpif(createSourcemap && !options.debug, sourcemaps.write('./'))) .pipe(gulp.dest(destination)) .on('end', function() { var time = (new Date().getTime() - startTime) / 1000; gutil.log('Browserified: ' + gutil.colors.cyan(options.output) + ' in ' + gutil.colors.magenta(time) + 's'); if (isWatch) { browserSync.reload(); } }); }; /* ------------------------------------------------------------------------- :: Create bundle properties such as if its is added or required etc. ------------------------------------------------------------------------- */ var createBundleProp = function(b, options) { var bundler = b; var externalise = function() { return externals.forEach(function(external) { bundler.external(external.expose); }); }; var i = 0; for (i; i < options.input.length; i++) { if (options.require) { bundler.require(options.input[i].require, { expose: options.input[i].expose }); } else { bundler.add(options.input[i]); externalise(); } } return bundler; }; /* ------------------------------------------------------------------------- :: Create single bundle using files options. ------------------------------------------------------------------------- */ var createBundle = function(options) { var bundler = browserify({ cache: {}, packageCache: {}, fullPaths: false, debug: false }); bundler = createBundleProp(bundler, options); if (isWatch) { bundler = watchify(bundler); bundler.on('update', function() { bundle(bundler, options); }); } return bundle(bundler, options); }; /* ------------------------------------------------------------------------- :: Create set of bundles. ------------------------------------------------------------------------- */ var createBundles = function(bundles, defer) { bundles.forEach(function(bundle) { createBundle(bundle).on('end', function() { defer.exec(); }); }); }; /* ------------------------------------------------------------------------- :: Gulp Browserify Task ------------------------------------------------------------------------- */ gulp.task('browserify', function(done) { var d = new Defer(files.length, done); if (!global.isProd) { isWatch = true; } createBundles(files, d); }); <file_sep>'use strict'; var config = require('../config'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync'), gulp = require('gulp'), gulpif = require('gulp-if'), handleErrors = require('../util/handleErrors'), sass = require('gulp-sass'), sourcemaps = require('gulp-sourcemaps'), replace = require('gulp-replace'); gulp.task('styles', function() { gulp.src(config.styles.src) .pipe(sourcemaps.init()) .pipe(sass({ includePaths: config.styles.include, outputStyle: 'compressed' })) .on('error', handleErrors) .pipe(autoprefixer({ browsers: ['last 2 versions', 'IE 9', 'Safari >= 7'], cascade: false })) .pipe(sourcemaps.write('./')) .pipe(replace('..\/', '../../')) .pipe(replace('..\/', '../../')) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true, match: '**/*.css' }))); }); <file_sep>'use strict'; module.exports = { // BrowserSync 'browserport': 35729, 'proxy': 'http://contiki.local', 'serverport': 35727, 'serverstart': 'index.html', 'uiport': 35728, // Browserify 'browserify': { 'dest': "",//'../Contiki.Website/Content/js', 'entries': [],//['./src/js/main.js'], 'bundleName': "",//'main.js', 'sourcemap': true, 'libs': [ { /*require: './src/js/plugins.js', expose: 'plugins'*/ } ], 'libName': ""//'libs.js' }, // Sass 'styles': { 'src': ['./standalone/server/main-page/scss/*.scss', './standalone/server/main-page/scss/*.sass'], 'dest': './standalone/server/main-page/css', 'include': './node_modules/susy/sass' }, }; <file_sep>'use strict'; var config = require('../config'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync'), gulp = require('gulp'), gulpif = require('gulp-if'), handleErrors = require('../util/handleErrors'), sass = require('gulp-sass'), sourcemaps = require('gulp-sourcemaps'), rename = require("gulp-rename"), _replace = require('gulp-replace'), debug = require('gulp-debug'); var replaceForMin = function(source, ext){ return _replace(source, '') .pipe(rename({ extname: ext }) ); }; gulp.task('styles-nav', function() { gulp.src(config.styles.src) .pipe(sourcemaps.init()) .pipe(sass({ includePaths: config.styles.include, outputStyle: 'compressed' })) .on('error', handleErrors) .pipe(autoprefixer({ browsers: ['last 2 versions', 'IE 9', 'Safari >= 7'], cascade: false })) .pipe(replaceForMin(".css", ".min.css")) .pipe(sourcemaps.write('./', { mapFile: function(mapFilePath) { return mapFilePath.replace('.css.map', '.min.css.map'); } })) .pipe(_replace('..\/', '../../')) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true, match: '**/*.css' }))); }); <file_sep>'use strict'; var config = require('../config'), gulp = require('gulp');// //browserSync = require('browser-sync'); //Disabled Browser SYNC by cache problem //gulp.task('watch', ['browserSync'], function() { //Disabled Browser SYNC by cache problem gulp.task('watch-nav', [], function() { // Scripts are automatically watched and rebundled by Watchify inside Browserify task // JavaScript Lint/Hint //gulp.watch(config.scripts.src, ['lint']); // Sass gulp.watch(config.styles.src, ['styles-nav']); // Views //gulp.watch(config.views.src, browserSync.reload); });
85a657df96b1fa281a156385bc5de04c7f7fc45a
[ "JavaScript" ]
5
JavaScript
genarinno/frontend-projects
a55b87600670c96a26374e6e365bdc3364510933
ba7f6c72975ccb74dd87c144d542126ce46977ac
refs/heads/main
<repo_name>maxMaksum/balijavasp<file_sep>/components/Card/CardContentServices.js import CardImage from "./CardImage"; function CardContentServices({mockData2}) { return ( <div className=" flex flex-col md:flex-row w-full rounded shadow-lg text-gray-50 overflow-hidden space-y-2 space-x-2"> <div className="flex items-center justify-center pt-0 flex-grow-0 sm:flex-grow w-full"> <CardImage url={mockData2.image} /> </div> <div className="text-gray-900 bg-teal-300 rounded w-full flex items-center justify-center flex-grow-0 sm:flex-grow mx-2"> {/* <div className="z-10 sm:hidden bg-teal-300 p-6 sm:p-6 w-full sm:h-full sm:w-2 sm:bottom-0 sm:-right-10 sm:skew-y-0 sm:-skew-x-3 transform skew-y-3 absolute -top-5 sm:hiiden"></div> <div className=" hidden sm:block z-10 bg-teal-300 p-8 h-full w-3 -left-10 -skew-x-6 transform absolute"></div> */} <div className="p-4 space-y-4 "> <p className="text-xl text-left">{mockData2.excerpt}</p> <p className="text-md text-left">{mockData2.description}</p> </div> </div> </div> ); } export default CardContentServices <file_sep>/components/Header/HeaderItemsPng.js function HeaderItemsPng({title, flexDir="flex-col", opacity="opacity-0", text="text-sm", spacex="space-x-5"}) { return ( <div className={`group flex items-center ${flexDir} cursor-pointer hover:text-green-500 w-100 rounded ${spacex}`}> <img src={`/cotton.png`} className=" h-5 group-hover:animate-bounce bg-green-500 bg-center bg-contain"/> <p className={`${opacity} group-hover:opacity-100 ${text} text-green-500 text-center w-full `}>{title}</p> </div> ) } export default HeaderItemsPng <file_sep>/pages/index.js import Head from 'next/head' import Link from 'next/link' import {mockData2} from '../components/MockData/MockData' import Products from '../components/Card/Products' import NewSlider from '../components/Slider/NewSlider' export default function Home() { return ( <div className="mx-0 w-full h-full"> <Head> <title>BaliJava Spirit</title> <link rel="icon" href="/cotton.png" /> </Head> <NewSlider /> <div className="max-w-screen-2xl mx-auto"> <div className="grid grid-flow-row-dense sm:grid-cols-2 lg:grid-cols-3 xl:grid-flow-row-dense mx-auto gap-2"> {mockData2.map((d) => ( <Link key={d.id} href={`/page/${d.id}`}> <a> <Products id={d.id} title={d.title} url={d.image} description={d.description} excerpt={d.excerpt} /> </a> </Link> ))} </div> </div> </div> ); } <file_sep>/components/Contact/ContactForm.js import CardContact from '../Card/CardContact'; import CardSocial from '../Card/CardSocial'; function ContactForm() { return ( <div className="flex w-full min-h-screen justify-center items-center sm:p-12 p-4 rounded mt-2"> <div className=""> <div className="flex flex-col md:flex-row md:space-x-6 md:space-y-6 space-y-6 bg-teal-500 w-full max-w-4xl p-4 rounded-xl shadow-lg text-gray-50 overflow-hidden"> <div className="flex md:flex-grow flex-col justify-between space-y-8"> <div> <h1 className="text-4xl font-bold tracking-wide">Contact Us</h1> <p className="pt-2 text-cyan-100 text-sm ">You could leave us message by filling the contact form below or you could message us by Whatsapp, facebook, or messenger</p> </div> <CardContact/> <CardSocial/> </div> <div className="relative"> <div style={{ backgroundImage: `url("/linen3.jpg")`}} className="p-6 rounded z-10 relative"> <div className="relative z-20 rounded-xl shadow-lg p-8 text-gray-700 md:w-80 "> <form className="flex flex-col space-y-4 z-10"> <div> <label for="" className="text-sm "> Your Name </label> <input type="text" placeholder="<NAME>" className="ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-teal-300 mt-2"/> </div> <div> <label for="" className="text-sm "> Your Email </label> <input type="email" placeholder="Email Address" className="ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-teal-300 mt-2"/> </div> <div> <label for="" className="text-sm "> Message </label> <textarea type="email" placeholder="Message " className="ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-teal-300 mt-2"> </textarea> </div> <button className="inline-block self-end bg-cyan-700 font-bold rounded-lg px-6 py-2 uppercase text-gray-50"> Send Message</button> </form> </div> </div> </div> </div> </div> </div> ) } export default ContactForm <file_sep>/components/Header/HeaderMenuSmall.js import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; function HeaderMenuSmall({title, icon}) { return ( <div className={`group flex items-center justify-between cursor-pointer hover:text-green-500 w-100 space-x-5`}> <FontAwesomeIcon icon={icon} className=" h-5 group-hover:animate-bounce text-green-500 "/> <p className="group-hover:animate-bounce text-green-500 text-lg ">{title}</p> </div> ) } export default HeaderMenuSmall <file_sep>/pages/page/[id].js import CardProducts from "../../components/Card/CardProducts"; import {mockData2} from '../../components/MockData/MockData' import NewSlider from "../../components/Slider/NewSlider"; export async function getStaticProps(context) { const {params} = context const data = mockData2.find((item)=>item.id.toString()===params.id) return { props: {data} // will be passed to the page component as props } } export async function getStaticPaths() { return { paths: mockData2.map((item)=>({ params:{ id:item.id.toString() } })), fallback: false // See the "fallback" section below }; } function pageDetail({data}) { return ( <div className="w-full h-full"> <NewSlider/> <CardProducts mockData2={data}/> </div> ) } export default pageDetail <file_sep>/components/Card/CardContent.js function CardContent({title, description, excerpt,img}) { const cardtitle = title? title :(`Contact Us`) const carddescription = description? description :(`Contact Us`) const cardexcerpt = excerpt? excerpt :(`lorem5 lorem ll`) return ( <div className="relative w-full flex flex-col"> <div className=" flex items-center justify-center p-4"> <div className="space-y-1 text-gray-900 bg-gray-50 rounded-xl w-full p-2"> <h1 className="text-xl font-bold text-left"> {cardtitle} </h1> <p className="text-md text-left">{cardexcerpt}</p> </div> </div> {/* <img className="absolute bottom-0 right-0 h-40" src={`/cotton2.png`} /> */} </div> ); } export default CardContent <file_sep>/redux/userSlice.js import { createSlice } from '@reduxjs/toolkit' const initialState= { user:null, userName:null, userEmail:null } export const userSlice = createSlice({ name: 'users', initialState, reducers: { loginA: (state, action) => { state.user=action.payload state.userName = action.payload.userName state.userEmail = action.payload.userEmail }, logout: (state) => { state.user=null state.userName = null state.userEmail = null }, }, }) // Action creators are generated for each case reducer function export const { loginA, logout } = userSlice.actions export const selectUserName = (state)=>state.user.userName export const selectUserEmail = (state)=>state.user.userEmail export const selectUser = (state)=>state.user.user export default userSlice.reducer<file_sep>/components/Card/CardContentWelcome.js function CardContentWelcome({title, description, excerpt,img}) { const cardtitle = title? title :(`Welcome to BaliJavaSpirit`) const cardexcerpt = description? description :(`We are happy to serve you`) return ( <div > <div className="flex items-center justify-center p-2"> <div className="space-y-1 text-gray-900"> <h1 className="text-lg font-bold text-center">{cardtitle}</h1> <p className="text-md text-center">{cardexcerpt}</p> </div> </div> </div> ); } export default CardContentWelcome <file_sep>/components/Slider/NewSlider.js import React from 'react' import Slider from "react-slick"; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import {mockData2} from '../MockData/MockData' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import {faArrowCircleRight, faArrowCircleLeft} from '@fortawesome/free-solid-svg-icons' import CardContentWelcome from '../Card/CardContentWelcome'; const PreviousBtn = (props)=>{ const {className, onClick} =props return( <div className={className} onClick ={onClick} className="left-0 absolute top-1/2"> <div className="flex items-center justify-center z-10 h-8 p-2 w-10"> <FontAwesomeIcon icon={faArrowCircleLeft} className=" z-10 h-5 hover:animate-bounce text-teal-500 text-xl" /> </div> </div> ) } const NextBtn = (props)=>{ const {className, onClick, style} =props return( <div className={className} onClick ={onClick} className=" z-0 right-3 absolute top-1/2 " > <div className=" flex items-center justify-center z-10 h-8 p-2 w-10"> <FontAwesomeIcon icon={faArrowCircleRight} className=" z-10 h-5 hover:animate-bounce text-teal-500 text-xl" /> </div> </div> ) } function NewSlider() { const settings = { dots: false, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, autoplay:false, prevArrow:<PreviousBtn/>, nextArrow:<NextBtn/>, }; return ( <Slider {...settings} className=" z-10 bg-teal-500 mb-2"> {mockData2.map((homedata) => ( <div className=" relative" key={homedata.id} id={homedata.id} > <div className ="flex flex-col sm:flex-row justify-start"> <div className=" z-10 flex"> <MyImage url={homedata.image} /> </div> <div className="flex justify-center items-center w-full"> <CardContentWelcome excerpt={homedata.excerpt} /> </div> </div> <div className="z-5 absolute h-96 w-full bg-gradient-to-t from-gray-900 to transparent top-0 left-0"></div> </div> ))} </Slider> ); } export default NewSlider function MyImage({url}){ return( <div className="p-2"> <img src={url} className="object-contain object-center h-48 z-0 w-full"/> </div> ) }<file_sep>/components/Card/CardProducts.js import CardContentServices from './CardContentServices'; function CardProducts({mockData2}) { return ( <div className="flex w-full justify-center items-center" > <div className="flex md:flex-grow flex-col justify-between space-y-8"> <CardContentServices mockData2={mockData2} /> </div> </div> ); } export default CardProducts <file_sep>/pages/login.js import firebase from 'firebase/auth' import Head from 'next/head' import {useEffect} from 'react' import {useRouter} from 'next/router' import { faWhatsapp } from '@fortawesome/free-brands-svg-icons' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import {auth, db, provider} from '../firebase' function Login() { const router =useRouter() const signIn = async()=>{ await auth.setPersistence("local").then( auth.signInWithPopup(provider) ) router.push("/chathome") } return ( <div> <Head> <title>Login</title> </Head> <div className="flex items-center justify-center bg-gray-100 h-screen"> <div className="flex flex-col space-x-2 justify-center items-center group space-y-12 h-96 w-96 bg-gray-50 p-12 rounded shadow"> <FontAwesomeIcon icon={faWhatsapp} className=" text-8xl group-hover:animate-bounce text-teal-500" /> <button onClick={signIn} className=" btn text-xl"> SIGN IN WITH GMAIL </button> </div> </div> </div> ); } export default Login <file_sep>/components/Card/CardContact.js import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faWhatsapp, faFacebookF,faFacebookMessenger, faInstagram, faTwitter, faLinkedinIn, } from '@fortawesome/free-brands-svg-icons' import { faPhoneAlt, faEnvelope, faMapMarkerAlt} from '@fortawesome/free-solid-svg-icons' function CardContact() { return ( <div className="flex flex-col space-y-4 "> <div className="inline-flex space-x-2 items-center group"> <FontAwesomeIcon icon={faPhoneAlt} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl"/> <span>0852 0510 4517</span> </div> <div className="inline-flex space-x-2 items-center group "> <FontAwesomeIcon icon={faEnvelope} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl"/> <span><EMAIL></span> </div> <div className="inline-flex space-x-2 items-center group "> <FontAwesomeIcon icon={faWhatsapp} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl"/> <span>0852 0510 4517</span> </div> <div className="inline-flex space-x-2 items-center group "> <FontAwesomeIcon icon={faMapMarkerAlt} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl"/> <span>LotTunduh Ubud Bali</span> </div> </div> ) } export default CardContact <file_sep>/components/Card/CardImage.js function CardImage({url}) { const img= url ? url : (`/boy.jpg`) return ( <div> <img src={img} className="bg-contain bg-center rounded-md" /> </div> ) } export default CardImage <file_sep>/components/Chat.js import {useState, useEffect, useContext} from 'react' import {auth, db} from '../firebase' import {AuthContext} from './AuthProvider' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUserCircle, faEllipsisV, faCommentAlt, faSearch} from '@fortawesome/free-solid-svg-icons' import getRecepientEmail from "../Utils/getRecepientEmail"; function Chat({id, users}) { const [dataUsers, setDataUsers] = useState(null) const {currentUser} = useContext(AuthContext) const recepientEmail = getRecepientEmail(users) // console.log(recepientEmail) // console.log(dataUsers) useEffect(() => { if(currentUser) { db.collection("users") .onSnapshot(async (snapshot) => { const messageChats = await snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })); }) } }, []); return ( <div className="flex items-center- p-4 border-b border-gray-100 hover:bg-gray-100 cursor-pointer"> <div> <div><FontAwesomeIcon icon={faUserCircle} className=" h-5 hover:animate-bounce text-green-500 cursor-pointer text-2xl mr-8"/> </div> {/* {dataUsers[0].id} */} <div>{recepientEmail}</div> </div> </div> ) } export default Chat <file_sep>/components/Header/HeaderItems.js import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; function HeaderItems({title, icon, flexDir="flex-col" }) { return ( <div className={`group flex ${flexDir} items-center cursor-pointer w-12 text-green-500`}> <FontAwesomeIcon icon={icon} className=" h-5 group-hover:animate-bounce text-green-500"/> <p className="opacity-0 group-hover:opacity-100 text-xs">{title}</p> </div> ) } export default HeaderItems <file_sep>/components/Card/CardSocialLogo.js import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faWhatsapp, faFacebookF,faFacebookMessenger, faInstagram, faTwitter, faLinkedinIn, } from '@fortawesome/free-brands-svg-icons' function CardSocialLogo() { return ( <div> <div className="flex items-center justify-around pt-2 bg-gray-200"> <div className="flex flex-col space-x-2 justify-center items-center group "> <FontAwesomeIcon icon={faWhatsapp} className=" h-5 group-hover:animate-bounce text-teal-500 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> WhatsApp </span> </div> <div className="flex flex-col space-x-2 justify-centeritems-center group "> <FontAwesomeIcon icon={faInstagram} className=" h-5 group-hover:animate-bounce text-teal-500 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Instagram </span> </div> </div> </div> ); } export default CardSocialLogo <file_sep>/components/Layout.js import Header from "./Header/Header"; function Layout({children}) { return ( <div className="relative h-screen"> <Header className="fixed top-0" /> <div className="relative ">{children}</div> </div> ); } export default Layout <file_sep>/Utils/getRecepientEmail.js const getRecepientEmail = (users, usersLogin) =>( users?.filter(userToFilter =>userToFilter !==usersLogin?.email)[1] ) export default getRecepientEmail<file_sep>/components/Slider/Slider2.js import React from 'react' import Slider from "react-slick"; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import {faArrowCircleRight, faArrowCircleLeft, faHome, faEnvelope, faUsers, faEllipsisV } from '@fortawesome/free-solid-svg-icons' import {mockData2} from '../MockData/MockData' import CardContentWelcome from '../Card/CardContentWelcome'; const PreviousBtn = (props)=>{ const {className, onClick} =props return( <div className={className} onClick ={onClick} className="left-0"> <div className="glass3 relative flex items-center justify-center -left-0 z-10 h-8 top-1/2 p-2 w-10"> <FontAwesomeIcon icon={faArrowCircleLeft} className=" left-0 absolute z-10 h-5 hover:animate-bounce text-teal-500 text-xl" /> </div> </div> ) } const NextBtn = (props)=>{ const {className, onClick, style} =props return( <div onClick ={onClick} className="" > <div className="glass3 relative flex items-center justify-center -right-0 z-10 h-8 top-1/2 p-2 w-10"> <FontAwesomeIcon icon={faArrowCircleRight} className="-right-0 absolute z-10 h-5 hover:animate-bounce text-teal-500 text-xl" /> </div> </div> ) } function Slider2() { const settings = { dots: true, infinite:true, infinite: true, speed: 500, slidesToShow: 4, slidesToScroll: 4, prevArrow:<PreviousBtn/>, nextArrow:<NextBtn/>, // autoplay:true, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2, initialSlide: 2 } }, { breakpoint: 480, settings: { slidesToShow: 2, slidesToScroll: 2 } } ] }; return ( <div className=" z-0 mx-0" > <Slider {...settings} className="w-full"> {mockData2.map((homedata)=>( <div id={homedata.id} className="z-0 p-2 flex flex-col items-center justify-center" > <div className=" m-2 bg-teal-500 flex flex-col items-center justify-center"> <MyImage url ={homedata.image} className="w-100 z-0"/> <CardContentWelcome excerpt={homedata.excerpt}/> </div> </div> ))} </Slider> </div> ) } export default Slider2 function MyImage({url}){ return( <div className=""> <img src={url} className="object-contain object-center w-full z-0"/> </div> ) }<file_sep>/components/Card/CardSocial.js import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faWhatsapp, faFacebookF,faFacebookMessenger, faInstagram, faTwitter, faLinkedinIn, } from '@fortawesome/free-brands-svg-icons' function CardSocial() { return ( <div className="inline-flex space-x-2"> <div className="flex flex-col space-y-2 items-center group "> <FontAwesomeIcon icon={faFacebookF} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Facebook </span> </div> <div className="flex flex-col space-y-2 items-center group "> <FontAwesomeIcon icon={faFacebookMessenger} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Messenger </span> </div> <div className="flex flex-col space-y-2 items-center group "> <FontAwesomeIcon icon={faInstagram} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Twitter </span> </div> <div className="flex flex-col space-y-2 items-center group "> <FontAwesomeIcon icon={faTwitter} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Twitter </span> </div> <div className="flex flex-col space-y-2 items-center group "> <FontAwesomeIcon icon={faLinkedinIn} className=" h-5 group-hover:animate-bounce text-teal-300 text-xl" /> <span className="opacity-0 group-hover:opacity-100 text-xs"> Linked In </span> </div> </div> ) } export default CardSocial <file_sep>/components/AuthProvider.js import React, {useEffect, useState, createContext} from 'react' import firebase from 'firebase' import {auth, db} from '../firebase' import { faSpinner } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; export const AuthContext = createContext(null); export function AuthProvider({children}) { const [currentUser, setCurrentUser] = useState(null) const [pending, setPending] = useState (true) useEffect(() => { auth.onAuthStateChanged( (user)=>{ setCurrentUser(user) setPending(false) }) }, []) useEffect( ()=>{ if(currentUser){ db.collection("users").doc(currentUser.uid).set({ email:currentUser.email, lastSeen: firebase.firestore.FieldValue.serverTimestamp(), photoURL:currentUser.photoURL }, {merge:true}) } },[currentUser]) if(pending){ return <div> <div className="flex items-center justify-center bg-gray-100 h-screen"> <div className="flex flex-col space-x-2 justify-center items-center group space-y-12 h-96 w-96 bg-gray-50 p-12 rounded shadow"> <FontAwesomeIcon icon={faSpinner} className={`animate-spin text-teal-500 text-8xl space-x-3`} /> </div> </div> </div> } return ( <AuthContext.Provider value={{ currentUser }}> {children} </AuthContext.Provider > ) } <file_sep>/components/MockData/MockData.js export const mockData2 = [ { id:1, image:"/tailor1.jpg", title:"Our Team", excerpt:"Our Team consist of people from different culture and experience", description: "Our Team consist of people from different culture and experience. There are teenagers, men and housewife. Who need to work and support their family.As our factories are in Bali Java, so are our staffs." }, { id:2, image:"/tailor2.jpg", title:"We are community Business", excerpt:"We have two factories and offices, one is in Ubud Bali, and the other is in Banyuwangi, East Java. ", description: "At BaliJava is inspired by the willingness to support local tailors who have skills, experience, and professional qualification, but they don’t get enough income.From the motivations to help local community and the spirit to provide best quality and services to the customers in the garment business, At BALIJAVA has been operated since 2000.We have two factories and offices, one is in Ubud Bali, and the other is in Banyuwangi, East Java" }, { id:3, image:"/tailor4.jpg", title:"Our Services", excerpt:"We offer handmade and customize tailor products with best quality and best price ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excerpteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, { id:4, image:"/tailor5.jpg", title:"Our Office and Facilities", excerpt:"Lorem Lorem ipsum dolor sit amet ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excerpteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, { id:5, image:"/tailor3.jpg", title:"About Us", excerpt:"At BaliJava is inspired by the willingness to support local tailors who have skills,...", description: "At BaliJava is inspired by the willingness to support local tailors who have skills, experience, and professional qualification, but they don’t get enough income.From the motivations to help local community and the spirit to provide best quality and services to the customers in the garment business, At BALIJAVA has been operated since 2000.We have two factories and offices, one is in Ubud Bali, and the other is in Banyuwangi, East Java" }, ] const mockData = [ { id:1, image:"./boy.jpg", title:"Lorem ipsum dolor sit amet", excerpt:"Lorem Lorem ipsum dolor sit amet ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excerpteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, { id:2, image:"./boy.jpg", title:"Lorem ipsum dolor sit amet", excerpt:"Lorem Lorem ipsum dolor sit amet ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, { id:3, image:"./boy.jpg", title:"Lorem ipsum dolor sit amet", excerpt:"Lorem Lorem ipsum dolor sit amet ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excerpteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, { id:4, image:"./boy.jpg", title:"Lorem ipsum dolor sit amet", excerpt:"Lorem Lorem ipsum dolor sit amet ", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excerpteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." }, ] export default mockData
5a48b5202bdc559600f409415239ff089587f340
[ "JavaScript" ]
23
JavaScript
maxMaksum/balijavasp
4ce733ae9847881b80e595cb7bdb1a401a578df3
8a2397a99cb6a4dfb7f94060a96a4f3af0b11c27
refs/heads/master
<file_sep>import json def get_config(): with open("config/config.json", encoding="utf-8") as config_file: return json.load(config_file) or None <file_sep>import os import cloudinary as Cloud from config.config_json import get_config def config_cloudinary(): cloudinary_config = get_config()["cloudinary"] cloud_name = cloudinary_config["cloud_name"] api_key = cloudinary_config["api_key"] api_secret = cloudinary_config["api_secret"] return { "cloud_name": os.environ.get("CLOUDINARY_CLOUD_NAME") or cloud_name, "api_key": os.environ.get("CLOUDINARY_API_KEY") or api_key, "api_secret": os.environ.get("CLOUDINARY_API_SECRET") or api_secret } <file_sep>import json class Image: url: str def __init__(self, url): self.url = url def __repr__(self): return { "url": self.url } <file_sep>import flask import json from flask import request, jsonify, send_from_directory from flask_cors import CORS from controllers.note_controller import NoteController from controllers.image_controller import ImageController app = flask.Flask(__name__) cors = CORS(app, resources={ r"/api/*": { "origins": "*" } }) app.config.from_pyfile("config/config_flask.py") @app.route("/", methods=["GET"]) def home(): return "API proyecto final - Sistemas Programables" # Notes endpoints @app.route("/api/notes", methods=["GET"]) def get_notes(): return NoteController().get_notes() @app.route("/api/notes", methods=["POST"]) def create_note(): return NoteController().create(request.form) @app.route("/api/notes", methods=["PATCH"]) def update_note(): return NoteController().update() @app.route("/api/notes", methods=["DELETE"]) def delete_note(): return NoteController().delete() # Images endpoints @app.route("/api/images", methods=["GET"]) def get_images(): return ImageController().get_images() @app.route("/api/images", methods=["POST"]) def create_image(): return ImageController().create(request) @app.route("/api/images/uploads") def uploaded_file(filename): return send_from_directory(app.config["UPLOAD_FOLDER"], filename) @app.route("/api/images", methods=["DELETE"]) def delete_image(): return ImageController().delete() app.run(host="0.0.0.0", port=80) <file_sep>import json class Note: title: str description: str def __init__(self, title, description): self.title = title self.description = description def __repr__(self): return { "title": self.title, "description": self.description } <file_sep>import flask, json, os, hashlib, requests from flask import request, jsonify, current_app, url_for from bson.json_util import dumps from bson.objectid import ObjectId from werkzeug.utils import secure_filename from database.db_connection import connection from config.config_json import get_config from config.cloudinary import config_cloudinary from models.image import Image class ImageController: def allowed_file(self, filename): return "." in filename and \ filename.split(".", 1)[1].lower() in current_app.config["ALLOWED_EXTENSIONS"] def get_images(self): if "id" in request.args: idImg = ObjectId(request.args["id"]) image = connection().images.find({ "_id": idImg }) return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(image))), ) else: images = connection().images.find() return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(images))), count = images.count() ) def upload_cloudinary(self, filename): cloud_name = get_config()["cloudinary"]["cloud_name"] or os.environ.get("CLOUDINARY_CLOUD_NAME") upload_preset = get_config()["cloudinary"]["upload_preset"] or os.environ.get("CLOUDINARY_UPLOAD_PRESET") api = get_config()["cloudinary"]["api"] or os.environ.get("CLOUDINARY_API") upload_url = f"{api}/{cloud_name}/image/upload" response = requests.post( upload_url, params={ "upload_preset": upload_preset }, files={ "file": filename } ) print(response.json()) return response.json()["secure_url"] def create(self, req): imageFile = request.files["file"] if "files" in req.files or imageFile.filename != "": if imageFile and self.allowed_file(imageFile.filename): url = self.upload_cloudinary(imageFile) payload = { "url": url } result = connection().images.insert_one(payload) if result.inserted_id: image = connection().images.find({ "_id": ObjectId(result.inserted_id) }) return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(image))) ) else: return jsonify( statusCode = 500, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Error saving file! Try again later." } ) else: return jsonify( statusCode = 400, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "File not supported!" } ) else: return jsonify( statusCode = 400, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Select at least one file!" } ) def delete(self): if "id" in request.args: idImg = ObjectId(request.args["id"]) result = connection().images.delete_one({ "_id": idImg }) images = connection().images.find() if result.deleted_count > 0: images = connection().images.find() return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(images))), count = images.count() ) else: return jsonify( statusCode = 500, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Error deleting image! Try again later." } ) else: return jsonify( statusCode = 400, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { message: "Error: No ID field provided. Please specify an id." } ) <file_sep>requests flask flask-cors dnspython pymongo cloudinary<file_sep># API # Installation + Run the next command in the current directory `pip install -r requirements.txt` # Linux daemon + Create service file `sudo nano /etc/systemd/system/proyecto-final-sp-api.service`, check `config/proyecto-final-sp-api.service`. + Change permissions `sudo chmod 644 /etc/systemd/system/proyecto-final-sp-api.service` + Reload os daemons `sudo systemctl daemon-reload` + Enable service `sudo systemctl enable proyecto-final-sp-api` + Start service `sudo systemctl start proyecto-final-sp-api` + Check status `sudo systemctl status proyecto-final-sp-api` # Database configuration The url from the database is hardcoded in the `database/db_connection.py` file. You should change the name of the key where your database would be placed. Temporaly, it will be using the MongoDB Atlas URL. # Upload folder All the files uploaded will be storage in [Cloudinary](cloudinary.com). Check `config/cloudinary.py`. <file_sep>import os from pymongo import MongoClient from config.config_json import get_config def connection(): client = MongoClient(os.environ.get("MONGODB_URL") or get_config()["mongoAtlas"]) db = client.cfpm return db <file_sep>import flask import json from flask import request, jsonify from bson.json_util import dumps from bson.objectid import ObjectId from database.db_connection import connection from models.note import Note class NoteController: def get_notes(self): if "id" in request.args: idNote = ObjectId(request.args["id"]) note = connection().notes.find({ "_id": idNote }) return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(note))), ) else: notes = connection().notes.find() return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(notes))), count = notes.count() ) def create(self, form): note = { "title": request.form.get("title"), "description": request.form.get("description") } result = connection().notes.insert_one(note) if result.inserted_id: note = connection().notes.find({ "_id": ObjectId(result.inserted_id) }) return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(note))) ) else: return jsonify( statusCode = 500, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Error creating new note! Try again later." } ) def update(self): if "id" in request.args: idNote = ObjectId(request.args["id"]) title = request.form.get("title") description = request.form.get("description") newData = {} if title is not None: newData["title"] = title if description is not None: newData["description"] = description result = connection().notes.update_one( { "_id": idNote }, { "$set": newData }, upsert = False ) if result.modified_count > 0: note = connection().notes.find({ "_id": idNote }) return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(note))) ) else: return jsonify( statusCode = 500, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Error updating note! Try again later." } ) else: return jsonify( statusCode = 400, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { message: "Error: No ID field provided. Please specify an id." } ) def delete(self): if "id" in request.args: idNote = ObjectId(request.args["id"]) result = connection().notes.delete_one({ "_id": idNote }) notes = connection().notes.find() if result.deleted_count > 0: notes = connection().notes.find() return jsonify( headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, statusCode = 200, data = json.loads(dumps(list(notes))), count = notes.count() ) else: return jsonify( statusCode = 500, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { "message": "Error deleting note! Try again later." } ) else: return jsonify( statusCode = 400, headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, error = { message: "Error: No ID field provided. Please specify an id." } )
3ea04cbbd680b8b1a54acb28c731d0c03dc2c4c2
[ "Markdown", "Python", "Text" ]
10
Python
jessicaramsa/proyecto-final-sp-api
fbe1e270819fc076cfeefca54f40651fe9d6f6aa
45d8a69d89ade7ef3d9b7311c251cff8c73fbd04
refs/heads/master
<repo_name>coiller/24Puzzle<file_sep>/main.py import copy import random import time class Node(object): def __init__(self, data, depth): Node.is_legal_data(data) self.data = data self.depth = depth def __eq__(self, other): return self.data == other.data and isinstance(other, Node) def __str__(self): s = '\n'.join(" ".join(['%02d' % (self.data[row][column]) for column in range(len(self.data[row]))]) for row in range(len(self.data))) return "".join(["当前步数:{}\n".format(self.depth + 1), s]) def __repr__(self): return '\n'.join(" ".join(['%02d' % (self.data[row][column]) for column in range(len(self.data[row]))]) for row in range(len(self.data))) def __getitem__(self, item): return self.data[item] @classmethod def copy(cls, node): '''return a deep copy of self.data, self.depth''' return Node(copy.deepcopy(node.data), copy.deepcopy(node.depth)) @classmethod def get_blank_position(cls, p_node): '''get the position of 0. range from (0, 0) to (4 , 4)''' for row in range(len(p_node.data)): for column in range(len(p_node.data[row])): if p_node.data[row][column] == 0: return row, column @classmethod def is_legal_data(cls, data): '''check if the data is 2-dimension data''' temp_list = list() assert len(data) == 5 for x in data: assert len(x) == 5 for y in x: temp_list.append(y) temp_list.sort() assert temp_list == list(range(25)) @classmethod def can_move(cls, p_node, direction_str): '''return if p_node can move to the specified direction U for up, D for down, L for left, R for right''' if direction_str == "U": return not Node.get_blank_position(p_node)[0] == 0 elif direction_str == "D": return not Node.get_blank_position(p_node)[0] == 4 elif direction_str == "L": return not Node.get_blank_position(p_node)[1] == 0 elif direction_str == "R": return not Node.get_blank_position(p_node)[1] == 4 else: SystemError("no such direction: {}".format(direction_str)) @classmethod def move(cls, p_node, direction_str): '''move the blank of p_node to the specified direction U for up, D for down, L for left, R for right''' x, y = Node.get_blank_position(p_node) if direction_str == "U": p_node[x][y], p_node[x - 1][y] = p_node[x - 1][y], p_node[x][y] elif direction_str == "D": p_node[x][y], p_node[x + 1][y] = p_node[x + 1][y], p_node[x][y] elif direction_str == "L": p_node[x][y], p_node[x][y - 1] = p_node[x][y - 1], p_node[x][y] elif direction_str == "R": p_node[x][y], p_node[x][y + 1] = p_node[x][y + 1], p_node[x][y] else: SystemError("no such direction: {}".format(direction_str)) @classmethod def random_node(cls, depth=0, max_dis=100): '''generate random node, default depth = 0''' dis = max_dis + 1 while (dis > max_dis): gen_list = list(range(25)) target_data = [] for i in range(5): temp = [] for j in range(5): choice = random.choice(gen_list) temp.append(choice) gen_list.remove(choice) target_data.append(temp) dis = Node.get_dis(Node(target_data, depth)) return Node(target_data, depth) @classmethod def get_parity(cls, p_node): '''return the parity, false to odd, true to oven''' temp = [] for row in range(len(p_node.data)): for column in range(len(p_node.data[row])): temp.append(p_node.data[row][column]) temp.remove(0) parity_count = 0 for i in range(len(temp)): for j in range(i): if temp[j] > temp[i]: parity_count += 1 @classmethod def get_dis(cls, p_nod): '''return the manhattan distence''' dis = 0 for row in range(len(p_nod.data)): for column in range(len(p_nod.data[row])): if p_nod.data[row][column] == 0: continue dis = dis + abs(row - int(p_nod.data[row][column] / 5)) +\ abs(column - p_nod.data[row][column] % 5) return dis @classmethod def heuristic_funtion(cls, p_node, target_node, factor_a=1, factor_b=1): '''return the value of F(x) = a*G(x) + b*H(x) where G(x) is the depth, a is factor, and H(x) is the expectation, b is factor''' # counter = 0 # for row in range(len(p_node.data)): # for column in range(len(p_node.data[row])): # if p_node.data[row][column] != target_node.data[row][column]: # counter += 1 # return factor_a * p_node.depth + factor_b * counter return factor_a * p_node.depth + factor_b * Node.get_dis(p_node) @classmethod def get_node_heuristic(cls, opened_list, target_node, factor_a, factor_b): '''get the best node from opened_list accroding to heuristic funtion''' best_node_index = 0 best_node_value = Node.heuristic_funtion( opened_list[0][1], target_node, factor_a, factor_b) for i in range(1, len(opened_list)): if opened_list[i][0] is None: temp_value = Node.heuristic_funtion( opened_list[i][1], target_node, factor_a, factor_b) opened_list[i][0] = temp_value else: temp_value = opened_list[i][0] if best_node_value >= temp_value: best_node_index = i best_node_value = temp_value return opened_list.pop(best_node_index)[1] class NodeUtils(object): '''some utils about the node''' @classmethod def show_resolve_path(cls, final_node): '''show the path from start to final''' cursor = final_node temp = [] while hasattr(cursor, "prev"): temp.append(cursor) cursor = cursor.prev temp.append(cursor) while not len(temp) == 0: yield temp.pop() def heuristic_search( p_startpoint, p_endpoint, factor_a=1, factor_b=1, vale=100): # 深拷贝 startpoint = copy.deepcopy(p_startpoint) endpoint = copy.deepcopy(p_endpoint) # 检查奇偶性 if Node.get_parity(startpoint) != Node.get_parity(endpoint): return list() # 数据结构初始化 opened_nodes = [[None, startpoint], ] closed_nodes = [] while True: if opened_nodes == []: print('Warning:Vale is too small!') return list() current_node = Node.get_node_heuristic( opened_nodes, endpoint, factor_a, factor_b) # 分析节点, 如果是目标节点则结束搜索 if current_node == endpoint: return list(NodeUtils.show_resolve_path(current_node)) # 如果不是目标节点,存入搜索历史 closed_nodes.append(current_node) # 拓展节点 for direction_str in ["U", "D", "L", "R"]: if Node.can_move(current_node, direction_str): new_node = Node.copy(current_node) Node.move(new_node, direction_str) if new_node not in closed_nodes: if Node.heuristic_funtion(new_node, endpoint, factor_a, factor_b) <= vale: opened_nodes.append([None, new_node]) new_node.depth += 1 new_node.prev = current_node # 搜索不到时返回空列表 return list() def backward(p_endpoint, steps=50): # 生成由目标节点任意倒退steps步的初始节点 current_node = copy.deepcopy(p_endpoint) for step in range(steps): direction_str = random.choice(["U", "D", "L", "R"]) if Node.can_move(current_node, direction_str): Node.move(current_node, direction_str) else: step -= 1 return current_node def main(): # 指定生成节点 # startpoint = Node([ # [0, 1, 2, 3, 4], # [5, 6, 7, 8, 9], # [10, 11, 12, 13, 14], # [15, 16, 17, 18, 19], # [20, 21, 22, 23, 24], # ], 0) endpoint = Node([ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], ], 0) startpoint = backward(endpoint, steps=200) # # 随机生成有效节点 # while True: # startpoint = Node.random_node(max_dis=50) # # endpoint = Node.random_node() # if Node.get_parity(startpoint) == Node.get_parity(endpoint): # break # 输出初始节点信息 print('起始状态:\n{}'.format(startpoint.__repr__())) print('结束状态:\n{}'.format(endpoint.__repr__())) # 启发式搜索 t1 = time.time() result_list = heuristic_search( startpoint, endpoint, factor_a=1, factor_b=11, vale=300) if result_list: print('[启发式搜索] 共耗时{:.3}s.'.format(time.time() - t1), end="") print('(共{}步):'.format(len(result_list))) for x in result_list: print(str(x)) else: print('max depth reached. search failed.') if __name__ == '__main__': main()
a2b7dbeb775ab0042b10f00c29930d0fae2d7169
[ "Python" ]
1
Python
coiller/24Puzzle
26dfbc989e271fa5aec6492f0f670eb5a7685962
49d57966612177448a53017005cc288203999741
refs/heads/master
<file_sep>package com.example.noteboi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.text.Layout; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.LogOutCallback; import com.parse.ParseACL; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import com.parse.SaveCallback; import java.util.ArrayList; import java.util.List; import co.dift.ui.SwipeToAction; import dmax.dialog.SpotsDialog; public class note_rows extends AppCompatActivity { boolean fav_stat; RecyclerView my_rv; List<RecyclerViewModel> data; MyAdapter adapter; FloatingActionButton newnote_button; TextView tv,my_no_note_tv; SwipeRefreshLayout swipe; ParseUser currentUser; android.app.AlertDialog dialog; SwipeToAction swipeToAction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note_rows); data = new ArrayList<>(); newnote_button = findViewById(R.id.newnote_b); my_rv = findViewById(R.id.rv); tv = findViewById(R.id.tv); my_no_note_tv = findViewById(R.id.no_note_tv); //making the "no note view" go away until we need to make it visible my_no_note_tv.setVisibility(View.GONE); //swipe to refresh swipe = findViewById(R.id.srLayout); swipe.setColorSchemeResources(R.color.colorAccent); swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); ParseACL.setDefaultACL(new ParseACL(), true); //checking current user currentUser = ParseUser.getCurrentUser(); if (currentUser == null){ Intent i = new Intent(note_rows.this, MainActivity.class); startActivity(i); } //Here i make an object form my adapter (for the Recycler view) adapter = new MyAdapter(data); my_rv.setAdapter(adapter); my_rv.setLayoutManager( new LinearLayoutManager( this, RecyclerView.VERTICAL, false )); //recycler view onClick / onSwipe swipeToAction = new SwipeToAction(my_rv, new SwipeToAction.SwipeListener<RecyclerViewModel>() { @Override public boolean swipeLeft(final RecyclerViewModel itemData) { if(isNetworkAvailable()){ AlertDialog.Builder builder = new AlertDialog.Builder(note_rows.this); builder.setMessage("Are you sure you want to delete this note?") .setTitle("Delete") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ParseQuery<ParseObject> query = ParseQuery.getQuery("notes"); query.getInBackground(itemData.getId(), new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (e == null) { object.deleteInBackground(); View parentLayout = findViewById(R.id.clayout); Snackbar.make(parentLayout,"Note Deleted",Snackbar.LENGTH_SHORT).show(); refresh(); } else { View parentLayout = findViewById(R.id.clayout); Snackbar.make(parentLayout,"Failed to Delete Note",Snackbar.LENGTH_SHORT).show(); } } }); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog dialog = builder.create(); dialog.show(); } else Toast.makeText(note_rows.this, "Check Your Network Connection", Toast.LENGTH_SHORT).show(); return true; } @Override public boolean swipeRight(final RecyclerViewModel itemData) { if (isNetworkAvailable()){ ParseQuery<ParseObject> query = ParseQuery.getQuery("notes"); query.getInBackground(itemData.getId(), new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { object.put("fav", true); object.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { View parentLayout = findViewById(R.id.clayout); Snackbar.make(parentLayout, "Note added to Favorites", Snackbar.LENGTH_SHORT).show(); refresh(); } else Toast.makeText(note_rows.this, "Failed to add note to favorites", Toast.LENGTH_SHORT).show(); } }); } }); } else Toast.makeText(note_rows.this, "Check Your Network Connection", Toast.LENGTH_SHORT).show(); return true; } @Override public void onClick(RecyclerViewModel itemData) { if(isNetworkAvailable()){ String clicked_id = itemData.getId(); finish(); Intent intent = new Intent(note_rows.this, note_page.class); intent.putExtra("id", clicked_id); startActivity(intent); }else { Toast.makeText(note_rows.this, "Check Your Network Connection", Toast.LENGTH_SHORT).show(); } } @Override public void onLongClick(RecyclerViewModel itemData) { } }); //setting the no connection tv invisible/visible if (isNetworkAvailable()) { tv.setVisibility(View.GONE); } else { my_rv.setVisibility(View.GONE); tv.setVisibility(View.VISIBLE); } //filling the Recycler View with objects containing title, memo and id refresh(); } public void refresh(){ if (isNetworkAvailable()){ my_rv.setVisibility(View.VISIBLE); tv.setVisibility(View.GONE); ParseQuery<ParseObject> query = ParseQuery.getQuery("notes"); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null){ data.clear(); for( ParseObject obj : objects){ Log.i("title", String.valueOf(obj.getString("title"))); Log.i("fav stat", String.valueOf(obj.getBoolean("fav"))); data.add(new RecyclerViewModel( obj.getString("title"), obj.getString("memo"), obj.getBoolean("fav"), obj.getObjectId() )); } adapter.notifyDataSetChanged(); if(data.isEmpty()){ //make no note view visible my_no_note_tv.setVisibility(View.VISIBLE); } }else{ Toast.makeText(note_rows.this, "Failed to Load Notes", Toast.LENGTH_SHORT).show(); } } }); }else{ if(currentUser != null){ View parentLayout = findViewById(R.id.clayout); Snackbar.make(parentLayout,"No Internet Connection\nCheck Your Connection and Swipe to Refresh",Snackbar.LENGTH_LONG).show(); } } swipe.setRefreshing(false); } public void make_note (View view) { if (isNetworkAvailable()) { Intent n = new Intent(note_rows.this, note_page.class); finish(); startActivity(n); } else Toast.makeText(this, "Check Your Network Connection", Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.note_row_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.log_out: dialog = new SpotsDialog.Builder() .setContext(this) .setMessage("Loading note") .setTheme(R.style.loading_dialog) .setCancelable(false) .build(); dialog.show(); currentUser.logOutInBackground(new LogOutCallback() { @Override public void done(ParseException e) { if (e != null){ Toast.makeText(note_rows.this, "Failed to log out", Toast.LENGTH_SHORT).show(); } } }); Intent i = new Intent(note_rows.this, MainActivity.class); finish(); startActivity(i); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu){ if(ParseUser.getCurrentUser() != null){ invalidateOptionsMenu(); menu.findItem(R.id.current_user).setTitle( "User: " + ParseUser.getCurrentUser().getUsername()); } return true; } //making the back button take you to home and add the activity to stack @Override public void onBackPressed() { Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } private boolean isNetworkAvailable(){ ConnectivityManager manager = (ConnectivityManager) getSystemService(MainActivity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()){ return true; } else return false; } }<file_sep># NoteBoi An online note application for android.<br/><br/> <p align="center"> <img src="https://user-images.githubusercontent.com/48511939/127957009-0e58ea7b-2a1f-417c-868f-1ad93cfc19eb.jpg", width=250/> <img src="https://user-images.githubusercontent.com/48511939/127957166-46d4a4a7-effa-47c7-93e7-3bb509d0b641.jpg", width=250/> </p> <br/> NoteBoi is an android note-taking app that lets you take your notes on the go and save them in an online account. The backend communications are done through Parse Server hosted on Back4App servers (https://www.back4app.com). Using the app comes with a quick sign up process which allows for the users to save their notes (but confirming the email is not mandatory for using the app).<br/><br/> <p align="center"> <img src="https://user-images.githubusercontent.com/48511939/127957802-60a82a46-b522-40eb-9c6f-7dbe7723ba1d.gif", width=250/> <img src="https://user-images.githubusercontent.com/48511939/127960511-b5eabc26-efbe-462b-93d5-8e9ee0ae6026.gif", width=250/> </p><br/> <i>Cheers!</i> <file_sep>package com.example.noteboi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; import com.parse.CountCallback; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import com.parse.SignUpCallback; import java.util.List; import dmax.dialog.SpotsDialog; public class sign_up extends AppCompatActivity { EditText new_user, new_pass, new_email, confirm_pass; Button new_signup; android.app.AlertDialog dialog; Boolean taken_username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); new_email = findViewById(R.id.ed_new_email); new_user = findViewById(R.id.ed_new_user); new_pass = findViewById(R.id.ed_new_pass); new_signup = findViewById(R.id.b_signup); confirm_pass = findViewById(R.id.ed_confirm_pass); } public void make_user(){ if (new_user.getText().toString().length() <= 12 && new_pass.getText().toString().length() >= 4 && new_pass.getText().toString().length() <= 16 && isValidEmail(new_email.getText().toString().trim()) && new_pass.getText().toString().equals(confirm_pass.getText().toString()) && !taken_username) { ParseUser user = new ParseUser(); user.setUsername(new_user.getText().toString().trim()); user.setPassword(<PASSWORD>().<PASSWORD>()); user.setEmail(new_email.getText().toString()); user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { Toast.makeText(sign_up.this ,"signed up successfully", Toast.LENGTH_LONG).show(); AlertDialog.Builder builder = new AlertDialog.Builder(sign_up.this); builder.setMessage("Please confirm your email\nAn email has been sent to you") .setTitle("Welcome to NoteBoi") .setPositiveButton("Got it", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent a = new Intent(sign_up.this, note_rows.class); startActivity(a); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { Intent a = new Intent(sign_up.this, note_rows.class); startActivity(a); } }); AlertDialog dialog = builder.create(); dialog.show(); } else { Toast.makeText(sign_up.this ,"sign up Failed", Toast.LENGTH_LONG).show(); } } });dialog.dismiss(); } else if(!isValidEmail(new_email.getText().toString())) { Toast.makeText(this, "Invalid email format", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else if(!new_pass.getText().toString().equals(confirm_pass.getText().toString())){ Toast.makeText(this, "Passwords don't match", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else if(taken_username){ Toast.makeText(this, "Username is already taken", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else if (new_user.getText().toString().length() > 12) { Toast.makeText(this, "Username must contain less than 13 characters", Toast.LENGTH_LONG).show(); dialog.dismiss(); } else if (new_pass.getText().toString().length() < 4 || new_pass.getText().toString().length() > 12){ Toast.makeText(this, "Password must contain 4-12 characters", Toast.LENGTH_LONG).show(); dialog.dismiss(); } } private boolean isNetworkAvailable(){ ConnectivityManager manager = (ConnectivityManager) getSystemService(MainActivity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()){ return true; } else return false; } public void sign_up(View view){ if(isNetworkAvailable()){ //show signing up dialog dialog = new SpotsDialog.Builder() .setContext(this) .setMessage("Signing up") .setTheme(R.style.loading_dialog) .setCancelable(false) .build(); dialog.show(); //dismiss the dialog after 10s automatically final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dialog.dismiss(); } }, 10000); if(new_user.getText().toString().isEmpty()){ Toast.makeText(this, "Pick a username", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else if(new_email.getText().toString().isEmpty()){ Toast.makeText(this, "Enter an email", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else{ ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereEqualTo("username",new_user.getText().toString()); query.countInBackground(new CountCallback() { @Override public void done(int count, ParseException e) { if(e == null){ if(count == 0) { taken_username = false; make_user(); } else { taken_username = true; make_user(); } } } }); } } else Toast.makeText(this, "Check Your Network Connection", Toast.LENGTH_LONG).show(); } //checking if the email format is valid public static boolean isValidEmail(CharSequence target) { return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches()); } } <file_sep>package com.example.noteboi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.RequestPasswordResetCallback; public class forgot extends AppCompatActivity { EditText forgot_e; Button reset_b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot); forgot_e = findViewById(R.id.ed_forgot); reset_b = findViewById(R.id.forgot_b); getSupportActionBar().setTitle("Login Help"); } private boolean isNetworkAvailable(){ ConnectivityManager manager = (ConnectivityManager) getSystemService(MainActivity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()){ return true; } else return false; } public void reset_pass(View view){ if(isNetworkAvailable()){ ParseUser.requestPasswordResetInBackground(forgot_e.getText().toString(), new RequestPasswordResetCallback() { public void done(ParseException e) { if (e == null) { AlertDialog.Builder builder = new AlertDialog.Builder(forgot.this); builder.setMessage("An email has been sent to you. You can now reset your password") .setPositiveButton("Got it", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent a = new Intent(forgot.this, MainActivity.class); startActivity(a); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { Intent a = new Intent(forgot.this, MainActivity.class); startActivity(a); } }); AlertDialog dialog = builder.create(); dialog.show(); } else { View parentLayout = findViewById(android.R.id.content); Snackbar.make(parentLayout,"Email not found. make sure you have verified your email address",Snackbar.LENGTH_LONG).show(); } } }); } else Toast.makeText(this, "Check Your Network Connection", Toast.LENGTH_LONG).show(); } }
1e198ddcac911c5b55053fcb1e244c02d1d00240
[ "Markdown", "Java" ]
4
Java
AmiraliSajadi/NoteBoi
d24bfc930e749f8ccf51cce135b2624649d7939f
2ac6363155d1bca255b427dbeea8475e5ab7cb7e
refs/heads/master
<file_sep># student-and-skill 랜덤으로 학생의 능력치를 배정하여 지정스킬을 수행한뒤 학생들의 능력치를 다시 재 점검한다. ------------------------------------------------------------- 2학년 1학기 프로그래밍언어에서 'C++'을 배울때 받았던 텀프로젝트이다. 학생들의 공통적인 능력치? 함수를 상위클래스에서 지정하여주고 또 가상클래스를 이용하여 각 학생들마다 능력치가 조금씩 다르게, 스킬들이 조금씩 다르게 하였다. 스킬은 직접 지정해준것을 사용하는데, 만약 수행할 능력치가 되지않을경우 스킬은 스킵하는걸로 한다. 학생들의 능력치와 학생들 개개인의 객체를 만들기위해 벡터를 사용하였는데, 솔직히 클래스보다 벡터(객체)에 대한 이해도가 떨어져 코드를 짜는데 어려움이 있었다.. .. 클래스와 벡터를 공부하기에 적합한 텀프로젝트였다고 생각한다. <file_sep>#include<iostream> #include<vector> #include <algorithm> #include<cstdlib> #include<ctime> using namespace std; ///////////////////////Student(학생) 클래스를 작성하라하라 class Student { protected: string name; int kor, eng, math; public: Student(); Student(string name) { this->name = name; kor = rand() % 31; math = rand() % 31; eng = rand() % 31; // 이름을 name을 초기화, 나머지 능력치는 0~30사이의 랜덤추첨. } Student(string name, int kor, int eng, int math) { this->eng = eng; this->kor = kor; this->math = math; this->name = name; } friend bool compare(Student* a, Student* b); void study(); void virtual info(); }; void Student::study() { this->kor += 2; this->eng += 2; this->math += 2; if (this->kor > 100) this->kor = 100; if (this->eng > 100) this->eng = 100; if (this->math > 100) this->math = 100; } void Student::info() { cout << "이름 :" << name << " 언어력:" << this->kor << " 영어력 :" << this->eng << " 수학력 :" << this->math << endl; } //////////////////////Student를 상속받아 CollegeStudent(대학생) 클래스를 작성하라 class CollegeStudent :public Student { protected: int general, major, hp; public: CollegeStudent(); CollegeStudent(string name) :Student(name) { this->name = name; general = rand() % 31; major = rand() % 31; hp = rand() % 31; // 이름을 name을 초기화, 나머지 능력치는 0~30사이의 랜덤추첨. } CollegeStudent(string name, int kor, int eng, int math) :Student(name, kor, eng, math) { general = rand() % 31; major = rand() % 31; hp = rand() % 31; }//전달된 매개변수로 멤버초기화. 나머지 능력치는 0~30사이의 랜덤추첨. CollegeStudent(string name, int kor, int eng, int math, int general, int major, int hp) :Student(name, kor, eng, math) { this->general = general; this->major = major; this->hp = hp; }//전달된 매개변수로 모든 멤버초기화 void study(); void report(); void rest(); void info(); }; void CollegeStudent::study() { this->general += 2; this->major += 2; if (this->general > 100) this->general = 100; if (this->major > 100) this->major = 100; } void CollegeStudent::report() { if (this->hp < 5) { cout << this->name << " 체력없어서 report 수행불가" << endl; return; } this->general += 5; this->major += 5; this->hp -= 5; if (this->general > 100) this->general = 100; if (this->major > 100) this->major = 100; if (this->hp <= 0) this->hp = 0; } void CollegeStudent::rest() { this->general -= 1; this->major -= 1; this->hp += 5; if (this->general <= 0) this->general = 0; if (this->major <= 0) this->major = 0; if (this->hp > 100) this->hp = 100; } void CollegeStudent::info() { cout << "이름 :" << name << " 언어력:" << this->kor << " 영어력 :" << this->eng << " 수학력 :" << this->math << " 교양 : " << general << " 전공지식 : " << major << " 체력 :" << hp << endl; } ///////////CollegeStudent를 상속받아 GraduateStudent(대학원생) 클래스를 작성하라 class GraduatedStudent :public CollegeStudent { int present; public: GraduatedStudent(); GraduatedStudent(string name) :CollegeStudent(name) { this->name = name; present = rand() % 31; //이름을 name을 초기화, 나머지 능력치는 0~30사이의 랜덤추첨. } GraduatedStudent(string name, int kor, int eng, int math) :CollegeStudent(name, kor, eng, math) { present = rand() % 31; } GraduatedStudent(string name, int kor, int eng, int math, int general, int major, int hp) :CollegeStudent(name, kor, eng, math, general, major, hp) { present = rand() % 31; } GraduatedStudent(string name, int kor, int eng, int math, int general, int major, int hp, int present) :CollegeStudent(name, kor, eng, math, general, major, hp) { this->present = present; } void presentation(); void research(); void info(); }; void GraduatedStudent::presentation() { if (this->hp < 5) { cout << this->name << " 체력없어서 presentation 수행불가" << endl; return; } this->present += 5; this->hp -= 5; if (this->present > 100) this->present = 100; if (this->hp <= 0) this->hp = 0; } void GraduatedStudent::research() { if (this->hp < 10) { cout << this->name << " 체력없어서 research 수행불가" << endl; return; } this->major += 10; this->hp -= 10; if (this->major > 100) this->major = 100; if (this->hp <= 0) this->hp = 0; } void GraduatedStudent::info() { cout << "이름 :" << name << " 언어력:" << this->kor << " 영어력 :" << this->eng << " 수학력 :" << this->math << " 교양 : " << general << " 전공지식 : " << major << " 체력 :" << hp << " 발표력 : " << present << endl; } /////////////////////////////////////////////////////////////////////// bool compare(Student* a, Student* b) { if ((*a).name > (*b).name) return 0; else return 1; } int main() { srand((unsigned int)time(NULL)); vector< Student*> v; vector< CollegeStudent*> vp; vector< GraduatedStudent*> p; //1번 작업 v.push_back(new Student("4학생")); v.push_back(new Student("3학생")); v.push_back(new Student("2학생", 50, 20, 10)); v.push_back(new Student("1학생", 30, 40, 80)); vp.push_back(new CollegeStudent("b대학생")); vp.push_back(new CollegeStudent("c대학생", 70, 90, 60)); vp.push_back(new CollegeStudent("a대학생", 50, 60, 70, 80, 90, 85)); p.push_back(new GraduatedStudent("b대학원생")); p.push_back(new GraduatedStudent("c대학원생", 40, 80, 90, 76, 20, 98)); p.push_back(new GraduatedStudent("a대학원생", 15, 25, 35, 45, 55, 65, 75)); vector<Student*>::iterator it; vector<CollegeStudent*>::iterator it1; vector<GraduatedStudent*>::iterator it2; for (it1 = vp.begin(); it1 < vp.end(); it1++) v.push_back(*it1); for (it2 = p.begin(); it2 < p.end(); it2++) v.push_back(*it2); //2번 작업 for (it = v.begin(); it < v.end(); it++) (*it)->info(); //3번작업 for (it = v.begin(); it < v.end(); it++) (*it)->study(); //4번작업 for (it1 = vp.begin(); it1 < vp.end(); it1++) { (*it1)->report(); (*it1)->rest(); } for (it2 = p.begin(); it2 < p.end(); it2++) { (*it2)->report(); (*it2)->rest(); } //5번작업 for (it2 = p.begin(); it2 < p.end(); it2++) { (*it2)->presentation(); (*it2)->research(); } //6번작업 sort(v.begin(), v.end(), compare); cout << endl << endl; //7번작업 for (it = v.begin(); it < v.end(); it++) (*it)->info(); return 0; }
f3f5a0d5edbf351504c7d51083919b3526603d25
[ "Markdown", "C++" ]
2
Markdown
Wise-eun/student-and-skill
d4da3aa49ebdae5f0049bea9c9bf0c946e1571d3
ac7541692a1131158d50174d0020c7f66215f959
refs/heads/main
<repo_name>KisaShket/internship65<file_sep>/65-2internship/Entities/DataModels/Entry.swift import Foundation struct Entry : Codable { var link : [Link]? var gdOrganization : [GdOrganization]? var gdEmail : [GdEmail]? var gdPhoneNumber : [GdPhoneNumber]? var id : String? var fullName : String? var profileType : String? enum EntryKeys: String, CodingKey { case id = "id" case fullName = "title" case link = "link" case profileType = "gal$type" case gdName = "gd$name" case gdWhere = "gd$where" case gdOrganization = "gd$organization" case gdEmail = "gd$email" case gdPhoneNumber = "gd$phoneNumber" } enum IdKeys: String, CodingKey { case id = "$t" } enum NameKeys: String, CodingKey { case fullName = "$t" } enum LinkKeys: String, CodingKey { case rel = "rel" case type = "type" case href = "href" } enum ProfileTypeKeys: String, CodingKey { case type = "type" } init(from decoder: Decoder) throws { if let entryContainer = try? decoder.container(keyedBy: EntryKeys.self){ link = try entryContainer.decodeIfPresent([Link].self, forKey: .link) gdOrganization = try entryContainer.decodeIfPresent([GdOrganization].self, forKey: .gdOrganization) gdEmail = try entryContainer.decodeIfPresent([GdEmail].self, forKey: .gdEmail) gdPhoneNumber = try entryContainer.decodeIfPresent([GdPhoneNumber].self, forKey: .gdPhoneNumber) //MARK: - Flattening nested Json if let idContainer = try? entryContainer.nestedContainer(keyedBy: IdKeys.self, forKey: .id){ self.id = try idContainer.decodeIfPresent(String.self, forKey: .id) } if let titleContainer = try? entryContainer.nestedContainer(keyedBy: NameKeys.self, forKey: .fullName){ self.fullName = try titleContainer.decodeIfPresent(String.self, forKey: .fullName) } if let profileTypeContainer = try? entryContainer.nestedContainer(keyedBy:ProfileTypeKeys.self, forKey: .profileType){ self.profileType = try profileTypeContainer.decodeIfPresent(String.self, forKey: .type) } } } } <file_sep>/65-2internship/Common/Error/AuthError/AuthError.swift // // AuthError.swift // 65-2internship // // Created by <NAME> on 13.02.2021. // Copyright © 2021 <NAME>. All rights reserved. // enum AuthError: Error { case userAuthError } <file_sep>/65-2internship/Common/Error/NetworkError/NetworkError.swift // // ErrorLocalized.swift // 65-2internship // // Created by <NAME> on 13.02.2021. // Copyright © 2021 <NAME>. All rights reserved. // enum NetworkError: Error { case unableToComplete case wrongRequest(statusCode: Int) case wrongData case noUrl } <file_sep>/65-2internship/Entities/DataModels/GdPhoneNumber.swift import Foundation struct GdPhoneNumber : Codable { let rel : String? let uri : String? let phoneNumber : String? enum CodingKeys: String, CodingKey { case rel = "rel" case uri = "uri" case phoneNumber = "$t" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) rel = try values.decodeIfPresent(String.self, forKey: .rel) uri = try values.decodeIfPresent(String.self, forKey: .uri) phoneNumber = try values.decodeIfPresent(String.self, forKey: .phoneNumber) } } <file_sep>/65-2internship/UserStories/LoginStrory/View/LoginController.swift // // ViewController.swift // 65-2internship // // Created by <NAME> on 28.10.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class LoginController: UIViewController { var viewModel: LoginViewModel? override func viewDidLoad() { super.viewDidLoad() } @IBAction func clickedLoginButton(_ sender: Any) { viewModel?.signIn(vc: self) } } <file_sep>/65-2internship/UserStories/ContactsStories/ViewModel/ContactTableViewModelFromEntry.swift // // ContactTableViewModelFromEntry.swift // 65-2internship // // Created by <NAME> on 05.11.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SDWebImage protocol ContactTableViewModel { var dynamicContact: Dynamic<[ContactsData]> { get } func fetchContacts() func signOut() } class ContactTableViewModelFromEntry: ContactTableViewModel { var dynamicContact: Dynamic<[ContactsData]> = Dynamic([]) private let authService : AuthService private let networkService : Networker private let router : ContactRouter init(networkService: Networker, authService: AuthService, router: ContactRouter) { self.authService = authService self.networkService = networkService self.router = router } func fetchContacts() { let token = authService.accessToken networkService.fetchContacts { [weak self] contacts in let entries = contacts?.feed?.entry guard let contacts = entries?.filter({type in type.profileType == "profile"}) else { return } let contactsData = contacts.map { cont in ContactsData( fullName: cont.fullName, eMail: cont.gdEmail?.first?.address, phoneNumber: cont.gdPhoneNumber?.first?.phoneNumber ?? "Телефон отсутствует.", imgUrl: URL(string: (cont.link?.first?.href)!+"?access_token=\(token)") ) } self?.dynamicContact.value = contactsData } } func signOut(){ authService.signOut { [weak self] in self?.router.showLoginStory() } } } <file_sep>/65-2internship/UserStories/LaunchStory/LaunchStory.swift // // LaunchStory.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit struct LaunchStory { let viewController: UIViewController init() { let storyboard = UIStoryboard(name: Constants.kLaunchStoryboardName, bundle: nil) let router = LaunchRouter() let viewModel = LaunchViewModel(router: router, authService: GoogleAuthService.shared) let viewController = storyboard.instantiateViewController(withIdentifier: Constants.kLaunchID) as! LaunchController viewController.viewModel = viewModel self.viewController = viewController } } <file_sep>/65-2internship/Common/Routs/LoginRoute.swift // // LoginRoute.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import Router protocol LoginRoute { func showLoginStory() } extension LoginRoute where Self: RouterProtocol { func showLoginStory() { let transition = WindowCrossDissolve() open(LoginStory().viewController, transition: transition) } } <file_sep>/65-2internship/Common/Routs/ContactsRoute.swift // // ContactsRoute.swift // 65-2internship // // Created by <NAME> on 26.01.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit import Router protocol ContactsRoute { func showContactsStory() } extension ContactsRoute where Self: RouterProtocol { func showContactsStory() { let transition = WindowCrossDissolve() open(ContactsStory().viewController, transition: transition) } } <file_sep>/65-2internship/Entities/DataModels/Link.swift import Foundation struct Link : Codable { let rel : String? let type : String? let href : String? enum CodingKeys: String, CodingKey { case rel = "rel" case type = "type" case href = "href" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) rel = try values.decodeIfPresent(String.self, forKey: .rel) type = try values.decodeIfPresent(String.self, forKey: .type) href = try values.decodeIfPresent(String.self, forKey: .href) } } <file_sep>/65-2internship/Application/AppDelegate.swift // // AppDelegate.swift // 65-2internship // // Created by <NAME> on 28.10.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate{ var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = LaunchStory().viewController window?.makeKeyAndVisible() return true } @available(iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { return GIDSignIn.sharedInstance()?.handle(url) ?? false } } <file_sep>/65-2internship/UserStories/LoginStrory/LoginStory.swift // // LoginStory.swift // 65-2internship // // Created by <NAME> on 26.01.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit struct LoginStory { let viewController: UIViewController let loginVCIdentifier = "login" init() { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let router = LoginRouter() let viewModel = LoginViewModel(router: router, authService: GoogleAuthService.shared) let viewController = storyBoard .instantiateViewController(withIdentifier: loginVCIdentifier) as! LoginController router.viewController = viewController viewController.viewModel = viewModel self.viewController = viewController } } <file_sep>/65-2internship/Common/Helpers/Constants.swift // // Constants.swift // 65-2internship // // Created by <NAME> on 01.11.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation enum Constants { static let kGidId = "981538645674-l1muu2f6k0gh4m5u20eqn89fjsdlgeod.apps.googleusercontent.com" static let kScope = "https://www.googleapis.com/auth/contacts.readonly" static let kStoryboardName = "Main" static let kLaunchStoryboardName = "Launch" static let kLaunchID = "launch" static let kLoginId = "login" static let kContactsId = "contacts" static let kRootId = "root" } <file_sep>/65-2internship/Common/Error/AuthError/AuthErrorExtension.swift // // AuthErrorExtension.swift // 65-2internship // // Created by <NAME> on 13.02.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation extension AuthError : LocalizedError { var errorDescription: String?{ switch self { case .userAuthError: return NSLocalizedString( "Unable authorize, please try again later.", comment: "") } } } <file_sep>/65-2internship/UserStories/LaunchStory/ViewModel/LaunchViewModel.swift // // LaunchViewModel.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation final class LaunchViewModel { private let router: LaunchRouter private let authService: AuthService init(router: LaunchRouter, authService: AuthService) { self.router = router self.authService = authService } func chooseStartStory(){ authService.signInSilently { [router] result in switch result { case .success(): router.showContactsStory() case .failure(_): router.showLoginStory() } } } } <file_sep>/65-2internship/UserStories/LaunchStory/View/LaunchController.swift // // LaunchViewController.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit class LaunchController: UIViewController { var viewModel: LaunchViewModel? override func viewDidLoad() { super.viewDidLoad() viewModel?.chooseStartStory() } } <file_sep>/65-2internship/Networking/Networker.swift // // Networker.swift // 65-2internship // // Created by <NAME> on 01.11.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import GoogleSignIn class Networker { private let service = GoogleAuthService.shared private let urlComponents = URLComponents() private var contactsURL: URL? private let acceptableCodes = [200, 201, 202, 203, 304] //MARK: Private Func private func request(completion: @escaping (Result<Data,NetworkError>)->()) { guard let url = createUrl(withAccessToken: service.accessToken) else { completion(.failure(.noUrl)) return } URLSession.shared.dataTask(with: url) { (data, response, error) in DispatchQueue.main.async { if let _ = error{ completion(.failure(.unableToComplete)) return } if let response = response as? HTTPURLResponse, self.acceptableCodes.contains(response.statusCode) == false { completion(.failure(.wrongRequest(statusCode: response.statusCode))) } guard let data = data else { completion(.failure(.wrongData)) return } completion(.success(data)) } }.resume() } private func createUrl(withAccessToken accessToken: String) -> URL?{ var components = URLComponents() components.scheme = "https" components.host = "www.google.com" components.path = "/m8/feeds/gal/65apps.com/full" components.queryItems = [ URLQueryItem(name: "access_token", value: accessToken), URLQueryItem(name: "alt", value: "json") ] return components.url } //MARK: Public Func func fetchContacts(response: @escaping (ContactsModel?) -> ()) { request() { result in switch result { case .success(let data): do{ let contacts = try JSONDecoder() .decode(ContactsModel.self, from: data) response(contacts) print("Fetched") }catch let jsonError{ print("Decode failed:", jsonError) response(nil) } case .failure(let error): print(error.localizedDescription) response(nil) } } } } <file_sep>/65-2internship/Entities/DataModels/GdOrganization.swift import Foundation struct GdOrganization : Codable { var rel : String? var primary : String? var orgTitle : String? enum OrganizationKeys: String, CodingKey { case rel = "rel" case primary = "primary" case orgTitle = "gd$orgTitle" } enum OrgTitleKeys: String, CodingKey { case post = "$t" } init(from decoder: Decoder) throws { if let organizationContainer = try? decoder.container(keyedBy: OrganizationKeys.self){ rel = try organizationContainer.decodeIfPresent(String.self, forKey: .rel) primary = try organizationContainer.decodeIfPresent(String.self, forKey: .primary) if let orgTitleContainer = try? organizationContainer.nestedContainer(keyedBy: OrgTitleKeys.self, forKey: .orgTitle){ self.orgTitle = try orgTitleContainer.decodeIfPresent(String.self, forKey: .post) } } } } <file_sep>/65-2internship/UserStories/LaunchStory/Router/LaunchRouter.swift // // LaunchRouter.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import Router class LaunchRouter : Router<LaunchController>, ContactsRoute, LoginRoute { } <file_sep>/65-2internship/Entities/DataModels/GdEmail.swift import Foundation struct GdEmail : Codable { let address : String? let primary : String? let rel : String? enum CodingKeys: String, CodingKey { case address = "address" case primary = "primary" case rel = "rel" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) address = try values.decodeIfPresent(String.self, forKey: .address) primary = try values.decodeIfPresent(String.self, forKey: .primary) rel = try values.decodeIfPresent(String.self, forKey: .rel) } } <file_sep>/65-2internship/UserStories/ContactsStories/Router/ContactRouter.swift // // ContactRouter.swift // 65-2internship // // Created by <NAME> on 23.04.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import Router class ContactRouter : Router<ContactTableViewController>, LoginRoute { } <file_sep>/65-2internship/UserStories/LoginStrory/Router/LoginRouter.swift // // LoginRouter.swift // 65-2internship // // Created by <NAME> on 26.01.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Router import Foundation class LoginRouter : Router<LoginController>, AlertRoute, AuthenticationRoute, ContactsRoute { } <file_sep>/65-2internship/UserStories/ContactsStories/ContactsStory.swift // // ContactsStory.swift // 65-2internship // // Created by <NAME> on 31.01.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit struct ContactsStory { let viewController: UIViewController let contactsVCIdentifier = "contacts" init() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let networkService = Networker() let router = ContactRouter() let viewModel = ContactTableViewModelFromEntry(networkService: networkService, authService: GoogleAuthService.shared, router: router) let viewController = storyboard.instantiateViewController(withIdentifier: contactsVCIdentifier) as! ContactTableViewController viewController.viewModel = viewModel self.viewController = UINavigationController(rootViewController: viewController) } } <file_sep>/65-2internship/UserStories/LoginStrory/ViewModel/LoginViewModel.swift // // LoginViewModel.swift // 65-2internship // // Created by <NAME> on 26.01.2021. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit final class LoginViewModel { private let router: LoginRouter private let authService: AuthService init(router: LoginRouter, authService: AuthService) { self.router = router self.authService = authService } func signIn(vc: UIViewController) { authService.signInSilently { [self] result in switch result { case .success(): router.showContactsStory() case .failure(_): router.showAuthenticationStory(authService: authService) { [router] result in switch result { case .success(): router.showContactsStory() case .failure(let error): router.show(title: "Error", message: error.localizedDescription, actions: [("Ok", nil)], animated: true, completion: {}) } } } } } } <file_sep>/65-2internship/Common/Helpers/Dynamic.swift import Foundation /// Класс обеспечивает уведомление View о изменении состояния ViewModel /// /// - note: Подробнее [Web site](https://www.toptal.com/ios/swift-tutorial-introduction-to-mvvm), /// раздел 'Making the ViewModel Dynamic'. /// /// Например: /// **SomeViewModel.swift** /// /// class SomeViewModel() /// Объявление объекта, видимого во View: /// /// let error: Dynamic<Error> { get } /// /// Инициализация пустым значением: /// /// - init() { /// self.error = Dynamic(nil) /// ... /// } /// Измение значения: /// /// func errorReceived(error: NSError) { /// self.error.value = error /// } /// В **SomeViewController.swift** сработает подписка. class Dynamic<T> { typealias Listener = (T) -> () var listener: Listener? /// Метод добавляет подписку на изменение значения наблюдаемго объекта. /// /// - Parameters: /// - listener: Замыкание к событию didSet наблюдаемого объекта. /// /// Например: /// **SomeViewController.swift** /// /// viewModel: SomeViewModel { didSet { /// viweModel.error.bind { [weak self] in error /// print(error) /// } /// .... /// } func bind(_ listener: Listener?) { self.listener = listener } /// Метод добавляет подписку на изменение значения наблюдаемого объекта и тут же выполняет зависимый код. /// /// - Parameters: /// - listener: Замыкание к событию didSet наблюдаемого свойства. /// /// Например: /// **SomeViewController.swift** /// /// viewModel: SomeViewModel { didSet { /// viweModel.error.bindAndFire { [weak self] in error /// print(error) /// } /// .... /// } func bindAndFire(_ listener: Listener?) { self.listener = listener listener?(value) } /// Наблюдаемый объект. var value: T { didSet { listener?(value) } } init(_ v: T) { value = v } /// Принудительно заставляет сработать событие по подписке, как если бы произошел didSet. /// /// - note: /// Полезно, если измение свойств наблюдаемого объекта не привели к возникновению события didSet. func fire() { listener?(value) } /// Обновляет значение без срабатывания триггера. func updateSilently(_ value: T) { let listener = self.listener self.listener = nil self.value = value self.listener = listener } } <file_sep>/65-2internship/Services/GoogleAuthService.swift // // AuthService.swift // 65-2internship // // Created by <NAME> on 29.10.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import GoogleSignIn /// Сервис по работе с авторизацией protocol AuthService { /// AccessToken var accessToken: String { get } /// Тихая авторизация func signInSilently(complition: @escaping (Result<Void, Swift.Error>) -> Void) /// Авторизовать пользователя func signIn(viewController: UIViewController, complition: @escaping (Result<Void, Swift.Error>) -> Void) /// Выход func signOut(complition: @escaping ()-> Void) } final class GoogleAuthService: NSObject, AuthService { static let shared = GoogleAuthService() var accessToken: String { return GIDSignIn.sharedInstance()?.currentUser.authentication.accessToken ?? "" } private var isLoggedIn: ((Result<Void,Error>) -> Void)? private override init() { super.init() GIDSignIn.sharedInstance()?.delegate = self GIDSignIn.sharedInstance()?.clientID = Constants.kGidId } // MARK: - AuthService func signIn(viewController: UIViewController, complition: @escaping (Result<Void, Error>) -> Void) { guard let shared = GIDSignIn.sharedInstance() else { return } shared.scopes = [Constants.kScope] shared.presentingViewController = viewController shared.signIn() isLoggedIn = complition } func signInSilently(complition: @escaping (Result<Void, Error>) -> Void) { guard let shared = GIDSignIn.sharedInstance() else { return } isLoggedIn = complition shared.delegate = self shared.restorePreviousSignIn() } func signOut(complition: @escaping () -> Void) { guard let shared = GIDSignIn.sharedInstance() else { return } shared.signOut() complition() } } extension GoogleAuthService: GIDSignInDelegate{ func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { guard error == nil else { isLoggedIn?(.failure(error)) return } guard user != nil else { return } isLoggedIn?(.success(())) } } <file_sep>/65-2internship/UserStories/ContactsStories/View/Subviews/ContactTableViewCell.swift // // ContactTableViewCell.swift // 65-2internship // // Created by <NAME> on 29.10.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import SDWebImage class ContactTableViewCell: UITableViewCell { @IBOutlet weak var bodyView: UIView! @IBOutlet weak var shadowView: UIView! @IBOutlet weak var contactMail: UILabel! @IBOutlet weak var contactNumber: UILabel! @IBOutlet weak var contactName: UILabel! @IBOutlet weak var contactImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() setupShadowView() setupBodyView() } override func layoutSubviews() { shadowView.layer.shadowPath = UIBezierPath( roundedRect: shadowView.bounds, cornerRadius: 14.0 ).cgPath } private func setupShadowView() { shadowView.backgroundColor = UIColor.clear shadowView.layer.shadowOpacity = 0.1 shadowView.layer.shadowColor = UIColor.gray.cgColor shadowView.layer.shadowRadius = 2.6 shadowView.layer.shadowOffset = CGSize(width: 3, height: 3) } private func setupBodyView() { bodyView.layer.cornerRadius = 14.0 bodyView.clipsToBounds = true } public func configureCell(withContactModel model: ContactsData) { contactMail.text = model.eMail contactNumber.text = model.phoneNumber contactName.text = model.fullName contactImage.sd_setImage(with: model.imgUrl, placeholderImage: UIImage(named: "Image"), options: .allowInvalidSSLCertificates, completed: nil) } } <file_sep>/65-2internship/Common/Routs/AuthenticationRoute.swift // // AuthenticationRoute.swift // 65-2internship // // Created by <NAME> on 11.02.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import Router protocol AuthenticationRoute { func showAuthenticationStory(authService: AuthService, callback: @escaping (Result<Void,Swift.Error>) -> Void) } extension AuthenticationRoute where Self: RouterProtocol{ func showAuthenticationStory(authService: AuthService, callback: @escaping (Result<Void,Swift.Error>) -> Void) { guard let viewController = viewController else { return } authService.signIn(viewController: viewController, complition: callback) } } <file_sep>/65-2internship/UserStories/ContactsStories/View/ContactTableViewController.swift // // ContactTableViewController.swift // 65-2internship // // Created by <NAME> on 29.10.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import SDWebImage class ContactTableViewController: UITableViewController { var viewModel: ContactTableViewModel? var contacts: [ContactsData] = [] { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() viewModel?.dynamicContact.bind { [weak self] contacts in self?.contacts = contacts } viewModel?.fetchContacts() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 200 } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Контакты 65apps" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tableCell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath) let cell = tableCell as! ContactTableViewCell let contact = contacts[indexPath.row] cell.configureCell(withContactModel: contact) return cell } @IBAction func signOut(_ sender: Any) { viewModel?.signOut() } } <file_sep>/65-2internship/Common/Error/NetworkError/NetworkErrorExtension.swift // // ErrorExtension.swift // 65-2internship // // Created by <NAME> on 13.02.2021. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation extension NetworkError : LocalizedError { var errorDescription: String?{ switch self { case .unableToComplete: return NSLocalizedString( "Unable to complete your request. Please check your internet connection.", comment: "") case .wrongRequest(statusCode: let statusCode): return NSLocalizedString( "The call failed with HTTP code: \(statusCode)", comment: "") case .wrongData: return NSLocalizedString( "The data recieved from the server was wrong. Please try again." , comment: "") case .noUrl: return NSLocalizedString( "There is wrong url or url not exist.", comment: "") } } } <file_sep>/65-2internship/Entities/DataModels/Feed.swift import Foundation struct Feed : Codable { let link : [Link]? let openSearchTotalResults : OpenSearchTotalResults? let galSyncToken : GalSyncToken? let galHasNext : GalHasNext? let entry : [Entry]? enum FeedKeys: String, CodingKey { case title = "title" case link = "link" case openSearchTotalResults = "openSearch$totalResults" case galSyncToken = "<PASSWORD>" case galHasNext = "gal$hasNext" case entry = "entry" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: FeedKeys.self) link = try values.decodeIfPresent([Link].self, forKey: .link) openSearchTotalResults = try values.decodeIfPresent(OpenSearchTotalResults.self, forKey: .openSearchTotalResults) galSyncToken = try values.decodeIfPresent(GalSyncToken.self, forKey: .galSyncToken) galHasNext = try values.decodeIfPresent(GalHasNext.self, forKey: .galHasNext) entry = try values.decodeIfPresent([Entry].self, forKey: .entry) } } <file_sep>/65-2internship/Entities/DataModels/VIewData.swift // // VIewData.swift // 65-2internship // // Created by <NAME> on 16.11.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct ContactsData { var fullName: String? var eMail: String? var phoneNumber: String? var imgUrl: URL? }
f2db1ac57d9ba7b4964ce9805097ba118a0bf94f
[ "Swift" ]
32
Swift
KisaShket/internship65
149b8258ff700f2b0cdf100aca7e97c2c00dd81a
73a03fab1d08f462096c8e3b7f8660cfb6f9acdd
refs/heads/main
<file_sep>"use strict"; const init = document.getElementById('init'); const load = document.getElementById('load'); const carousel = document.createElement("main"); let carousel_fragment = document.createDocumentFragment(); carousel.classList.add("scroll-container"); load.addEventListener('change', read_file); let progress = document.getElementById("progress"); let sections = []; let current_section = 0; const prev = document.createElement("button"); const next = document.createElement("button"); async function createFile(path){ let response = await fetch(path); let data = await response.blob(); let metadata = { type: 'text/plain' }; let file = new File([data], path, metadata); let reader = new FileReader(); reader.onload = process_file; reader.readAsText(file); } function read_file() { // document.body.requestFullscreen(); let reader = new FileReader(); reader.onload = process_file; reader.readAsText(this.files[0]); } function process_file(data) { // let user know of potentially slow operation alert("Loading... This could take a few seconds"); let text = data.target.result; // split on new lines and shuffle let lines = text.split("\n").sort(() => Math.random() - 0.5); //.filter(entry => /\S/.test(entry))); // create sections let i = 0; for (const line of lines) { let content = []; // check prefix and format section appropriately if (line.slice(0, 6).toLowerCase() == "taboo:") { let length = 6; if (line[length] == " ") length += 1; content = line.slice(length).split(",").map(item => item.trim()); } else { // just forward the section on as content content.push(line); } // create flashcards sections.push(create_flashcard(content, i++, i * 137.5 % 360)); } // add lazy loading const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { let section = entry.target; if (entry.intersectionRatio >= 0.25) { section.firstElementChild.style.opacity = 1; current_section = parseInt(section.id.slice(8)); } else { section.firstElementChild.style.opacity = 0; } }) }, { rootMargin: '0px', threshold: 0.25 }); sections.forEach((section, index) => { carousel_fragment.appendChild(section); observer.observe(section); }); // create scroll buttons prev.className = "arrow left"; prev.onclick = () => carousel.scroll(carousel.scrollLeft - window.innerWidth, 0); next.className = "arrow right"; next.onclick = () => carousel.scroll(carousel.scrollLeft + window.innerWidth, 0); const show_hide_arrows = () => { if (carousel.scrollLeft < window.innerWidth) { window.requestAnimationFrame(() => { prev.style.opacity = 0.2; prev.disabled = true; }); } else { window.requestAnimationFrame(() => { prev.style.opacity = 1; prev.disabled = false; }); }; if (carousel.scrollLeft >= carousel.scrollWidth - window.innerWidth) { window.requestAnimationFrame(() => { next.style.opacity = 0.2 next.disabled = true; }); } else { window.requestAnimationFrame(() => { next.style.opacity = 1 next.disabled = false; }); }; }; carousel.addEventListener("scroll", show_hide_arrows); document.body.appendChild(prev); document.body.appendChild(next); // signal completion carousel.appendChild(carousel_fragment); document.body.removeChild(init); document.body.appendChild(carousel); window.screen.orientation.lock("landscape").catch((e)=>{}); document.body.requestFullscreen(); // resize the text once it´s been added to DOM sections.forEach( (element) => window.fitText(element) ); // update the arrows show_hide_arrows(); } function create_flashcard(content, i, hue) { let section = document.createElement("section"); section.id = `section-${i}`; section.style.background = `linear-gradient(to top, hsl(${hue},50%,66%) 0%, hsl(0,0%,66%) 100%)`; if (content.length > 1) { // the first is the title, the rest are sub let innerHTML = "<div style='width: 88%;' class='content'><dl><dt>" + content[0] + "</dt></dl><ul>"; for (let i = 1; i < content.length; i++) { innerHTML += "<li>" + content[i] + "</li>"; } innerHTML += "</ul></div>"; section.innerHTML = innerHTML; } else { // single index array, regular flashsection section.innerHTML = `<div class='content'>${content[0]}</div>`; } return section; } // INPUT (function detectSwipe(){ let touchstartX = 0, touchstartY = 0, touchendX = 0, touchendY = 0; window.addEventListener('touchstart', function(event) { touchstartX = event.changedTouches[0].screenX; touchstartY = event.changedTouches[0].screenY; // document.documentElement.requestFullscreen(); }); window.addEventListener('touchend', function(event) { const SENSITIVITY = 25; touchendX = event.changedTouches[0].screenX; touchendY = event.changedTouches[0].screenY; // determine horizontal swipe if (Math.abs(touchstartX - touchendX) > SENSITIVITY) touchendX > touchstartX ? swipe(-1) : swipe(1); }); })(); document.addEventListener('wheel', e => { console.log('wheel'); e.deltaY < 0 ? swipe(-1) : swipe(1); }); function swipe(direction) { window.requestAnimationFrame(()=>sections[current_section + direction].scrollIntoView({behavior: "smooth"})); }
cf0cb6e10a90dce9b210193b0cb92a63574b1ba2
[ "JavaScript" ]
1
JavaScript
arifd/flashcards
8a4e665bea8b55bb7464c2b21d3fb04855114b73
11510ace16f38a5f874c1631e72ee87744a22e69
refs/heads/master
<file_sep>import logging.config from logging import FileHandler, StreamHandler import os.path #LOGS Configuration default_formatter = logging.Formatter(\ "%(asctime)s:%(levelname)s:%(message)s") console_handler = StreamHandler() console_handler.setFormatter(default_formatter) error_handler = FileHandler("log/error.log", "a") error_handler.setLevel(logging.ERROR) error_handler.setFormatter(default_formatter) root = logging.getLogger() root.addHandler(console_handler) root.addHandler(error_handler) root.setLevel(logging.DEBUG) def set_log_config(): LOGGING_CONF=os.path.join(os.path.dirname(__file__), "logging.ini") logging.config.fileConfig(LOGGING_CONF) if __name__ == '__main__': set_log_config() <file_sep># Coucbase to ElasticSearch data pipeline Bare data pipepline ## Getting Started - [x] MacOS based machine. - [ ] Linux based machine --TODO. ### Prerequisites 1. Use python > 3.6 2. Add python to path 3. Install libraries ``` brew update # get list of latest packages brew install libcouchbase brew install python pip install couchbase ``` 4. Install python environment manager ``` python3 -m pip install virtualenv ``` ### Running the Program 1. Create a specific python version for virtual environment ``` virtualenv --python=<path_to>/python3.6 <virtaul_env_folder_name> ``` 2. Activate virtual environment ``` source <path>/bin/activate ``` 3. Rename the file settings/config.template.py to template.py 4. Run program ``` python ./main.py ``` ## Running the tests TODO ## Deployment TODO ## Built With None ## Contributing None ## Versioning 0.0.1 ## Authors * **<NAME>** ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details ## Acknowledgments * Open Source Community <file_sep>import settings.config from lib.couchBase import SyncGatewayConnect, N1QLConnect from lib.elasticSearch import ElasticsearchConnect from lib.transform import CurisV2ETL cb_ENV = 'dev' es_ENV = 'local' cb = settings.config.CouchbaseConfig[cb_ENV] es = settings.config.ElasticSearchConfig[es_ENV] CB_CONNECTION = cb cbs = SyncGatewayConnect(CB_CONNECTION) cbs_data = cbs.get_all() cb = N1QLConnect(CB_CONNECTION) cb_data = cb.get_all() etl = CurisV2ETL() es_data = etl.map_address(cb_data) ES_CONNECTION = es es = ElasticsearchConnect(ES_CONNECTION) es.bulk_dump(es_data) <file_sep>import sys import json import time import requests from couchbase.bucket import Bucket from couchbase.n1ql import N1QLQuery, N1QLError from couchbase.exceptions import CouchbaseTransientError, CouchbaseNetworkError from requests.exceptions import RequestException from log.config import set_log_config, logging logger = logging.getLogger("couchbase.connection") class SyncGatewayConnect: def __init__(self, conn, **kwargs): self._bucket = conn['BUCKET'] self._url = conn['HOST'] + conn['BUCKET'] self._ip_address = conn['IP'] self._timeout = conn['TIMEOUT'] def get_all(self): headers = self._conn_headers() filters = self._conn_filters() url = self._conn_config() try: r = requests.get(url, headers = headers, params=filters) logger.info(r.status_code) logger.info(r.elapsed.total_seconds()) except RequestException as err: logger.error(err) def _conn_headers(self, *kwargs): return { "accept": "application/json", "allow_redirects": "True", "timeout": str(self._timeout), } def _conn_filters(self, *kwargs): return { "access" : "false", "channels": "false", "include_docs": "true", "revs": "false", "update_seq": "false", "limit": "10" } def _conn_config(self, *kwargs): ip_address = self._ip_address bucket = self._bucket scheme = "http" port = "4984" api_endpoint = "_all_docs?" return scheme + "://" + ip_address + ":" + port + "/" + bucket + "/" + api_endpoint def get_changes(self): pass def find(self): pass class N1QLConnect: def __init__(self, conn, *args,**kwargs): self._bucket = conn['BUCKET'] self._url = conn['HOST'] + conn['BUCKET'] self._timeout = conn['TIMEOUT'] def get_all(self): try: bucket = Bucket(self._url) bucket.n1ql_timeout = self._timeout script = self._set_query() query = N1QLQuery(script) query.timeout = self._timeout res = bucket.n1ql_query(query) logger.info(res) return self._dict2json(res) except CouchbaseTransientError as err: logger.error(err) except CouchbaseNetworkError as err: logger.error(err) def _set_query(self, **kwargs): return ("SELECT meta("+self._bucket+").id as cb_id, " + self._bucket + ".* FROM " + self._bucket +" limit 10") def _dict2json(self, results): counter = 0 data = [] for row in results: data.append(json.dumps(row)) counter += 1 logger.info(counter) return data <file_sep>import sys import uuid import json import logging import mappings.schema from elasticsearch import Elasticsearch from elasticsearch.exceptions import ConnectionError from log.config import set_log_config, logging logger = logging.getLogger("elasticsearch.connection") class ElasticsearchConnect: def __init__(self, conn, *args,**kwargs): self._index = conn['INDEX'] self._doc_type = conn['TYPE'] self._es = Elasticsearch( conn['HOST'], http_auth=(conn['USERNAME'],conn['PASSWORD']), scheme=conn['SCHEME'], port=conn['PORT'], timeout=conn['TIMEOUT']) def batch_dump(self, docs): self._set_mappings() counter = 0 try: for doc in docs: res = self._es.index(index = self._index, doc_type = self._doc_type, id = uuid.uuid1(), body = doc) counter += 1 self._total_entries(counter) self._es.indices.refresh(index=self._index) self._refresh_index() except ConnectionError as err: logger.error(error) def bulk_dump(self, docs): self._set_mappings() counter = 0 bulk_data = [] try: for doc in docs: _header = { "create" : { "_index" : self._index, "_type" : self._doc_type, "_id" : str(uuid.uuid1()) } } bulk_data.append(json.dumps(_header)) bulk_data.append(doc) counter += 1 self._total_entries(counter) return self._es.bulk(bulk_data) except ConnectionError as err: logger.error(error) def get_total(self): try: query = self._es.search(index = self._index, body = {"query": {"match_all": {}}}) print("Total Elastic records %d Hits:" % query['hits']['total']) except ConnectionError as err: logger.error(error) def _set_mappings(self): body = mappings.schema.elastic_mapping if self._es.indices.exists(self._index): logger.debug("index exists") else: try: res = self._es.indices.create(index = self._index, body = json.dumps(body)) print(" response: '%s'" % (res)) if res["acknowledged"] != True: logger.info("Index creation failed") else: logger.info("Index created") except ConnectionError as err: logger.error(err) def _refresh_index(self): return self._es.indices.refresh(index=self._index) def _total_entries(self, count): print("Total Batch Entries: {%}", count) <file_sep>import sys CouchbaseConfig = { 'local': { 'BUCKET': 'awhcurisdb_dev', 'USERNAME': '', 'PASSWORD': '', 'HOST': 'couchbase://127.0.0.1/', 'PORT': '', 'TIMEOUT': 7200 }, 'dev': { 'BUCKET': '', 'USERNAME': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TIMEOUT': 7200 }, 'uat': { 'BUCKET': '', 'USERNAME': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TIMEOUT': 7200 }, 'prod': { 'BUCKET': '', 'USERNAME': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TIMEOUT': 7200 } } ElasticSearchConfig = { 'local': { 'USERNAME': '', 'PASSWORD': '', 'INDEX': 'philippines', 'TYPE': 'patients', 'SCHEME': 'HTTP', 'HOST': 'localhost', 'PORT': 9200, 'TIMEOUT': 7200 }, 'dev': { 'USERNAME': '', 'PASSWORD': '', 'INDEX': 'philippines', 'TYPE': 'patients', 'SCHEME': 'HTTP', 'HOST': 'localhost', 'PORT': 9200, 'TIMEOUT': 7200 }, 'prod': { 'USERNAME': '', 'PASSWORD': '', 'INDEX': 'philippines', 'TYPE': 'patients', 'SCHEME': 'HTTP', 'HOST': 'localhost', 'PORT': 9200, 'TIMEOUT': 7200 } } <file_sep>import sys import json from collections import namedtuple from log.config import set_log_config, logging logger = logging.getLogger("transform.etl") class CurisV2ETL: def __init__(self): pass def pipeline(self,data): #TODO insert all pipeline here return data def map_address(self, documents): #TODO map json to object counter = 0 els_data = [] if not documents: raise TypeError("no value") else: for doc in documents: x = self._json2obj(str(doc)) try: address = { "address" : { "community" : x.address.barangay, "province": x.address.province, "zip" : x.address.postal_code } } except AttributeError: address = { "address" : { "community" : "", "province": "" , "zip" : "" } } els_data.append(json.dumps(address)) counter += 1 return els_data def compute_birthdate(self, datas): pass def _json2obj(self, data): return json.loads(data, object_hook = self._json_object_hook) def _json_object_hook(self, d): return namedtuple('X', d.keys(), rename = True)(*d.values())
cee8e4174d22e5d03b1065a4a685e2161fbf1754
[ "Markdown", "Python" ]
7
Python
philipsales/airflow-couchbase-elasticsearch
f9bf06d88956d3e2322a7dfa6207becbdc1d1769
911850d6328077361252ab5fbc7738726334892e
refs/heads/master
<repo_name>yusadogru/Challenges<file_sep>/Palindromes.playground/Contents.swift // Challenge: Write code that will evaluate if all the elements in the list are palindromes using Swift // e.g. racecar reveresed is still racecar // // Palindrome: a word or phrase that can be read the same way forwards and backwards // Relevant Reading: https://en.wikipedia.org/wiki/Palindrome // import Foundation let list = ["racecar", "codilitytilidoc", "neveroddoreven", "Don't nod.", "I did, did I?", "My gym", "Red rum, sir, is murder", "Step on no pets", "Top spot", "Was it a cat I saw?", "Eva, can I see bees in a cave?", "No lemon, no melon" ] /// Solution 1 func isPalindrome(_ sentence: String) -> Bool { var set = Set<Character>() sentence.forEach { ch in if set.contains(ch) { set.remove(ch) } else { set.insert(ch) } } return set.count <= 1 } /// Solution 2 func isPalindrome2(_ sentence: String) -> Bool { var set = Set<Character>() sentence.forEach { ch in set.insert(ch) } let halfOfSentenceCount = Float(sentence.count)/2 return set.count <= lroundf(halfOfSentenceCount) } /// Solution 3 func isPalindrome3(_ sentence: String) -> Bool { var set = Set<Character>() return sentence.filter{ set.insert($0).inserted }.count <= lroundf(Float(sentence.count)/2) } // Is entire list Palindrome? print(list.reduce(true) { $0 && isPalindrome($1) }) print("\n---- Solution 1 -----\n") list.forEach { string in print("Is \"\(string)\" Palindrome ? - \(isPalindrome(string))") } print("\n---- Solution 2 -----\n") list.forEach { string in print("Is \"\(string)\" Palindrome ? - \(isPalindrome2(string))") } print("\n---- Solution 3 -----\n") list.forEach { string in print("Is \"\(string)\" Palindrome ? - \(isPalindrome3(string))") } <file_sep>/CalculateArea.playground/Contents.swift import Foundation import XCTest // Calculate total area of two rectangles // // ______________(R,S) // | | // _____|_____(M,N) | // | | | | // | |____|_______| // | (P,Q) | // | | // |_________| // (K,L) // // K < M, L < N, P < R, Q < S func calculateArea(K: Int, L: Int, M: Int, N: Int, P: Int, Q: Int, R: Int, S: Int) -> Int { let area = abs(M - K) * abs(N - L) let arae2 = abs(P - R) * abs(Q - S) let x1 = max(K, P) let x2 = min(M, R) let y1 = max(L, Q) let y2 = min(N, S) var intersectionArea = 0 if x1 < x2 && y1 < y2 { intersectionArea = abs(x2 - x1) * abs(y2 - y1) } let totalArea = area + arae2 - intersectionArea return totalArea } // MARK: Test class Tests: XCTestCase { func testCalculateArea() { var area = calculateArea(K: 5, L: 5, M: 15, N: 15, P: 10, Q: 10, R: 20, S: 20) XCTAssertEqual(area, 175) area = calculateArea(K: 5, L: 5, M: 15, N: 15, P: 25, Q: 10, R: 30, S: 20) XCTAssertEqual(area, 150) area = calculateArea(K: -5, L: 5, M: 5, N: 15, P: 0, Q: 10, R: 10, S: 20) XCTAssertEqual(area, 175) area = calculateArea(K: -10, L: -10, M: 20, N: 20, P: 0, Q: 0, R: 10, S: 10) XCTAssertEqual(area, 900) area = calculateArea(K: -10, L: -10, M: 20, N: 20, P: 20, Q: -10, R: 50, S: 20) XCTAssertEqual(area, 1800) area = calculateArea(K: 5, L: -15, M: 10, N: -5, P: 7, Q: -20, R: 9, S: -10) XCTAssertEqual(area, 60) } } Tests.defaultTestSuite.run()
761ba00bd7e18d02743dd8aa2953395cdbf4620b
[ "Swift" ]
2
Swift
yusadogru/Challenges
6cbc6deaee2498fda246f61e686819ba2aa31c0e
d67bf40aa0fac114a1c8ee6a80ba1c8be6bbbab0
refs/heads/master
<file_sep>CREATE TABLE nodes ( id integer primary key, path integer[] ); -- node1(root) -- ->node2 -- | ->node5 -- | | -- ->node3 -- | ->node6 -- | | ->node8 -- | | | -- | ->node7 -- | ->node9 -- | ->mode10 -- | ->node11 -- | ->node12 -- ->node4 INSERT INTO nodes VALUES (1, ARRAY[1]), (2, ARRAY[1,2]), (3, ARRAY[1,3]), (4, ARRAY[1,4]), (5, ARRAY[1,2,5]), (6, ARRAY[1,3,6]), (7, ARRAY[1,3,7]), (8, ARRAY[1,3,6,8]), (9, ARRAY[1,3,7,9]), (10, ARRAY[1,3,7,9,10]), (11, ARRAY[1,3,7,9,11]), (12, ARRAY[1,3,7,9,12]); <file_sep># RESTful API with Node.js, Express and Postgres running in Docker Create, read and update in a Node.js app with an Express server and Postgres database. The app is running in Docker container. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ## Prerequisites To run this project, you need to have: ``` Docker for Desktop ``` You can download here: https://www.docker.com/ ## Installing and Running * `git clone <EMAIL>:SoutisV/RESTful_api_Docker.git` * `cd root_directory_of_project` * `sudo docker-compose up --build` The `sudo docker-compose up --build` will bring up the RESTful API and the Postgres database. ## Building details In `docker-compose.yml` we set up two services named `api` and `postgres`. The `api` is dependent on `postgres`. In `docker-compose.yml` we also use a volume named `my_dbdata` for storing the database data. Even if the container and image are deleted, the volume will remain unless explicitly deleted using `sudo docker system prune --volumes`. Also, during this very first build of the application, an initialization script is used for the db. It is located again in `docker-compose.yml`, it is called `init.sql` and it runs only during the first build. If you want to re-populate the Postgres db you have to delete the volume with `sudo docker system prune --volumes` and bring up the project again with `sudo docker-compose up`. The state of the db after the `init.sql` looks like this: [initial_state](https://github.com/SoutisV/RESTful_api_Docker/blob/master/init_db.png) ## GET Routes * visit http://localhost:3000 , where also the README file is present. * `/nodes` , lists all available nodes * `/node/:id` , list info of specified node * `/children/:id` , list children of specified node * `/descendants/:id` , list all descendants of specified node ## Running GET requests For my GET requests i used `postman` : https://www.getpostman.com/downloads/ . Alternatively, you can visit in the web browser also the following URLs: * `http://localhost:3000/nodes` , lists all available nodes * `http://localhost:3000/node/9` , lists info regarding node 9 * `http://localhost:3000/children/3` , lists all children of node 3 (node6 and node7 of the initialized db) * `http://localhost:3000/descendants/3` , lists all descendants of node3 (node3,node6,node7,node8,node9,node10,node11 and node12 of the initialized db). The difference between `GET /children/:id` and `GET /descendants/:id` is that the first one returns only the children of the specified node whereas the second one returns the children of a node together with all the descendants of the children of a node. You can also curl the requests from the terminal: * `curl -v http://localhost:3000/nodes` * `curl -v http://localhost:3000/node/9` * `curl -v http://localhost:3000/children/3` * `curl -v http://localhost:3000/descendants/3` ## PUT Route * `/nodes/:id` , update an existing node and put it under a new parent. It is worth noting that `PUT` is idempotent, meaning the exact same call can be made over and will produce the same result. This is different that `POST`, in which the exact same call repeated will continuously create new nodes. Also, when a node is updated and moved under a new parent, it's descendants are also moved and dynamically adjusted with new height. Let's do our first update... ## Running our first PUT request In case you want to use `postman`: * URL: `http://localhost:3000/nodes/7` * Method: `PUT` * Body: `x-www-form-urlencoded` * Body Key: `new_parent` * Body Key Value: `8` In case you want to use curl from terminal: * `curl -v -X PUT -d "new_parent=8" http://localhost:3000/nodes/7` This method will move node 7 and all it's descendants under node 8. Heights will be adjusted. Here is how it looks like now: [update_state](https://github.com/SoutisV/RESTful_api_Docker/blob/master/update_db.png) You can check it: * `curl -v http://localhost:3000/descendants/8` ## POST Route * `/nodes` , will create a new node under an existing parent. If a new parent is not provided then, the new node will be added as root. ## Running our first POST request In case you want to use `postman`: * URL: `http://localhost:3000/nodes` * Method: `POST` * Body: `x-www-form-urlencoded` * Body Key: `new_node` * Body Key Value for new_node: `13` * Body Key: `new_parent` * Body Key Value for new_parent: `8` In case you want to use curl from terminal: * `curl -v -d "new_node=13" -d "new_parent=8" http://localhost:3000/nodes` This method will add a new node 13 under existing node 8. Here is how it looks like now: [post_state](https://github.com/SoutisV/RESTful_api_Docker/blob/master/post_db.png) You can check it: * `curl -v http://localhost:3000/descendants/8` ## Running POST request for adding a new root In case you want to use `postman`: * URL: `http://localhost:3000/nodes` * Method: `POST` * Body: `x-www-form-urlencoded` * Body Key: `new_node` * Body Key Value for new_node: `55` In case you want to use curl from terminal: * `curl -v -d "new_node=55" http://localhost:3000/nodes` As you can notice there is no body key `new_parent`. That means a new node 55 is added as root! This method will add a new node 55 as root. Here is how it looks like now: [root_state](https://github.com/SoutisV/RESTful_api_Docker/blob/master/root_db.png) You can check it: * `curl -v http://localhost:3000/descendants/55` , which is the same as * `curl -v http://localhost:3000/nodes` ## Docker commands that might come handy All docker commands must be executed from the project directory. * `sudo docker-compose up --build` , run the project and build a new image * `sudo docker-compose up ` , run the project without building a new image * `sudo docker system prune --volumes` , deletes all volumes. Useful when you want to run the `init.sql` and re-populate the db with initial data. * `sudo docker image prune -a`, remove all docker images * `sudo docker container ls -a`, list all docker containers * `sudo docker images -a`, list all docker images Each time you want to run the project: * `sudo docker-compose up ` , inside the project directory <file_sep>const Pool = require('pg').Pool const pool = new Pool({ user: 'user', database: 'db', password: '<PASSWORD>', host: 'postgres', port: 5432 }) const length = 'array_length(path,1)-1' //length of the actual path -1, to identify the parent and also the actual height //GET method to list all nodes const getNodes = (request, response) => { pool.query('SELECT id, path[1] AS root, path['+length+'] as parent, '+length+' as height FROM nodes;', (error, results) => { if (error) { throw error } response.status(200).json(results.rows) }) } //GET method to get the info of a node const getNodeById = (request, response) => { const id = parseInt(request.params.id) pool.query('SELECT id, path[1] AS root, path['+length+'] as parent, '+length+' as height FROM nodes WHERE id=$1;', [id], (error, results) => { if (error) { throw error }else{ if(results.rows.length > 0){ response.status(200).json(results.rows) }else{ response.status(200).send('Given node does not exist! Please provide an existing one!!') } } }) } //GET method to list all children of specific node const getChildrenById = (request, response) => { const id = parseInt(request.params.id) var depth; pool.query('SELECT array_length(path,1) as depth FROM nodes WHERE id = $1;', [id], (error, results) => { if (error) { throw error }else{ if(results.rows.length > 0){ depth = results.rows[0].depth + 1 // we know there is only one match - children would be in +1 position and only!!!! pool.query( 'SELECT id, path[1] AS root, path['+length+'] as parent, '+length+' height FROM nodes WHERE ((path && ARRAY[$1]::integer[]) AND (array_length(path,1) = $2));',[id,depth],function(error,results) { if(error){ throw error }else{ response.status(200).json(results.rows) } }) }else{ response.status(200).send('Given node does not exist! Please provide an existing one!!') } } }) } //GET method to list all descendants of specific node const getDescendantsById = (request, response) => { const id = parseInt(request.params.id) pool.query('SELECT id, path[1] AS root, path['+length+'] as parent, '+length+' as height FROM nodes WHERE path && ARRAY[$1]::integer[];', [id], (error, results) => { if (error) { throw error }else{ if(results.rows.length > 0){ response.status(200).json(results.rows) }else{ response.status(200).send('Given node does not exist! Please provide an existing one!!') } } }) } //PUT method to update existing node and move it under new parent const updateNode = (request, response) => { const id = parseInt(request.params.id) const { new_parent } = request.body var new_parent_path,given_node_depth //get the path of the new parent pool.query('SELECT path FROM nodes WHERE id = $1;',[new_parent],function(error,results) { if(error){ throw error }else{ if(results.rows.length > 0){ new_parent_path = results.rows[0].path; // there is only one match //get the depth of the given_node pool.query('SELECT array_length(path,1) as depth FROM nodes WHERE id = $1;',[id],function(error,results) { if(error){ throw error }else{ if(results.rows.length > 0){ given_node_depth = results.rows[0].depth; // there is only one match //path of new parent and depth of given node are used to update pool.query('UPDATE nodes SET path = ARRAY['+new_parent_path+'] || path['+given_node_depth+':array_length(path,1)]::integer[] WHERE path && ARRAY[$1]::integer[];',[id],function(error,results) { if(error){ throw error }else{ console.log(`Node with ID: ${id} moved under parent with ID: ${new_parent}`) response.status(200).send(`Node with ID: ${id} moved under parent with ID: ${new_parent}. You can check here: curl http://localhost:3000/node/${id}`) } }) }else{ console.log('Given node does not exist! Please provide an existing one!!') response.status(200).send('Given node does not exist! Please provide an existing one!!') } } }) }else{ console.log('Given parent node does not exist! Please provide an existing one!!') response.status(200).send('Given parent node does not exist! Please provide an existing one!!') } } }) } //POST method to insert a new node const createNode = (request, response) => { const { new_node, new_parent } = request.body if(new_parent == null){ // insert as root pool.query('INSERT INTO nodes VALUES ($1, ARRAY[$1]::integer[]) ON CONFLICT (id) DO NOTHING;',[new_node],function(error,results) { if(error){ throw error }else{ //new root node is added and we need to updade the rest of nodes pool.query( 'UPDATE nodes SET path = ARRAY[$1]::integer[] || path WHERE $1 != ALL(path);',[new_node],function(error,results) { if(error){ throw error }else{ console.log('Insert successful!!') //the status of 201 is meant for the successful insert and NOT for the update of the rest of the nodes!!!! response.status(201).send(`Root Node with ID: ${new_node} is successfuly inserted.If you tried to insert an existing node, then the INSERT is not executed.ON CONFLICT we do nothing. You can check here: curl http://localhost:3000/node/${new_node}`) } }) } }) }else { //find the path of the father pool.query('SELECT path FROM nodes WHERE id = $1;',[new_parent],function(error,results) { if(error){ throw error }else{ if(results.rows.length > 0){ parent_path = results.rows[0].path ; //insert as child to a parent pool.query('INSERT INTO nodes VALUES ($1, ARRAY['+parent_path+'] || ARRAY[$1]::integer[]) ON CONFLICT (id) DO NOTHING;',[new_node],function(error,results) { if(error){ throw error }else{ //new node is added console.log('Insert successful!!') response.status(201).send(`New Node with ID: ${new_node} is successfuly inserted.If you tried to insert an existing node, then the INSERT is not executed.ON CONFLICT we do nothing. You can check here: curl http://localhost:3000/node/${new_node}`) } }) }else{ console.log('Given parent node does not exist! Please provide an existing one!!') response.status(200).send('Given parent node does not exist! Please provide an existing one!!') } } }) } } module.exports = { getNodes, getNodeById, getChildrenById, getDescendantsById, updateNode, createNode, }
a6d0336d4897f6141a5d408a211c914a1b14df16
[ "Markdown", "SQL", "JavaScript" ]
3
SQL
SoutisV/RESTful_api_Docker
9c19f81e695ad555495ab9a04ae52bb0fa48bed3
8d447ad436c119fd8ac2544921538206ce11c610
refs/heads/master
<repo_name>Barney117/AAL-Assistant<file_sep>/android relay/AALassistant/app/src/main/java/com/example/aal_assistant/locationCon.java package com.example.aal_assistant; public class locationCon { static double latitude; static double longitude; static String address; public locationCon() { } public locationCon(double latitude, double longitude, String address) { this.latitude = latitude; this.longitude = longitude; this.address = address; } public static double getLatitude() { return latitude; } public static double getLongitude() { return longitude; } public static String getAddress() { return address; } }<file_sep>/android relay/AALassistant/app/src/main/java/com/example/aal_assistant/sensor.java package com.example.aal_assistant; public class sensor { double X_data, Y_data, Z_data; private String Time; public sensor() { } /** * Constructor for a basic measurement. * * @param X_data the x axis acceleration * @param Y_data the y axis acceleration * @param Z_data the z axis acceleration * */ public sensor(double X_data, double Y_data, double Z_data) { this.X_data = X_data; this.Y_data = Y_data; this.Z_data = Z_data; } public double getCombined() { return Math.sqrt(X_data * X_data + Y_data * Y_data + Z_data * Z_data); } } <file_sep>/android relay/AALassistant/app/src/main/java/com/example/aal_assistant/representations.java package com.example.aal_assistant; public class representations { public static double[] convertAccelerometerdata(byte[] value) { final float G_UNIT = 32768 / 8; int X = (value[7] << 8) + value[6]; int y = (value[9] << 8) + value[8]; int z = (value[11] << 8) + value[10]; return new double[]{((X / G_UNIT) * -1), y / G_UNIT, ((z / G_UNIT) * -1)}; } } <file_sep>/android relay/AALassistant/app/src/main/java/inter/updateAction.java package inter; public interface updateAction { void onListFragmentInteraction(String address); void onShowProgress(); void onHideProgress(); }<file_sep>/README.md # AAL-Assistant <file_sep>/android relay/AALassistant/app/src/main/java/com/example/aal_assistant/MainActivity.java package com.example.aal_assistant; import android.Manifest; import android.content.DialogInterface; import android.support.v4.app.ActivityCompat; import android.content.Intent; import android.content.pm.PackageManager; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements inter.updateAction { private static final int PERMISSIONS_REQUEST = 100; private Fragment currentFragment; private FragmentManager fragmentManager; private SwipeRefreshLayout refresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); refresh = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); refresh.setEnabled(false); // exit if the device doesn't have BLE if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.no_ble, Toast.LENGTH_SHORT).show(); finish(); } //Check whether GPS tracking is enabled// LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { } //Check whether this app has access to the location permission// int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); //If the locationCon permission has been granted, then start the TrackerService// if (permission != PackageManager.PERMISSION_GRANTED) { //If the app doesn’t currently have access to the user’s locationCon, then request access// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST); } fragmentManager = getSupportFragmentManager(); currentFragment = Accelerometer_frag.newInstance("54:6C:0E:53:01:1B"); //enter MAC fragmentManager.beginTransaction().replace(R.id.container, currentFragment).commit(); } @Override public void onListFragmentInteraction(String address) { currentFragment = Accelerometer_frag.newInstance(address); } @Override public void onShowProgress() { runOnUiThread(new Runnable() { @Override public void run() { refresh.setRefreshing(true); } }); } @Override public void onHideProgress() { runOnUiThread(new Runnable() { @Override public void run() { refresh.setRefreshing(false); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_about: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.about_title); builder.setMessage(R.string.about_message); builder.setNegativeButton(R.string.github, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(getString(R.string.github_url))); startActivity(intent); } }); builder.setPositiveButton(R.string.close, null); builder.show(); break; } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSIONS_REQUEST && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText(this, "Please enable location to allow tracking", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.information, menu); return super.onCreateOptionsMenu(menu); } } <file_sep>/android relay/AALassistant/app/src/main/java/com/example/aal_assistant/Accelerometer_frag.java package com.example.aal_assistant; import android.content.Intent; import android.support.v4.app.Fragment; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Calendar; import java.util.UUID; public class Accelerometer_frag extends Fragment { private DatabaseReference databaseReference; locationCon mloc = new locationCon(); private static final String Address = "Address"; private String macAddress; private boolean isConnected = true; private inter.updateAction Listener; private Calendar lastVal; private static double L1, L2; private String locAddress; private BluetoothAdapter BluetoothAdapter; private BluetoothGatt gattProfile; private BluetoothGattService gattService; private BluetoothGattCharacteristic ReadCharacteristic, Start, Time; private TextView xAxis, yAxis, zAxis, lat, lon, textAddress; public Accelerometer_frag() { } /** * Returns a new instance of this Fragment. * * @param address the MAC address of the device to connect * @return A new instance of {@link Accelerometer_frag} */ public static Accelerometer_frag newInstance(String address) { Accelerometer_frag fragment = new Accelerometer_frag(); Bundle args = new Bundle(); args.putString(Address, address); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { macAddress = getArguments().getString(Address); } databaseReference = FirebaseDatabase.getInstance().getReference(); BluetoothManager manager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter = manager.getAdapter(); } @Override public void onResume() { super.onResume(); connectToSensor(macAddress); } @Override public void onPause() { deviceDisconnected(); super.onPause(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof inter.updateAction) { Listener = (inter.updateAction) context; } else { throw new RuntimeException(context.toString() + " must implement OnStatusListener"); } } private void connectToSensor(String address) { if (!BluetoothAdapter.isEnabled()) { BluetoothAdapter.getDefaultAdapter().enable(); Toast.makeText(getActivity(), R.string.enable, Toast.LENGTH_SHORT).show(); getActivity(); } Listener.onShowProgress(); BluetoothDevice device = BluetoothAdapter.getRemoteDevice(address); gattProfile = device.connectGatt(getActivity(), true, callback); } private void deviceConnected() { startTrackerService(); Listener.onHideProgress(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { } }); // start connection watcher thread new Thread(new Runnable() { @Override public void run() { boolean Connected = true; while (Connected) { long diff = Calendar.getInstance().getTimeInMillis() - lastVal.getTimeInMillis(); if (diff > 2000) { Connected = false; stopTrackerService(); new Thread(new Runnable() { @Override public void run() { } }); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } private void startTrackerService() { getContext().startService(new Intent(getContext(), location_service.class)); } public void stopTrackerService() { getContext().stopService(new Intent(getContext(), location_service.class)); } private void deviceDisconnected() { if (gattProfile != null) gattProfile.disconnect(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.accelerometer_fragment, container, false); xAxis = layout.findViewById(R.id.XAxis); yAxis = layout.findViewById(R.id.YAxis); zAxis = layout.findViewById(R.id.ZAxis); lat = layout.findViewById(R.id.latitude); lon = layout.findViewById(R.id.longitude); textAddress = (TextView) layout.findViewById(R.id.StringAdd); return layout; } /** * makes connection with the gatt profile of the CC2650 * requests connection * Looks for Accelerometer * Reads Accelerometer * Writes to Firebase */ private BluetoothGattCallback callback = new BluetoothGattCallback() { double axisVals[]; @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); switch (newState) { case BluetoothGatt.STATE_CONNECTED: gatt.discoverServices(); break; } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); gattService = gattProfile.getService(UUID.fromString("F000AA80-0451-4000-B000-000000000000")); Start = gattService.getCharacteristic(UUID.fromString("F000AA82-0451-4000-B000-000000000000")); Start.setValue(0b1000111000, BluetoothGattCharacteristic.FORMAT_UINT16, 0); gattProfile.writeCharacteristic(Start); } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); if (characteristic == Start) { Time = gattService.getCharacteristic(UUID.fromString("F000AA83-0451-4000-B000-000000000000")); Time.setValue(0x0A, BluetoothGattCharacteristic.FORMAT_UINT8, 0); gattProfile.writeCharacteristic(Time); } else if (characteristic == Time) { ReadCharacteristic = gattService.getCharacteristic(UUID.fromString("F000AA81-0451-4000-B000-000000000000")); lastVal = Calendar.getInstance(); gattProfile.readCharacteristic(ReadCharacteristic); deviceConnected(); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicRead(gatt, characteristic, status); axisVals = representations.convertAccelerometerdata(characteristic.getValue()); if (isConnected) { double X = axisVals[0]; double Y = axisVals[1]; double Z = axisVals[2]; sensor fire = new sensor(X, Y, Z);//here databaseReference.child("Accelerometer").setValue(fire); L1 = mloc.getLatitude(); L2 = mloc.getLongitude(); locAddress = mloc.getAddress(); databaseReference.child("Location").child("latitude").setValue(L1); databaseReference.child("Location").child("longitude").setValue(L2); databaseReference.child("Location").child("address").setValue(locAddress); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (isAdded()) { // update current acceleration readings xAxis.setText(String.format(getString(R.string.xAxis), Math.abs(axisVals[0]))); yAxis.setText(String.format(getString(R.string.yAxis), Math.abs(axisVals[1]))); zAxis.setText(String.format(getString(R.string.zAxis), Math.abs(axisVals[2]))); lat.setText(String.format(getString(R.string.Lat), mloc.getLatitude())); lon.setText(String.format(getString(R.string.Lon), mloc.getLongitude())); textAddress.setText(mloc.getAddress()); } } }); gattProfile.readCharacteristic(ReadCharacteristic); } }; }
aa9522fd4b73463031a8cfc629100fcb260bf36c
[ "Markdown", "Java" ]
7
Java
Barney117/AAL-Assistant
9b34d57893a0060d66e65448d9a5cad15e3eb814
c261130a2c5095d28e5406618e566dcd0417d138
refs/heads/master
<file_sep>package cn.liu.mobilesafe.activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import org.xutils.http.RequestParams; import org.xutils.x; import cn.liu.mobilesafe.R; import cn.liu.mobilesafe.utils.ContantValues; import cn.liu.mobilesafe.utils.InputStreamUtils; import cn.liu.mobilesafe.utils.SpUtils; import cn.liu.mobilesafe.utils.ToastUtils; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; import android.view.animation.AlphaAnimation; import android.widget.RelativeLayout; import android.widget.TextView; public class SplashActivity extends AppCompatActivity { private TextView vn; private static final String TAG = "SplashActivity"; protected static final int UPDATE_VERSION = 100; protected static final int ENTER_MAIN = 101; protected static final int IO_ERROR = 102; protected static final int JSON_ERROR = 103; protected static final int URL_ERROR = 104; private int mVersionCode; private String description; private String download_url; private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case ENTER_MAIN: //进入主界面 enterHomeActivity(); break; case URL_ERROR: ToastUtils.showToast(SplashActivity.this, "url错误"); enterHomeActivity(); break; case JSON_ERROR: ToastUtils.showToast(SplashActivity.this, "json解析错误"); enterHomeActivity(); break; case UPDATE_VERSION: boolean update = (boolean) SpUtils.get(getApplicationContext(), ContantValues.OPEN_UPDATE, false); if (update){ UpdateApp(); }else { //在handler发送消息四秒后处理ENTER_MAIN状态码对应的消息 mHandler.sendEmptyMessageDelayed(ENTER_MAIN,4000); } break; case IO_ERROR: ToastUtils.showToast(SplashActivity.this, "io异常"); enterHomeActivity(); break; default: break; } } /** *是否更新app */ private void UpdateApp(){ AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this); builder.setTitle("是否更新软件"); builder.setMessage(description); builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //请求更新 downloadApk(); } }); builder.setNegativeButton("稍后更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { enterHomeActivity(); } }); builder.show(); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { enterHomeActivity(); dialog.dismiss(); } }); } /** * 下载apk方法 */ private void downloadApk() { //判断sd卡状态,File.separator 表示:/ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //获取sd卡路径 // String path = Environment.getExternalStorageDirectory().getAbsolutePath() + // File.separator + "aa.apk"; RequestParams parms=new RequestParams(download_url); parms.setSaveFilePath(Environment.getExternalStorageDirectory()+"/myapp/"); x.http().post(parms, new org.xutils.common.Callback.ProgressCallback<File>() { //网络请求之前回调 @Override public void onWaiting() { } @Override public void onStarted() { Log.i(TAG, "onStarted: 开始下载"); } @Override public void onLoading(long total, long current, boolean isDownloading) { } @Override public void onSuccess(File result) { Log.i(TAG, "onSuccess: 下载成功"); installApk(result); } @Override public void onError(Throwable ex, boolean isOnCallback) { Log.i(TAG, "onError: 下载失败"); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } } }; private RelativeLayout rlroot; //安装apk private void installApk(File file) { //系统应用界面,源码,安装apk入口 Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); /*//文件作为数据源 intent.setData(Uri.fromFile(file)); //设置安装的类型 intent.setType("application/vnd.android.package-archive");*/ intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); // startActivity(intent); startActivityForResult(intent, 0); } //开启一个activity后,返回结果后调用的方法 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { enterHomeActivity(); super.onActivityResult(requestCode, resultCode, data); } //进入主界面 private void enterHomeActivity() { Log.i(TAG, "enterHomeActivity: 跳转"); Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); //结束导航页面 finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vn = (TextView) findViewById(R.id.tv_version_name); rlroot = (RelativeLayout) findViewById(R.id.rl_root); initData(); StartAnimation(); } private void StartAnimation() { //渐变动画 AlphaAnimation alphaAnimation = new AlphaAnimation(0,1); alphaAnimation.setDuration(2000); //为控件设置动画 rlroot.startAnimation(alphaAnimation); } //初始化数据 private void initData() { String versionName = getVersionName(); mVersionCode = getVersionCode(); Log.i(TAG, "mVersionCode " + mVersionCode); getDataFromServer(); vn.setText("版本名称" + versionName); } private void getDataFromServer() { new Thread(new Runnable() { Message msg = Message.obtain(); @Override public void run() { long startCurrentTimeMillis = System.currentTimeMillis(); try { URL url = new URL("http://192.168.1.107:8080/data.json"); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(2000); connection.setReadTimeout(2000); int code = connection.getResponseCode(); //请求成功 if (code == 200) { InputStream is = connection.getInputStream(); String json = InputStreamUtils.streamToString(is); JSONObject jsonObject = new JSONObject(json); Log.v(TAG, json); String versionName = jsonObject.getString("version_name"); String versionCode = jsonObject.getString("version_code"); description = jsonObject.getString("description"); download_url = jsonObject.getString("download_url"); Log.i(TAG, "run: " + versionCode); if (mVersionCode < Integer.parseInt(versionCode)) { //弹出更新对话框 Log.d(TAG, "run: 弹出更新对话框" + versionCode + mVersionCode); msg.what = UPDATE_VERSION; } else { //进入主界面 msg.what = ENTER_MAIN; } } } catch (IOException e) { e.printStackTrace(); msg.what = IO_ERROR; } catch (JSONException e) { msg.what = JSON_ERROR; e.printStackTrace(); } } catch (MalformedURLException e) { msg.what = URL_ERROR; e.printStackTrace(); } finally { long endCurrentTimeMillis = System.currentTimeMillis(); long dit = endCurrentTimeMillis - startCurrentTimeMillis; if (dit < 4000) { try { Thread.sleep(4000 - dit); } catch (InterruptedException e) { e.printStackTrace(); } } mHandler.sendMessage(msg); } } }).start(); } private String getVersionName() { PackageManager manager = getPackageManager(); try { PackageInfo info = manager.getPackageInfo(getPackageName(), 0); String name = info.versionName; return name; } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } private int getVersionCode() { PackageManager manager = getPackageManager(); try { PackageInfo info = manager.getPackageInfo(getPackageName(), 0); int Code = info.versionCode; return Code; } catch (NameNotFoundException e) { e.printStackTrace(); } return 0; } }
97e63cb6aee97b071b9664b2a1584a70181b65bc
[ "Java" ]
1
Java
liuyuquan123/MobileSafe
e9195e0acc73bb920d2148bff1648f7e7540f868
d4cfc619e7fbe1de7328a3b1e4faf75444f72023
refs/heads/master
<file_sep><?php /** * The header for our theme. * * This is the template that displays all of the <head> section and everything up until <div id="content"> * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * * @package hdmk */ ?><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <?php wp_head(); ?> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-8011509-3', 'auto'); ga('send', 'pageview'); </script> <script type='text/javascript' src='/wp-content/themes/drmk/js/script.js'></script> </head> <body <?php body_class(); ?>> <div id="page" class="site"> <div id="network-container"> <nav> <span style="color:#000;">design:retail Network</span> <h5 class=""><span class="ir"><a href="javascript:void(0)" class="">Menu</a></span></h5> <ul> <li><a href="http://www.designretailonline.com/">design:retail</a></li> <li><a href="http://www.designretailforum.com/">design:retail forum</a></li> <li><a href="http://www.globalshop.org/">GlobalShop</a></li> <li><a class="active" href="http://mediakit.designretailonline.com/">Media Kit</a></li> </ul> </nav> </div> <header id="masthead" class="site-header" role="banner"> <div class="wrapper clearfix"> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <div id="publication-of"><a href="http://www.globalshop.org/" target="_blank">&nbsp;</a></div> <?php $description = get_bloginfo( 'description', 'display' ); if ( $description || is_customize_preview() ) : ?> <p class="site-description"><?php echo $description; /* WPCS: xss ok. */ ?></p> <?php endif; ?> </div> <nav id="site-navigation" class="main-navigation" role="navigation"> <div class="wrapper clearfix"> <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Menu', 'hdmk' ); ?></button> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?> </div> </nav><!-- #site-navigation --> <div class="wrapper clearfix"> <?php if (!$post->post_parent){ $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0"); } else{ if($post->ancestors) { $ancestors = end($post->ancestors); $children = wp_list_pages("title_li=&child_of=".$ancestors."&echo=0&sort_column=menu_order"); } } if ($children) { ?> <nav class="sub-navigation"> <ul class="secondary-menu"><?php echo $children; ?></ul> <?php //the_field('pdf_link') ."//"; if(get_field('pdf_1_link') || get_field('pdf_link')) { ?> <div class="pdfs-container float-right"> <?php if(get_field('pdf_1_link')) { ?> <span class="pdf-link"><a href="<?=the_field('pdf_1_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=the_field('pdf_1_title');?></a></span> <?php } elseif (get_field('pdf_link')) { ?> <span class="pdf-link"><a href="<?=the_field('pdf_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=the_field('pdf_1_title');?></a></span> <?php } if(get_field('pdf_2_title')) { ?> <span class="pdf-link pdf-link-2"><a href="<?=the_field('pdf_2_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=the_field('pdf_2_title');?></a></span> <?php } ?> </div> <?php } else if(get_field('current_pdf_title')) { ?> <div class="pdfs-container float-right"> <span class="pdf-link"><a href="<?=get_field('current_pdf_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=get_field('current_pdf_title');?></a></span> </div> <? } } ?> </nav> </div> </header><!-- #masthead --> <div id="content" class="site-content wrapper clearfix"> <file_sep><?php /* Template Name: Editorial Calendar Template */ ?> <?php get_header(); ?> <div class="main-container page-editorial-cal"> <div class="main wrapper clearfix"> <div id="contentwrapper"> <div class="content-right"> <div class="pdfs-container"> <span class="pdf-link"><a href="<?=the_field('pdf_1_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=the_field('pdf_1_title');?></a></span> </div> </div> <article> <section> <div class="table-header"> <span class="title"><h3><? the_field('page_title'); ?></h3></span> </div> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); $print_highlights = get_field('editorial_calendar'); $object = get_field_object('editorial_calendar'); ?> <div class="table"> <table cellspacing="0" cellpadding="0" border="0" align="left"> <thead> <tr class="header-row"> <th><strong><?php echo $object['sub_fields'][0]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][1]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][2]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][3]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][4]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][5]['label'] ?></strong></th> <th><strong>Rotating Departments</strong></th> <th><strong><?php echo $object['sub_fields'][6]['label'] ?></strong></th> <th><strong><?php echo $object['sub_fields'][7]['label'] ?></strong></th> </tr> </thead> <tbody> <?php if(!empty($print_highlights)) { $count = 0; foreach($print_highlights as $print_highlight) { ?> <tr> <td><strong><?=$print_highlight['month']; ?></strong></td> <td><?=$print_highlight['ad_close']; ?></td> <td><?=$print_highlight['materials_due']; ?></td> <td><?=$print_highlight['issue_highlights']; ?></td> <td><?=$print_highlight['columns']; ?></td> <td><?=$print_highlight['product_coverage']; ?></td> <?php if ($count == 0) { ?> <td rowspan="11" style="background-color: #ebebeb; width:12%;vertical-align: top;"><? the_field('rotating_departments'); ?></td> <?php } ?> <td><?=$print_highlight['bonus_distribution']; ?></td> <td><? if($print_highlight['sales_advantage']==1) { ?> &#10003; <? } else { echo ""; } ?></td> </tr> <?php $count++; } } ?> </tbody> </table> </div> <?php if(get_field('note')) { ?> <div class="note"> <span><? the_field('note'); ?></span> </div><br /> <? } ?> <?php if(get_field('pdf_title_1')) { ?> <div class="table-footer"> <span class="pdf-link"><a href="<?=the_field('pdf_2_link');?>" target="_blank"><img src="/wp-content/themes/drmk/images/PDFlogo.png" alt="pdf" class="PDF_LogoLink"><?=the_field('pdf_2_title');?></a></span> </div><br /> <? } ?> <?php endwhile; ?> <?php endif; ?> </section> </article> </div> </div> </div> <?php get_footer(); ?>
06069fc9cc98c6d5bb2f2c26d5b0a4006ba5cccf
[ "PHP" ]
2
PHP
daniilz/mediakit.designretailonline.com
1b795e7bb24a8998e50282a93eb6146c48dd59e0
ec8a8a6db07ebe95fdc8cb2d38110c2f563c836e
refs/heads/main
<repo_name>dariav-sys/goit-js-hw-11-timer<file_sep>/js/task-1.js class CountdownTimer { constructor({ selector, targetDate }) { this.selector = selector; this.targetDate = targetDate; this.refs = { days: document.querySelector('[data-value = "days"]'), hours: document.querySelector('[data-value = "hours"]'), mins: document.querySelector('[data-value = "mins"]'), secs: document.querySelector('[data-value = "secs"]'), }; } updateTime() { setInterval(() => { this.currentTime = new Date(); this.remainingTime = this.targetDate - this.currentTime; this.days = Math.floor(this.remainingTime / (1000 * 60 * 60 * 24)); this.hours = pad( Math.floor((this.remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)), ); this.mins = pad(Math.floor((this.remainingTime % (1000 * 60 * 60)) / (1000 * 60))); this.secs = pad(Math.floor((this.remainingTime % (1000 * 60)) / 1000)); this.refs.days.textContent = `${this.days}`; this.refs.hours.textContent = `${this.hours}`; this.refs.mins.textContent = `${this.mins}`; this.refs.secs.textContent = `${this.secs}`; }, 1000); function pad(value) { return String(value).padStart(2, '0'); } } } const example = new CountdownTimer({ selector: '#timer-1', targetDate: new Date('Mar 17, 2021'), }); example.updateTime() <file_sep>/README.md # dariav-sys-goit-js-hw-11-timer
dfd5ee29aa63a51c68bd9454244d573b0b136354
[ "JavaScript", "Markdown" ]
2
JavaScript
dariav-sys/goit-js-hw-11-timer
68e62f2b15f2d5bcaf8bf0a444013e997146eec1
39ae2f0358829897172d32650fc5601cf1d734c1
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_many :trips_as_driver, class_name: 'Trip', foreign_key: 'driver_id' has_many :gps_locations, class_name: 'GpsLocation', foreign_key: 'user_id' #TODO: # has_many :trips_as_follower, end <file_sep>Rails.application.routes.draw do match 'api/start_trip', to: 'users#start_trip', via: 'post' match 'api/follower_accepts_trip', to: 'users#follower_accepts_trip', via: 'post' match 'api/follower_polling', to: 'users#follower_polling', via: 'post' match 'api/driver_polling', to: 'users#driver_polling', via: 'post' match 'api/test', to: 'users#test', via: 'get' match 'api/gps_test', to: 'users#gps_test', via: 'get' match 'api/gps_test_f', to: 'users#gps_test_f', via: 'get' end <file_sep>source 'https://rubygems.org' gem 'rails', '4.1.8' gem 'rails-api', '0.4.0' gem 'spring', :group => :development gem 'mysql2', '0.3.16' gem 'jbuilder', '2.2.4' gem 'unicorn', '4.8.3' <file_sep>class CreateGpsLocations < ActiveRecord::Migration def change create_table :gps_locations do |t| t.integer :user_id t.integer :trip_id t.datetime :time #Latitude Range -90 to 90 t.decimal :latitude, precision: 12, scale: 8 #Longitude Range -180 to 180 t.decimal :longitude, precision: 12, scale: 8 t.timestamps end end end <file_sep># Set the working application directory # working_directory "/path/to/your/app" working_directory File.expand_path('') # Unicorn PID file location # pid "/path/to/pids/unicorn.pid" pid File.expand_path('', "pids/unicorn.pid") # Path to logs # stderr_path "/path/to/log/unicorn.log" # stdout_path "/path/to/log/unicorn.log" stderr_path File.expand_path('', "log/unicorn.error.log") stdout_path File.expand_path('', "log/unicorn.log") # Unicorn socket listen "/tmp/unicorn.croc_follower.sock" # Number of processes worker_processes 4 # Time-out timeout 30 <file_sep>class Follower < ActiveRecord::Base belongs_to :trip, class_name: 'Trip', foreign_key: 'trip_id' end <file_sep>class Trip < ActiveRecord::Base belongs_to :driver, class_name: 'User', foreign_key: 'driver_id' has_many :followers, class_name: 'Follower', foreign_key: 'trip_id' has_many :gps_locations, class_name: 'GpsLocation', foreign_key: 'trip_id' end <file_sep>class UsersController < ApplicationController #Initiates a trip. # trip_name: # driver_phone_no # followers_phone_nos = [] def start_trip #STEP: Find or Create a user for driver and its followers. driver = User.find_or_create_by!(phone: params[:driver_phone_no]) #STEP: Create a Trip trip = Trip.create!(name: params[:trip_name], driver_id: driver.id) #STEP: For followers followers = [] followers_phone_nos = params[:followers_phone_nos].gsub("[","").gsub("]","").split(",") followers_phone_nos.each do |phone| phone = phone.gsub(" ", "").strip.last(10) follower = User.find_or_create_by!(phone: phone) followers << follower Follower.create!(trip_id: trip.id, user_id: follower.id) end render json: { success: "Submitted Successfully!", trip_id: trip.id, driver_phone_no: driver.phone }, status: :ok return end #Method def follower_accepts_trip phone = params[:phone_no].gsub(" ", "").strip.last(10) #user has already been created. user = User.find_by(phone: phone) #Find the latest trip from follower table. follower_object = Follower.where(user_id: user.id).order('id desc').first if follower_object render json: { trip_id: follower_object.trip.id, trip_name: follower_object.trip.name, driver_phone_no: follower_object.trip.driver.phone }, status: :ok else render json: { message: "Follower Not Found"}, status: :ok end return end #Followers keeps POLLING on this API for: # - updating its GPS # - getting its driver gps def follower_polling phone = params[:phone_no].gsub(" ", "").strip.last(10) trip = Trip.find(params[:trip_id]) user = User.find_by(phone: phone) time = Time.strptime(params[:time], '%s').to_s(:db) #STEP: Follower creates its GPS GpsLocation.create!(trip_id: trip.id, user_id: user.id, latitude: params[:latitude], longitude: params[:longitude], time: time) #STEP: Follower gets the GPS of trip's driver driver_gps = GpsLocation.where(trip_id: trip.id, user_id: trip.driver_id).order('id desc').first render json: { driver_id: driver_gps.user_id, time: driver_gps.time, latitude: driver_gps.latitude, longitude: driver_gps.longitude }, status: :ok return end #Drivers keeps on POLLING on this api for: # - updating its GPS # - getting its followers gps def driver_polling time = Time.strptime(params[:time], '%s').to_s(:db) @trip = Trip.find(params[:trip_id]) #STEP: Driver updates its GPS GpsLocation.create!(trip_id: @trip.id, user_id: @trip.driver.id, latitude: params[:latitude], longitude: params[:longitude], time: time) #STEP: Driver gets its followers for a given Trip trip_followers_ids = @trip.followers.collect(&:user_id) #STEP: Get the latest GPS for all its followers @gps_locations = [] trip_followers_ids.each do |user_id| @gps_locations << GpsLocation.where(trip_id: @trip.id, user_id: user_id).order('id desc').first end render json: {gps: @gps_locations} # render json: { follower_gps: @gps_locations.each { |gps| { # user_id: gps.user_id, # time: gps.time, # latitude: gps.latitude, # longitude: gps.longitude # } # } # }, status: :ok return end #============================================================================== # # For Simulation. # #============================================================================== def test dist_times = GpsLocation.where(user_id: params[:user_id]) render json: dist_times return end def gps_test trip = Trip.find(1) distance_time = [] trip.followers.each do |user| next if (trip.driver_id == user.id) dist_time = GpsLocation.where(user_id:user.id, trip_id: trip.id)[params[:id].to_i - 1] distance_time << dist_time end driver_lat = GpsLocation.where(user_id: trip.driver_id, trip_id: trip.id)[params[:id].to_i - 1] render json: {followers_lat: distance_time, driver_lat: driver_lat} return end def gps_test_f trip = Trip.find(1) driver_lat = GpsLocation.where(user_id: trip.driver_id, trip_id: trip.id)[params[:id].to_i - 1] render json: {driver_lat: driver_lat} return end #============================================================================== # # Simulation Ends. # #============================================================================== end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) u1 = User.create!(name: "Alankrit", email: "<EMAIL>", phone: "9911639164") u2 = User.create!(name: "Neha", email: "<EMAIL>", phone: "8587010286") u3 = User.create!(name: "Sahil", email: "<EMAIL>", phone: "9718842482") u4 = User.create!(name: "Megha", email: "<EMAIL>", phone: "8587079020") u5 = User.create!(name: "Himanshu", email: "<EMAIL>", phone: "8053830574") u6 = User.create!(name: "Prachi", email: "<EMAIL>", phone: "9599266768") t1 = Trip.create!(driver_id: u1.id, name: "Domestic Airport") t2 = Trip.create!(driver_id: u2.id, name: "MGF Mall") t3 = Trip.create!(driver_id: u3.id, name: "India Gate") t4 = Trip.create!(driver_id: u4.id, name: "<NAME>") Follower.create!(trip_id: t1.id, user_id: u2.id) Follower.create!(trip_id: t1.id, user_id: u3.id) Follower.create!(trip_id: t1.id, user_id: u4.id) Follower.create!(trip_id: t1.id, user_id: u5.id) Follower.create!(trip_id: t1.id, user_id: u6.id) Follower.create!(trip_id: t2.id, user_id: u1.id) Follower.create!(trip_id: t2.id, user_id: u3.id) Follower.create!(trip_id: t2.id, user_id: u4.id) Follower.create!(trip_id: t2.id, user_id: u5.id) Follower.create!(trip_id: t2.id, user_id: u6.id) Follower.create!(trip_id: t3.id, user_id: u2.id) Follower.create!(trip_id: t3.id, user_id: u1.id) Follower.create!(trip_id: t3.id, user_id: u4.id) Follower.create!(trip_id: t3.id, user_id: u5.id) Follower.create!(trip_id: t3.id, user_id: u6.id) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.491039, longitude: 77.081741) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.494302, longitude: 77.084877) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.497263, longitude: 77.087774) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.499771, longitude: 77.090091) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.503099, longitude: 77.092988) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.504348, longitude: 77.094029) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.505003, longitude: 77.094490) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.505164, longitude: 77.094576) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.505980, longitude: 77.094898) GpsLocation.create!(user_id: u1.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.506975, longitude: 77.094995) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.488017, longitude: 77.078812) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.489172, longitude: 77.079981) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.490478, longitude: 77.081161) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.491822, longitude: 77.082545) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.493288, longitude: 77.083929) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.494669, longitude: 77.085238) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.495805, longitude: 77.086418) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.497124, longitude: 77.087665) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.498420, longitude: 77.088888) GpsLocation.create!(user_id: u2.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.499877, longitude: 77.090229) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.487814, longitude: 77.078694) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.488469, longitude: 77.079338) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.489228, longitude: 77.080035) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.489817, longitude: 77.080571) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.490548, longitude: 77.081279) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.491515, longitude: 77.082234) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.492529, longitude: 77.083257) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.494203, longitude: 77.084831) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.495235, longitude: 77.085807) GpsLocation.create!(user_id: u3.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.496315, longitude: 77.086869) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.487668, longitude: 77.078544) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.488031, longitude: 77.078920) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.488507, longitude: 77.079392) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.489210, longitude: 77.080025) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.489780, longitude: 77.080540) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.490435, longitude: 77.081184) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.491081, longitude: 77.081753) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.491651, longitude: 77.082311) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.492287, longitude: 77.082965) GpsLocation.create!(user_id: u4.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.492989, longitude: 77.083512) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.487418, longitude: 77.078351) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.487847, longitude: 77.078748) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.488238, longitude: 77.079102) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.488667, longitude: 77.079531) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.489077, longitude: 77.079907) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.489581, longitude: 77.080368) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.490001, longitude: 77.080754) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.490543, longitude: 77.081215) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.490755, longitude: 77.081526) GpsLocation.create!(user_id: u5.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.491052, longitude: 77.081794) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 10.minutes, latitude: 28.487272, longitude: 77.078190) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 9.minutes, latitude: 28.487437, longitude: 77.078329) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 8.minutes, latitude: 28.487583, longitude: 77.078501) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 7.minutes, latitude: 28.487880, longitude: 77.078716) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 6.minutes, latitude: 28.488026, longitude: 77.078941) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 5.minutes, latitude: 28.488295, longitude: 77.079113) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 4.minutes, latitude: 28.488498, longitude: 77.079338) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 3.minutes, latitude: 28.489031, longitude: 77.079821) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 2.minutes, latitude: 28.489469, longitude: 77.080186) GpsLocation.create!(user_id: u6.id, trip_id: t1.id, time: Time.now - 1.minutes, latitude: 28.489823, longitude: 77.080615) <file_sep>class GpsLocation < ActiveRecord::Base belongs_to :trip, class_name: 'Trip', foreign_key: 'trip_id' belongs_to :user, class_name: 'User', foreign_key: 'user_id' end
df1dc2f1dd32086062f6e94bfd9cbcfbd7ae8617
[ "Ruby" ]
10
Ruby
alankrit/follow_crocodiles
313b62f3d8dbee80ca562ab8b3ef34a4a6e3beba
b628f93752f619810fd44515ed3e8d298113269a
refs/heads/master
<repo_name>Rachitahuja20/Ruby<file_sep>/Sentianalysis.rb require 'rubygems' require 'json' require 'sentimental' a=[] from_file = ARGV.first indata = open(from_file).read #JSON Parser json = JSON.parse(indata) json["user_reviews"].each do |user_reviews| a.push(user_reviews["review"]["review_text"]) end analyzer = Sentimental.new #analyzer.threshold = 1 analyzer.load_defaults a.push("I just completely hate this place.") a.each do |a| puts a puts "\v" puts analyzer.sentiment a puts "\v" puts analyzer.score a puts "\v" end <file_sep>/README.md # Ruby programs Sentianalysis is about sentiment analysis of reviews on Zomato. <file_sep>/practice.rb input_file = ARGV.first current_file = open(input_file) words = [] current_file.each_line do |f| words.push(f) end def chooseword(w) number = w.length ch = rand(0...number) word = w[ch] return word end puts "Want to play Hangman? (y/n)" resp = $stdin.gets.chomp if resp == 'y' word = chooseword(words) else puts "WTF!" end puts "#" * 10 + "Let's start the game!" + "#" * 10 blanks = (word.length * 0.3).round i = 0 rando = [] while i < blanks l = (rand(0..word.length-1)) c = rando.include? l if c == false rando.push(l) i+=1 else i+=1 end end num = word.dup check = word.dup def blankgen(rando, num) cum = num rando.each do |x| cum[x] = '-' end return cum end hang = [] hang1 = ['H', 'A', 'N', 'G', 'M', 'A', 'N'].reverse def put(check, num, rando, hang, hang1) flag = 0 j=0 z=0 rev=0 puts "Word is #{check}" puts "Guess is #{num}" begin puts "Please enter the letter" letter = $stdin.gets.chomp rando.each do |x| m = check[x].include? letter if m == true num[x] = letter flag+=1 rev+=1 else flag-=1 end end puts num if flag < 0 && rev == 0 hang[j] = hang1.pop j+=1 puts hang end z+=1 flag = 0 rev = 0 if check == num puts "You WON!!!!!" break end end while hang.length < 7 return hang end cum = blankgen(rando, num) put(check, cum, rando, hang, hang1) if hang.length > 6 puts "You LOOSE!! HANGMAN" else puts "Yipeee!!!!" end <file_sep>/ex25.rb module Ex25 #Thid function will break up the words for us. def Ex25.break_words(stuff) words = stuff.split(" ") return words end #Sorts the words. def Ex25.sort_words(words) return words.sort end #prints the first word after shifting it off. def Ex25.print_first_word(words) word = words.shift puts word end #Prints the last word after popping it off. def Ex25.print_last_word(words) word = words.pop puts word end # Takes in a full sentence and returns the sorted words. def Ex25.sort_sentence(sentence) words = Ex25.break_words(sentence) return Ex25.sort_words(words) end #Sorts the words then prints the first and last one def Ex25.print_first_and_last_sorted(sentence) words = Ex25.sort_sentence(sentence) Ex25.print_first_word(words) Ex25.print_last_word(words) end end # ## # #>> require "./ex25.rb" # #=> true # #>> # #?> sentence = "All good things come to those who wait." # #=> "All good things come to those who wait." # #>> words = Ex25.break_words(sentence) # => ["All", "good", "things", "come", "to", "those", "who", "wait."] # >> words # => ["All", "good", "things", "come", "to", "those", "who", "wait."] # >> sorted_words = Ex25.sort_words(words) # => ["All", "come", "good", "things", "those", "to", "wait.", "who"] # >> sorted_words # => ["All", "come", "good", "things", "those", "to", "wait.", "who"] # >> Ex25.print_first_word(words) # All # => nil # >> Ex25.print_last_word(words) # wait. # => nil # >> words # => ["good", "things", "come", "to", "those", "who"] # >> Ex25.print_first_word(sorted_words) # All # => nil # >> Ex25.print_last_word(sorted_words) # who # => nil # >> sorted_words # => ["come", "good", "things", "those", "to", "wait."] # >> sorted_words = Ex25.sort_sentence(sentence) # => ["All", "come", "good", "things", "those", "to", "wait.", "who"] # >> sorted_words # => ["All", "come", "good", "things", "those", "to", "wait.", "who"] # >> Ex25.print_first_and_last(sentence) # All # wait. # => nil # >> Ex25.print_first_and_last_sorted(sentence) # All # who # #=> nil <file_sep>/Webscraper/Scrapper.rb require 'HTTParty' require 'Nokogiri' require 'JSON' require 'Pry' require 'csv' page = HTTParty.get('https://newyork.craigslist.org/search/pet?s=0') parse_page = Nokogiri::HTML(page) pets_array = [] parse_page.css('.content').css('.row').css('.hdrlnk').map do |a| post_name = a.text pets_array.push(post_name) end CSV.open('pets.csv', 'w') do |csv| csv << pets_array end <file_sep>/module_ex.rb #This is a module example file module mystuff def mystuff.apple() puts "I am apples" end # this is just a variable TANGERINE = "Living reflection of a dream" end
df6706514383da553ddcce48fc92bf6fbecdc630
[ "Markdown", "Ruby" ]
6
Ruby
Rachitahuja20/Ruby
c99d3010382288f14c8f189dade99b079c99fae7
7c70ef8eacb7188d88a0c287d4ec062a7072694b
refs/heads/master
<repo_name>evargasguarniz/symfony<file_sep>/src/Distrito/CaseriosBundle/Entity/Galeria.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Galeria * * @ORM\Table() * @ORM\Entity */ class Galeria { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="imgGaleria", type="string" ) */ private $imgGaleria; /** * @var text * * @ORM\Column(name="descripcionGaleria", type="text") */ private $descripcionGaleria; /** * @var integer * @ORM\ManyToOne(targetEntity="Caserios") * @ORM\JoinColumn(name="caserios_id", nullable=false, referencedColumnName="id") **/ protected $caserios_id; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set imgGaleria * * @param string $imgGaleria * @return Galeria */ public function setImgGaleria($imgGaleria) { $this->imgGaleria = $imgGaleria; return $this; } /** * Get imgGaleria * * @return string */ public function getImgGaleria() { return $this->imgGaleria; } /** * Set descripcionGaleria * * @param string $descripcionGaleria * @return Galeria */ public function setDescripcionGaleria($descripcionGaleria) { $this->descripcionGaleria = $descripcionGaleria; return $this; } /** * Get descripcionGaleria * * @return string */ public function getDescripcionGaleria() { return $this->descripcionGaleria; } /** * Set caserios_id * * @param \Distrito\CaseriosBundle\Entity\Caserios $caseriosId * @return Galeria */ public function setCaseriosId(\Distrito\CaseriosBundle\Entity\Caserios $caseriosId) { $this->caserios_id = $caseriosId; return $this; } /** * Get caserios_id * * @return \Distrito\CaseriosBundle\Entity\Caserios */ public function getCaseriosId() { return $this->caserios_id; } public function __toString() { return $this->imgGaleria; } } <file_sep>/src/Distrito/CaseriosBundle/DistritoCaseriosBundle.php <?php namespace Distrito\CaseriosBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class DistritoCaseriosBundle extends Bundle { } <file_sep>/caseriosdb.sql -- phpMyAdmin SQL Dump -- version 4.0.10deb1 -- http://www.phpmyadmin.net -- -- Servidor: localhost -- Tiempo de generación: 27-03-2015 a las 19:35:56 -- Versión del servidor: 5.5.41-0ubuntu0.14.04.1 -- Versión de PHP: 5.5.9-1ubuntu4.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de datos: `caseriosdb` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Autoridades` -- CREATE TABLE IF NOT EXISTS `Autoridades` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_caserio` int(11) NOT NULL, `NombreAutoridad` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Cargo` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Dni` int(11) NOT NULL, `Edad` int(11) NOT NULL, `Descripcion` longtext COLLATE utf8_unicode_ci NOT NULL, `GradoEstudio` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Blog` -- CREATE TABLE IF NOT EXISTS `Blog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `NombreBlog` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Descripcion` longtext COLLATE utf8_unicode_ci NOT NULL, `FechaPublicacion` date NOT NULL, `HoraPublicacion` time NOT NULL, `AutorPublicacion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Caserios` -- CREATE TABLE IF NOT EXISTS `Caserios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Nombre` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Descripcion` longtext COLLATE utf8_unicode_ci NOT NULL, `Fecha` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Comentarios` -- CREATE TABLE IF NOT EXISTS `Comentarios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `idBlog` int(11) NOT NULL, `Comentario` longtext COLLATE utf8_unicode_ci NOT NULL, `FechaComentario` date NOT NULL, `horaComentario` time NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Comidas` -- CREATE TABLE IF NOT EXISTS `Comidas` ( `id` int(11) NOT NULL AUTO_INCREMENT, `NombreComida` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Ingredientes` longtext COLLATE utf8_unicode_ci NOT NULL, `Preparacion` longtext COLLATE utf8_unicode_ci NOT NULL, `Cocinero` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `VitaminasComida` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `idCaserio` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Deportes` -- CREATE TABLE IF NOT EXISTS `Deportes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `NombreDeporte` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Descripcion` longtext COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Galeria` -- CREATE TABLE IF NOT EXISTS `Galeria` ( `id` int(11) NOT NULL AUTO_INCREMENT, `imgGaleria` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `GaleriaDeportes` -- CREATE TABLE IF NOT EXISTS `GaleriaDeportes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `idDeporte` int(11) NOT NULL, `imgDeporte` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Perfiles` -- CREATE TABLE IF NOT EXISTS `Perfiles` ( `id` int(11) NOT NULL AUTO_INCREMENT, `NombrePerfil` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Descripcion` longtext COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Proyectos` -- CREATE TABLE IF NOT EXISTS `Proyectos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `idCaserio` int(11) NOT NULL, `NombreProyecto` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Costructora` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `FechaInicio` date NOT NULL, `FechaFin` date NOT NULL, `Ubicacion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Usuarios` -- CREATE TABLE IF NOT EXISTS `Usuarios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `NobreUsuario` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Nombre` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Apellidos` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `id_Perfil` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/src/Distrito/CaseriosBundle/Entity/Caserios.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\Common\Collections\ArrayCollection; /** * Caserios * * @ORM\Table() * @ORM\Entity */ class Caserios { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="Nombre", type="string", length=255) */ private $nombre; /** * @var string * * @ORM\Column(name="Descripcion", type="text") */ private $descripcion; /** * @var string * @ORM\Column(name="Imagencaserio", type="text") */ private $Imagencaserio; /** * @var string * @ORM\Column(name="Video_1", type="text") */ private $Video_1; /** * @var string * @ORM\Column(name="Video_2", type="text") */ private $Video_2; /** * @var string * @ORM\Column(name="Video_3", type="text") */ private $Video_3; /** * @var string * @ORM\Column(name="Video_4", type="text") */ private $Video_4; /** * @var \DateTime * * @ORM\Column(name="Fecha", type="date") */ private $fecha; /** * @ORM\OneToMany(targetEntity="Autoridades", mappedBy="Caserios") **/ private $Autoridades; /** * @var integer * @ORM\OneToMany(targetEntity="Galeria", mappedBy="caserios_id") **/ protected $galeria; /** * Constructor */ public function __construct() { $this->Autoridades = new \Doctrine\Common\Collections\ArrayCollection(); $this->galeria = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return Caserios */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set descripcion * * @param string $descripcion * @return Caserios */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } /** * Set Imagencaserio * * @param string $imagencaserio * @return Caserios */ public function setImagencaserio($imagencaserio) { $this->Imagencaserio = $imagencaserio; return $this; } /** * Get Imagencaserio * * @return string */ public function getImagencaserio() { return $this->Imagencaserio; } /** * Set Video_1 * * @param string $video1 * @return Caserios */ public function setVideo1($video1) { $this->Video_1 = $video1; return $this; } /** * Get Video_1 * * @return string */ public function getVideo1() { return $this->Video_1; } /** * Set Video_2 * * @param string $video2 * @return Caserios */ public function setVideo2($video2) { $this->Video_2 = $video2; return $this; } /** * Get Video_2 * * @return string */ public function getVideo2() { return $this->Video_2; } /** * Set Video_3 * * @param string $video3 * @return Caserios */ public function setVideo3($video3) { $this->Video_3 = $video3; return $this; } /** * Get Video_3 * * @return string */ public function getVideo3() { return $this->Video_3; } public function setVideo4($video4) { $this->Video_4 = $video4; return $this; } /** * Get Video_3 * * @return string */ public function getVideo4() { return $this->Video_4; } /** * Set fecha * * @param \DateTime $fecha * @return Caserios */ public function setFecha($fecha) { $this->fecha = $fecha; return $this; } /** * Get fecha * * @return \DateTime */ public function getFecha() { return $this->fecha; } /** * Add Autoridades * * @param \Distrito\CaseriosBundle\Entity\Autoridades $autoridades * @return Caserios */ public function addAutoridade(\Distrito\CaseriosBundle\Entity\Autoridades $autoridades) { $this->Autoridades[] = $autoridades; return $this; } /** * Remove Autoridades * * @param \Distrito\CaseriosBundle\Entity\Autoridades $autoridades */ public function removeAutoridade(\Distrito\CaseriosBundle\Entity\Autoridades $autoridades) { $this->Autoridades->removeElement($autoridades); } /** * Get Autoridades * * @return \Doctrine\Common\Collections\Collection */ public function getAutoridades() { return $this->Autoridades; } /** * Add galeria * * @param \Distrito\CaseriosBundle\Entity\Galeria $galeria * @return Caserios */ public function addGalerium(\Distrito\CaseriosBundle\Entity\Galeria $galeria) { $this->galeria[] = $galeria; return $this; } /** * Remove galeria * * @param \Distrito\CaseriosBundle\Entity\Galeria $galeria */ public function removeGalerium(\Distrito\CaseriosBundle\Entity\Galeria $galeria) { $this->galeria->removeElement($galeria); } /** * Get galeria * * @return \Doctrine\Common\Collections\Collection */ public function getGaleria() { return $this->galeria; } public function __toString() { return $this->nombre; } } <file_sep>/web/js/main.js $(document).ready(function(){ /*form edit caserios*/ function addClassformEditControl(){ $('#form-edit-caserios > div').addClass("form-group"); $('#form-edit-caserios > div > button').addClass("btn btn-info"); $('#form-edit-caserios > div > label').addClass(""); } addClassformEditControl(); function addClassformDeleteControl(){ $('#form-delete-caserios > div > button').addClass("btn btn-danger"); $('#form-delete-caserios > div > label').addClass(""); } addClassformDeleteControl(); function addClassPrimerElemento(){ $('.item').eq(0).addClass('active'); } addClassPrimerElemento(); /*plagin venobox*/ function venoboxInit(){ $('.venobox').venobox({ // default: '' border: '10px', // default: '0' bgcolor: '#5dff5e', // default: '#fff' titleattr: 'data-title', // default: 'title' numeratio: true, // default: false infinigall: true // default: false }); } venoboxInit(); /*incluyendo el mapa */ function gomap(){ $("#map").goMap({ zoom: 17, maptype: 'SATELLITE', markers: [{ latitude: -7.546959, longitude: -78.476283, id: 'info1', html: { content: '<NAME> ', popup: true } }], hideByClick: false }); } gomap(); });<file_sep>/src/Distrito/CaseriosBundle/Entity/Comentarios.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Comentarios * * @ORM\Table() * @ORM\Entity */ class Comentarios { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="idBlog", type="integer") */ private $idBlog; /** * @var string * * @ORM\Column(name="Comentario", type="text") */ private $comentario; /** * @var \DateTime * * @ORM\Column(name="FechaComentario", type="date") */ private $fechaComentario; /** * @var \DateTime * * @ORM\Column(name="horaComentario", type="time") */ private $horaComentario; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set idBlog * * @param integer $idBlog * @return Comentarios */ public function setIdBlog($idBlog) { $this->idBlog = $idBlog; return $this; } /** * Get idBlog * * @return integer */ public function getIdBlog() { return $this->idBlog; } /** * Set comentario * * @param string $comentario * @return Comentarios */ public function setComentario($comentario) { $this->comentario = $comentario; return $this; } /** * Get comentario * * @return string */ public function getComentario() { return $this->comentario; } /** * Set fechaComentario * * @param \DateTime $fechaComentario * @return Comentarios */ public function setFechaComentario($fechaComentario) { $this->fechaComentario = $fechaComentario; return $this; } /** * Get fechaComentario * * @return \DateTime */ public function getFechaComentario() { return $this->fechaComentario; } /** * Set horaComentario * * @param \DateTime $horaComentario * @return Comentarios */ public function setHoraComentario($horaComentario) { $this->horaComentario = $horaComentario; return $this; } /** * Get horaComentario * * @return \DateTime */ public function getHoraComentario() { return $this->horaComentario; } } <file_sep>/src/Distrito/CaseriosBundle/Entity/Proyectos.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Proyectos * * @ORM\Table() * @ORM\Entity */ class Proyectos { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="idCaserio", type="integer") */ private $idCaserio; /** * @var string * * @ORM\Column(name="NombreProyecto", type="string", length=255) */ private $nombreProyecto; /** * @var string * * @ORM\Column(name="Costructora", type="string", length=255) */ private $costructora; /** * @var \DateTime * * @ORM\Column(name="FechaInicio", type="date") */ private $fechaInicio; /** * @var \DateTime * * @ORM\Column(name="FechaFin", type="date") */ private $fechaFin; /** * @var string * * @ORM\Column(name="Ubicacion", type="string", length=255) */ private $ubicacion; /** * @var string * * @ORM\Column(name="Descripcion", type="string", length=255) */ private $descripcion; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set idCaserio * * @param integer $idCaserio * @return Proyectos */ public function setIdCaserio($idCaserio) { $this->idCaserio = $idCaserio; return $this; } /** * Get idCaserio * * @return integer */ public function getIdCaserio() { return $this->idCaserio; } /** * Set nombreProyecto * * @param string $nombreProyecto * @return Proyectos */ public function setNombreProyecto($nombreProyecto) { $this->nombreProyecto = $nombreProyecto; return $this; } /** * Get nombreProyecto * * @return string */ public function getNombreProyecto() { return $this->nombreProyecto; } /** * Set costructora * * @param string $costructora * @return Proyectos */ public function setCostructora($costructora) { $this->costructora = $costructora; return $this; } /** * Get costructora * * @return string */ public function getCostructora() { return $this->costructora; } /** * Set fechaInicio * * @param \DateTime $fechaInicio * @return Proyectos */ public function setFechaInicio($fechaInicio) { $this->fechaInicio = $fechaInicio; return $this; } /** * Get fechaInicio * * @return \DateTime */ public function getFechaInicio() { return $this->fechaInicio; } /** * Set fechaFin * * @param \DateTime $fechaFin * @return Proyectos */ public function setFechaFin($fechaFin) { $this->fechaFin = $fechaFin; return $this; } /** * Get fechaFin * * @return \DateTime */ public function getFechaFin() { return $this->fechaFin; } /** * Set ubicacion * * @param string $ubicacion * @return Proyectos */ public function setUbicacion($ubicacion) { $this->ubicacion = $ubicacion; return $this; } /** * Get ubicacion * * @return string */ public function getUbicacion() { return $this->ubicacion; } /** * Set descripcion * * @param string $descripcion * @return Proyectos */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } } <file_sep>/src/Distrito/CaseriosBundle/Entity/Blog.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Blog * * @ORM\Table() * @ORM\Entity */ class Blog { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="NombreBlog", type="string", length=255) */ private $nombreBlog; /** * @var string * * @ORM\Column(name="Descripcion", type="text") */ private $descripcion; /** * @var \DateTime * * @ORM\Column(name="FechaPublicacion", type="date") */ private $fechaPublicacion; /** * @var \DateTime * * @ORM\Column(name="HoraPublicacion", type="time") */ private $horaPublicacion; /** * @var string * * @ORM\Column(name="AutorPublicacion", type="string", length=255) */ private $autorPublicacion; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombreBlog * * @param string $nombreBlog * @return Blog */ public function setNombreBlog($nombreBlog) { $this->nombreBlog = $nombreBlog; return $this; } /** * Get nombreBlog * * @return string */ public function getNombreBlog() { return $this->nombreBlog; } /** * Set descripcion * * @param string $descripcion * @return Blog */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } /** * Set fechaPublicacion * * @param \DateTime $fechaPublicacion * @return Blog */ public function setFechaPublicacion($fechaPublicacion) { $this->fechaPublicacion = $fechaPublicacion; return $this; } /** * Get fechaPublicacion * * @return \DateTime */ public function getFechaPublicacion() { return $this->fechaPublicacion; } /** * Set horaPublicacion * * @param \DateTime $horaPublicacion * @return Blog */ public function setHoraPublicacion($horaPublicacion) { $this->horaPublicacion = $horaPublicacion; return $this; } /** * Get horaPublicacion * * @return \DateTime */ public function getHoraPublicacion() { return $this->horaPublicacion; } /** * Set autorPublicacion * * @param string $autorPublicacion * @return Blog */ public function setAutorPublicacion($autorPublicacion) { $this->autorPublicacion = $autorPublicacion; return $this; } /** * Get autorPublicacion * * @return string */ public function getAutorPublicacion() { return $this->autorPublicacion; } } <file_sep>/src/Distrito/CaseriosBundle/Entity/Comidas.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Comidas * * @ORM\Table() * @ORM\Entity */ class Comidas { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="NombreComida", type="string", length=255) */ private $nombreComida; /** * @var string * * @ORM\Column(name="Ingredientes", type="text") */ private $ingredientes; /** * @var string * * @ORM\Column(name="Preparacion", type="text") */ private $preparacion; /** * @var string * * @ORM\Column(name="Cocinero", type="string", length=255) */ private $cocinero; /** * @var string * * @ORM\Column(name="VitaminasComida", type="string", length=255) */ private $vitaminasComida; /** * @var integer * * @ORM\Column(name="Caserio", type="integer") */ private $Caserio; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombreComida * * @param string $nombreComida * @return Comidas */ public function setNombreComida($nombreComida) { $this->nombreComida = $nombreComida; return $this; } /** * Get nombreComida * * @return string */ public function getNombreComida() { return $this->nombreComida; } /** * Set ingredientes * * @param string $ingredientes * @return Comidas */ public function setIngredientes($ingredientes) { $this->ingredientes = $ingredientes; return $this; } /** * Get ingredientes * * @return string */ public function getIngredientes() { return $this->ingredientes; } /** * Set preparacion * * @param string $preparacion * @return Comidas */ public function setPreparacion($preparacion) { $this->preparacion = $preparacion; return $this; } /** * Get preparacion * * @return string */ public function getPreparacion() { return $this->preparacion; } /** * Set cocinero * * @param string $cocinero * @return Comidas */ public function setCocinero($cocinero) { $this->cocinero = $cocinero; return $this; } /** * Get cocinero * * @return string */ public function getCocinero() { return $this->cocinero; } /** * Set vitaminasComida * * @param string $vitaminasComida * @return Comidas */ public function setVitaminasComida($vitaminasComida) { $this->vitaminasComida = $vitaminasComida; return $this; } /** * Get vitaminasComida * * @return string */ public function getVitaminasComida() { return $this->vitaminasComida; } /** * Set idCaserio * * @param integer $idCaserio * @return Comidas */ public function setIdCaserio($idCaserio) { $this->idCaserio = $idCaserio; return $this; } /** * Get idCaserio * * @return integer */ public function getIdCaserio() { return $this->idCaserio; } } <file_sep>/src/Distrito/CaseriosBundle/Entity/Deportes.php <?php namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Deportes * * @ORM\Table() * @ORM\Entity */ class Deportes { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="NombreDeporte", type="string", length=255) */ private $nombreDeporte; /** * @var string * * @ORM\Column(name="Descripcion", type="text") */ private $descripcion; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombreDeporte * * @param string $nombreDeporte * @return Deportes */ public function setNombreDeporte($nombreDeporte) { $this->nombreDeporte = $nombreDeporte; return $this; } /** * Get nombreDeporte * * @return string */ public function getNombreDeporte() { return $this->nombreDeporte; } /** * Set descripcion * * @param string $descripcion * @return Deportes */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } } <file_sep>/src/Distrito/CaseriosBundle/Controller/CaseriosController.php <?php namespace Distrito\CaseriosBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Distrito\CaseriosBundle\Entity\Caserios; use Symfony\Component\HttpFoundation\File\UploadedFile; use Distrito\CaseriosBundle\Form\CaseriosType; /** * Caserios controller. * */ class CaseriosController extends Controller { /** * Lists all Caserios entities. * */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('DistritoCaseriosBundle:Caserios')->findAll(); return $this->render('DistritoCaseriosBundle:Caserios:index.html.twig', array( 'entities' => $entities, )); } /** * Creates a new Caserios entity. crenado un cambio para ve git * */ public function createAction(Request $request) { $entity = new Caserios(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('caserios_show', array('id' => $entity->getId()))); } return $this->render('DistritoCaseriosBundle:Caserios:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Creates a form to create a Caserios entity. * * @param Caserios $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Caserios $entity) { $form = $this->createForm(new CaseriosType(), $entity, array( 'action' => $this->generateUrl('caserios_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new Caserios entity. * */ public function newAction() { $entity = new Caserios(); $form = $this->createCreateForm($entity); return $this->render('DistritoCaseriosBundle:Caserios:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Finds and displays a Caserios entity. * */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DistritoCaseriosBundle:Caserios')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Caserios entity.'); } $deleteForm = $this->createDeleteForm($id); return $this->render('DistritoCaseriosBundle:Caserios:show.html.twig', array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing Caserios entity. * */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DistritoCaseriosBundle:Caserios')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Caserios entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return $this->render('DistritoCaseriosBundle:Caserios:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Creates a form to edit a Caserios entity. * * @param Caserios $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Caserios $entity) { $form = $this->createForm(new CaseriosType(), $entity, array( 'action' => $this->generateUrl('caserios_update', array('id' => $entity->getId())), //'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing Caserios entity. * */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DistritoCaseriosBundle:Caserios')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Caserios entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('caserios', array('id' => $id))); } return $this->render('DistritoCaseriosBundle:Caserios:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a Caserios entity. * */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DistritoCaseriosBundle:Caserios')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Caserios entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('caserios')); } /** * Creates a form to delete a Caserios entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('caserios_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } } <file_sep>/src/Distrito/CaseriosBundle/Controller/CaseriosDistritoController.php <?php namespace Distrito\CaseriosBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Distrito\CaseriosBundle\Entity\Galeria; use Distrito\CaseriosBundle\Entity\Caserios; use Symfony\Component\HttpFoundation\File; class CaseriosDistritoController extends Controller { /* *Funcion para el index */ public function indexAction() { /*$em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DistritoCaseriosBundle:Caserios')->findAll();*/ $em = $this->getDoctrine()->getManager(); /* $query = $em->createQuery( "SELECT c.id, c.nombre,c.descripcion,g.imgGaleria FROM DistritoCaseriosBundle:Caserios c INNER JOIN c.galeria g WITH g.caserios_id = c.id GROUP BY c.id ORDER BY c.nombre ASC" ); */ $query = $em->createQuery( "SELECT c.id, c.nombre,c.descripcion,c.Imagencaserio FROM DistritoCaseriosBundle:Caserios c" ); $entity = $query->getResult(); /*traer imagenes de slider */ $query = $em->createQuery( "SELECT g.Imagencaserio,g.descripcion FROM DistritoCaseriosBundle:Caserios g" ); $gallery = $query->getResult(); return $this->render('DistritoCaseriosBundle:CaseriosDistrito:caserio.html.twig',array( 'entity'=>$entity, 'gallery'=>$gallery, )); } public function detalleAction($id){ $em = $this->getDoctrine()->getManager(); /*esta consulta trae todos los caserios */ $query= $em->createQuery( 'SELECT c.id,c.nombre FROM DistritoCaseriosBundle:Caserios c' ); $queryall =$query->getResult(); /*esta consulta trae el detalle del caserio */ $query = $em->createQuery( "SELECT c.id, c.nombre,c.Imagencaserio,c.descripcion,c.Video_1,c.Video_2,c.Video_3,c.Video_4 FROM DistritoCaseriosBundle:Caserios c WHERE c.id=$id" ); $entity = $query->getResult(); /*esta consulta trae imagenes de la galeria del caserio */ $query = $em->createQuery( "SELECT g.imgGaleria FROM DistritoCaseriosBundle:Galeria g WHERE g.caserios_id=$id" ); $queryg = $query->getResult(); return $this->render('DistritoCaseriosBundle:CaseriosDistrito:detallecaserio.html.twig',array( 'queryall'=> $queryall, 'entity'=>$entity, 'queryg'=>$queryg, )); } /* * funcion para vista quienes somos */ public function quienesAction() { return $this->render('DistritoCaseriosBundle:CaseriosDistrito:quienes-somos.html.twig'); } /* * funcion para vista del blog */ public function blogAction() { return $this->render('DistritoCaseriosBundle:CaseriosDistrito:blog.html.twig'); } /* * funcion para vista contacto */ public function contactAction() { return $this->render('DistritoCaseriosBundle:CaseriosDistrito:contact.html.twig'); } } <file_sep>/src/Distrito/CaseriosBundle/Entity/Autoridades.php <?php namespace Distrito\CaseriosBundle\Entity; namespace Distrito\CaseriosBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Autoridades * * @ORM\Table() * @ORM\Entity */ class Autoridades { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="NombreAutoridad", type="string", length=255) */ private $nombreAutoridad; /** * @var string * * @ORM\Column(name="Cargo", type="string", length=255) */ private $cargo; /** * @var integer * * @ORM\Column(name="Dni", type="integer") */ private $dni; /** * @var integer * * @ORM\Column(name="Edad", type="integer") */ private $edad; /** * @var string * * @ORM\Column(name="Descripcion", type="text") */ private $descripcion; /** * @var string * * @ORM\Column(name="GradoEstudio", type="string", length=255) */ private $gradoEstudio; /** * @var integer * @ORM\ManyToOne(targetEntity="Caserios") * @ORM\JoinColumn(name="Caserios_id", nullable=false, referencedColumnName="id") **/ private $Caserios_id; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombreAutoridad * * @param string $nombreAutoridad * @return Autoridades */ public function setNombreAutoridad($nombreAutoridad) { $this->nombreAutoridad = $nombreAutoridad; return $this; } /** * Get nombreAutoridad * * @return string */ public function getNombreAutoridad() { return $this->nombreAutoridad; } /** * Set cargo * * @param string $cargo * @return Autoridades */ public function setCargo($cargo) { $this->cargo = $cargo; return $this; } /** * Get cargo * * @return string */ public function getCargo() { return $this->cargo; } /** * Set dni * * @param integer $dni * @return Autoridades */ public function setDni($dni) { $this->dni = $dni; return $this; } /** * Get dni * * @return integer */ public function getDni() { return $this->dni; } /** * Set edad * * @param integer $edad * @return Autoridades */ public function setEdad($edad) { $this->edad = $edad; return $this; } /** * Get edad * * @return integer */ public function getEdad() { return $this->edad; } /** * Set descripcion * * @param string $descripcion * @return Autoridades */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } /** * Set gradoEstudio * * @param string $gradoEstudio * @return Autoridades */ public function setGradoEstudio($gradoEstudio) { $this->gradoEstudio = $gradoEstudio; return $this; } /** * Get gradoEstudio * * @return string */ public function getGradoEstudio() { return $this->gradoEstudio; } /** * Set Caserios_id * * @param \Distrito\CaseriosBundle\Entity\Caserios $caseriosId * @return Autoridades */ public function setCaseriosId(\Distrito\CaseriosBundle\Entity\Caserios $caseriosId) { $this->Caserios_id = $caseriosId; return $this; } /** * Get Caserios_id * * @return \Distrito\CaseriosBundle\Entity\Caserios */ public function getCaseriosId() { return $this->Caserios_id; } public function __toString() { return $this->nombreAutoridad; } }
9db6a2bbdbfe8fdc517a5f10d813b9aa080c8937
[ "JavaScript", "SQL", "PHP" ]
13
PHP
evargasguarniz/symfony
45ca266767f9cace8aeee64be7fa9a095d697f7d
2538901b8eb9963c787f23f7b2eb04368429bf24
refs/heads/master
<repo_name>Kumahia-R/EECE.3220-Programs<file_sep>/EECE.3220 Programs/Prog3_stack_calc.cpp #include <iostream> #include <string> #include <cctype> #include "Node.h" #include "Stack.h" using namespace std; int pemdas(char op) { if (op == '*' || op == '/') { return 2; } else { return 1; } } int operation(char operand, int int1, int int2) { switch (operand) { case '*': return int1 * int2; break; case '/': return int1 / int2; break; case '+': return int1 + int2; break; case '-': return int1 - int2; break; } } int postfixMath(string postfix) { char intFirst, intSecond; int result; Stack<char> numbers; for (unsigned int i = 0; i < postfix.length(); i++) { if (postfix.at(i) >= '0' && postfix.at(i) <= '9') { numbers.push(postfix.at(i)); } else if ((postfix.at(i)) == '*' || (postfix.at(i)) == '/' || (postfix.at(i)) == '+' || (postfix.at(i)) == '-' ) { intSecond = numbers.getTop() - '0'; numbers.pop(); intFirst = numbers.getTop() - '0'; numbers.pop(); result = operation(postfix.at(i),intFirst, intSecond) + 48; numbers.push(result); } } result = numbers.getTop() - 48; return result; } string postfix(string infix) { Stack<char> operators; string postfix; for (int i = 0; i < infix.size(); i++) { if (isdigit(infix.at(i))) { postfix.push_back(infix.at(i)); postfix.push_back(' '); } else if (infix.at(i) == '(') { operators.push(infix.at(i)); } else if (infix.at(i) == ')') { while (operators.getTop() != '(') { postfix.push_back(operators.getTop()); postfix.push_back(' '); operators.pop(); } operators.pop(); } else if (infix.at(i) != ' ') { if (operators.empty() || pemdas(infix.at(i) >= pemdas(operators.getTop() || operators.getTop() == '('))) { operators.push(infix.at(i)); } else { if (infix.at(i) != '+' || infix.at(i) != '-') { postfix.push_back(operators.getTop()); operators.pop(); } else { while (!operators.empty() && operators.getTop() != '(') { postfix.push_back(operators.getTop()); postfix.push_back(' '); operators.pop(); } postfix.push_back(infix.at(i)); postfix.push_back(' '); } } } } while (!operators.empty()) { postfix.push_back(operators.getTop()); postfix.push_back(' '); operators.pop(); } return postfix; } int main() { string infix; Stack<char> inDigits; while (infix != "exit") { cout << "Enter expression (or exit to end):\n"; getline(cin, infix); string post = postfix(infix); if (infix.at(0) == '(' || isdigit(infix.at(0))) { cout << "Expression: " << infix << endl; cout << "Postfix form: " << post << endl; cout << "Result: " << postfixMath(post) << endl; } else if (infix.at(0) != 'e') { cout << "Invalid expression\n"; } } cout << "Exiting program ...\n"; }<file_sep>/EECE.3220 Programs/PLtest.cpp /* <NAME> EECE.3220: Data Structures Code for Summer 2020 Midterm PLtest.cpp: code to test PointList functions */ #include "PointList.h" // Implicitly includes Point.h #include <cstdlib> // Needed for srand(), rand() #include <iostream> using namespace std; int main() { char fn; // Used to determine which function is being tested // 'P' -> printList(), 'F' -> isFull(), 'L' -> isLine() PointList pl1, pl2, pl3, pl4; // pointList objects to be tested Point temp; // Temporary Point object double x, y; // Coordinates to be tested unsigned i; // Loop index srand(1); // Seed RNG // Fill PointList objects; pl4 remains empty x = -32; y = -20; for (i = 0; i < 10; i++) { // Fill pl1 so it's a line--difference temp.setX(x); // in x, y coordinates same for all temp.setY(y); // consecutive points pl1.addPoint(temp); x += 3.2; y += 2.5; } for (i = 0; i < 20; i++) { // Fill pl2 with 20 random values between +/- 10 temp.setX(rand() % 21 - 10); // Highly unlikely to be a line temp.setY(rand() % 21 - 10); pl2.addPoint(temp); } for (i = 0; i < 50; i++) { // Fill pl3 with 50 random values between +/- 5 temp.setX(rand() % 11 - 5); // Highly unlikely to be a line temp.setY(rand() % 11 - 5); // isFull() will return true for this list pl3.addPoint(temp); } cout << "Which function are you testing? "; cin >> fn; switch (fn) { case 'P': // Print pl1, pl2, and pl4 (nobody wants to see 50 points in pl3) cout << "TESTING printList():\npl1:\n"; pl1.printList(cout); cout << "\npl2:\n"; pl2.printList(cout); cout << "\npl4:\n"; pl4.printList(cout); break; case 'F': // Check isFull()--pl3 should return true, all others should return false cout << "TESTING isFull():\n" << "pl1: " << (pl1.isFull() ? "Full\n" : "Not full\n") << "pl2: " << (pl2.isFull() ? "Full\n" : "Not full\n") << "pl3: " << (pl3.isFull() ? "Full\n" : "Not full\n") << "pl4: " << (pl4.isFull() ? "Full\n" : "Not full\n"); break; case 'L': cout << "TESTING isLine():\n" << "pl1: " << (pl1.isLine() ? "Line\n" : "Not a line\n"); cout<< "pl2: " << (pl2.isLine() ? "Line\n" : "Not a line\n") << "pl3: " << (pl3.isLine() ? "Line\n" : "Not a line\n") << "pl4: " << (pl4.isLine() ? "Line\n" : "Not a line\n"); break; } return 0; }<file_sep>/EECE.3220 Programs/LList_test_main.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * Linked list definition * * LList_test_main.cpp: test program for sort() function */ #include "LList.h" #include <cstdlib> #include <iostream> using namespace std; int main() { LList L1, L2; // Linked lists to use for testing unsigned i; // Loop indexes int seed; // RNG seed // RNG seed--ensures you'll get same "random" values across // multiple runs with same seed cout << "Seed value: "; cin >> seed; srand(seed); // Fill lists for (i = 0; i < 10; i++) { L1.insert(rand() % 50); L2.insert(rand() % 50); } // Print lists before sorting cout << "Before sorting:\nL1: "; L1.display(cout); cout << "\nL2: "; L2.display(cout); // Sort and print lists again L1.sort(); L2.sort(); cout << "After sorting:\nL1: "; L1.display(cout); cout << "\nL2: "; L2.display(cout); return 0; }<file_sep>/EECE.3220 Programs/prog5main.cpp #include "Queue.h" #include "QItem.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream file; string fileName; string line; Queue<QItem> expCus; Queue<QItem> normCus; cout << "Enter input file name: "; cin >> fileName; cout << "Reading " << fileName << " ..." << endl; file.open(fileName); int cusPos = 1; while (getline(file, line)) { string arrive; string service; string lane; string letter; int index = 2; while (line.at(index) != ' ') { arrive.push_back(line.at(index)); index++; } index++; service.push_back(line.at(index)); QItem temp(cusPos, arrive, service); if (line.at(0) == 'E') { lane = "express"; expCus.enqueue(temp); } else if (line.at(0) == 'N') { lane = "normal"; normCus.enqueue(temp); } cout << "Customer " << cusPos << " to " << lane << " lane " << "(A = " << arrive << ", S = " << service << ")" << endl; cusPos++; } file.close(); cout << "Done reading " << fileName << endl; int time = 0; int normieTime = 0; int expTime = 0; int normCusServ = 0; int ExpCusServ = 0; while (!expCus.empty() || !normCus.empty()) { if (normieTime == 0 && normCus.getFront().getArr() <= time && normCusServ == 0) { cout << "T=" << time << ": Serving customer " << normCus.getFront().getcNum() << " in normal lane" << endl; normieTime = normCus.getFront().getSvc(); normCusServ = 1; } if (expTime == 0 && expCus.getFront().getArr() <= time && ExpCusServ == 0) { cout << "T=" << time << ": Serving customer " << expCus.getFront().getcNum() << " in express lane" << endl; expTime = expCus.getFront().getSvc(); ExpCusServ = 1; } if (normieTime != 0) { normieTime--; } if (expTime != 0) { expTime--; } if (normieTime == 0 && normCusServ == 1) { cout << "T=" << time << ": Done serving customer " << normCus.getFront().getcNum() << " in normal lane" << endl; normCusServ = 0; normCus.dequeue(); } if (expTime == 0 && ExpCusServ == 1) { cout << "T=" << time << ": Done serving customer " << expCus.getFront().getcNum() << " in express lane" << endl; ExpCusServ = 0; expCus.dequeue(); } time++; } cout << "Done serving all customers" << endl; return 0; }<file_sep>/EECE.3220 Programs/Prog1Part3.cpp #include <iostream> using namespace std; int main() { int arrowBaseHeight = 0; int arrowBaseWidth = 0; int arrowHeadWidth = 0; cout << "Enter arrow base height:" << endl; cin >> arrowBaseHeight; cout << "Enter arrow base width:" << endl; cin >> arrowBaseWidth; while (arrowHeadWidth <= arrowBaseWidth) { cout << "Enter arrow head width:" << endl; cin >> arrowHeadWidth; } cout << endl; // Draw arrow base (height = 3, width = 2) for (int i = 0; i < arrowBaseHeight; i++) { for (int j = 0; j < arrowBaseWidth; j++) { cout << '*'; } cout << endl; } // Draw arrow head (width = 4) for (int i = 0; i < arrowHeadWidth; i++) { for (int j = 0; j < arrowHeadWidth - i; j++) { cout << '*'; } cout << endl; } return 0; }<file_sep>/EECE.3220 Programs/Prog2Part1main.cpp #include <iostream> using namespace std; #include "ItemToPurchase.h" int main() { string userName; int userPrice; int userQuantity; cout << "Item 1" << endl << "Enter the item name:" << endl; getline(cin, userName); cout << "Enter the item price:" << endl; cin >> userPrice; cout << "Enter the item quantity:" << endl << endl; cin >> userQuantity; ItemToPurchase item1; item1.SetName(userName); item1.SetPrice(userPrice); item1.SetQuantity(userQuantity); cin.ignore(); cout << "Item 2" << endl << "Enter the item name:" << endl; getline(cin, userName); cout << "Enter the item price:" << endl; cin >> userPrice; cout << "Enter the item quantity:" << endl << endl; cin >> userQuantity; ItemToPurchase item2; item2.SetName(userName); item2.SetPrice(userPrice); item2.SetQuantity(userQuantity); int totPrice1 = item1.GetPrice() * item1.GetQuantity(); int totPrice2 = item2.GetPrice() * item2.GetQuantity(); cout << "TOTAL COST" << endl; cout << item1.GetName() << " " << item1.GetQuantity() << " @ $" << item1.GetPrice() << " = $" << totPrice1 << endl; cout << item2.GetName() << " " << item2.GetQuantity() << " @ $" << item2.GetPrice() << " = $" << totPrice2 << endl << endl; cout << "Total: $" << totPrice1 + totPrice2 << endl; /* Type your code here */ return 0; }<file_sep>/EECE.3220 Programs/Point.h /* <NAME> EECE.3220: Data Structures Point example code for in-class operator overloading example (Modified version of composition example) Class definition */ #ifndef Point_h // Header guard #define Point_h #include <iostream> // Necessary for printPoint prototype using std::ostream; // ... but it doesn't work without // indicating what part of <iostream> // we're using class Point { public: Point(); // Default constructor Point(double X, double Y); // Parameterized constructor void setX(double newX); // Set X coordinate void setY(double newY); // Set Y coordinate double getX(); // Returns X coordinate double getY(); // Returns Y coordinate // OVERLOADED OPERATORS Point& operator =(const Point &rhs); // Assignment // e.g., p1 = p2; --> p1.operator=(p2); bool operator ==(const Point &rhs); // Equality friend ostream& operator <<(ostream& out, const Point& p); // Output operator private: double xCoord; // X coordinate double yCoord; // Y coordinate }; #endif<file_sep>/EECE.3220 Programs/ItemToPurchase.h #ifndef ITEM_TO_PURCHASE_H #define ITEM_TO_PURCHASE_H #include <string> using namespace std; class ItemToPurchase { public: ItemToPurchase(); ItemToPurchase(string Name, string Description, int Price, int Quantity); void SetName(string Name); void SetDescription(string Description); void PrintItemCost(); void SetPrice(int Price); void SetQuantity(int Quantity); void PrintItemDescription(); string GetName(); string GetDescription(); int GetPrice(); int GetQuantity(); private: string I_Name; string I_Description; int I_Price; int I_Quantity; }; #endif<file_sep>/EECE.3220 Programs/BST_test_main.cpp /* * <NAME> * EECE.3220: Data Structures * * Exam 3 code * Main program to test BST functions */ #include <iostream> using namespace std; #include <cstdlib> // Used for RNG--same seed value, same "random" values #include "BST.h" int main() { BST b1, b2, b3; // BSTs unsigned i; // Loop indexes int seed; // RNG seed int rval; // Value used to insert multiples unsigned part; // Used to determine which BST function is being tested // RNG seed--ensures you'll get same "random" values across // multiple runs with same seed cout << "Seed value: "; cin >> seed; srand(seed); // b1 contains 10 values--fill tree, then print contents for (i = 0; i < 10; i++) b1.insert(rand() % 25); cout << "\nAfter filling b1\n"; b1.printInOrder(cout); // b2 contains 15 values--each loop iteration adds // 2 copies of one random value (to ensure // duplicates) and one other value for (i = 0; i < 5; i++) { rval = rand() % 50; b2.insert(rval); b2.insert(rand() % 50); b2.insert(rval); } cout << "\nAfter filling b2\n"; b2.printInOrder(cout); // b3 is empty, and the output reflects that cout << "\nWithout filling b3\n"; b3.printInOrder(cout); // Testing exam functions cout << "\nWhich part? "; cin >> part; switch (part) { case 1: // Testing findMin() cout << "\nMinimum value in b1 = " << b1.findMin() << endl; cout << "\nMinimum value in b2 = " << b2.findMin() << endl; cout << "\nMinimum value in b3 (should be 0) = " << b3.findMin() << endl; break; case 2: // Testing countNodes() cout << "\nNumber of nodes in b1 = " << b1.countNodes() << endl; cout << "\nNumber of nodes in b2 = " << b2.countNodes() << endl; cout << "\nNumber of nodes in b3 = " << b3.countNodes() << endl; break; case 3: // Testing printDuplicates() cout << "\nTesting printDuplicates() for b1:\n"; b1.printDuplicates(cout); cout << "\nTesting printDuplicates() for b2:\n"; b2.printDuplicates(cout); } return 0; }<file_sep>/EECE.3220 Programs/Prog1Part1.cpp #include <iostream> #include <cmath> // Note: Needed for math functions in part (3) #include <iomanip> using namespace std; int main() { double wallHeight; double wallWidth; double wallArea; cout << "Enter wall height (feet):" << endl; cin >> wallHeight; cout << "Enter wall width (feet):" << endl; cin >> wallWidth; // FIXME (1): Prompt user to input wall's width // Calculate and output wall area wallArea = wallHeight * wallWidth; // FIXME (1): Calculate the wall's area cout << "Wall area: " << setprecision(2) << fixed << wallArea << " square feet" << endl; // FIXME (1): Finish the output statement // FIXME (2): Calculate and output the amount of paint in gallons needed to paint the wall double paintNeeded; paintNeeded = wallArea / 350; cout << "Paint needed: " << paintNeeded << " gallons" << endl; // FIXME (3): Calculate and output the number of 1 gallon cans needed to paint the wall, rounded up to nearest integer int cansNeeded; cansNeeded = ceil(paintNeeded); cout << "Cans Needed: " << cansNeeded << " can(s)" << endl; return 0; }<file_sep>/EECE.3220 Programs/ItemToPurchase.cpp #include <iostream> using namespace std; #include "ItemToPurchase.h" ItemToPurchase::ItemToPurchase() { I_Name = "none"; I_Description = "none"; I_Price = 0; I_Quantity = 0; } ItemToPurchase::ItemToPurchase(string Name, string Description, int Price, int Quantity) { I_Name = Name; I_Description = Description; I_Price = Price; I_Quantity = Quantity; } void ItemToPurchase::SetName(string Name) { I_Name = Name; } void ItemToPurchase::SetDescription(string Description) { I_Description = Description; } void ItemToPurchase::SetQuantity(int Quantity) { I_Quantity = Quantity; } void ItemToPurchase::SetPrice(int Price) { I_Price = Price; } string ItemToPurchase::GetName() { return I_Name; } string ItemToPurchase::GetDescription() { return I_Description; } int ItemToPurchase::GetPrice() { return I_Price; } int ItemToPurchase::GetQuantity() { return I_Quantity; } void ItemToPurchase::PrintItemCost() { int n = I_Price * I_Quantity; cout << I_Name << " " << I_Quantity << " @ $" << I_Price << " = $" << n << endl; } void ItemToPurchase::PrintItemDescription() { cout << I_Name << ": " << I_Description << endl; }<file_sep>/EECE.3220 Programs/RTC.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * * RTC.cpp: Function to run Program 3 test cases */ #include "Time.h" #include <iostream> #include <string> using namespace std; // Print results of comparing 2 time objects (RunTestCases helper function) void conditionTest(Time& T1, Time& T2) { cout << T1 << " == " << T2 << ": " << (T1 == T2 ? "true\n" : "false\n") << T1 << " != " << T2 << ": " << (T1 != T2 ? "true\n" : "false\n") << T1 << " < " << T2 << ": " << (T1 < T2 ? "true\n" : "false\n") << T1 << " > " << T2 << ": " << (T1 > T2 ? "true\n" : "false\n"); } // Print results of arithmetic operations 2 time objects (RunTestCases helper function) // This function copies original Time objects so they aren't actually modified void arithTest(const Time& T1ref, const Time& T2ref) { Time T1 = T1ref; Time T2 = T2ref; cout << T1 << " + " << T2 << " = " << T1 + T2 << '\n' << T1 << " - " << T2 << " = " << T1 - T2 << '\n' << T1 << " += " << T2 << " = "; T1 += T2; cout << T1 << '\n' << T1 << " -= " << T2 << " = "; T1 -= T2; cout << T1 << "\n\n"; } // RunTestCases() handles all input and output for actual test cases // When running in submit mode, main() should only contain a call // to this function; leaving the call out of your main() function // allows you to run the program in develop mode and test your work // without worrying about the test cases void RunTestCases() { unsigned tCase; // Number representing test case(s) to run string repeat; // Indicates desire to repeat program // Standalone Time objects for testing Time T1(3, 35, 'P'); Time T2(12, 17, 'A'); Time T3(8, 0, 'A'); Time T4(7, 6, 'P'); do { cout << "\nWhich operators would you like to test?\n" << "1 = input/output, 2 = comparisons,\n" << "3 = arithmetic, 4 = pre-/post increment: "; cin >> tCase; switch (tCase) { case 1: // >> and << operator tests cout << "<< and >> operator tests:\n"; cout << "T1-T4 original values:\nT1: "; cout << T1; cout << "\nT2: " << T2; cout << "\nT3: " << T3 << "\nT4: " << T4 << '\n'; cout << "Enter new time for T1: "; cin >> T1; cout << "Enter new times for T2 & T3: "; cin >> T2 >> T3; cout << "New times:\nT1: " << T1 << "\nT2: " << T2 << "\nT3: " << T3 << '\n'; break; case 2: // Comparisons: == != < > cout << "Relative operator tests\n"; T3.set(3, 35, 'P'); // T1 & T3 now match T4.set(12, 17, 'P'); // T2 & T4 hrs and minutes match, but not AM/PM cout << "\nComparing T1 & T2:\n"; conditionTest(T1, T2); cout << "\nComparing T2 & T3:\n"; conditionTest(T2, T3); cout << "\nComparing T1 & T3:\n"; conditionTest(T1, T3); cout << "\nComparing T2 & T4:\n"; conditionTest(T2, T4); break; case 3: // Arithmetic: + - += -= cout << "Arithmetic operator tests:\n"; arithTest(T1, T2); arithTest(T3, T4); T3.set(4, 15, 'A'); T4.set(3, 20, 'A'); arithTest(T3, T4); T3.set(1, 15, 'P'); T4.set(3, 20, 'P'); arithTest(T3, T4); break; case 4: // ++ operators (pre- and post-increment) cout << "Pre- and post-increment operator tests:\n"; cout << "T1: " << T1; cout << "\nT1++ before increment: " << T1++; cout << ", and after increment: " << T1; cout << "\n++T1: " << ++T1; T1.set(11, 59, 'A'); cout << "\n\nNow, T1: " << T1; cout << "\nT1++ before increment: " << T1++; cout << ", and after increment: " << T1; T1.set(11, 59, 'P'); cout << "\n\nFinally, T1: " << T1; cout << "\n++T1: " << ++T1 << '\n'; break; default: cout << "Invalid selection " << tCase << '\n'; } do { cout << "Would you like to test more operators (yes/no)? "; cin >> repeat; if (repeat != "yes" && repeat != "no") cout << "Invalid response " << repeat << '\n'; } while (repeat != "yes" && repeat != "no"); } while (repeat == "yes"); // Return to start of function if user enters "yes" }<file_sep>/EECE.3220 Programs/ShoppingCart.h #pragma once #ifndef SHOPPING_CART_H #define SHOPPING_CART_H #include <vector> #include "ItemToPurchase.h" using namespace std; class ShoppingCart { public: ShoppingCart(); ShoppingCart(string customerName, string Inputdate); void AddItem(ItemToPurchase addNewItem); void RemoveItem(string I_Name); void ModifyItem(ItemToPurchase Mod_Item); string GetCustomerName(); string GetDate(); int GetNumItemsInCart(); int GetCostOfCart(); void PrintTotal(); void PrintDescriptions(); private: string nameEntered; string dateEntered; vector<ItemToPurchase> cartItems; }; #endif // !SHOPPING_CART_H<file_sep>/EECE.3220 Programs/Prog2Part2main.cpp #include <iostream> using namespace std; #include <string> #include "ItemToPurchase.h" #include "ShoppingCart.h" void PrintMenu(ShoppingCart shoppingCart) { string nameofItem; string itemDescription; string modName; int itemPrice = 0; int itemQuantity = 0; int newQuantity = 0; ItemToPurchase Item_new; ItemToPurchase Item_mod; cout << endl << "MENU" << endl << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; cout << "Choose an option: " << endl; char userInput; cin >> userInput; cin.ignore(); while (userInput != 'a' && userInput != 'd' && userInput != 'c' && userInput != 'i' && userInput != 'o' && userInput != 'q') { cout << "Choose an option: " << endl; cin >> userInput; } while (userInput != 'q') { while (userInput != 'a' && userInput != 'd' && userInput != 'c' && userInput != 'i' && userInput != 'o' && userInput != 'q') { cout << "Choose an option: " << endl; cin >> userInput; } switch (userInput) { case 'a': cout << endl << "ADD ITEM TO CART" << endl << endl; cout << "Enter the item name: "; getline(cin, nameofItem); cout << endl << "Enter the item description: "; getline(cin, itemDescription); cout << endl << "Enter the item price: "; cin >> itemPrice; cout << endl << "Enter the item quantity: "; cin >> itemQuantity; Item_new.SetName(nameofItem); Item_new.SetDescription(itemDescription); Item_new.SetPrice(itemPrice); Item_new.SetQuantity(itemQuantity); shoppingCart.AddItem(Item_new); break; case 'd': cout << endl << "REMOVE ITEM FROM CART" << endl; cout << "Enter name of item to remove: " << endl; getline(cin, modName); shoppingCart.RemoveItem(modName); break; case 'c': cout << endl << "CHANGE ITEM QUANTITY" << endl; cout << "Enter the item name: " << endl; cin.ignore(); getline(cin, nameofItem); cout << endl << "Enter the new quantity: " << endl; cin >> newQuantity; Item_mod.SetName(nameofItem); Item_mod.SetQuantity(newQuantity); shoppingCart.ModifyItem(Item_mod); break; case 'o': cout << endl << "OUTPUT SHOPPING CART" << endl; shoppingCart.PrintTotal(); break; case 'i': cout << endl << "OUTPUT ITEMS' DESCRIPTIONS" << endl << endl; shoppingCart.PrintDescriptions(); break; } cout << endl << "MENU" << endl << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; cout << "Choose an option: " << endl; cin >> userInput; cin.ignore(); } } int main() { string userName; string date; cout << "Enter customer's name: " << endl; getline(cin, userName); cout << "Enter today's date: " << endl; getline(cin, date); cout << endl << "Customer name: " << userName << endl; cout << "Today's date: " << date << endl << endl; ShoppingCart Customer_Cart(userName, date); PrintMenu(Customer_Cart); return 0; } <file_sep>/EECE.3220 Programs/Time.h #pragma once /* * EECE.3220: Data Structures * Instructor: <NAME> * * Time.h: Time class definition * Includes prototypes for overloaded operators to be written for Program 3 */ // Header guard directives--ensures header included only once #ifndef TIME_H #define TIME_H #include <iostream> using std::ostream; using std::istream; class Time { public: /*** FUNCTIONS DEFINED FOR YOU IN Time.cpp ***/ Time(); // Default constructor Time(unsigned h, unsigned m, char AP); // Parameterized constructor void set(unsigned h, unsigned m, char AP); // Set time data members void display(ostream& out); // Print time to desired output stream void advance(unsigned h, unsigned m); // Advance time by given number of hours and minutes bool lessThan(const Time& rhs); // Returns true if calling object is less than argument /*** OVERLOADED OPERATORS TO BE ADDED FOR PROGRAM 3 ***/ // Input/output operators friend ostream& operator <<(ostream& out, const Time& rhs); friend istream& operator >>(istream& in, Time& rhs); // Comparison operators bool operator ==(const Time& rhs); bool operator !=(const Time& rhs); bool operator <(const Time& rhs); bool operator >(const Time& rhs); // Arithmetic operators Time operator +(const Time& rhs); Time operator -(const Time& rhs); Time& operator +=(const Time& rhs); Time& operator -=(const Time& rhs); // Increment operators--adds 1 minute to current time Time& operator++(); Time operator++(int); /*** END OVERLOADED OPERATORS TO BE ADDED FOR PROGRAM 3 ***/ private: unsigned hours, minutes; // Time in hrs/mins (combined with AM/PM) char AMorPM; // Indicates morning/afternoon--'A' for AM, 'P' for PM unsigned miltime; // Military (24-hour) time equivalent }; #endif // TIME_H <file_sep>/EECE.3220 Programs/BST.cpp /* * <NAME> * EECE.3220: Data Structures * * Exam 3 code * Source file for BST class * * In definitions below, nullptr == NULL */ #include "BST.h" /************ EXAM 3 FUNCTIONS TO BE COMPLETED ************/ // Find and return the minimum value in the BST // Returns 0 if tree is empty int BST::findMin() { /***** ADD YOUR OWN SOLUTION *****/ if (empty()) { return 0; } else { BST* minAdd = new BST; BST& min = *minAdd; *minAdd = *this; int minVal = min.root->val; int searchVal = minVal; while (searchVal > 0) { if (min.search(--searchVal)) { minVal = searchVal; } } return minVal; } } // Count all nodes in tree // HINT: You may want a helper function--recursive or iterative--that visits each node unsigned BST::countNodes() { /***** ADD YOUR OWN SOLUTION *****/ if (empty()) { return 0; } else { int numCount = 0; int *nodeCount = new int; *nodeCount = numCount; findNode(root, *nodeCount); return *nodeCount; } } // Finds all duplicates and prints them to out // Hint: You may want a helper function to traverse the tree void BST::printDuplicates(ostream& out) { /***** ADD YOUR OWN SOLUTION *****/ BST* tmp1 = new BST; *tmp1 = *this; BST& tmpAdd1 = *tmp1; int dupNum = 0; int* isDup = new int; *isDup = dupNum; int dupVal = tmpAdd1.root->val; findDup(this->root, *isDup, dupVal); out << "Duplicates:"; if (*isDup > 1) { out << " " << dupVal; tmpAdd1.remove(dupVal); } while (tmpAdd1.root != NULL) { *isDup = 0; if (tmpAdd1.root->left == NULL) { while (tmpAdd1.root->right != NULL) { findDup(tmpAdd1.root, *isDup, tmp1->root->val); if (*isDup > 1) { out << " " << tmp1->root->val; tmpAdd1.remove(tmp1->root->val); } tmpAdd1.root = tmpAdd1.root->right; } } else { tmpAdd1.root = root->left; } } if (*isDup > 1) { cout << " " << *isDup; } } /************ END EXAM 3 FUNCTIONS TO BE COMPLETED ************/ /**** FUNCTIONS BELOW THIS LINE ARE ALREADY DEFINED FOR YOU--DO NOT CHANGE ****/ // Returns true if tree empty; false otherwise bool BST::empty() { return (root == nullptr); } // Adds new node with value v void BST::insert(int v) { BSTNode* n = new BSTNode(v); if (root == nullptr) root = n; else insertNode(root, n); } // Removes node with value v // Returns true if node found & removed; false otherwise bool BST::remove(int v) { return removeNode(root, nullptr, v); } // Returns true if v in tree; false otherwise bool BST::search(int v) { return (searchNode(root, v) != nullptr); } // Prints tree contents in order void BST::printInOrder(ostream& out) { if (root == nullptr) out << "Tree is empty\n"; else { out << "Tree contents:\n"; printNode(root, out); out << "\n"; } } // Recursive helper functions void BST::insertNode(BSTNode* tree, BSTNode* n) { if (n->val < tree->val) { if (tree->left == nullptr) tree->left = n; else insertNode(tree->left, n); } else { if (tree->right == nullptr) tree->right = n; else insertNode(tree->right, n); } } // Recursively remove node with value v // Takes parent pointer so we don't need another search function to find it bool BST::removeNode(BSTNode* tree, BSTNode* parent, int v) { if (tree == nullptr) // Base case 1 return false; if (tree->val == v) { // Found node--base case 2 // Node to remove is leaf if (tree->left == nullptr && tree->right == nullptr) { if (parent->right == tree) parent->right = nullptr; else parent->left = nullptr; delete tree; } // Node has one child on right else if (tree->left == nullptr) { if (parent->right == tree) parent->right = tree->right; else parent->left = tree->right; delete tree; } // Node has one child on left else if (tree->right == nullptr) { if (parent->right == tree) parent->right = tree->left; else parent->left = tree->left; delete tree; } // Node has two children else { // Find in-order successor, copy data from that node to "tree", then delete successor BSTNode* s = tree->right; BSTNode* sp = tree; // Parent node to pass to delete function while (s->left != nullptr) { sp = s; s = s->left; } tree->val = s->val; removeNode(s, sp, s->val); } return true; } else if (v < tree->val) // Go left return removeNode(tree->left, tree, v); else // Go right return removeNode(tree->right, tree, v); } // Returns node where v is found or nullptr otherwise BST::BSTNode* BST::searchNode(BSTNode* tree, int v) { if (tree == nullptr || v == tree->val) return tree; else if (v < tree->val) return searchNode(tree->left, v); else return searchNode(tree->right, v); } // Recursively visit all nodes in order and print their values void BST::printNode(BSTNode* tree, ostream& out) { if (tree != nullptr) { printNode(tree->left, out); out << " " << tree->val; printNode(tree->right, out); } } void BST::findNode(BSTNode* tree, int& numNodes) { if (tree != NULL) { numNodes++; findNode(tree->left, numNodes); findNode(tree->right, numNodes); } } void BST::findDup(BSTNode* tree, int& dupNum, int dupVal) { if (tree != nullptr && tree->val == dupVal) { dupNum++; if (tree->left != NULL) { findDup(tree->left, dupNum, dupVal); } if (tree->right != NULL) { findDup(tree->right, dupNum, dupVal); } } else { if (tree->left != NULL) { findDup(tree->left, dupNum, dupVal); } if (tree->right != NULL) { findDup(tree->right, dupNum, dupVal); } } }<file_sep>/FinalStack.h #pragma once /* * <NAME> * EECE.3220: Data Structures * * Header file for in-class stack example * Stack class definition * * FOR EXAM 2, ADDED TWO FUNCTIONS TO BE WRITTEN * DEFINITIONS WILL BE WRITTEN IN STACK.CPP */ #ifndef STACK_H #define STACK_H #include <iostream> using namespace std; class Stack { public: // FUNCTIONS TO BE WRITTEN FOR EXAM 2 void print(ostream& out); // Print stack contents from top to bottom, one value per line // Also prints stack capacity and # values currently in stack void swap(Stack& aStack); // Exchange contents of calling object with argument aStack // END OF FUNCTIONS TO BE WRITTEN FOR EXAM 2 Stack(unsigned maxSize = 1024); // Constructor ~Stack(); // Destructor bool empty() const; // Returns true if stack empty void push(const double& val); // Push val to top of stack void pop(); // Remove top of stack double top(); // Read contents of top of stack private: unsigned cap; // Capacity (max size) of stack int tos; // Index for top of stack double* list; // The actual data stored on the stack }; #endif // STACK_H<file_sep>/EECE.3220 Programs/QItem.h #ifndef QITEM_H #define QITEM_H #include <string> using namespace std; class QItem { public: QItem(); QItem(int cNum, string arrTime, string svcTime); int getcNum(); void setcNum(int num); int getArr(); void setArr(int num); int getSvc(); void setSvc(int num); private: unsigned cNum; // Customer number unsigned arrTime; // Arrival time unsigned svcTime; // Time required to service customer }; #endif<file_sep>/EECE.3220 Programs/PointList.cpp /* <NAME> EECE.3220: Data Structures Code for Summer 2020 Midterm PointList.cpp: PointList member function definitions */ #include "PointList.h" #include <iostream> using namespace std; /***** FUNCTIONS TO BE WRITTEN FOR MIDTERM EXAM *****/ // printList(): print a single Point object per line // to output stream "out" // Function should print "List empty\n" if no Points in list // DO NOT ASSUME OUTPUT ALWAYS GOES TO cout void PointList::printList(ostream& out) { for (int i = 0; i < np; i++) { out << list[i] << endl; } if (np == 0) { out << "List empty" << endl; } /***** WRITE YOUR SOLUTION HERE AND REMOVE THIS COMMENT *****/ } // isFull(): returns true if list has no room // for additional Points; false otherwise bool PointList::isFull() { if (np == 50) { return true; } else { return false; } /***** REMOVE THIS LINE--IT'S HERE ONLY TO ENSURE YOUR CODE COMPILES EVEN IF YOU HAVEN'T WRITTEN THIS FUNCTION *****/ } // isLine(): returns true if list represents // straight line (slope between any two // points is the same); false otherwise bool PointList::isLine() { int slopeInit = (list[1].getY() - list[0].getY()) / (list[1].getX() - list[0].getX()); for (int i = 0; i < np - 1; i++) { int slope = (list[i+1].getY() - list[i].getY()) / (list[i+1].getX() - list[i].getX()); if (slope != slopeInit) { return false; } } /***** WRITE YOUR SOLUTION HERE AND REMOVE THIS COMMENT *****/ return true; /***** REMOVE THIS LINE--IT'S HERE ONLY TO ENSURE YOUR CODE COMPILES EVEN IF YOU HAVEN'T WRITTEN THIS FUNCTION *****/ } /***** END OF FUNCTIONS TO BE WRITTEN FOR MIDTERM EXAM *****/ // Default constructor--start with empty list PointList::PointList() : np(0) {} // Add a single point to list void PointList::addPoint(Point& p) { if (np < 50) list[np++] = p; else cout << "Error: list full\n"; }<file_sep>/EECE.3220 Programs/Prog1Part4.cpp #include <iostream> #include <string> using namespace std; int GetNumOfNonWSCharacters(string inString) { int numChars = 0; for (int i = 0; i < inString.size(); i++) { if (inString.at(i) != ' ') { numChars++; } } return numChars; } int GetNumOfWords(string inString) { int numWords = 0; for (int i = 0; i < inString.size(); i++) { if (inString.at(i) == ' ' && inString.at(i - 1) != ' ') { numWords++; } } numWords++; return numWords; } int FindText(string userSample, string inString) { int numInstances = 0; int index = 0; for (int i = 0; i < inString.size(); i++) { if (inString.find(userSample, index) != -1) { numInstances++; index = inString.find(userSample, index); index++; } } return numInstances; } void ReplaceExclamation(string& inString) { for (int i = 0; i < inString.size(); i++) { if (inString.at(i) == '!') { inString.replace(i, 1, "."); } } } void ShortenSpace(string& inString) { for (int i = 0; i < inString.size(); i++) { if (inString.find(" ") != -1) { inString.erase(inString.find(" "), 1); } } } void PrintMenu(string inString) { string menuChoice; int numWords; while (menuChoice.compare("q")) { cout << "MENU" << endl; cout << "c - Number of non-whitespace characters" << endl; cout << "w - Number of words" << endl; cout << "f - Find text" << endl; cout << "r - Replace all !'s" << endl; cout << "s - Shorten spaces" << endl; cout << "q - Quit" << endl << endl; cout << "Choose an option:" << endl; cin >> menuChoice; if (!menuChoice.compare("c")) { cout << "Number of non-whitespace characters: " << GetNumOfNonWSCharacters(inString) << endl; cout << endl; } if (!menuChoice.compare("w")) { cout << "Number of words: " << GetNumOfWords(inString) << endl; cout << endl; } if (!menuChoice.compare("f")) { string sample; cin.ignore(); cout << "Enter a word or phrase to be found:" << endl; getline(cin, sample); cout << "\"" << sample << "\" instances: " << FindText(sample, inString) << endl; cout << endl; } if (!menuChoice.compare("r")) { ReplaceExclamation(inString); cout << "Edited text: " << inString << endl; cout << endl; } if (!menuChoice.compare("s")) { ShortenSpace(inString); cout << "Edited text: " << inString << endl; cout << endl; } } } int main() { string inputString; cout << "Enter a sample text:" << endl << endl; getline(cin, inputString); cout << "You entered: " << inputString << endl << endl; PrintMenu(inputString); return 0; }<file_sep>/EECE.3220 Programs/QItem.cpp #include <iostream> #include <string> #include "QItem.h" using namespace std; QItem::QItem() { cNum = 0; arrTime = '0'; svcTime = '0'; } QItem::QItem(int cust, string arr, string serv) { cNum = cust; arrTime = stoi(arr); svcTime = stoi(serv); } int QItem::getcNum() { return cNum; } void QItem::setcNum(int num) { cNum = num; } int QItem::getArr() { return arrTime; } void QItem::setArr(int num) { arrTime = num; } int QItem::getSvc() { return svcTime; } void QItem::setSvc(int num) { svcTime = num; }<file_sep>/EECE.3220 Programs/time_test_p3.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * * time_test_p3.cpp: Main program to test Time class for Program 3 */ #include "Time.h" #include <iostream> using namespace std; // RunTestCases() handles all input and output for actual test cases // When running in submit mode, main() should only contain a call // to this function; leaving the call out of your main() function // allows you to run the program in develop mode and test your work // without worrying about the test cases // Function definition can be found in RTC.cpp (which is read-only) void RunTestCases(); int main() { RunTestCases(); // See function description above // Comment out/remove this function call if you want // to write your own test code, but make sure your // main() function only contains this function call // when you're ready to run the program in submit mode return 0; }<file_sep>/EECE.3220 Programs/LList.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * Linked list definition * * LList.cpp: function definitions * * MODIFIED FOR EXAM 3 AS FOLLOWS: * - One new function to write, sort() * - insert() now creates unordered list * - remove() searches full list * - display() prints all values on one line */ #include "LList.h" using namespace std; /***** EXAM 3 FUNCTION TO BE WRITTEN *****/ void LList::sort() { // Sort linked list using selection sort /***** ADD YOUR OWN SOLUTION *****/ Node* lower = first; Node* higher = lower; int temp; while (lower != NULL) { while (higher != NULL) { if (lower->val > higher->val) { temp = lower->val; lower->val = higher->val; higher->val = temp; } higher = higher->next; } lower = lower->next; if (lower != NULL) { higher = lower->next; } } } /***** FUNCTIONS BELOW THIS LINE ARE ALREADY WRITTEN--DO NOT MODIFY *****/ // Default constructor LList::LList() : first(NULL) {} // Destructor LList::~LList() { Node* temp; while (first != NULL) { temp = first; first = first->next; delete temp; } } // True if list is empty bool LList::empty() { return (first == NULL); } // Add new value to list /***** MODIFIED FOR EXAM 3 TO CREATE UNORDERED LIST *****/ void LList::insert(int v) { // Allocate new node and place at beginning of list Node* newNode = new Node; newNode->val = v; newNode->next = first; first = newNode; } // Remove node with v void LList::remove(int v) { Node* prev; // Predecessor of node to be deleted Node* cur; // Node to be deleted // Find node, if it's in list cur = first; prev = NULL; while (cur != NULL && cur->val != v) { /***** MODIFIED FOR EXAM 3--NO LONGER ASSUMES LIST ORDERED *****/ prev = cur; cur = cur->next; } // Didn't find node if (cur == NULL) { cout << "Node with value " << v << " not found\n"; return; } // Otherwise, remove node if (prev == NULL) // Special case for first node first = cur->next; else prev->next = cur->next; delete cur; } // Display contents of list void LList::display(ostream& out) { Node* ptr = first; while (ptr != NULL) { out << ptr->val << ' '; ptr = ptr->next; } out << '\n'; }<file_sep>/EECE.3220 Programs/Exam1.cpp /* <NAME> EECE.3220: Data Structures Code for Summer 2020 Midterm string.cpp: Program to test understanding of C++ strings */ #include <string> #include <iostream> using namespace std; // Finds the longest matching substring in the two arguments // s1 and s2 and returns it string longestSubMatch(string s1, string s2) { unsigned i, j; // Loop indexes string longest; // Current longest matching substring string sub; // Substring to search for //char addSub; int streak = 1; /***** ADD YOUR OWN CODE HERE TO CORRECTLY COMPLETE THIS FUNCTION *****/ for (i = 0; i < s1.length()-1; i++) { //addSub = s1.at(i); for (j = 0; j < s1.length()-i; j++) { if (s1.size() < s2.size()) { if (s1.at(i + streak) == s2.at(j)) { sub += s2.at(j); streak++; } else { streak = 0; if (sub.length() > longest.length()) { longest = sub; } sub.erase(); } } else { if (i + streak < s2.size() && s2.at(i + streak) == s1.at(j)) { sub += s1.at(j); streak++; } else { streak = 0; if (sub.length() > longest.length()) { longest = sub; } sub.erase(); } } } if (sub.length() > longest.length()) { longest = sub; } sub.erase(); } return longest; } int main() { string test1 = "EECE.3220"; string test2 = "ECE Application Programming"; string test3 = "program"; string test4 = "Vacation"; string L; cout << "Longest matching substring in \"" << test1 << "\" and \"" << test2 << "\" is: \"" << longestSubMatch(test1, test2) << "\"\n"; cout << "Longest matching substring in \"" << test2 << "\" and \"" << test3 << "\" is: \"" << longestSubMatch(test2, test3) << "\"\n"; cout << "Longest matching substring in \"" << test2 << "\" and \"" << test4 << "\" is: \"" << longestSubMatch(test2, test4) << "\"\n"; cout << "Longest matching substring in \"" << test3 << "\" and \"" << test4 << "\" is: \"" << longestSubMatch(test3, test4) << "\"\n"; cout << "Longest matching substring in \"" << test1 << "\" and \"" << test3 << "\" is: \"" << longestSubMatch(test1, test3) << "\"\n"; L = longestSubMatch(test1, test2); return 0; }<file_sep>/EECE.3220 Programs/BST.h #pragma once /* * <NAME> * EECE.3220: Data Structures * * Exam 3 code * Header file for BST class * * In definitions below, nullptr == NULL */ #include <iostream> using namespace std; class BST { public: /************ EXAM 3 FUNCTIONS TO BE COMPLETED ************/ int findMin(); // Find the minimum value in the BST // Returns 0 if tree empty (so you // shouldn't call it on an empty tree) unsigned countNodes(); // Count all nodes in tree void printDuplicates(ostream& out); // Finds all duplicates /**** FUNCTIONS BELOW THIS LINE ARE ALREADY DEFINED FOR YOU--DO NOT CHANGE ****/ BST() : root(nullptr) {} bool empty(); // Returns true if tree empty; false otherwise void insert(int v); // Adds new node with value v bool remove(int v); // Removes node with value v // Returns true if node found & removed; false otherwise bool search(int v); // Returns true if v in tree; false otherwise void printInOrder(ostream& out); // Prints tree contents in order private: // BST node to be used in implementation class BSTNode { public: BSTNode(int v) : val(v), left(nullptr), right(nullptr) {} int val; // Value stored in node BSTNode* left, * right; // Pointers to left and right subtrees }; BSTNode* root; // Root of tree // Recursive helper functions--called only in other BST functions void insertNode(BSTNode* tree, BSTNode* n); bool removeNode(BSTNode* tree, BSTNode* parent, int v); BSTNode* searchNode(BSTNode* tree, int v); void printNode(BSTNode* tree, ostream& out); /***** ADD YOUR OWN HELPER FUNCTION PROTOTYPES BELOW THIS LINE *****/ void findNode(BSTNode* tree, int& numNodes); void findDup(BSTNode* tree, int& dupNum, int dupVal); };<file_sep>/EECE.3220 Programs/PointList.h /* <NAME> EECE.3220: Data Structures Code for Summer 2020 Midterm PointList.h: PointList class definition */ #ifndef POINTLIST_H #define POINTLIST_H #include "Point.h" class PointList { private: Point list[50]; // A PointList can hold up to 50 points unsigned np; // Actual number of points stored in array public: PointList(); // Default constructor (empty list) void addPoint(Point& p); // Add a single point at the end of the list void printList(ostream& out); // Print every point in list bool isFull(); // Returns true if list is full bool isLine(); // Returns true if list represents a line }; #endif // POINTLIST_H<file_sep>/EECE.3220 Programs/Time.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * * Time.cpp: Time function definitions * Includes blank definitions for overloaded operators to be written for Program 3 */ #include "Time.h" // Necessary for Time class definition; implicitly includes <iostream> #include <iomanip> // Necessary for setw(), setfill() using std::setw; using std::setfill; /*** OVERLOADED OPERATORS TO BE ADDED FOR PROGRAM 3 ***/ /*** PREVIOUSLY DEFINED FUNCTIONS START ON LINE 145 (BEFORE YOU START ADDING CODE) ***/ /*** UPDATED 10/11 TO FIX PARAMETERIZED CONSTRUCTOR, advance() ***/ // Output operator ostream& operator <<(ostream& out, const Time& rhs) { Time print = rhs; print.display(out); /************************************************* * Print time using form: * h:mm _M or hh:mm _M * where: * h or hh = # of hours (1 or 2 digits) * mm = # of minutes (always 2 digits) * _M = AM or PM **************************************************/ return out; } // Input operator istream& operator >>(istream& in, Time& rhs) { char colon; in >> rhs.hours; in >> colon; in >> rhs.minutes; in >> rhs.AMorPM; in.ignore(); /************************************************* * Read time assuming it is written in form: * h:mm _M or hh:mm _M * where: * h or hh = # of hours (1 or 2 digits) * mm = # of minutes (always 2 digits) * _M = AM or PM **************************************************/ return in; } // Comparison operators bool Time::operator ==(const Time& rhs) { if (hours == rhs.hours && minutes == rhs.minutes && AMorPM == rhs.AMorPM) { return true; } else { return false; } /******************************************** * Returns true if calling object matches rhs, * false otherwise *********************************************/ } bool Time::operator !=(const Time& rhs) { if (hours == rhs.hours && minutes == rhs.minutes && AMorPM == rhs.AMorPM) { return false; } else { return true; } /************************************************** * Returns true if calling object doesn't match rhs, * false otherwise ***************************************************/ } bool Time::operator <(const Time& rhs) { if (miltime < rhs.miltime) { return true; } else { return false; } /********************************************** * Returns true if calling object is less * (earlier in day) than rhs, false otherwise ***********************************************/ } bool Time::operator >(const Time& rhs) { if (miltime > rhs.miltime) { return true; } else { return false; } /******************************************** * Returns true if calling object is greater * (later in day) than rhs, false otherwise *********************************************/ return false; } // Arithmetic operators Time Time::operator +(const Time& rhs) { Time sum; sum.advance(rhs.miltime/100, rhs.minutes); sum.advance(miltime/100, minutes); /******************************************** * Add two Time objects and return sum * See examples in spec *********************************************/ return sum; } Time Time::operator -(const Time& rhs) { Time diff; if (rhs.miltime > miltime) { miltime += 2400; diff.miltime = (miltime - rhs.miltime); } else { diff.miltime = (miltime - rhs.miltime); } if (diff.miltime % 100 > 60) { diff.miltime -= 40; } if ((diff.miltime / 100) % 12 == 0 ) { diff.hours = 12; } else { diff.hours = (diff.miltime / 100) % 12; } diff.minutes = diff.miltime % 60; if (diff.miltime < 1200) { diff.AMorPM = 'A'; } else { diff.AMorPM = 'P'; } /************************************************* * Subtract two Time objects and return difference * See examples in spec **************************************************/ return diff; } Time& Time::operator +=(const Time& rhs) { advance(rhs.miltime / 100 , rhs.minutes); /************************************************** * Same as + operator, but modifies calling object * and returns reference to calling object ***************************************************/ return *this; } Time& Time::operator -=(const Time& rhs) { if (rhs.miltime > miltime) { miltime += 2400; miltime -= rhs.miltime; } else { miltime = (miltime - rhs.miltime); } if (miltime % 100 > 60) { miltime -= 40; } if ((miltime / 100) % 12 == 0) { hours = 12; } else { hours = (miltime / 100) % 12; } minutes = miltime % 100; if (miltime < 1200) { AMorPM = 'A'; } else { AMorPM = 'P'; } /************************************************** * Same as - operator, but modifies calling object * and returns reference to calling object ***************************************************/ return *this; } // Increment operators--adds 1 minute to current time Time& Time::operator++() { advance(0, 1); return *this; /************************* * Pre-increment operator **************************/ } Time Time::operator++(int) { Time newTime = *this; advance(0, 1); return newTime; /************************* * Post-increment operator **************************/ } /*** END OVERLOADED OPERATORS TO BE ADDED FOR PROGRAM 3 ***/ /*** DO NOT MODIFY CODE BELOW THIS LINE ***/ // Default constructor Time::Time() : hours(0), minutes(0), miltime(0), AMorPM('A') {} // Parameterized constructor Time::Time(unsigned h, unsigned m, char AP) : hours(h), minutes(m), AMorPM(AP) { miltime = 100 * h + m; /*** FIXED 10/11: ORIGINAL VERSION DID NOT CORRECTLY HANDLE 12 AM OR 12 PM ***/ if (AP == 'P' && h != 12) miltime += 1200; else if (AP == 'A' && h == 12) miltime -= 1200; } // Set time data members void Time::set(unsigned h, unsigned m, char AP) { hours = h; minutes = m; AMorPM = AP; miltime = 100 * h + m; if (AP == 'P') miltime += 1200; } // Print time to desired output stream void Time::display(ostream& out) { out << hours << ':' << setw(2) << setfill('0') << minutes // setw(2) forces minutes to be printed with 2 chars << ' ' << AMorPM << 'M'; // setfill('0') adds leading 0 to minutes if needed } // Advance time by h hours, m minutes // Use modulo arithmetic to ensure // 1 <= hours <= 12, 0 <= minutes <= 59 /*** FIXED 10/11: ORIGINAL VERSION DIDN'T WORK FOR ALL CASES AND WAS FAR TOO CONVOLUTED ***/ /*** NEW VERSION DOES ALL MATH ON MILTIME AND THEN CORRECTS HOURS, MINUTES ***/ void Time::advance(unsigned h, unsigned m) { unsigned tempMT = h * 100 + m; // Temporary miltime representing amount // of time to advance by, since math // is much easier using miltime! // If sum of minutes >= 60, need to account for extra hour added if (minutes + m >= 60) miltime = (miltime + tempMT + 40) % 2400; // % 2400 ensures time between 0 & 2359 // (since minutes adjustment guarantees // last two digits < 60) else miltime = (miltime + tempMT) % 2400; // Convert back from miltime to new hours/minutes hours = miltime / 100; // Special case 1: time in PM (other than 12 PM) if (hours > 12) hours -= 12; // Special case 2: 12:xx AM --> miltime / 100 = 0 else if (hours == 0) hours = 12; minutes = miltime % 100; // Figure out if new time is in AM or PM AMorPM = (miltime < 1200 ? 'A' : 'P'); } // Returns true if calling object is less than argument bool Time::lessThan(const Time& rhs) { if (miltime < rhs.miltime) return true; else return false; }<file_sep>/EECE.3220 Programs/ShoppingCart.cpp #include <iostream> using namespace std; #include "ShoppingCart.h" ShoppingCart::ShoppingCart() { nameEntered = "none"; dateEntered = "January 1, 2016"; } ShoppingCart::ShoppingCart(string customerName, string Inputdate) { nameEntered = customerName; dateEntered = Inputdate; } void ShoppingCart::AddItem(ItemToPurchase addNewItem) { cartItems.push_back(addNewItem); } void ShoppingCart::RemoveItem(string I_Name) { int ItemSearch = 0; int n = cartItems.size(); for (int i = 0; i < n; i++) { if (cartItems.at(i).GetName() == I_Name) { ItemSearch = 1; cartItems.erase(cartItems.begin() + i); } } if (!ItemSearch) { cout << "Item not found in cart. Nothing removed." << endl; } } void ShoppingCart::ModifyItem(ItemToPurchase Mod_Item) { int ItemToMod = 0; if (!ItemToMod) { cout << "Item not found in cart. Nothing modified." << endl; } int n = cartItems.size(); for (int i = 0; i < n; i++) { if (cartItems.at(i).GetName() == Mod_Item.GetName()) { cartItems.at(i).SetQuantity(Mod_Item.GetQuantity()); ItemToMod = 1; } } } string ShoppingCart::GetCustomerName() { return nameEntered; } string ShoppingCart::GetDate() { return dateEntered; } int ShoppingCart::GetNumItemsInCart() { int i = 0, n = cartItems.size(); int Cart_Items = 0; while (i < n) { Cart_Items = Cart_Items + cartItems.at(i).GetQuantity(); i++; } return Cart_Items; } int ShoppingCart::GetCostOfCart() { int total = 0, i = 0, n = cartItems.size(); if (n == 0) { return 0; } while (i < n) { total = total + cartItems.at(i).GetPrice() * cartItems.at(i).GetQuantity(); i++; } return total; } void ShoppingCart::PrintTotal() { cout << nameEntered << "'s Shopping Cart - " << dateEntered << endl; cout << "Number of Items: " << GetNumItemsInCart() << endl << endl; int n = cartItems.size(); if (n == 0) { cout << "SHOPPING CART IS EMPTY" << endl; } else { int i = 0, n = cartItems.size(); while (i < n) { cartItems.at(i).PrintItemCost(); i++; } } cout << endl << "Total: $" << GetCostOfCart() << endl; } void ShoppingCart::PrintDescriptions() { cout << nameEntered << "'s Shopping Cart - " << dateEntered << endl << endl; cout << "Item Descriptions" << endl; int i = 0, n = cartItems.size(); while (i < n) { cartItems.at(i).PrintItemDescription(); i++; } } <file_sep>/EECE.3220 Programs/Stack.cpp /* * <NAME> * EECE.3220: Data Structures * * Source file for in-class stack example * Stack member function definitions * * COMPLETE THE FUNCTION DEFINITIONS IN THIS FILE * FOR THE print() AND swap() FUNCTIONS */ #include "Stack.h" #include <iostream> using std::cout; using std::endl; // FUNCTIONS TO BE WRITTEN FOR EXAM 2 // Print stack contents from top to bottom, one per line // Also prints stack capacity and # values currently in stack void Stack::print(ostream& out) { // COMPLETE THIS FUNCTION TO EARN CREDIT FOR PART 1 Stack *tmpAdd = new Stack; Stack& tmpPrint = *tmpAdd; *tmpAdd = *this; out << "Stack capacity: " << cap << endl; out << "Current size: " << tos + 1 << endl; out << "Current contents:" << endl; if (tmpPrint.empty()) { out << "None--stack empty"<< endl; } else { while (!tmpPrint.empty()) { out << tmpPrint.top() << endl; tmpPrint.pop(); } } } // Exchange contents of calling object with argument aStack void Stack::swap(Stack& aStack) { // COMPLETE THIS FUNCTION TO EARN CREDIT FOR PART 2 Stack *tmp1 = new Stack; Stack *tmp2 = new Stack; *tmp1 = *this; *tmp2 = aStack; Stack& tmpAdd1 = *tmp1; Stack& tmpAdd2 = *tmp2; aStack = tmpAdd1; *this = tmpAdd2; } // END OF FUNCTIONS TO BE WRITTEN FOR EXAM 2 /***********************************************************************************/ /* ORIGINAL ARRAY-BASED STACK FUNCTIONS--DO NOT MODIFY CODE AFTER THIS POINT */ /***********************************************************************************/ // Constructor Stack::Stack(unsigned maxSize) : cap(maxSize), tos(-1) { list = new double[cap]; } // Destructor Stack::~Stack() { delete[] list; } // Returns true if stack empty bool Stack::empty() const { // Could write as: // return (tos == -1); if (tos == -1) return true; else return false; } // Push val to top of stack void Stack::push(const double& val) { if (tos == (int)cap - 1) cout << "Stack is full" << endl; else { tos++; list[tos] = val; // Could have written: list[++tos] = val; } } // Remove top of stack void Stack::pop() { if (empty()) cout << "Stack is empty" << endl; else tos--; } // Read top of stack double Stack::top() { if (empty()) { cout << "Stack is empty" << endl; return list[cap - 1]; // Have to return something ... } else return list[tos]; }<file_sep>/EECE.3220 Programs/Point.cpp /* <NAME> EECE.3220: Data Structures Point example code for in-class operator overloading example (Modified version of composition example) Function definitions */ #include "Point.h" // Default constructor Point::Point() : xCoord(0), yCoord(0) {} // Parameterized constructor Point::Point(double X, double Y) : xCoord(X), yCoord(Y) {} // "Set" functions void Point::setX(double newX) { xCoord = newX; } void Point::setY(double newY) { yCoord = newY; } // "Get" functions double Point::getX() { return xCoord; } double Point::getY() { return yCoord; } // OVERLOADED OPERATORS // p2 = p1; --> p2.operator =(p1); Point& Point::operator =(const Point& rhs) { // Ensure no self-assignment (for example, p1 = p1) if (!(*this == rhs)) { // xCoord == this->xCoord (two expressions are equivalent) xCoord = rhs.xCoord; yCoord = rhs.yCoord; } return *this; } // Example usage: if (p1 == p2) { } bool Point::operator ==(const Point& rhs) { if (xCoord == rhs.xCoord && yCoord == rhs.yCoord) return true; else return false; /* Could write as: return (xCoord == rhs.xCoord && yCoord == rhs.yCoord); */ } // Example usage: cout << p1; or // cout << p1 << " " << p2; ostream& operator <<(ostream& out, const Point& p) { out << "(" << p.xCoord << ", " << p.yCoord << ")"; return out; }<file_sep>/EECE.3220 Programs/StackTest.cpp /* * EECE.3220: Data Structures * Instructor: <NAME> * * Exam 2 code * Main program to test Stack functions */ #include <iostream> using namespace std; #include "Stack.h" int main() { unsigned part; // Which part of the problem is being tested? Stack S1, S2(10), S3(256); // Stacks to be used in part 1 unsigned i; // Loop index double val; // Value to be pushed on stack cout << "Which part? "; cin >> part; switch (part) { case 1: // Code to test part 1 (print function) val = 1.1; for (i = 0; i < 5; i++) { S1.push(val); S2.push(100 - val); val *= 2; } S1.push(val); S1.push(0.3220); cout << "Printing S1:\n"; S1.print(cout); cout << "\nPrinting S2:\n"; S2.print(cout); cout << "\nPrinting S3:\n"; S3.print(cout); break; case 2: // Code to test part 2 () for (i = 0; i < 5; i++) { S1.push(i); S2.push(5 - i); } S1.push(5); S1.push(6); cout << "S1 before swap:\n"; S1.print(cout); cout << "\nS2 before swap:\n"; S2.print(cout); S1.swap(S2); cout << "\nS1 after swap\n"; S1.print(cout); cout << "\nS2 after swap\n"; S2.print(cout); break; } return 0; }
ed2835b46a3d5cffbef453ac11a0cf3792b0bc0b
[ "C++" ]
31
C++
Kumahia-R/EECE.3220-Programs
f205b8bb61a795c25a530800c68abfb375375735
873d4152db0f3dd115ad7c6c269a2af4b26e9873
refs/heads/master
<repo_name>anubhavashok/must_talk_cs_math<file_sep>/README.txt Code from talk on Monday night; EditDistance - EditDistance path problem + graph visualization (Doesn't work in IE); ImageRectification - Painting problem (Requires opencv libs and python binding to run code); Check out my startup: www.textedb.com; And follow me on twitter: www.twitter.com/bhavashok;<file_sep>/ImageRectification/rectification.py import numpy as np import cv2 img = cv2.imread('img.jpg') rows,cols,ch = img.shape # mapping of coordinates in base image to coordinates in rectified image pts1 = np.float32([[900,rows-186], [900, rows-70], [1300, rows-70]]) pts2 = np.float32([[0, cols],[0, 0],[rows, 0]]) M = cv2.getAffineTransform(pts1, pts2) print M dst = cv2.warpAffine(img, M, (cols,rows)) cv2.imwrite('dst_out.jpg', dst) img2 = cv2.imread('img2.jpg') rows,cols,ch = img.shape # mapping of coordinates in base image to coordinates in rectified image pts1 = np.float32([[300, cols-126], [279, cols-100], [571, cols-100]]) pts2 = np.float32([[0, cols],[0, 0],[rows, 0]]) M = cv2.getAffineTransform(pts1, pts2) print M dst2 = cv2.warpAffine(img, M, (cols,rows)) cv2.imwrite('dst2_out.jpg', dst2)
7e0f05e474cd9dbe80c5207667ddce461e80d114
[ "Python", "Text" ]
2
Text
anubhavashok/must_talk_cs_math
54f2f7d6121e52b7ec25e12e96db6c07414bd64a
b57e9fc9b6378ff6fa4fa98fa9ff85743e793d5a
refs/heads/master
<file_sep>import { ADD, EDIT, REMOVE } from "../actions"; const initialState = { todos: [], count: 0 } //reducer export default (state = initialState, action) => { switch (action.type) { case ADD: return Object.assign({}, state, state.todos.push(action.value, state.count), state.count++); case EDIT: return Object.assign({}, state, state.todos[action.id] = action.value); case REMOVE: return Object.assign({}, state, state.todos.splice(action.id, 1)); default: return state; } }<file_sep>import React, { Component } from 'react'; import logo from './logo.svg'; import { createEntry } from './reducers'; import './App.css'; import Entry from './components/Entry'; class App extends Component { handleSubmit = (event) => { event.preventDefault() this.props.onCreate(event.target.value) } render() { const todoList = this.props.value.map((item, index) => <Entry value={item} key={index}/>) return ( <div className="App"> <form id="" onSubmit={this.handleSubmit}> <input type="text"></input> </form> {todoList} </div> ); } } export default App; <file_sep>## Todo - List App ##### Authors: <NAME>, <NAME> **Description** A simple todo - list application that uses Redux and React.js
c8ae9af2128bb851175df6630c57f97e08679876
[ "JavaScript", "Markdown" ]
3
JavaScript
Fioringo/CUNY2X-Todo-List
ce2a70de999dc212c27fd76387887917dfcdd6b4
66ea1d57625e189665afc0eab5a32232b03830a3
refs/heads/master
<repo_name>GabrielMorais2/api_atividade<file_sep>/utils.py from models import Pessoas #insere dados na tabela pessoa def insere_pessoas(): pessoa = Pessoas(nome='selma', idade=47) print(pessoa) Pessoas.save(pessoa) #realiza consulta na tabela Pessoas def consulta_pessoas(): pessoa = Pessoas.query.all() for i in pessoa: print(i.nome, i.idade) #altera dados na tabela Pessoa def alterar_pessoa(): pessoa = Pessoas.query.filter_by(nome='rafael').first() pessoa.nome = 'Felipe' Pessoas.save(pessoa) #deleta dados na tablea Pessoas def exclui_pessoa(): pessoa = Pessoas.query.filter_by(nome='Felipe').first() Pessoas.delete(pessoa) if __name__ == '__main__': #insere_pessoas() #alterar_pessoa() exclui_pessoa() consulta_pessoas()
6968bb4e93a64002d83722f9cb20671a612b440c
[ "Python" ]
1
Python
GabrielMorais2/api_atividade
ec6e04f1d44efc1ad29f95b9ce16a76e6038e4a6
fee0afa56c771bfd415004da5cefb5626d9d55aa
refs/heads/master
<repo_name>bonarl/Arduino-Flex-Tester<file_sep>/flex_tester.py # -*- coding: utf-8 -*- """ Created on Tue Feb 14 11:44:17 2017 @author: bonar """ from port_finder import listSerialPorts from Expander import EXPANDER import serial import time import datetime import socket import sys from flex_tools import * #Flex-Tape network #all pins on all boards are named according to the network they belong to com_ports = listSerialPorts().reverse() #here an instance of flex_tape class is called and a a dictionary is created for storing test #results for sender/receiver board pairs, the dictionary is an attribute of the FLEX_TAPE #instance and contains test results #the dictionary is stuctured as flex_tape['sender name']['netname']['receiver name'] #the above key then contains the expected results reading the 'receiver' board when setting a pin with #that 'netname' high on the sender board. The expected results are a list [0, 1, 0, 1, ....] etc #describing the high or low logic of pins expected on the receiver, generated by comparing the #sender and receiver pin lists and searching for common names. The real list is in the same format #and shows the actual values read from each board, these lists are compared to find possible defects. flex_tape = FLEX_TAPE(network, board_names) #baudrate must be 115200 to match Arduino firmware #GPIO signals are declared (these are the signals which Arduinos are set up to receive) baudrate = 115200 GPIO_HIGH = 's' GPIO_LOW = 'c' GPIO_IN = 'i' GPIO_OUT = 'o' #this loop goes through every sender/receiver pair and parses the boards. #results of each senderboard+senderpin+receiver board test are stored in FLEX_TAPE dictionary/net flex_tape.net() for i in range(len(board_names)): sender = board_names[i] for j in range(i+1, len(board_names)-1): receiver = board_names[j] flex_tape.parse(sender, receiver, com_ports, baudrate) results = flex_tape.net() #then can check results for errors (if checked == true and errors == true) and display information
0a7bec0bc7d23bff5758357562cfc213cc0ddc7c
[ "Python" ]
1
Python
bonarl/Arduino-Flex-Tester
719cc58be41e2d79c5745d8175319316db86d342
98d1d65b40314cd2cd78b2869d5131438891f4ea
refs/heads/master
<repo_name>ed-khalid/SWE642<file_sep>/HW5/src/resources/db.properties db.url=jdbc:oracle:thin:@apollo.vse.g<EMAIL>:1521/ITE10G.ITE.GMU.EDU db.username=amuhamm3 db.password=<PASSWORD> <file_sep>/HW4/web/scripts/main.js //namespaces var App = {}; var Cookies = {} var SurveyMath = {}; var EventHandlers = {}; var Error = {}; var Validator = {}; var Constructors = {}; Constructors.Validators = {}; Constructors.NodeObjects = {}; //constructor functions Constructors.Error = function() { var isPending=false; var text = ""; function flushText() { var retv = text; text = ""; setIsPending(false); return retv; } function appendText(errText) { text += errText+"\n"; setIsPending(true); } this.collect = function(error) { appendText(error); } this.throwInvalidDataContent = function(errType,el,ind) { if (errType === "number") { appendText("Invalid Data Input: Please enter 10 numbers"+ " between 0 and 100") ; } else if (errType === "range") { appendText("Input number " + ind +" Out Of Range: "+el); } }; function getIsPending() { return isPending; }; function setIsPending(val) { if ((val === true) || (val === false)) { isPending = val; } }; this.flush = function() { var retv=false; if (getIsPending()) { alert(flushText()); retv = true; } return retv; }; this.notify = function(valResults) { valResults.map(function(el) { if (el !== true) { Error.collect(el); } }); }; }; Constructors.Validators.Selector = function(_type,_min) { var min = _min; var type; if(_type === 'checkbox') { type = "checkboxes"; } else if (_type === 'radio') { type = 'radio buttons'; } function val(obj) { if (obj.numberOfSelectedInputs < min) { return obj.name + " You must select at least " + min + " " + type; } return true; }; this.validate = function(obj) { return val(obj); } }; Constructors.Validators.Text = function(_regex,_error) { var regex = new RegExp(_regex); var error = _error; function val(obj, identifier) { if (regex.test(obj.node.value) == false) { var _oldval = obj.node.value; //clear node value obj.node.value=""; return obj.name + " "+ error +", You entered: " + _oldval; } else { return true; } }; this.validate = function(obj) { return val(obj); }; } Constructors.Validators.Repository = function() { var _validators = {}; var alphabetOnly = new Constructors.Validators.Text('^[a-zA-Z]*$', "must contain only letters"); var alphaNumericOnly = new Constructors.Validators.Text('^[a-zA-Z0-9]*$', "must contain only letters or numbers"); var zipValidator = new Constructors.Validators.Text('^\\d{5}$', "must contain 5 digits only"); var campusValidator = new Constructors.Validators.Selector('checkbox', 2); var recommendationValidator = new Constructors.Validators.Selector('radio', 1); var emailValidator = new Constructors.Validators.Text('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[A-Za-z]{2,4}$', "email address format is not valid"); _validators['alphabet'] = alphabetOnly; ; _validators['alphaNumeric'] = alphaNumericOnly; _validators['zipRegex'] = zipValidator; _validators['emailRegex'] = emailValidator; _validators['checkbox'] = campusValidator; _validators['radio'] = recommendationValidator; function getValidationFor(validationType) { return _validators[validationType]; } this.validate = function(obj) { var _validator = getValidationFor(obj.validationType); return _validator.validate(obj); } }; Constructors.NodeObjects.Selector = function(container,_type) { var _inputs = container.getElementsByTagName('input'); var retv = {}; retv.name = _inputs[0].parentNode.textContent; retv.inputs = []; retv.numberOfSelectedInputs = 0; retv.validationType = _type; for (var i = 0; i<_inputs.length; i++) { if (_inputs[i].type === _type) { retv.inputs.push(_inputs[i]); if (_inputs[i].checked) { retv.numberOfSelectedInputs++; } }//if }//for return retv; }; Constructors.NodeObjects.Text = function(container,target,vtype) { var _node = container.getElementsByTagName('input')[target]; this.node = _node; this.name = _node.parentNode.textContent; this.validationType = vtype; }; //Cookies namespace Cookies.nameCookie= "swe642name"; Cookies.retrieveName = function() { var retv; if (document.cookie) { var _cookie = unescape(document.cookie); var _tokens = _cookie.split(";"); _tokens.forEach( function(element,index,arry) { var _elTokens = element.split("="); console.log(_elTokens); if (_elTokens[0].trim() === Cookies.nameCookie ){ if (_elTokens[1] !== "null") { retv = _elTokens[1]; } } }); } //if retv is not found in document.cookie if (retv == undefined) { retv = window.prompt("Please enter your name", "Ahmed"); document.cookie = Cookies.nameCookie + "=" + escape(retv); } return retv; }; Cookies.clearName = function() { var date = new Date(); document.cookie = Cookies.nameCookie+"="+ "null;" + " expires="+date; }; //SurveyMath namespace SurveyMath.average = function(numbers) { var avg = 0.0; var sum = 0.0; numbers.forEach(function(el) { sum += el; }); avg = sum / numbers.length; return avg; }; SurveyMath.maximum = function(numbers) { var max = -Infinity; numbers.forEach(function (el, ind, arr) { if (el > max){ max = el; } }); return max; }; //Error namespace Error = new Constructors.Error(); Validator = new Constructors.Validators.Repository(); //EventHandler namespace EventHandlers.dataSanitizer = function(event) { var text = event.currentTarget.value; var arr = text.split(","); var _arr = []; arr.forEach(function(el,ind,array) { var number = Number(el); if (number === NaN) { return Error.collect("Invalid Data Input: " + el + " is not a number."); } else if (number < 1 || number > 100) { return Error.collect("Invalid Data Input: " + "Input number " + ind + " out of range: "+ number + ". Please enter"+ " a number betwen 1 and 100."); } //valid number else { _arr.push(number); } }); if (Error.flush()) { return; } else { var average = SurveyMath.average(_arr); var max = SurveyMath.maximum(_arr); var _nodeAvg = document.getElementsByName("average")[0]; var _nodeMax = document.getElementsByName("maximum")[0]; _nodeAvg.value = average; _nodeMax.value = max; } }; EventHandlers.formSanitizer = function(formEvent) { formEvent.preventDefault(); var form = formEvent.currentTarget; function validateNodes(nodeArray) { var results = nodeArray.map(Validator.validate); return results; }; function validateName(form) { var firstName = new Constructors.NodeObjects.Text(form, 'firstName', 'alphabet'); var lastName = new Constructors.NodeObjects.Text(form,'lastName', 'alphabet'); var result = validateNodes([firstName, lastName]); Error.notify(result); }; function validateAddress(form) { var street = new Constructors.NodeObjects.Text(form, 'street', 'alphaNumeric'); var city = new Constructors.NodeObjects.Text(form, 'city', 'alphabet'); var zip = new Constructors.NodeObjects.Text(form, 'zip', 'zipRegex'); var result = validateNodes([street, city, zip]); Error.notify(result); }; function validateEmail(form) { var email = new Constructors.NodeObjects.Text(form, 'email', 'emailRegex'); var result = validateNodes([email]); Error.notify(result); }; function validateCheckboxes(form) { var checkboxes = new Constructors.NodeObjects.Selector(form, 'checkbox'); var result = validateNodes([checkboxes]); Error.notify(result); }; function validateRadioButtons(form) { var radioButtons = new Constructors.NodeObjects.Selector(form, 'radio'); var result = validateNodes([radioButtons]); Error.notify(result); }; validateName(form); validateAddress(form); validateCheckboxes(form); validateRadioButtons(form); validateEmail(form); //submit if no errors found if (Error.flush() == false) { this.submit(); } }; EventHandlers.zipCodeLookup = function() { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 ) { if (xmlHttp.status == 200) { var userZip = document.getElementsByTagName('input')['zip'].value; var json = JSON.parse(xmlHttp.responseText); var _return = json.zipcodes.some(function(el) { if (el.zip === userZip) { var city = document.getElementsByTagName('input')['city']; city.value = el.city; var state = document.getElementsByTagName('input')['state']; state.value = el.state; } }); if (_return === false) { var zipError = document.getElementsByTagName('div')['zip_error']; zipError.innerHTML = "Zip not found." } }//if else if (xmlHttp.status == 400) { alert('error reading zipcodes file'); } }//if } xmlHttp.open('GET', 'http://mason.gmu.edu/~amuhamm3/hw3/zipcodes.json',true); xmlHttp.send(); } App.registerEventListeners = function() { /* var _dataNode = document.getElementsByName("data")[0]; _dataNode.addEventListener("blur", EventHandlers.dataSanitizer);*/ var _formNode = document.getElementsByTagName("form")[0]; _formNode.addEventListener("submit", EventHandlers.formSanitizer); var _zipNode = document.getElementsByTagName('input')['zip']; _zipNode.addEventListener('blur', EventHandlers.zipCodeLookup); }; App.salute = function() { var retv = ""; var date = new Date(); var hrs = date.getHours(); if (hrs < 12) { retv = "Morning"; } else { hrs = hrs - 12; if (hrs < 3) { retv = "Day"; } else if (hrs < 6) { retv = "Afternoon" ; } else if (hrs < 9) { retv = "Evening"; } else { retv = "Night"; } } return "Good " + retv + " " ; }; App.greet = function() { var name = Cookies.retrieveName(); var personDiv = document.getElementById('greeting'); //create greeting text node var _text = App.salute() + name + ", welcome to the George Mason Department Website!" var _node = document.createTextNode(_text); personDiv.appendChild(_node); //create line break personDiv.appendChild(document.createElement('br')); //create wrong person link _node = document.createElement('a'); _node.setAttribute('href', 'javascript:wrongPerson()'); _node.innerText = 'Click here if you are not ' + name ; personDiv.appendChild(_node); }; App.wrongPerson = function() { Cookies.clearName(); location.reload(); }; App.init = function() { App.registerEventListeners(); App.greet(); } //kickoff window.onload = App.init(); <file_sep>/HW5/src/main/java/survey/domain/DataBean.java package survey.domain; /** * Created by <NAME> on 3/31/15. */ public class DataBean { public DataBean( double mean, double stdDev) { this.mean = mean; this.stdDev = stdDev; } private double mean; private double stdDev; public double getMean() { return mean; } public void setMean(double mean) { this.mean = mean; } public double getStdDev() { return stdDev; } public void setStdDev(double stdDev) { this.stdDev = stdDev; } } <file_sep>/HW5/src/main/java/survey/domain/StudentBean.java package survey.domain; import survey.util.SurveyStringUtils; /** * Created by <NAME> on 3/29/15. */ public class StudentBean { public String firstName; public String lastName; public String street; public String city; public String zip; public String telephone; public String email; public String url; public String referralSource; public String[] campus; public String graduationMonth; public String recommendationLikelihood; public String graduationYear; public String additionalComments; public String studentID; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getReferralSource() { return referralSource; } public void setReferralSource(String referralSource) { this.referralSource = referralSource; } public String[] getCampus() { return campus; } public void setCampus(String[] campus) { this.campus = campus; } public String getGraduationMonth() { return graduationMonth; } public void setGraduationMonth(String graduationMonth) { this.graduationMonth = graduationMonth; } public String getRecommendationLikelihood() { return recommendationLikelihood; } public void setRecommendationLikelihood(String recommendationLikelihood) { this.recommendationLikelihood = recommendationLikelihood; } public String getGraduationYear() { return graduationYear; } public void setGraduationYear(String graduationYear) { this.graduationYear = graduationYear; } public String getAdditionalComments() { return additionalComments; } public void setAdditionalComments(String additionalComments) { this.additionalComments = additionalComments; } public String getStudentID() { return studentID; } public void setStudentID(String studentID) { this.studentID = studentID; } public void setFirstName(String firstName) { this.firstName = firstName; } //convenience print methods for JSP's convenience public String getGraduationDate() { if ((graduationMonth == null) || (graduationYear == null)) { return "N/A"; } else { return graduationMonth + ", " + graduationYear; } } public String printAttribute(String[] attr) { if(attr == null) { return "N/A"; } else { return SurveyStringUtils.convertStringArrayToString(attr); } } public String printAttribute(String attr) { return (attr == null) ? "N/A" : attr; } }
5f98ac8f105d660aeeb5c93e7f0ea11127224869
[ "JavaScript", "Java", "INI" ]
4
INI
ed-khalid/SWE642
8292da733498f8bb7292ae98371488c509addc89
db13cb74ef86e2e90345c3b5f3fdfcba9d3e2f2c
refs/heads/master
<repo_name>iliescua/JoystickAPI<file_sep>/joystickAPI/joystick.h /* * <NAME> * 4/1/19 * The .h file for the joystick */ #ifndef JOYSTICK_H_ #define JOYSTICK_H_ #include "alt_types.h" #include <unistd.h> #include "servoControl.h" #include "sevenSegDisplay.h" //The method that allows the servos to move based on joystick dir void joystickRotate(); //Method used to toggle whether the joystick data gets sent through or not void toggleJoystick(int choice); #endif <file_sep>/joystickAPI/sevenSegDisplay.c /* * <NAME> * Lab1: SevenSegDisplay.c * Holds the logic for the sevenSegDisplay.c */ #include "sevenSegDisplay.h" #include "system.h" #include "alt_types.h" #include <stdio.h> alt_u32* sevenSegBase = (alt_u32*) HEX3_HEX0_BASE; //7Seg Base //alt_u16* switchBase = (alt_u16*) SLIDER_SWITCHES_BASE; //Switches base char val[5] = { 0 }; //Value array that stores user input int num[10] = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x67 }; //Array that stores 7Seg display vals void clearSeg() { //Sets 0 on first 7 Seg *sevenSegBase = num[0]; } void displayNum(alt_u32 input) {//Displays the switch number on 7Seg sprintf(val, "%d", input); if ((input / 1000) > 0) { //If the value entered is 4 digits *sevenSegBase = (num[(val[0] - 48)] << 24) + (num[(val[1] - 48)] << 16) + (num[(val[2] - 48)] << 8) + (num[(val[3] - 48)]); //Num entered -48 is the deci val to be shown } else if ((input / 100) > 0) { //If the value entered is 3 digits *sevenSegBase = (num[(val[0] - 48)] << 16) + (num[(val[1] - 48)] << 8) + (*sevenSegBase = num[(val[2] - 48)]); } else if ((input / 10) > 0) { //If the value entered is 2 digits *sevenSegBase = (num[(val[0] - 48)] << 8) + (num[(val[1] - 48)]); } else { //If the value entered is 1 digit *sevenSegBase = num[(val[0] - 48)]; } } //void updateVal() { //Updates the value from which switches are flipped // sprintf(val, "%d", input); //} <file_sep>/joystickAPI/sevenSegDisplay.h /* * <NAME> * Lab1: SevenSegDisplay.h * Holds all of the files for the sevenSegDisplay.c file */ #ifndef SEVENSEGDISPLAY_H_ #define SEVENSEGDISPLAY_H_ void clearSeg(); //Sets 0 on 7Seg void displayNum(); //Sets switch num on 7Seg void updateVal(); //Updates the val from the pins #endif <file_sep>/joystickAPI/servoControl.c /* * <NAME> * 3/26/19 * File the provides logic to all servo functions */ #include "servoControl.h" #include "system.h" volatile alt_u32* servoBot = SERVO_ONE_BASE; //Bot servo base addr volatile alt_u32* servoTop = SERVO_TWO_BASE; //Top servo base addr /* * This method allows someone to move either servos and in * any dir they want by passing in the 2 parameters for * dir and servo choice */ void moveServos(int num, int choice) { if (choice == 0) { //Move bot servo *servoBot = num; } else if (choice == 1) { //Move top servo *servoTop = num; } usleep(25000); //Delay to not cause servos to stall } /* * Resets both servos to default start pos */ void resetPos() { *servoBot = 100; *servoTop = 0; usleep(25000);//Delay to not cause servos to stall } /* * This method is used to pan the servos however many * times the user wants to */ void panServos(int turns) { resetPos(); //Has pan process start at default pos alt_u32 dur = turns * 200; //200 is the total moves i needs to make 1 turn int count = 0; //Var used to keep track of position alt_u32 temp = 0; //Keeps track of the number of turns left while (temp != dur) { *servoBot = count; //Moves 1 turn value usleep(5000); //Small delay to allow panning motion temp++; count++; if (count == 200) { //If Bot servo reaches the end of its turn cycle while (count != 0) { count--; //Moves bot servo back in the other dir *servoBot = count; usleep(5000); //Small delay to allow panning motion } } } usleep(25000); //Delay to not cause servos to stall } <file_sep>/joystickAPI/main.c /* * <NAME> * 4/1/19 * Main method */ #include "joystick.h" int main() { toggleJoystick(1); //Enable reading from ADC while (1) { joystickRotate(); //Takes joystick data and moves servos } return 0; } <file_sep>/README.md # JoystickAPI This is an API that allows control of 2 servos on the DE10Lite. Written specifically for embedded systems class and displays the values from the ADC to 7seg. Having 2 channels allows for smooth movement of the servos. <file_sep>/joystickAPI/joystick.c /* * <NAME> * 4/1/19 * File the provides logic for what the servos should do based on joystick movement */ #include "alt_types.h" #include "system.h" volatile alt_u32* joystickBase = JOYSTICK_ADC_SEQUENCER_CSR_BASE; volatile alt_u32* joystickBot = JOYSTICK_ADC_SAMPLE_STORE_CSR_BASE; volatile alt_u32* joystickTop = JOYSTICK_ADC_SAMPLE_STORE_CSR_BASE + 0x4; volatile alt_u32* switchBase = SLIDER_SWITCHES_BASE; volatile alt_u32* hex5Base = HEX5_HEX4_BASE; int distBot = 0; int distTop = 0; /* By taking the data from the Sample Store and splitting it based on channel, * that number then divided by 20 falls into the range for the servo and then moves * the servos based on that */ void joystickRotate() { distBot = *joystickBot / 20; //Puts it in servo range distTop = *joystickTop / 20; //Puts it in servo range moveServos(distBot, 0); //Move bot servo moveServos(distTop, 1); //Move top servo //Added to show Sample Store and channel data on 7Seg if (*switchBase == 0) { //Channel 0 displayNum(*joystickBot); *hex5Base = (0x3F) << 8; } else if (*switchBase == 1) { //Channel 1 displayNum(*joystickTop); *hex5Base = (0x06) << 8; } } /* This method is used to simply toggle whether the josytick data gets read or * not if it is moved */ void toggleJoystick(int choice) { if (choice == 0) { //joystick off *joystickBase = 0; } else if (choice == 1) { //joystick on *joystickBase = 1; } } <file_sep>/joystickAPI/servoControl.h /* * <NAME> * 3/26/19 * The .h file for the servoControl */ #ifndef SERVOCONTROL_H_ #define SERVOCONTROL_H_ #include "alt_types.h" #include <unistd.h> //Moves servo and dir based on user choice void moveServos(int num, int choice); //Sets both servos to 0 pos void resetPos(); //Pans the bot servo for the number of turns the user wants void panServos(int turns); #endif
777e60093daa9862ef2f308775154a37a904c865
[ "Markdown", "C" ]
8
C
iliescua/JoystickAPI
6b533afa1ba901c4984ed4d73f21c3aa45eb4851
8999a785067fc27a4a88a2bfd9122ced21920791
refs/heads/master
<repo_name>davisgrubin/district_tweets<file_sep>/GeoStream.py import os import tweepy import DistrictDict as dd import sys import jsonpickle dist_dict = dd.get_files() dist_lookup = [] for k, v in dist_dict.items(): dist_lookup.append((v,k)) TWITTER_APP_KEY = os.environ['TW_CONSUMER_KEY'] TWITTER_APP_SECRET = os.environ['TW_CONSUMER_SECRET'] TWITTER_KEY= os.environ['TW_ACCESS_TOKEN'] TWITTER_SECRET = os.environ['TW_ACCESS_SECRET'] auth = tweepy.OAuthHandler(TWITTER_APP_KEY, TWITTER_APP_SECRET) auth.set_access_token(TWITTER_KEY, TWITTER_SECRET) api = tweepy.API(auth) class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): tweetCount=0 if status.user.location != None: for i in dist_lookup: if status.user.location in i[0]: with open('stream_tweets/{0}.txt'.format(i[1]),'a') as f: f.write(jsonpickle.encode(status._json, unpicklable=False) + '\n') tweetCount += 1 if tweetCount%1000 == 0: print('Tweets Downloaded:{0}'.format(tweetCount)) def on_error(self, status_code): print(sys.stderr, 'Encountered error with status code:', status_code) return True # Don't kill the stream def on_timeout(self): print(sys.stderr, 'Timeout...') return True # Don't kill the stream if __name__ == '__main__': tweetCount = 0 sapi = tweepy.streaming.Stream(auth, CustomStreamListener()) sapi.filter(locations=[-125,24,-66,50]) <file_sep>/sentiment_timeseries.py import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import psycopg2 import pandas as pd import json import datetime as dt app = dash.Dash(__name__) #get global data conn = psycopg2.connect('dbname=ubuntu user=ubuntu host=/var/run/postgresql') state_codes = {'53': 'WA', '10': 'DE', '11': 'DC', '55': 'WI', '54': 'WV', '15': 'HI', '12': 'FL', '56': 'WY', '72': 'PR', '34': 'NJ', '35': 'NM', '48': 'TX', '22': 'LA', '37': 'NC', '38': 'ND', '31': 'NE', '47': 'TN', '36': 'NY', '42': 'PA', '2': 'AK', '32': 'NV', '33': 'NH', '51': 'VA', '8': 'CO', '6': 'CA', '1': 'AL', '5': 'AR', '50': 'VT', '17': 'IL','13':'GA', '18': 'IN','19': 'IA', '25': 'MA', '4': 'AZ', '16': 'ID', '9': 'CT','23':'ME', '24': 'MD', '40': 'OK', '39': 'OH', '49': 'UT', '29': 'MO', '27': 'MN', '26': 'MI', '44': 'RI', '20': 'KS', '30': 'MT', '28': 'MS', '45': 'SC', '21': 'KY', '41': 'OR', '46': 'SD'} app.css.append_css({ "external_url": "https://cdn.rawgit.com/plotly/dash-app-stylesheets/2d266c578d2a6e8850ebce48fdb52759b2aef506/stylesheet-oil-and-gas.css" }) app.layout =html.Div([ html.Div([ html.Label(children='Search Term Sentiment'), dcc.Input(id='search-term',type='text', value=''), html.Button(id='submit-button', children='Submit'), html.Label('Date Range (UTC)'), dcc.DatePickerRange( id='my-date-picker-range', initial_visible_month=dt.datetime.now()), dcc.RadioItems( id = 'hourly-or-daily', options=[ {'label': 'Hourly Avg','value': 'H'}, {'label': 'Daily Avg', 'value': 'D'},], value='H', labelStyle={'display': 'inline-block'}), dcc.Checklist( id = 'all-parties', options = [ {'label':'All Democratic Districts', 'value': 'D'}, {'label':'All Republican Districts', 'value': 'R'} ], values = [], labelStyle={'display': 'inline-block'} ), ]), html.Div([html.Label('Multi-Select Districts for Comparison'), dcc.Dropdown( id = 'district-selection', options=[], value = [], multi=True)]), html.Div(id='time-series'), html.Div(id='intermediate-value', style={'display': 'none'})]) #Helper/Cleaning Functions def state_from_num(i,dictionary=None): a = i.split('-') a[0] = dictionary[a[0]] return '-'.join(a) def num_state_format(): dem_dists, rep_dists = get_parties() codes = {v:k for k,v in state_codes.items()} dem_dists = {state_from_num(i,codes) for i in dem_dists} rep_dists = {state_from_num(i,codes) for i in rep_dists} return dem_dists, rep_dists def get_unique_dists(dists): return [{'label': i , 'value': i} for i in dists] def get_parties(stream=False): df = pd.read_csv('legislators-current.csv') df = df[df['type'] != 'sen'] df = df[df['state'] != 'GU'] df = df[df['state'] != 'MP'] df = df[df['state'] != 'PR'] df = df[df['state'] != 'AS'] df = df[df['state'] != 'VI'] df['district'] = [str(int(i)) for i in df['district']] df['district'] = ['0'+i if len(i) < 2 else i for i in df['district']] df['state_dist'] = df['state'] + '-' + df['district'] dem_dists = df.loc[df['party'] == 'Democrat'] rep_dists = df.loc[df['party'] == 'Republican'] dem_dists = set(dem_dists['state_dist']) rep_dists = set(rep_dists['state_dist']) return dem_dists, rep_dists def downsample(filter_df,freq,name): downsamp = filter_df.polarity.resample(freq).mean() n_tweets = filter_df.polarity.resample(freq).count() n_tweets = ['n_tweets: ' + str(i) for i in n_tweets.values] return {'x':downsamp.index,'y':downsamp.values,'name':name,'text':n_tweets} def filter_by_dists(dists,df,freq): data = [] for i in dists: filter_df = df[df.district.str.match(i)==True] data.append(downsamp(filter_df,freq,i)) return data def filter_by_party(parties,df,freq): dem_dists, rep_dists = get_parties() data = [] for i in parties: if i == 'D': filter_df = df[df['district'].isin(dem_dists)] name = 'All ' + i + ' avg' dems = downsample(filter_df,freq,name) dems['line'] = {'color':'rgb(22, 96, 167)'} data.append(dems) else: filter_df = df[df['district'].isin(rep_dists)] name = 'All ' + i + ' avg' reps = downsample(filter_df,freq,name) reps['line'] = {'color':'rgb(205, 12, 24)'} data.append(reps) return data #Search and store resulting df in client Browser @app.callback( Output('intermediate-value', 'children'), [Input('submit-button', 'n_clicks')], [State('search-term', 'value'), State('my-date-picker-range','start_date'), State('my-date-picker-range','end_date')] ) def search_data(n_clicks,input1,min_date,max_date): query = """ SELECT polarity, date_time, district FROM tweetstest WHERE content LIKE %(input1)s AND date_time BETWEEN %(min_date)s AND %(max_date)s ORDER BY date_time DESC; """ params = {'input1':'%' +input1+ '%','min_date':min_date,'max_date':max_date} cur = conn.cursor() cur.execute(query,params) df = pd.DataFrame(cur.fetchall(),columns=['polarity','date_time','district']) # df_search = df[df.content.str.contains('{}'.format(str(input1)),case=False, # regex=False) == True] df.district = df.district.apply(state_from_num,dictionary=state_codes) # more generally, this line would be # json.dumps(cleaned_df) return df.to_json(date_format='iso', orient='split') @app.callback( Output('time-series', 'children'), [Input('intermediate-value','children'), Input('district-selection','value'), Input('hourly-or-daily','value'), Input('all-parties','values')] ) def update_time_series(jsonified_cleaned_data,dist,freq,parties): # return("You've clicked {0} times and entered {1}".format(n_clicks,input1)) df = pd.read_json(jsonified_cleaned_data, orient='split') # df.date_time = df.date_time.values.astype('datetime64[h]') df.set_index('date_time',inplace=True) downsamp = df.polarity.resample(freq).mean() n_tweets = df.polarity.resample(freq).count() n_tweets = ['n_tweets: ' + str(i) for i in n_tweets.values] data = [] data.append({'x':downsamp.index,'y':downsamp.values,'name':"<NAME>", 'text':n_tweets,'line':{'color':'rgb(115,54,97)'}}) data_districts = filter_by_dists(dist,df,freq) data_parties = filter_by_party(parties,df,freq) all_data = data + data_districts + data_parties return dcc.Graph(id='output-graph',figure = {'data':all_data}) @app.callback( Output('district-selection','options'), [Input('intermediate-value','children')] ) def update_dists(jsonified_cleaned_data): df_search = pd.read_json(jsonified_cleaned_data, orient='split') return(get_unique_dists(df_search.district.unique())) if __name__ == '__main__': app.run_server(host='0.0.0.0') <file_sep>/README.md # Examining the Twitterverse of Democratic and Republican Congressional Districts ![screenshot from 2018-07-30 13-52-20](https://user-images.githubusercontent.com/25091693/43414188-110ba3b2-9400-11e8-849c-8bcdb5679ab9.png) Visualization of Word2Vec embeddings trained on 11,000,000 democratic and 9,000,000 republican tweets.</br> (just democratic are seen above) ## Tensorboard Visualizations of Tweets These two tensorboard visualizations of word2vec models trained on democratic and republican tweets allow you to see diffrences and simliarities in twitter discourse. Simply pick a topic, user, or term in the search bar and narrow it down to however many nearest neighbors you'd like. The closer words are to eachother, the more semantic context they share in their use.<br/> Link to democratic dists tensorboard: http://ec2-18-222-37-25.us-east-2.compute.amazonaws.com:8080/#projector&run=.<br/> Link to republican dists tensorboard: http://ec2-18-222-37-25.us-east-2.compute.amazonaws.com:8090/#projector&run=. Here is an example of using the T-SNE option to compare clusters of the 100 nearest neighbors of the term 'politics' for both democratic and republican districts. Ctl+click on the photos to see them in fullscreen. #### Republican districts 'politics' clusters ![screenshot from 2018-07-30 13-18-29](https://user-images.githubusercontent.com/25091693/43412407-1d244fdc-93fb-11e8-8c82-b6c166592de9.png) #### Democratic districts 'politics' clusters ![screenshot from 2018-07-30 13-18-13](https://user-images.githubusercontent.com/25091693/43412408-1ea7b948-93fb-11e8-8279-841380609cdf.png) You can also project along an 'axis' using terms within the corpus - i.e. 'good to bad' or 'harm to care'. Feel free to get creative! #### Republican districts 'politics' nearest neighbors good to bad: ![rep_goodtobad](https://user-images.githubusercontent.com/25091693/43413266-9bd87a22-93fd-11e8-8278-84f143f34dab.png) #### Democratic districts 'politics' nearest neighbors good to bad: ![dem_goodtobad](https://user-images.githubusercontent.com/25091693/43413450-179f00d6-93fe-11e8-9aa0-d19b23fdd499.png) I've also created a Dash app that allows you to track the sentiment polarity (positive vs. negative) of all tweets that contain your search term over time. There are also options to filter on congressional districts at the individual and party level. The corresponding code is in sentiment_timeseries.py. Click the plot_studio option in the toolbar to get fancy. #### Dash interactive visualization of sentiment polarity time-series: http://ec2-18-222-37-25.us-east-2.compute.amazonaws.com:8050/ ![senitment_timeseries](https://user-images.githubusercontent.com/25091693/43411810-49cdc574-93f9-11e8-932d-038a958ba91d.png) Below is my original Galvanize Data Science Capstone and how I collected tweets filtered by congressional district. #### Can tweets be used to predict the partisanship of congressional districts? ## How to use this repo *I've updated the method I used for my capstone with a new Tweepy Stream Listener that puts the tweets directly into a Postgresql database(Stream_2_Postgres.py), along with other improvements. I'm keeping the description of the original method below and the original file (GeoStream.py) just to showcase how I used it for my capstone. Just clone the repo and run GeoStream.py in a terminal. It will create a stream_tweets folder with each district's tweets & metadata saved in the format <State FIPS #>-<District #>.txt. Once you have collected enough tweets (du -sbh stream_tweets in the bash until its around 9gb to get around how many I had). You can then look at the Partisanship Prediction notebook to see how to read in just the tweets, districts, and parties into a dataframe for reproducing predictions using scikit learn. # Collecting Data ## Twitter Streaming API w/ Tweepy The Twitter Streaming API allows for the collection of tweets by specifiying bounding boxes - in my case I enclosed the continental U.S. and then filtered on tweet metadata. While a very small amount of this data has exact geographic coordinates, many do have user specified locations. By creating a index of place names by congressional district using the [relationship](https://www.census.gov/geo/maps-data/data/relationship.html) and [name-lookup](https://www.census.gov/geo/maps-data/data/nlt.html) files made public by census.gov, I was able to create a pipeline that saved tweets originating from accounts with these locations as .txt files with the State FIPS code and district number as a title. Currently I have around 9GB of tweets and corresponding metadata. # Methods First I loaded the tweets into a dataframe and did some twitter-specific tokenization and text pre-processing by removing links and english stopwords using Stanford NLP's preprocessing script. By treating each district's tweets as a document, I created a TF-IDF matrix and a bag-of-words (as well as SVD for both of them) and used a Multinomial Naive Bayes and SVM classifier trained using Stochastic Gradient Descent on each for a baseline. The labels were whether that district was represented by a Democrat(0) or a Republican(1). # Results For the model evaluation I split the districts and their associated tweets into a training set of 307. Surprisingly the most simple approach, a bag of words with Naive Bayes had a 3 fold cross validated score of 70 % while the Tfidf reduced to 50d using SVD with a SVM as classifier performed at 74% accuracy. # Goals I'm currently working on how to apply more dense, semantically rich features such as GloVe and word2vec along with neural nets to this "district as document" classification schema. In the future I'd like to change my dependent variable to COOK PVI, a measure of congressional partisanship in each district that is calculated by comparing district-level presidential election results to those of the national presidential election. I'm curious to see how far I can get with just using vector representations without trying any extensive feature engineering. I may also use tensorboard or t-SNE to create visualizations of republican and democratic word vectors side by side for comparison. If you missed it at the top, I've created a simple interactive visualization using Dash that allows users to search terms and get a time-series of sentiment polarity of tweets containing those terms. The code is in sentiment_timeseries.py and the application is here: http://ec2-18-222-37-25.us-east-2.compute.amazonaws.com:8050/ Keep in mind this uses the free Twitter API and therefore doesn't have very large numbers of tweets for certain terms! <file_sep>/tweets_to_df.py import pandas as pd from collections import defaultdict import os import json import pickle def tweets2df(): tweets_data = dict() for i in os.listdir('stream_tweets'): with open('stream_tweets/{0}'.format(i),mode='r') as json_data: district = i.split(".")[0] tweets_data[district] = [] for line in json_data: tweet = json.loads(line) tweets_data[district].append((tweet['user']['location'], tweet['text'])) tweets_df = pd.DataFrame() text = [] dists = [] for k, v in tweets_data.items(): text.append(list(map(lambda tweet: tweet[1], v))) dists.append(k) tweets_df['text'] = text tweets_df['district'] = dists tweets_df.to_pickle('tweets_df.pikl') def get_parties(): state_codes = { 'WA': '53', 'DE': '10', 'DC': '11', 'WI': '55', 'WV': '54', 'HI': '15', 'FL': '12', 'WY': '56', 'PR': '72', 'NJ': '34', 'NM': '35', 'TX': '48', 'LA': '22', 'NC': '37', 'ND': '38', 'NE': '31', 'TN': '47', 'NY': '36', 'PA': '42', 'AK': '2', 'NV': '32', 'NH': '33', 'VA': '51', 'CO': '8', 'CA': '6', 'AL': '1', 'AR': '5', 'VT': '50', 'IL': '17', 'GA': '13', 'IN': '18', 'IA': '19', 'MA': '25', 'AZ': '4', 'ID': '16', 'CT': '9', 'ME': '23', 'MD': '24', 'OK': '40', 'OH': '39', 'UT': '49', 'MO': '29', 'MN': '27', 'MI': '26', 'RI': '44', 'KS': '20', 'MT': '30', 'MS': '28', 'SC': '45', 'KY': '21', 'OR': '41', 'SD': '46' } df = pd.read_csv('legislators-current.csv') df = df[df['type'] != 'sen'] df = df[df['state'] != 'GU'] df = df[df['state'] != 'MP'] df = df[df['state'] != 'PR'] df = df[df['state'] != 'AS'] df = df[df['state'] != 'VI'] df['state'] = [state_codes[i] for i in df['state']] party_dict = {"Democrat":0,"Republican":1} df['party'] = [party_dict[i] for i in df['party']] df['district'] = [str(int(i)) for i in df['district']] df['district'] = ['0'+i if len(i) < 2 else i for i in df['district']] df['state_dist'] = df['state'] + '-' + df['district'] df = df[['state_dist','party']] return df def get_tweets(no_districts=False): with open('tweets_df.pikl','rb') as pickle_file: tweets_df = pickle.load(pickle_file) by_party = get_parties() by_party = by_party.rename(columns={"state_dist":"district"}) tweets_df = tweets_df.merge(by_party,how='left',on='district') if no_districts == True: tweets_df.drop('district',axis=1,inplace=True) return tweets_df if __name__ == '__main__': tweets_df = get_tweets() <file_sep>/Stream_2_Postgres.py import os import tweepy import DistrictDict as dd import sys import boto3 from textblob import TextBlob import json import psycopg2 import numpy as np import itertools from time import sleep from sentiment_timeseries import num_state_format dist_dict = dd.get_files() dist_lookup = [] for k, v in dist_dict.items(): dist_lookup.append((v,k)) TWITTER_APP_KEY = os.environ['TW_CONSUMER_KEY'] TWITTER_APP_SECRET = os.environ['TW_CONSUMER_SECRET'] TWITTER_KEY= os.environ['TW_ACCESS_TOKEN'] TWITTER_SECRET = os.environ['TW_ACCESS_SECRET'] auth = tweepy.OAuthHandler(TWITTER_APP_KEY, TWITTER_APP_SECRET) auth.set_access_token(TWITTER_KEY, TWITTER_SECRET) aws_key = os.environ['AWS_SECRET_ACCESS_KEY'] aws_key_id = os.environ['AWS_ACCESS_KEY'] conn = psycopg2.connect('dbname=ubuntu user=ubuntu host=/var/run/postgresql') cur = conn.cursor() # cur.execute('''CREATE TABLE tweetstest( # id SERIAL, content varchar, location varchar, # polarity real, subjectivity real, screen_name varchar, # district varchar,date_time timestamp);''') # conn.commit() class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): if status.user.location != None: filt = [True if status.user.location in i[0] else False for i in dist_lookup] if any(filt): district = np.random.choice([i[1] for i in list(itertools.compress(dist_lookup,filt))]) polarity = TextBlob(status.text).sentiment[0] subjectivity = TextBlob(status.text).sentiment[1] content = status.text location = status.user.location screen_name = status.user.screen_name date_time = status.created_at #For constantly updating to Kinesis Stream # data = {'text':str(status.text),'district':str(i[1]), # 'location':str(status.user.location), # 'polarity':TextBlob(status.text).sentiment[0], # 'subjectivity':TextBlob(status.text).sentiment[1], # 'time':str(status.created_at)} # client.put_record(DeliveryStreamName ='tweet_stream', # Record = {'Data':json.dumps(data)}) cur.execute('''INSERT INTO tweetstest(content,location, polarity,subjectivity,screen_name,district,date_time) VALUES(%s,%s,%s, %s,%s,%s,%s)''',(content,location,polarity,subjectivity,screen_name, district,date_time)) conn.commit() def on_error(self, status_code): print(sys.stderr, 'Encountered error with status code:', status_code) return True # Don't kill the stream def on_timeout(self): print(sys.stderr, 'Timeout...') return True # Don't kill the stream def on_exception(self, exception): print(exception) return True if __name__ == '__main__': #Establishing Kinesis Stream # client = boto3.client('firehose',region_name ='us-east-2',aws_access_key_id=aws_key_id, # aws_secret_access_key=aws_key) backoff = 1 while True: api = tweepy.API(auth) try: sapi = tweepy.streaming.Stream(auth, CustomStreamListener()) sapi.filter(locations=[-125,24,-66,50]) except: e = sys.exc_info()[0] print('I just caught the exception: %s' % e) backoff += 1 sleep(60 * backoff) continue <file_sep>/weekly_check.py import psycopg2 import os import preprocess_twitter as pre import numpy from datetime import datetime conn = psycopg2.connect('dbname=ubuntu user=ubuntu host=/var/run/postgresql') cur = conn.cursor() cur.execute('''UPDATE tweetstest SET party = (SELECT dist_parties.party FROM dist_parties WHERE dist_parties.district = tweetstest.district)''') conn.commit() #Get Number of Democratic Tweets cur.execute('''SELECT COUNT(*) FROM tweetstest WHERE party = True''') num_dem_tweets = cur.fetchall() num_dem_tweets = num_dem_tweets[0][0] conn.commit() #Get Number of Republican Tweets cur.execute('''SELECT COUNT(*) FROM tweetstest WHERE party = False''') num_rep_tweets = cur.fetchall() num_rep_tweets = num_rep_tweets[0][0] conn.commit() if os.path.exists('num_of_tweets.txt'): with open("num_of_tweets.txt",'r') as f: old_num_dem_tweets = f.readline() old_num_rep_tweets = f.readline() with open("num_of_tweets.txt",'w') as f: f.write(str(num_dem_tweets)) f.write('\n') f.write(str(num_rep_tweets)) f.close() else: with open("num_of_tweets.txt",'w') as f: f.write(str(num_dem_tweets)) f.write('\n') f.write(str(num_rep_tweets)) f.close() # if num_rep_tweets - old_num_rep_tweets > 10000000: date = datetime.now().strftime('%Y_%m_%d') cur2 = conn.cursor('repcur') cur2.execute('''SELECT content FROM tweetstest WHERE party = False''') with open('rep_tweets_{}.txt'.format(date),'w') as f: for record in cur2: f.write(pre.tokenize(record[0]) + '\n') f.close() # if num_dem_tweets - int(old_num_dem_tweets) > 10000000: date = datetime.now().strftime('%Y_%m_%d') cur3 = conn.cursor('demcur') cur3.execute('''SELECT content FROM tweetstest WHERE party = True''') with open('dem_tweets_{}.txt'.format(date),'w') as f: for record in cur3: f.write(pre.tokenize(record[0] + '\n')) f.close() <file_sep>/DistrictDict.py import pandas as pd from collections import deque import os state_codes = { 'WA': '53', 'DE': '10', 'DC': '11', 'WI': '55', 'WV': '54', 'HI': '15', 'FL': '12', 'WY': '56', 'PR': '72', 'NJ': '34', 'NM': '35', 'TX': '48', 'LA': '22', 'NC': '37', 'ND': '38', 'NE': '31', 'TN': '47', 'NY': '36', 'PA': '42', 'AK': '2', 'NV': '32', 'NH': '33', 'VA': '51', 'CO': '8', 'CA': '6', 'AL': '1', 'AR': '5', 'VT': '50', 'IL': '17', 'GA': '13', 'IN': '18', 'IA': '19', 'MA': '25', 'AZ': '4', 'ID': '16', 'CT': '9', 'ME': '23', 'MD': '24', 'OK': '40', 'OH': '39', 'UT': '49', 'MO': '29', 'MN': '27', 'MI': '26', 'RI': '44', 'KS': '20', 'MT': '30', 'MS': '28', 'SC': '45', 'KY': '21', 'OR': '41', 'SD': '46' } state_codes = {v:k for k,v in state_codes.items()} def place_by_dist(cd_file,cdp_file,incp_file): df_cd = pd.read_csv(cd_file) df_cdp = pd.read_csv(cdp_file,sep="|") df_incp = pd.read_csv(incp_file,sep="|") df_cd = df_cd.reset_index() tab_name = df_cd.columns[3] df_cd = df_cd.rename(columns={'level_0':'State','level_1':'PLACEFP','level_2':'County', '{0}'.format(tab_name):'CongressionalDistrict'}) df_cd = df_cd.drop(index=0) df_cd['PLACEFP'] = [str(i).lstrip('0') for i in df_cd['PLACEFP']] df_cd['PLACEFP'] = df_cd['PLACEFP'].astype(int) df_place_names = pd.concat([df_cdp,df_incp]) df_place_names['PLACEFP'] = df_place_names['PLACEFP'].astype(int) master_df = pd.merge(df_place_names,df_cd,how='inner',on='PLACEFP') master_df['State_Abrv'] = [state_codes[str(i)] for i in master_df['STATEFP']] master_df['NAME']= master_df['NAME'] +', '+ master_df['State_Abrv'] return master_df def make_dict(df): dist_dict = dict() for dist in df.CongressionalDistrict.unique(): statefp = df['STATEFP'][0] dist_dict["{0}-{1}".format(statefp,dist)] = set(df[df.CongressionalDistrict == dist]['NAME'].values) return dist_dict def get_files(): files = os.listdir('place_names/') files.sort() one_dist = ['AK','WY','DE','MT','ND','SD','VT','DC'] for i in one_dist: files = [j for j in files if i not in j] files = deque(files) listofdict = [] for i in range(int(len(files)/3)): state_dict = make_dict(place_by_dist('place_names/{0}'.format(files[0]), 'place_names/{0}'.format(files[1]), 'place_names/{0}'.format(files[2]))) listofdict.append(state_dict) files.rotate(-3) one_dist_files = [] for i in one_dist: for j in os.listdir('place_names/'): if i in j: one_dist_files.append(j) one_dist_files = deque(one_dist_files) one_dist_dfs = [] for j in range(len(one_dist_files)//2): df = pd.read_csv('place_names/{0}'.format(one_dist_files[0]),sep = '|') df2 = pd.read_csv('place_names/{0}'.format(one_dist_files[1]),sep = '|') df = pd.concat([df,df2]) df = df.reset_index() df['CongressionalDistrict'] = '00' df['State_Abrv'] = [state_codes[str(i)] for i in df['STATEFP']] df['NAME']= df['NAME'] +', '+ df['State_Abrv'] one_dist_dfs.append(make_dict(df)) one_dist_files.rotate(-2) listofdict = listofdict + one_dist_dfs main_dict = { k: v for d in listofdict for k, v in d.items() } return main_dict if __name__ == '__main__': DistDict = get_files() <file_sep>/training_word2vec.py from gensim.models import Word2Vec, word2vec import sys, os #make sure we are using Cython to utilize mutltiple cores assert word2vec.FAST_VERSION > -1 #Generator object for reading tweets line by line class MySentences(object): def __init__(self, dirname): self.dirname = dirname def __iter__(self): for fname in os.listdir(self.dirname): for line in open(os.path.join(self.dirname, fname)): yield line.split() if __name__ == '__main__': '''python training_word2vec.py tweets_filepath''' sentences = MySentences('test_folder') model = Word2Vec(sentences,iter=15,workers=4) model.save('first_model')
de7c56978c5be2e0150a54ad646831144b04459c
[ "Markdown", "Python" ]
8
Python
davisgrubin/district_tweets
1180fca455b7ed3321e12c1d7bc477db052dfb1e
c9ff1593f16ae36988ebfb45e60dba73b898d278
refs/heads/master
<repo_name>clube-do-malte/checkout<file_sep>/Carrinho.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Carrinho extends Model { protected $table = "Carrinho"; protected $fillable = [ 'id_trayCorp', 'nome', 'email', 'telefone', 'valor', 'logradouroOrig', 'numeroOrig', 'complementoOrig', 'bairroOrig', 'cidadeOrig', 'estadoOrig', 'cepOrig', 'referenciaOrig', 'logradouroDest', 'numeroDest', 'complementoDest', 'bairroDest', 'cidadeDest', 'estadoDest', 'cepDest', 'referenciaDest', 'dt_processado', 'situacao', ]; public $timestamps = false; } <file_sep>/README.md # checkout Projeto Checkout O Projeto foi desenvolvido em PHP 7.3 e com Framework Laravel 5.8 API do Checkout está divida em dois enpoint Cartão e Frete <file_sep>/CarrinhoItem.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class CarrinhoItem extends Model { protected $fillable = [ 'id_carrinho', 'id_produto', 'nome', 'sku', 'peso', 'altura', 'largura', 'comprimento', 'valor' ]; protected $table = 'carrinhoItem'; public $timestamps = false; } <file_sep>/Cartao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Cartao extends Model { ## Alterando protected $table = "CarrinhoCard"; public $timestamps = false; protected $fillable = [ 'id_carrinho', 'cardFlag', 'cardName', 'cardNumber', 'cardExpYear', 'cardExpMonth', 'cardSegCod', 'situacao' ]; } <file_sep>/FreteController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use \RecursiveIteratorIterator; use \RecursiveArrayIterator; use App\Carrinho; use App\CarrinhoItem; use DB; #use App\DIContainer; class FreteController extends Controller { public function frete(Request $request, Response $response){ #dd($request->pacote); $basket = json_decode($request->getContent()); #dd($basket); //Variaveis $origem = $basket->pacote->origem; $destino = $basket->pacote->destino; $carrinho_itens = $basket->pacote->produto; $carrinho = $basket->pacote->carrinho; //Ultimo ID Inserido na Carrinho $last_insert_id = null; $error_msg = array(); //Loop de Produtos foreach ($carrinho_itens as $prod) { //ID Produto if(!isset($prod->id)){ array_push($error_msg, 'ID do produto não pode ser nulo'); } //Nome Produto if(!isset($prod->nome)){ array_push($error_msg,'Nome do produto não pode ser nulo'); } //SKU Produto if(!isset($prod->sku)){ array_push($error_msg,'SKU do produto não pode ser nulo'); } //Peso Produto if(!isset($prod->peso)){ array_push($error_msg,'Peso do produto não pode ser nulo'); } //Altura Produto if(!isset($prod->altura)){ array_push($error_msg,'Altura do produto não pode ser nulo'); } //Largura Produto if(!isset($prod->largura)){ array_push($error_msg,'Largura do produto não pode ser nulo'); } //Comprimento Produto if(!isset($prod->comprimento)){ array_push($error_msg,'Comprimento do produto não pode ser nulo'); } //Valor Produto if(!isset($prod->valor)){ array_push($error_msg,'Valor do produto não pode ser nulo'); } } //fim loop produto //carrinho-info //Carrinho id if(!isset($carrinho->id)){ array_push($error_msg,'ID do Carrinho não pode ser nulo'); } //Carrinho valor if(!isset($carrinho->valor)){ array_push($error_msg,'Valor do Carrinho não pode ser nulo'); } // fim carrinho-info //Carrinho-Usuario //Usuario nome if(!isset($carrinho->usuario->nome)){ array_push($error_msg, 'Nome do usuário não pode ser nulo'); } //Usuario email if(!isset($carrinho->usuario->email)){ array_push($error_msg, 'E-mail do usuário não pode ser nulo'); } //Usuario telefone if(!isset($carrinho->usuario->telefone)){ array_push($error_msg, 'Telefone do usuario não pode ser nulo'); } //Origem $origem->logradouro; $origem->numero; $origem->complemento; $origem->bairro; $origem->cidade; $origem->estado; $origem->cep; $origem->referencia; //Destino if(!isset($destino->logradouro)){ array_push($error_msg, 'Logradouro de destino não pode ser nulo'); } if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } /* if(!isset($destino->complemento)){ $destino->complemento; }else{ array_push($error_msg, 'Número do destino não pode ser nulo'); } */ $destino->complemento; if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } if(!isset($destino->bairro)){ array_push($error_msg, 'Bairro do destino não pode ser nulo'); } if(!isset($destino->cidade)){ array_push($error_msg, 'Cidade do destino não pode ser nulo'); } if(!isset($destino->estado)){ array_push($error_msg, 'Estado do destino não pode ser nulo'); } if(!isset($destino->cep)){ array_push($error_msg, 'Cep do destino não pode ser nulo'); } $destino->referencia; //Testa se tem erros if(!empty($error_msg)){ return response()->json($error_msg, 400); }else { //Grava na Tabela Carriho $gravaCarrinho = Carrinho::Create([ 'id_trayCorp' => $carrinho->id, 'nome' => $carrinho->usuario->nome, 'email' => $carrinho->usuario->email, 'telefone' => $carrinho->usuario->telefone, 'valor' => $carrinho->valor, 'logradouroOrig' => $origem->logradouro, 'numeroOrig' => $origem->numero, 'complementoOrig'=> $origem->complemento, 'bairroOrig' => $origem->bairro, 'cidadeOrig' => $origem->cidade, 'estadoOrig' => $origem->estado, 'cepOrig' => $origem->cep, 'referenciaOrig' => $origem->referencia, 'logradouroDest' => $destino->logradouro, 'numeroDest' => $destino->numero, 'complementoDest'=> $destino->complemento, 'bairroDest' => $destino->bairro, 'cidadeDest' => $destino->cidade, 'estadoDest' => $destino->estado, 'cepDest' => $destino->cep, 'referenciaDest' => $destino->referencia, 'dt_processado' => Now(), 'situacao' => 'P' //Pendente ]); $last_insert_id = $gravaCarrinho->id; if($last_insert_id > 0){ //Grava na Tabela Carriho foreach ($carrinho_itens as $linha) { $grava_item = CarrinhoItem::Create([ 'id_carrinho' => $last_insert_id, 'id_produto' => $linha->id, 'nome' => $linha->nome, 'sku' => $linha->sku, 'peso' => $linha->peso, 'altura' => $linha->altura, 'largura' => $linha->largura, 'comprimento' => $linha->comprimento, 'valor' => $linha->valor ]); } $frete = null; $json_proc = DB::SELECT("SET NOCOUNT ON EXEC spcRetornaVlFrete ?,?,?,?", array($last_insert_id, $frete, null, null)); if($json_proc){ //Retorno da Procedure $frete = $json_proc[0]->jsonFrete; $retorno = json_decode($frete); return response()->json($retorno, 200); $error_msg = null; }else { return response()->json(['Não foi possivel retornar um frete'], 400); } } /* return response()->json(['Gravado com sucesso'], 200); $error_msg = null; */ } } } <file_sep>/CartaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\Crypt; use App\Cartao; use \RecursiveIteratorIterator; use \RecursiveArrayIterator; use App\Carrinho; use App\CarrinhoItem; use DB; class CartaoController extends Controller { /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response * @return \Illuminate\Http\Request */ public function create(Request $request, Response $response) { /* cardFlag: "mastercard", cardIsValid: true, cardName: "fulandodeta", cardNumber: "2503210658454612", cardExpYear: '2019', cardExpMonth: '04', cardSegCod: "213" */ #$content = json_decode($json); $content = json_decode($request->getContent()); //Variaveis $origem = $content->pacote->origem; $destino = $content->pacote->destino; $carrinho_itens = $content->pacote->produto; $carrinho = $content->pacote->carrinho; $cartao = $content->pacote->carrinho->cartao; //Ultimo ID Inserido na Carrinho $last_insert_id = null; $error_msg = []; $error_card = []; //Loop de Produtos foreach ($carrinho_itens as $prod) { //ID Produto if(!isset($prod->id)){ array_push($error_msg, 'ID do produto não pode ser nulo'); } //Nome Produto if(!isset($prod->nome)){ array_push($error_msg,'Nome do produto não pode ser nulo'); } //SKU Produto if(!isset($prod->sku)){ array_push($error_msg,'SKU do produto não pode ser nulo'); } //Peso Produto if(!isset($prod->peso)){ array_push($error_msg,'Peso do produto não pode ser nulo'); } //Altura Produto if(!isset($prod->altura)){ array_push($error_msg,'Altura do produto não pode ser nulo'); } //Largura Produto if(!isset($prod->largura)){ array_push($error_msg,'Largura do produto não pode ser nulo'); } //Comprimento Produto if(!isset($prod->comprimento)){ array_push($error_msg,'Comprimento do produto não pode ser nulo'); } //Valor Produto if(!isset($prod->valor)){ array_push($error_msg,'Valor do produto não pode ser nulo'); } } //fim loop produto //carrinho-info //Carrinho id if(!isset($carrinho->id)){ array_push($error_msg,'ID do Carrinho não pode ser nulo'); } //Carrinho valor if(!isset($carrinho->valor)){ array_push($error_msg,'Valor do Carrinho não pode ser nulo'); } // fim carrinho-info //Carrinho-Usuario //Usuario nome if(!isset($carrinho->usuario->nome)){ array_push($error_msg, 'Nome do usuário não pode ser nulo'); } //Usuario email if(!isset($carrinho->usuario->email)){ array_push($error_msg, 'E-mail do usuário não pode ser nulo'); } //Usuario telefone /* if(!isset($carrinho->usuario->telefone)){ array_push($error_msg, 'Telefone do usuario não pode ser nulo'); } */ //Origem $origem->logradouro; $origem->numero; $origem->complemento; $origem->bairro; $origem->cidade; $origem->estado; $origem->cep; $origem->referencia; //Destino if(!isset($destino->logradouro)){ array_push($error_msg, 'Logradouro de destino não pode ser nulo'); } if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } /* if(!isset($destino->complemento)){ $destino->complemento; }else{ array_push($error_msg, 'Número do destino não pode ser nulo'); } */ $destino->complemento; if(!isset($destino->numero)){ array_push($error_msg, 'Número do destino não pode ser nulo'); } if(!isset($destino->bairro)){ array_push($error_msg, 'Bairro do destino não pode ser nulo'); } if(!isset($destino->cidade)){ array_push($error_msg, 'Cidade do destino não pode ser nulo'); } if(!isset($destino->estado)){ array_push($error_msg, 'Estado do destino não pode ser nulo'); } if(!isset($destino->cep)){ array_push($error_msg, 'Cep do destino não pode ser nulo'); } $destino->referencia; //Testa se tem erros if(!empty($error_msg)){ return response()->json($error_msg, 400); }else { //Grava na Tabela Carriho $gravaCarrinho = Carrinho::Create([ 'id_trayCorp' => $carrinho->id, 'nome' => $carrinho->usuario->nome, 'email' => $carrinho->usuario->email, 'telefone' => $carrinho->usuario->telefone, 'valor' => $carrinho->valor, 'logradouroOrig' => $origem->logradouro, 'numeroOrig' => $origem->numero, 'complementoOrig'=> $origem->complemento, 'bairroOrig' => $origem->bairro, 'cidadeOrig' => $origem->cidade, 'estadoOrig' => $origem->estado, 'cepOrig' => $origem->cep, 'referenciaOrig' => $origem->referencia, 'logradouroDest' => $destino->logradouro, 'numeroDest' => $destino->numero, 'complementoDest'=> $destino->complemento, 'bairroDest' => $destino->bairro, 'cidadeDest' => $destino->cidade, 'estadoDest' => $destino->estado, 'cepDest' => $destino->cep, 'referenciaDest' => $destino->referencia, 'dt_processado' => Now(), 'situacao' => 'F' //Pendente ]); $last_insert_id = $gravaCarrinho->id; //Verifica se foi inserido na tabela com sucesso if($last_insert_id > 0){ //Grava na Tabela Carriho foreach ($carrinho_itens as $linha) { $grava_item = CarrinhoItem::Create([ 'id_carrinho' => $last_insert_id, 'id_produto' => $linha->id, 'nome' => $linha->nome, 'sku' => $linha->sku, 'peso' => $linha->peso, 'altura' => $linha->altura, 'largura' => $linha->largura, 'comprimento' => $linha->comprimento, 'valor' => $linha->valor ]); } //validacao if(!isset($cartao->cardFlag)){ array_push($error_card, 'Cartão sem bandeira'); } if(!isset($cartao->cardName)){ array_push($error_card, 'Cartão sem nome'); } if(!isset($cartao->cardNumber)){ array_push($error_card, 'Número do cartão pode ser nulo'); } if(!isset($cartao->cardExpYear)){ array_push($error_card, 'Ano de Expiração não pode ser nulo'); } if(!isset($cartao->cardExpMonth)){ array_push($error_card, 'Mês de Expiração não pode ser nulo'); } if(!isset($cartao->cardSegCod)){ array_push($error_card, 'Código de segurança não pode ser nulo'); } //Testa se tem erros if(!empty($error_card)){ return response()->json($error_card, 400); }else { $error_card = null; $grava_card = Cartao::Create([ 'id_carrinho' => $last_insert_id , 'cardFlag' => trim($cartao->cardFlag) , 'cardName' => trim($cartao->cardName) , 'cardNumber' => trim($cartao->cardNumber) , 'cardExpYear' => trim($cartao->cardExpYear) , 'cardExpMonth' => trim($cartao->cardExpMonth), 'cardSegCod' => trim($cartao->cardSegCod) , 'situacao' => trim('F') #Carinho fechado ]); return response()->json('', 200); } } } } }
1bc084f40fc973314ce65b04f583e39f4395d28e
[ "Markdown", "PHP" ]
6
PHP
clube-do-malte/checkout
232e00c6e1549ccb960caa714ef523334cb2b181
ade490de7915905d678ade33bf7db25af7b0d1f4
refs/heads/main
<file_sep>import React from 'react'; import closeIcon from '../../icons/closeImage.png'; import onlineIcon from '../../icons/onlineImage.png'; import './InfoBar.css'; const InfoBar = ({room}) => ( <div className = "infoBar"> <div className = "leftInnerContainer"> <img className = "onlineIcon" src = {onlineIcon} width = "30" height = "30" alt = "Online"/> <h1> <div className = "roomid"> RoomID </div> <div className = "roomname"> {room} </div> </h1> </div> <div className = "rightInnerContainer"> <a href = "/"> <img src = {closeIcon} width = "20" height = "20" alt = "Close Chat"/> </a> </div> </div> ) export default InfoBar; <file_sep>const users = []; const userAdd = ({id, name, room}) => { name = name.trim().toLowerCase(); room = room.trim().toLowerCase(); const sameUser = users.find((user) => user.room === room && user.name === name); if (sameUser) { return { error: 'Another User with Same username is already present in the room \nPlease pick a different username.'}; } const user = {id, name, room}; users.push(user); return {user} } const userDel = (id) => { const idx = users.findIndex((user) => user.id === id); if (idx != -1) { return users.splice(idx, 1)[0]; } } const userGet = (id) => users.find((user) => user.id === id); const userGetRoom = (room) => users.filter((user) => user.room === room); module.exports = {userAdd, userDel, userGet, userGetRoom};<file_sep>import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import './Join.css'; const Join = () => { const [name, setName] = useState(''); const [room, setRoom] = useState(''); return ( <div className = "joinOuterContainer"> <div className = "joinInnerContainer"> <h1 className = "welcome"> Welcome to rChat </h1> <h1 className = "heading"> Sign In </h1> <div> <input placeholder = "Enter User Name" className = "joinInput" type = "text" onChange = {(event) => setName(event.target.value)} /> </div> <div> <input placeholder = "Enter Room ID" className = "joinInput mt-20" type = "text" onChange = {(event) => setRoom(event.target.value)} /> </div> <Link onClick = {event => (!name || !room) ? event.preventDefault() : null} to = {`/chat?name=${name}&room=${room}`}> <button className = "button mt-20" type = "submit"> ENTER CHAT ROOM </button> </Link> <h2 className = "ending"> <p> Source </p> <a href = "https://github.com/sanchay9/rchat"> https://github.com/sanchay9/rchat </a> </h2> </div> </div> ) } export default Join; <file_sep># rchat a real time chat app
a1bc47ede23119218dd1a57b4119055e057cf623
[ "JavaScript", "Markdown" ]
4
JavaScript
sanchay9/rchat
187abe9a43ba2387d5528febe63fe8c148c4b66f
ffc3e23aae06276896a9f3cf3d812dbf381a7dba
refs/heads/master
<file_sep>import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import Grid from '@material-ui/core/Grid'; import TextField from '@material-ui/core/TextField'; import withStyles from '@material-ui/core/styles/withStyles'; import PropTypes from 'prop-types'; import React from 'react'; import strings from '../strings'; const inputs = [ { autoComplete: 'given-name', label: 'Vorname', name: 'first-name', required: true, }, { autoComplete: 'family-name', label: 'Nachname', name: 'last-name', required: true, }, { label: 'Email', name: 'email', required: true, type: 'email', }, { autoComplete: 'organization', label: 'Firma', name: 'company', required: true, }, { label: 'Position', name: 'position', required: true, }, { label: 'Anzahl der Angestellten', name: 'number-of-employees', required: true, }, { autoComplete: 'address-level2', label: 'Stadt', name: 'city', required: true, }, { label: 'LinkedIn Profil URL', name: 'linked-in', type: 'url', required: true, }, ]; function HeroModal({ classes, onClick, open }) { return ( <Dialog open={open} onClose={onClick} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">{strings.appTitle}</DialogTitle> <DialogContent> <DialogContentText>{strings.modalInstructions}</DialogContentText> <DialogContentText>{strings.rules}</DialogContentText> <Grid container spacing={2} direction="column" alignContent="center"> <form className={classes.form} name="slack-request" method="post" onSubmit={onClick} > <input type="hidden" name="form-name" value="slack-request" /> {inputs.map(({ type, name, ...rest }) => ( <Grid className={classes.gridItem} item key={name}> <TextField fullWidth id={name} name={name} type={type || 'text'} {...rest} /> </Grid> ))} <Grid className={classes.gridItem} item> <Button color="primary" type="submit" variant="contained"> Abschicken </Button> </Grid> </form> </Grid> </DialogContent> </Dialog> ); } HeroModal.propTypes = { classes: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, open: PropTypes.bool.isRequired, }; const styles = theme => ({ form: { width: '100%', }, gridItem: { marginBottom: theme.spacing(2), }, }); export default withStyles(styles)(HeroModal); <file_sep>import { withStyles } from '@material-ui/core'; import Link from '@material-ui/core/Link'; import Typography from '@material-ui/core/Typography'; import PropTypes from 'prop-types'; import React from 'react'; import strings from '../strings'; const styles = ({ palette, spacing }) => ({ footer: { backgroundColor: palette.background.paper, padding: spacing(6), }, }); function MadeWithLove() { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Kreiert mit ❤️ von '} <Link color="inherit" href="https://nikolas-chapoupis.com/"> <NAME>. </Link> </Typography> ); } function Footer({ classes }) { return ( <footer className={classes.footer}> <Typography variant="h6" align="center" gutterBottom> {strings.appTitle} </Typography> <Typography variant="subtitle1" align="center" color="textSecondary" component="p" > {strings.footerQuote} </Typography> <MadeWithLove /> </footer> ); } Footer.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Footer); <file_sep>import { withStyles } from '@material-ui/core'; import Button from '@material-ui/core/Button'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Container from '@material-ui/core/Container'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import PropTypes from 'prop-types'; import React from 'react'; const styles = ({ spacing }) => ({ cardGrid: { paddingTop: spacing(8), paddingBottom: spacing(8), }, card: { display: 'flex', flexDirection: 'column', height: '100%', }, cardMedia: { paddingTop: '56.25%', // 16:9 }, cardContent: { flexGrow: 1, }, }); function Events({ classes, events }) { return ( <Container className={classes.cardGrid} maxWidth="md"> <Grid container spacing={4} justify="center"> {events.map(event => ( <Grid item key={event.id} xs={12} sm={6} md={events.length <= 2 ? 6 : 4} > <Card className={classes.card}> <CardMedia className={classes.cardMedia} image={event.photo} title={event.title} /> <CardContent className={classes.cardContent}> <Typography gutterBottom variant="h5" component="h2"> {event.title} </Typography> <Typography gutterBottom variant="subtitle2"> {event.date} </Typography> <Typography>{event.content}</Typography> </CardContent> <CardActions> <Button size="small" href={event.link} target="_blank"> Mehr erfahren </Button> </CardActions> </Card> </Grid> ))} </Grid> </Container> ); } Events.propTypes = { classes: PropTypes.object.isRequired, events: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, date: PropTypes.string.isRequired, link: PropTypes.string.isRequired, content: PropTypes.string.isRequired, photo: PropTypes.string.isRequired, }) ).isRequired, }; Events.defaultProps = { events: [ { id: '1', title: 'Entrepreneur Giving Circle Meetup Aachen #2', date: 'Mon, 22.7.2019 - 19:00 @ DigiHub Aachen', link: 'http://meetu.ps/e/GN9x3/zy89Z/f', content: 'Nach einer kurzen Vorstellungsrunde hat jeder 5 Minuten Zeit, um von seinen aktuellen Herausforderungen zu erzählen. Während diesen 5 Minuten kann sich der Rest der Gruppe melden und sagen wobei derjenige helfen kann.', photo: 'https://secure.meetupstatic.com/photos/event/e/9/f/b/highres_481499899.jpeg', }, ], }; export default withStyles(styles)(Events); <file_sep>import Footer from './footer'; import Header from './header'; import Hero from './hero'; export { Footer, Header, Hero }; <file_sep>import CssBaseline from '@material-ui/core/CssBaseline'; import React from 'react'; import Events from './events'; import { Footer, Header, Hero } from './layout'; function App() { return ( <> <CssBaseline /> <Header /> <main> <Hero /> <Events /> </main> <Footer /> </> ); } export default App;
2a4286b637b1a69564ded59a31a0349db0f23311
[ "JavaScript" ]
5
JavaScript
entrepreneurgivingcircle/giving-circle.com
b379a7822b2ffc0d0c143bfbdce70490781dbac1
bae4759f260473ff41b4fb874acc0289ca41fb7f
refs/heads/master
<file_sep> from __future__ import print_function import datetime from google.auth import default, iam from google.auth.transport import requests from google.oauth2 import service_account from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials CLOUD_FUNCTION = False CF_SUSPEND = False SCOPES = ['https://www.googleapis.com/auth/admin.directory.user'] TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' # Email of the Service Account SERVICE_ACCOUNT_EMAIL = '<EMAIL>' # Path to the Service Account's Private Key file SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/Users/mathew.roy/mathew/tf/gcpkey/gcp.p12' CUSTOMER_ID = 'C03cmqlyp' G_ADMIN_USER = '<EMAIL>' def key_credentials(): creds = ServiceAccountCredentials.from_p12_keyfile(SERVICE_ACCOUNT_EMAIL,SERVICE_ACCOUNT_PKCS12_FILE_PATH,'notasecret',scopes=SCOPES) creds2 = creds.create_delegated(G_ADMIN_USER) return creds2 def delegated_credentials(credentials, subject, scopes): try: updated_credentials = credentials.with_subject(subject).with_scopes(scopes) except AttributeError: request = requests.Request() # Refresh the default credentials. This ensures that the information # about this account, notably the email, is populated. credentials.refresh(request) # Create an IAM signer using the default credentials. signer = iam.Signer( request, credentials, credentials.service_account_email ) # Create OAuth 2.0 Service Account credentials using the IAM-based # signer and the bootstrap_credential's service account email. updated_credentials = service_account.Credentials( signer, credentials.service_account_email, TOKEN_URI, scopes=scopes, subject=subject ) except Exception: raise return updated_credentials def getUsers(event, context): creds = None if CLOUD_FUNCTION: creds, project = default() creds2 = delegated_credentials(creds, G_ADMIN_USER, SCOPES) else: creds2 = key_credentials() service = build('admin', 'directory_v1', credentials=creds2) print('Getting the first 500 users in the domain') results = service.users().list(customer=CUSTOMER_ID, maxResults=500, orderBy='email').execute() users = results.get('users', []) date_of_today = datetime.datetime.today() print(date_of_today.isoformat()) kill_list = [] if not users: print('No users in the domain.') else: print('Users:') for user in users: #print(user) print(u'{0} ({1})'.format(user['primaryEmail'], user['name']['fullName'])) print(user['lastLoginTime']) userLastLoginDate = datetime.datetime.strptime(user['lastLoginTime'], "%Y-%m-%dT%H:%M:%S.%fZ") #print(userLastLoginDate) num_days = abs((date_of_today - userLastLoginDate).days) print(num_days) if num_days > 90: kill_list.append(user['primaryEmail']) if CF_SUSPEND: print('Suspending Eligible Users') for x in kill_list: print(x) user = service.users().get(userKey=x).execute() user['suspended'] = True service.users().update(userKey=x, body=user).execute(); else: print('List of Eligible Users') print(kill_list) if __name__ == '__main__': event = None context = None getUsers(event, context)
bebfe730fd5a4ec88fba4cb532d1b2ee67655089
[ "Python" ]
1
Python
sheemat/UnUsedUsers
8046524b6c1e97e3e169c78643b626dfcbce3a89
96442d45ad6d9d90a2ebf1fa9f9cb4d01defa13d
refs/heads/master
<file_sep>__author__ = 'tal' from myrubik import * def problem1(): cube1 = createCube() R2U(cube1, 0) F2U(cube1, 1) R2U(cube1, 1) R2F(cube1, 2) R2U(cube1, 0) F2U(cube1, 1) U2R(cube1, 2) R2U(cube1, 0) return cube1 def problem2(): cube1 = createCube() R2U(cube1, 0) F2U(cube1, 1) R2U(cube1, 1) U2R(cube1, 1) U2F(cube1, 1) U2R(cube1, 0) return cube1 def main(): cube1 = problem2() printCube(cube1) if __name__ == "__main__": main()<file_sep>__author__ = 'tal' import pycuber as pc def main(): # Create a Cube object mycube = pc.Cube() # Do something at the cube. mycube("R U R' U'") print(mycube) main()<file_sep>__author__ = 'tal' import random from myrubik import * from problemsToSolve import * NUM_OF_INITIAL_PARALLEL_SOLUTIONS = 100 NUM_OF_RANDOM_SOLUTION_MOVES = 20 NUM_OF_MUTATIONS = random.randint(1, 5) # NUM_OF_MUTATIONS = 1 NUM_OF_BEST_SOLUTIONS_FOR_NEXT_GENERATION = 45 NUM_OF_MAJOR_BEST_SOLUTIONS = 2 NUM_OF_GOOD_ENOUGH_GRADE = 45 THRESHLOD_MOVES = 0 THRESHLOD_MOVES_DEGRADE = 5 NUM_OF_GENERATIONS_TO_PRINT = 10 NUM_OF_MUTATIONS_FOR_BEST_SOLUTIONS = 3 KEEP_THE_SAME_SOLUTION = False # hueristicCheckCube = hueristicCheckCube1 allowedMoves = [ 'F2U1', 'F2U2', 'F2U3', 'U2F1', 'U2F2', 'U2F3', 'F2R1', 'F2R2', 'F2R3', 'R2F1', 'R2F2', 'R2F3', 'R2U1', 'R2U2', 'R2U3', 'U2R1', 'U2R2', 'U2R3', ] def generateRandomSolutions(): tempSolutions = [] for i in range(NUM_OF_INITIAL_PARALLEL_SOLUTIONS): randomMoves = random.randint(1, NUM_OF_RANDOM_SOLUTION_MOVES) tempSolution1 = [] for j in range(randomMoves): tempSolution1 += [allowedMoves[random.randint(0, len(allowedMoves) - 1)]] tempSolutions += [{'moves': tempSolution1}] return tempSolutions def hueristicCheckCube1(cube1, numOfMoves): numOfMatches = 0 colorsToCheck = { 'up': 0, 'down': 1, 'left': 2, 'right': 3, 'front': 4, 'back': 5 } for tempColor in colorsToCheck.keys(): for i in range(0, len(cube1[tempColor])): for j in range(0, len(cube1[tempColor][i])): if cube1[tempColor][i][j] == colorsToCheck[tempColor]: numOfMatches += 1 # if numOfMoves < THRESHLOD_MOVES: # numOfMatches -= THRESHLOD_MOVES_DEGRADE return numOfMatches def hueristicCheckCube2(cube1, numOfMoves): numOfMatches = 0 colorsToCheck = { 'up': 0, 'down': 1, 'left': 2, 'right': 3, 'front': 4, 'back': 5 } colorsFound = {} for tempColor in colorsToCheck.keys(): colorsFound = {} for i in range(0, len(cube1[tempColor])): for j in range(0, len(cube1[tempColor][i])): if cube1[tempColor][i][j] not in colorsFound: colorsFound[cube1[tempColor][i][j]] = 0 colorsFound[cube1[tempColor][i][j]] += 1 maxGradeColor = 0 for temp1 in colorsFound.keys(): if colorsFound[temp1] > maxGradeColor: maxGradeColor = colorsFound[temp1] numOfMatches += maxGradeColor # for keeping the grades more realistic if numOfMoves < THRESHLOD_MOVES: numOfMatches -= THRESHLOD_MOVES_DEGRADE return numOfMatches def getGradeOfSolution(solution): return hueristicCheckCube1(solution['currentCube'], len(solution['moves'])) def merge2Solutions(solution1, solution2): random1 = random.randint(0, min(len(solution1) - 1, len(solution2) - 1)) # newSoultion1 = solution1[:random1] + solution2[random1:] # newSoultion2 = solution2[:random1] + solution1[random1:] newSoultion1 = solution1 newSoultion2 = solution2 return [newSoultion1, newSoultion2] def undoMove(cube1, moveType): if moveType == 'F2U1': U2F(cube1, 0) if moveType == 'F2U2': U2F(cube1, 1) if moveType == 'F2U3': U2F(cube1, 2) if moveType == 'U2F1': F2U(cube1, 0) if moveType == 'U2F2': F2U(cube1, 1) if moveType == 'U2F3': F2U(cube1, 2) if moveType == 'F2R1': R2F(cube1, 0) if moveType == 'F2R2': R2F(cube1, 1) if moveType == 'F2R3': R2F(cube1, 2) if moveType == 'R2F1': F2R(cube1, 0) if moveType == 'R2F2': F2R(cube1, 1) if moveType == 'R2F3': F2R(cube1, 2) if moveType == 'R2U1': U2R(cube1, 0) if moveType == 'R2U2': U2R(cube1, 1) if moveType == 'R2U3': U2R(cube1, 2) if moveType == 'U2R1': R2U(cube1, 0) if moveType == 'U2R2': R2U(cube1, 1) if moveType == 'U2R3': R2U(cube1, 2) def addMove(cube1, moveType): if moveType == 'F2U1': F2U(cube1, 0) if moveType == 'F2U2': F2U(cube1, 1) if moveType == 'F2U3': F2U(cube1, 2) if moveType == 'U2F1': U2F(cube1, 0) if moveType == 'U2F2': U2F(cube1, 1) if moveType == 'U2F3': U2F(cube1, 2) if moveType == 'F2R1': F2R(cube1, 0) if moveType == 'F2R2': F2R(cube1, 1) if moveType == 'F2R3': F2R(cube1, 2) if moveType == 'R2F1': R2F(cube1, 0) if moveType == 'R2F2': R2F(cube1, 1) if moveType == 'R2F3': R2F(cube1, 2) if moveType == 'R2U1': R2U(cube1, 0) if moveType == 'R2U2': R2U(cube1, 1) if moveType == 'R2U3': R2U(cube1, 2) if moveType == 'U2R1': U2R(cube1, 0) if moveType == 'U2R2': U2R(cube1, 1) if moveType == 'U2R3': U2R(cube1, 2) def mutation(solution): random1 = NUM_OF_MUTATIONS for tempRand in range(random1): addRemoveOrChange = random.randint(1,3) if addRemoveOrChange == 3: # change the last move undoMove(solution['currentCube'], solution['moves'][-1]) solution['moves'][-1] = allowedMoves[random.randint(0, len(allowedMoves) - 1)] addMove(solution['currentCube'], solution['moves'][-1]) if addRemoveOrChange == 1: solution['moves'] += [allowedMoves[random.randint(0, len(allowedMoves) - 1)]] # add move in last position addMove(solution['currentCube'], solution['moves'][-1]) if addRemoveOrChange == 2: # if delete if len(solution['moves']) != 1: undoMove(solution['currentCube'], solution['moves'][-1]) del solution['moves'][-1] return solution def getNextGeneration(currentSolutions): best15Solutions = [] solutionsGrades = [] for tempSolution in currentSolutions: solutionsGrades += [{ 'grade': getGradeOfSolution(tempSolution), 'solution': tempSolution }] from operator import itemgetter best15Solutions = sorted(solutionsGrades, key=itemgetter('grade'), reverse=True)[:NUM_OF_BEST_SOLUTIONS_FOR_NEXT_GENERATION] bestSolution = copy.deepcopy(best15Solutions[0]) newSolutions = [] # for tempSolution in best15Solutions[NUM_OF_MAJOR_BEST_SOLUTIONS:]: # for tempMajorSolution in range(NUM_OF_MAJOR_BEST_SOLUTIONS): # merged = merge2Solutions(best15Solutions[tempMajorSolution]['solution'], tempSolution['solution']) # newSolutions += [mutation(merged[0])] # newSolutions += [mutation(merged[1])] # # for i in range(NUM_OF_MAJOR_BEST_SOLUTIONS): # for j in range(i + 1, NUM_OF_MAJOR_BEST_SOLUTIONS): # merged = merge2Solutions(best15Solutions[i]['solution'], best15Solutions[j]['solution']) # newSolutions += [mutation(merged[0])] # newSolutions += [mutation(merged[1])] # # for tempSolution in best15Solutions: # newSolutions += mutation(tempSolution['solution']) # # newSolutions += tempSolution['solution'] for tempSolution in best15Solutions: # maybe check that we didnt have this solution yet for i in range(NUM_OF_MUTATIONS_FOR_BEST_SOLUTIONS): newMutataionSolution = copy.deepcopy(tempSolution['solution']) newSolutions += [mutation(newMutataionSolution)] if KEEP_THE_SAME_SOLUTION: newSolutions += [best15Solutions[0]['solution'], copy.deepcopy(best15Solutions[0]['solution'])] # keep the best result twice return [newSolutions, bestSolution] def initSolutions(cubeProblem): currentSolutions = generateRandomSolutions() for tempSolution in currentSolutions: tempSolution['currentCube'] = copy.deepcopy(cubeProblem) for tempMove in tempSolution['moves']: addMove(tempSolution['currentCube'], tempMove) return currentSolutions def main(): cubeProblem1 = problem1() currentSolutions = initSolutions(cubeProblem1) bestSolutionGrade = 0 bestSolutionGradeGlobal = 0 currentGeneration = -1 i = -1 moreThan36Grade = 0 printOnce = False while bestSolutionGrade < NUM_OF_GOOD_ENOUGH_GRADE: currentGeneration += 1 result1 = getNextGeneration(currentSolutions) bestSolutionGrade = result1[1]['grade'] currentSolutions = result1[0] if bestSolutionGrade > bestSolutionGradeGlobal: bestSolutionGradeGlobal = bestSolutionGrade i += 1 if i == NUM_OF_GENERATIONS_TO_PRINT: print 'generation ' + str(currentGeneration) + ' - best solution grade: ' + str(bestSolutionGrade) + \ ' - num of moves: ' + str(len(result1[1]['solution']['moves'])) + ' more than grade 36 - ' + str(moreThan36Grade) + \ ' best global solution - ' + str(bestSolutionGradeGlobal) i = 0 if not printOnce and bestSolutionGrade >= 36: moreThan36Grade += 1 # printOnce = True printCube(result1[1]['solution']['currentCube']) print 'done' if __name__ == "__main__": main()<file_sep>__author__ = 'tal' import copy NUM_OF_CUBE = 3 cube = { 'up': [ [0,0,0], [0,0,0], [0,0,0] ], # Up 'down': [ [1,1,1], [1,1,1], [1,1,1] ], # Down 'left': [ [2,2,2], [2,2,2], [2,2,2] ], # Left 'right': [ [3,3,3], [3,3,3], [3,3,3] ], # Right 'front': [ [4,4,4], [4,4,4], [4,4,4] ], # Front 'back': [ [5,5,5], [5,5,5], [5,5,5] ] # Back } def createCube(): return copy.deepcopy(cube) def rotateLeft(side): oldside = copy.deepcopy(side) side[0][0] = oldside[0][2] side[0][1] = oldside[1][2] side[0][2] = oldside[2][2] side[1][2] = oldside[2][1] side[2][2] = oldside[2][0] side[2][1] = oldside[1][0] side[2][0] = oldside[0][0] side[1][0] = oldside[0][1] def rotateRight(side): oldside = copy.deepcopy(side) side[0][0] = oldside[2][0] side[0][1] = oldside[1][0] side[0][2] = oldside[0][0] side[1][2] = oldside[0][1] side[2][2] = oldside[0][2] side[2][1] = oldside[1][2] side[2][0] = oldside[2][2] side[1][0] = oldside[2][1] def convertRow(side1, side2, level): side1[level] = side2[level] def convertColumn(side1, side2, level): for i in range(NUM_OF_CUBE): side1[i][level] = side2[i][level] def F2R(cube, level): tempCube = copy.deepcopy(cube) convertRow(cube['front'], tempCube['left'], level) convertRow(cube['left'], tempCube['back'], level) convertRow(cube['back'], tempCube['right'], level) convertRow(cube['right'], tempCube['front'], level) if level == 0: rotateLeft(cube['up']) if level == 2: rotateRight(cube['down']) def R2F(cube, level): tempCube = copy.deepcopy(cube) convertRow(cube['front'], tempCube['right'], level) convertRow(cube['right'], tempCube['back'], level) convertRow(cube['back'], tempCube['left'], level) convertRow(cube['left'], tempCube['front'], level) if level == 0: rotateRight(cube['up']) if level == 2: rotateLeft(cube['down']) def F2U(cube, level): tempCube = copy.deepcopy(cube) convertColumn(cube['front'], tempCube['down'], level) convertColumn(cube['down'], tempCube['back'], level) convertColumn(cube['back'], tempCube['up'], level) convertColumn(cube['up'], tempCube['front'], level) if level == 0: rotateRight(cube['right']) if level == 2: rotateLeft(cube['left']) def U2F(cube, level): tempCube = copy.deepcopy(cube) convertColumn(cube['front'], tempCube['up'], level) convertColumn(cube['up'], tempCube['back'], level) convertColumn(cube['back'], tempCube['down'], level) convertColumn(cube['down'], tempCube['front'], level) if level == 0: rotateLeft(cube['right']) if level == 2: rotateRight(cube['left']) def R2U(cube, level): tempCube = copy.deepcopy(cube) # right to up for i in range(NUM_OF_CUBE): cube['up'][NUM_OF_CUBE - 1 - level][i] = tempCube['right'][i][level] # down to right for i in range(NUM_OF_CUBE): cube['right'][i][level] = tempCube['down'][level][NUM_OF_CUBE - 1 - i] # left to down for i in range(NUM_OF_CUBE): cube['down'][level][NUM_OF_CUBE - 1 - i] = tempCube['left'][NUM_OF_CUBE - 1 - i][NUM_OF_CUBE - 1 - level] # up to left for i in range(NUM_OF_CUBE): cube['left'][NUM_OF_CUBE - 1 - i][NUM_OF_CUBE - 1 - level] = tempCube['up'][NUM_OF_CUBE - 1 - level][i] if level == 0: rotateLeft(cube['front']) if level == 2: rotateRight(cube['back']) def U2R(cube, level): tempCube = copy.deepcopy(cube) # left to up for i in range(NUM_OF_CUBE): cube['up'][NUM_OF_CUBE - 1 - level][i] = tempCube['left'][NUM_OF_CUBE - 1 - i][NUM_OF_CUBE - 1 - level] # down to left for i in range(NUM_OF_CUBE): cube['left'][NUM_OF_CUBE - 1 - i][NUM_OF_CUBE - 1 - level] = tempCube['down'][level][NUM_OF_CUBE - 1 - i] # right to down for i in range(NUM_OF_CUBE): cube['down'][level][NUM_OF_CUBE - 1 - i] = tempCube['right'][i][level] # up to right for i in range(NUM_OF_CUBE): cube['right'][i][level] = tempCube['up'][NUM_OF_CUBE - 1 - level][i] if level == 0: rotateLeft(cube['back']) if level == 2: rotateRight(cube['front']) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' colors = [ bcolors.OKBLUE, bcolors.OKGREEN, bcolors.FAIL, bcolors.WARNING, bcolors.HEADER, bcolors.BOLD ] def printLittleCube(cubeColor): sys.stdout.write(colors[cubeColor] + unichr(0x2588) + bcolors.ENDC + ' ') import sys def printSide(side): for i in range(NUM_OF_CUBE): for j in range(NUM_OF_CUBE): printLittleCube(side[i][j]) print def printCube(cube): orderOfPrint = ['front', 'right', 'up', 'left', 'back', 'down'] for i in orderOfPrint: print i printSide(cube[i]) def main(): # R2F(cube, 0) # F2R(cube, 1) # R2U(cube, 2) U2R(cube, 2) printCube(cube) if __name__ == "__main__": main()
4bf16c2d573454743624ba00281874f9fd94a8b0
[ "Python" ]
4
Python
ttaallll/MyRubikCube
21f49faba0f5b8943fce919cc7c7d98871e3be55
28bd47fabb2e6cfeba49152f4f16528eee76b96c
refs/heads/master
<repo_name>KonradJanica/react-datetime-pickers<file_sep>/example/src/App.js import React from 'react' import DateTimePicker from 'react-datetime-pickers' import 'react-datetime-pickers/dist/index.css' import './App.scss' const App = () => { const [selected, setSelected] = React.useState(new Date()); const [selector, setSelector] = React.useState("day"); const [showTimePicker, setShowTimePicker] = React.useState(true); const [logs, setLogs] = React.useState([]); const handleDateChange = React.useCallback((date) => { console.debug('DatePicker', 'onChange', date); setSelected(date); setLogs((logs) => [`Date changed: ${date.toLocaleString()}`, ...logs]) }, []); const handleSelectorChange = React.useCallback((e) => { setSelector(e.target.value); }, []); const handleShowTimePickerChange = React.useCallback((e) => { setShowTimePicker(!!e.target.checked); }, []); const minDate = new Date(2018, 2, 20); const maxDate = new Date(2021, 5, 15); return ( <> <div> <label>Selector</label> <select onChange={handleSelectorChange} value={selector}> <option value={"day"}>Day</option> <option value={"week"}>Week</option> <option value={"month"}>Month</option> </select> </div> <div> <label>Show time picker</label> <input type={"checkbox"} checked={showTimePicker} onChange={handleShowTimePickerChange} /> </div> <div> <DateTimePicker selected={selected} selector={selector} timePicker={showTimePicker} onChange={handleDateChange} maxDate={maxDate} minDate={minDate} /> </div> <pre style={{display: 'none'}}> {logs.join("\n")} </pre> </> ); } export default App <file_sep>/README.md # react-datetime-pickers > React ready picker components for dates and time (month picker, week picker, day picker) [![NPM](https://img.shields.io/npm/v/react-datetime-pickers.svg)](https://www.npmjs.com/package/react-datetime-pickers) [![Downloads](https://img.shields.io/npm/dm/react-datetime-pickers.svg)](https://www.npmjs.com/package/react-datetime-pickers) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) <img alt="calendar" src="https://raw.githubusercontent.com/mauriziocarella/react-datetime-pickers/master/example/public/images/calendar.png" width="300"> <img alt="time" src="https://raw.githubusercontent.com/mauriziocarella/react-datetime-pickers/master/example/public/images/time.png" width="300"> ## Install ```bash npm install --save react-datetime-pickers ``` or ```bash yarn install react-datetime-pickers ``` ## Usage ```jsx import React, {useState} from 'react'; import DateTimePicker from 'react-datetime-pickers'; import 'react-datetime-pickers/dist/index.css'; export default function Example() { const [date, setDate] = useState(new Date()); return ( <DateTimePicker selected={date} onChange={setDate} /> ); } ``` ## License MIT © [mauriziocarella](https://github.com/mauriziocarella) <file_sep>/src/index.js import React from 'react' import classNames from 'classnames' import { IconArrowDown, IconArrowLeft, IconArrowRight, IconArrowUp, IconCalendar, IconClock } from './icons' import PropTypes from 'prop-types' import './index.scss' const useDidMountEffect = function(fn, inputs) { const didMountRef = React.useRef(false); React.useEffect(() => { if (didMountRef.current) fn(); else didMountRef.current = true; }, inputs); }; const Helper = function(firstDayOfWeek) { let months = [ { month: 0, name: 'January' }, { month: 1, name: 'February' }, { month: 2, name: 'March' }, { month: 3, name: 'April' }, { month: 4, name: 'May' }, { month: 5, name: 'June' }, { month: 6, name: 'July' }, { month: 7, name: 'August' }, { month: 8, name: 'September' }, { month: 9, name: 'October' }, { month: 10, name: 'November' }, { month: 11, name: 'December' } ]; let dows = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']; dows = dows.concat(dows.splice(0, firstDayOfWeek)); return { months, dows, isSameDayAs(a, b) { return ( a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate() ) }, isSameMonthAs(a, b) { return ( a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() ) }, isSameYearAs(a, b) { return ( a.getFullYear() === b.getFullYear() ) }, isSameTimeAs(a, b) { return ( a.getHours() === b.getHours() && a.getMinutes() === b.getMinutes() && a.getSeconds() === b.getSeconds() && a.getMilliseconds() === b.getMilliseconds() ) }, dayStart(date) { let ret = new Date(date) ret.setHours(0, 0, 0, 0) return ret }, dayEnd(date) { let ret = new Date(date) ret.setHours(23, 59, 59, 999) return ret }, weekStart(date) { let ret = new Date(date) ret.setDate(date.getDate() - date.getDay() + firstDayOfWeek) return ret }, weekEnd(date) { let ret = this.weekStart(date) ret.setDate(ret.getDate() + 6) ret.setHours(23, 59, 59, 999) return ret }, monthStart(date) { let ret = new Date(date) ret.setDate(1) return ret }, monthEnd(date) { return new Date(date.getFullYear(), date.getMonth() + 1, 0) }, yearStart(date) { return new Date(date.getFullYear(), 0, 1) }, yearEnd(date) { return new Date(date.getFullYear(), 11, 31) }, getMonthWeeks(year, month) { let lastDayOfMonth = (new Date(year, month + 1, 0)) let weeks = [] let date = new Date(year, month, 1) let week do { week = { start: this.weekStart(date), end: this.weekEnd(date), days: [] } for (let d = new Date(week.start); d.getTime() <= week.end.getTime(); d.setDate(d.getDate() + 1)) { let day = new Date(d) week.days.push({ date: day, disabled: day.getMonth() !== month }) } date = new Date(week.end) date.setDate(date.getDate() + 1) weeks.push(week) } while (week.end.getTime() <= lastDayOfMonth.getTime() || weeks.length < 6) return weeks; } } }; const TimePicker = ({selected, onChange, helper}) => { const times = React.useMemo(() => { let start = (new Date(selected)).setHours(0,0,0,0); let end = (new Date(selected)).setHours(23,59,59,999); let times = []; for (let m = start; m < end; m += (600*1000)) { times.push({ date: new Date(m), }); } return times; }, []); const handleClick = React.useCallback(({date}) => () => { selected.setHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); onChange(selected); }, [selected]); const isSelectedTime = ({date}) => { if (selected) { return helper.isSameTimeAs(date, selected) } return false } return ( <div className="react-datetime-pickers-times"> {times.map((time, index) => ( <button key={`time-${index}`} type="button" className={classNames("react-datetime-pickers-time", { disabled: time.disabled, selected: isSelectedTime(time), })} onClick={handleClick(time)} > {`${time.date.getHours()}`.padStart(2, '0')}:{`${time.date.getMinutes()}`.padStart(2, '0')} </button> ))} </div> ) } const TimePickerScroller = ({selected, onChange}) => { const timeout = React.useRef(null); const interval = React.useRef(null); const setHour = (h) => { if (h >= 24) h = 0 else if (h < 0) h = 23 selected.setHours(h) onChange(selected) } const addHour = (offset) => setHour(selected.getHours() + offset); const handleHourChange = (e) => { setHour(e.target.value) } const setMinute = (m) => { if (m >= 60) m = 0 else if (m < 0) m = 59 selected.setMinutes(m) onChange(selected) } const addMinute = (offset) => setMinute(selected.getMinutes() + offset); const handleMinuteChange = (e) => { setMinute(e.target.value) } const clearTimers = () => { clearTimeout(timeout.current); clearInterval(interval.current) } const startAddHour = (offset) => { clearTimers() timeout.current = setTimeout(() => { interval.current = setInterval(() => { addHour(offset) }, 100) }, 100) } const startAddMinute = (offset) => { clearTimers() timeout.current = setTimeout(() => { interval.current = setInterval(() => { addMinute(offset) }, 100) }, 100) } React.useEffect(() => { const onMouseUp = () => clearTimers(); document.addEventListener('mouseup', onMouseUp, {capture: true}) return () => { document.removeEventListener('mouseup', onMouseUp, {capture: true}) } }, []) return ( <div className={classNames("react-datetime-pickers-time")}> <div className={classNames("react-datetime-pickers-time-hour")}> <button type="button" className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={() => addHour(1)} onMouseDown={() => startAddHour(1)} > <IconArrowUp/> </button> <input type="number" value={`${selected.getHours()}`.padStart(2, '0')} onChange={handleHourChange} /> <button type="button" className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={() => addHour(-1)} onMouseDown={() => startAddHour(-1)} > <IconArrowDown/> </button> </div> <div className={classNames("react-datetime-pickers-time-minute")}> <button type="button" className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={() => addMinute(1)} onMouseDown={() => startAddMinute(1)} > <IconArrowUp/> </button> <input type="number" value={`${selected.getMinutes()}`.padStart(2, '0')} onChange={handleMinuteChange} /> <button type="button" className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={() => addMinute(-1)} onMouseDown={() => startAddMinute(-1)} > <IconArrowDown/> </button> </div> </div> ) }; const TimeToggle = (props) => { const {timePicker, timeOpen, toggleTime} = props; if (!timePicker) return null return ( <button type="button" className={classNames("react-datetime-pickers-button react-datetime-pickers-time-toggle react-datetime-pickers-button-outline")} onClick={toggleTime} > {timeOpen ? <IconCalendar/> : <IconClock/>} </button> ) }; const Calendar = (props) => { const {view, setView, timeOpen, toggleTime, selector, selected, setDate, minDate, maxDate, firstDayOfWeek} = props; const [year, setYear] = React.useState(selected.getFullYear()); const [month, setMonth] = React.useState(selected.getMonth()); const helper = React.useMemo(() => Helper(firstDayOfWeek), [firstDayOfWeek]); const handleChange = (offset) => { switch (view) { case 'week': case 'day': { let _month = month let _year = year _month += offset if (_month === -1) { _month = 11 _year -= 1 } else if (_month === 12) { _month = 0 _year += 1 } setMonth(_month) setYear(_year) break } case 'month': { let _year = year _year += offset setYear(_year) break } case 'year': { let _year = year _year += offset * 15 setYear(_year) break } } }; const handleNext = () => handleChange(1); const handlePrevious = () => handleChange(-1); switch (timeOpen ? 'time' : view) { case 'time': { return ( <React.Fragment> <div className={classNames("react-datetime-pickers-body")}> <TimePicker selected={selected} onChange={setDate} helper={helper} /> </div> <div className={classNames("react-datetime-pickers-footer")}> <TimeToggle timeOpen={timeOpen} toggleTime={toggleTime} {...props} /> </div> </React.Fragment> ) } case 'week': case 'day': { if (selector !== 'day' && selector !== 'week') return null const weeks = helper.getMonthWeeks(year, month).map((week) => { week.days.map((day) => { if (minDate && day.date < helper.dayStart(minDate)) { day.disabled = true } if (maxDate && day.date > helper.dayEnd(maxDate)) { day.disabled = true } return day }); return week }); const isSelectedDay = ({date}) => { if (selected) { return helper.isSameDayAs(date, selected) } return false } const isTodayDay = ({date}) => { const today = new Date() return helper.isSameDayAs(date, today) }; const onDayClick = ({date}) => { let _selected = selected _selected.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()) switch (selector) { case 'week': { _selected = helper.weekStart(_selected) break } } setDate(_selected) }; return ( <React.Fragment> <div className={classNames("react-datetime-pickers-head")}> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handlePrevious}> <IconArrowLeft/> </div> <div className={classNames("react-datetime-pickers-selector")} onClick={() => setView('month')}> {month + 1}/{year} </div> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handleNext}> <IconArrowRight/> </div> </div> <div className={classNames("react-datetime-pickers-body")}> <div className={classNames("react-datetime-pickers-week-days")}> {helper.dows.map((d, i) => <div key={i} className={classNames("react-datetime-pickers-week-day")}>{d}</div>)} </div> <div className={classNames("react-datetime-pickers-days")}> {weeks.map((week, index) => ( <div key={index} className={classNames("react-datetime-pickers-week", { selected: selector === 'week' && isSelectedDay(week.days[0]) })}> {week.days.map((day, index) => ( <button type="button" className={classNames("react-datetime-pickers-day", { disabled: day.disabled, selected: isSelectedDay(day), today: isTodayDay(day) })} key={index} onClick={() => onDayClick(day)} disabled={day.disabled} > {day.date.getDate()} </button> ))} </div> ))} </div> </div> <div className={classNames("react-datetime-pickers-footer")}> <TimeToggle timeOpen={timeOpen} toggleTime={toggleTime} {...props} /> </div> </React.Fragment> ) } case 'month': { const months = helper.months.map((month, index) => { month.date = new Date(year, month.month, 1); if (minDate && helper.monthEnd(month.date) < minDate) { month.disabled = true } if (maxDate && month.date > maxDate) { month.disabled = true } return month; }) const isSelectedMonth = ({date}) => { if (selected) { return helper.isSameMonthAs(date, selected) } return false } const isTodayMonth = ({date}) => { const today = new Date() return helper.isSameMonthAs(date, today) }; const onMonthClick = ({month}) => { setMonth(month) if (selector === 'month') { let _selected = selected _selected.setMonth(month, 1) setDate(_selected) } else { setView('day') } }; return ( <React.Fragment> <div className={classNames("react-datetime-pickers-head")}> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handlePrevious}> <IconArrowLeft/> </div> <div className={classNames("react-datetime-pickers-selector")} onClick={() => setView('year')}> {year} </div> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handleNext}> <IconArrowRight/> </div> </div> <div className={classNames("react-datetime-pickers-body")}> <div className={classNames("react-datetime-pickers-months")}> {months.map((month, index) => ( <button type="button" className={classNames("react-datetime-pickers-month", { disabled: month.disabled, selected: isSelectedMonth(month), today: isTodayMonth(month) })} key={index} onClick={() => onMonthClick(month)} disabled={month.disabled} > {month.name} </button> ))} </div> </div> <div className={classNames("react-datetime-pickers-footer")}> <TimeToggle timeOpen={timeOpen} toggleTime={toggleTime} {...props} /> </div> </React.Fragment> ) } case 'year': { const years = [] for (let i = year - 7; i <= year + 7; i++) { const year = { year: i, date: new Date(i, 0, 1) }; if (minDate && helper.yearEnd(year.date) < minDate) { year.disabled = true } if (maxDate && year.date > maxDate) { year.disabled = true } years.push(year) } const isSelectedYear = ({date}) => { if (selected) { return helper.isSameYearAs(date, selected) } return false } const isTodayYear = ({date}) => { const today = new Date() return helper.isSameYearAs(date, today) }; const onYearClick = ({year}) => { setYear(year) //TODO Check if is year picker // let selected = this.state.selected; // selected.setFullYear(year); // this.setState({selected: new Date(selected)}) setView('month') }; return ( <React.Fragment> <div className={classNames("react-datetime-pickers-head")}> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handlePrevious}> <IconArrowLeft/> </div> <div className={classNames("react-datetime-pickers-selector")} onClick={() => setView('year')}> {year} </div> <div className={classNames("react-datetime-pickers-button react-datetime-pickers-button-outline react-datetime-pickers-button-icon")} onClick={handleNext}> <IconArrowRight/> </div> </div> <div className={classNames("react-datetime-pickers-body")}> <div className={classNames("react-datetime-pickers-years")}> {years.map((year, index) => ( <button type="button" className={classNames("react-datetime-pickers-year", { disabled: year.disabled, selected: isSelectedYear(year), today: isTodayYear(year) })} key={index} onClick={() => onYearClick(year)} disabled={year.disabled} > {year.year} </button> ))} </div> </div> <div className={classNames("react-datetime-pickers-footer")}> <TimeToggle timeOpen={timeOpen} toggleTime={toggleTime} {...props} /> </div> </React.Fragment> ) } } return null } const Container = (props) => { const {selector, minDate, maxDate} = props; const [open, setOpen] = React.useState(false); const [view, setView] = React.useState(selector); const [timeOpen, setTimeOpen] = React.useState(false); const [selected, setSelected] = React.useState(props.selected || new Date()); const container = React.useRef(null); const overlay = React.useRef(null); const input = React.useRef(null); const toggleOpen = React.useCallback(() => setOpen((open) => !open), []); const toggleTime = React.useCallback(() => setTimeOpen((open) => !open), []); const setDate = React.useCallback((date) => { let d = new Date(date); if (d < minDate) d = minDate; if (d > maxDate) d = maxDate; setSelected(d); }, [minDate, maxDate]); const Input = React.useCallback(({onClick}) => { if (React.isValidElement(props.children)) { return React.cloneElement(props.children, { ...props.children.props, ref: input, className: classNames(props.children.props.className, "react-datetime-pickers-input"), onClick, }) } return ( <input ref={input} type="text" className="react-datetime-pickers-input" onClick={onClick} /> ); }, []); useDidMountEffect(() => { if (typeof props.onChange === "function") { props.onChange(selected) } if (props.closeOnSelect) { setOpen(false); } }, [selected, props.closeOnSelect]) useDidMountEffect(() => { if (!open) { setTimeOpen(false); } }, [open]); React.useEffect(() => { if (input.current) { const formatter = (date) => { if (typeof props.formatter === 'function') return props.formatter(date) let value = date.toLocaleDateString() if (props.timePicker) value = date.toLocaleString() return value } input.current.value = formatter(selected) } }, [selected, view, selector, timeOpen]) React.useEffect(() => { const onClick = (e) => { if (!container.current.contains(e.target)) { setOpen(false) } } document.addEventListener('click', onClick, {capture: true}) return () => { document.removeEventListener('click', onClick, {capture: true}) } }, []); React.useEffect(() => setView(selector), [selector]); return ( <div ref={container} className={classNames("react-datetime-pickers", `react-datetime-pickers-selector-${selector}`)} > <Input onClick={toggleOpen}/> <div ref={overlay} className={classNames("react-datetime-pickers-overlay", `react-datetime-pickers-mode-${view}`)} hidden={!open} > <Calendar {...props} open={open} view={view} setView={setView} selected={selected} setDate={setDate} timeOpen={timeOpen} toggleTime={toggleTime} /> </div> </div> ) } Container.defaultProps = { selected: new Date(), selector: 'month', firstDayOfWeek: 1, timePicker: false, closeOnSelect: true, }; Container.propTypes = { formatter: PropTypes.func, onChange: PropTypes.func, } export default Container
ace966ac3627891443cdbf34fb444406083473fd
[ "JavaScript", "Markdown" ]
3
JavaScript
KonradJanica/react-datetime-pickers
581166080526394b4ce4938cbb601eba843ce085
d4525a6dbabcd71fb6d674a1daa15cc8384ab9a6
HEAD
<file_sep>// // Constants.swift // StoreApp // // Created by yuaming on 12/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation enum FileTypes { case json var name: String { switch self { case .json: return "json" } } } struct Constants { static let storeList = "storeList" static let list = "list" static let detailTitle = "detailTitle" static let detailData = "detailData" static let thumbnail = "thumbnail" static let detailSection = "detailSection" static let imageIndex = "imageIndex" static let image = "image" static let text = "text" static let isConnected = "isConnected" } <file_sep>target 'StoreApp' do use_frameworks! pod 'SwiftLint' pod 'Toaster' pod 'Alamofire' target 'StoreAppTests' do inherit! :search_paths end end <file_sep>// // NetworkManager.swift // StoreApp // // Created by yuaming on 20/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation import Alamofire class NetworkManager { static let shared = NetworkManager() fileprivate let host = Host.base.path fileprivate var reachabilityManager: NetworkReachabilityManager fileprivate init() { if let reachabilityManager = NetworkReachabilityManager(host: host) { self.reachabilityManager = reachabilityManager } else { self.reachabilityManager = NetworkReachabilityManager(host: Host.apple.path)! } } var isConnected: Bool { return reachabilityManager.isReachable } func startObserver() { NotificationCenter.default.post(name: .isConnected, object: nil, userInfo: [Constants.isConnected: isConnected]) reachabilityManager.startListening() } func stopObserver() { reachabilityManager.stopListening() } deinit { NotificationCenter.default.removeObserver(self) } } extension Notification.Name { static let isConnected = Notification.Name(Constants.isConnected) } <file_sep>// // FoodType.swift // StoreApp // // Created by yuaming on 13/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation enum FoodType: String { case main, soup, side static var allValues: [FoodType] { return [.main, .soup, .side] } var name: String { return self.rawValue } var title: String { switch self { case .main: return "메인반찬" case .soup: return "국.찌게" case .side: return "밑반찬" } } var subtitle: String { switch self { case .main: return "한그릇 뚝딱 메인 요리" case .soup: return "김이 모락모락 국.찌게" case .side: return "언제 먹어도 든든한 밑반찬" } } } <file_sep>// // ViewController.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit import Toaster class ViewController: UIViewController { @IBOutlet weak var storeItemTableView: UITableView! { didSet { self.storeItemTableView.delegate = self self.storeItemTableView.dataSource = self } } fileprivate let cellIdentifier = "StoreItemCell" fileprivate let sectionHeaderIdentifier = "StoreSectionHeader" fileprivate let detailViewControllerIdentifier = "DetailViewController" fileprivate let rowHeight = CGFloat(100) fileprivate let headerHeight = CGFloat(80) fileprivate var storeDataManager: StoreDataManager? { didSet { DispatchQueue.main.async { self.storeItemTableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() setup() registerTableViewStyle() configueToastView() } fileprivate func setup() { NotificationCenter.default.addObserver(self, selector: #selector(refreshTableView(notification:)), name: Notification.Name.storeList, object: nil) self.storeDataManager = StoreDataManager() self.storeDataManager?.generateData() } fileprivate func registerTableViewStyle() { storeItemTableView.register(StoreSectionHeader.self, forHeaderFooterViewReuseIdentifier: sectionHeaderIdentifier) storeItemTableView.register(StoreItemCell.self, forCellReuseIdentifier: cellIdentifier) } fileprivate func configueToastView() { let appearance = ToastView.appearance() appearance.backgroundColor = .mint appearance.textColor = .white appearance.font = UIFont.boldSystemFont(ofSize: 15) appearance.textInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10) appearance.bottomOffsetPortrait = 350 appearance.cornerRadius = 10 } @objc fileprivate func refreshTableView(notification: Notification) { guard let userInfo = notification.userInfo, let list = userInfo[Constants.list] as? [StoreItems] else { return } self.storeDataManager = StoreDataManager(list: list) } deinit { NotificationCenter.default.removeObserver(self) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let storeManager = self.storeDataManager else { return 0 } return storeManager.numberOfCells(section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? StoreItemCell else { return UITableViewCell() } guard let storeManager = storeDataManager else { return UITableViewCell() } let item = storeManager[at: indexPath.section][at: indexPath.row] cell.setItem(item) return cell } func numberOfSections(in tableView: UITableView) -> Int { guard let storeManager = self.storeDataManager else { return 0 } return storeManager.numberOfSections } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return rowHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: sectionHeaderIdentifier) as? StoreSectionHeader else { return UIView() } guard let storeManager = storeDataManager else { return UIView() } header.setContent(title: storeManager[at: section].title, subtitle: storeManager[at: section].subtitle) return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return headerHeight } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let storeManager = self.storeDataManager else { return } let item = storeManager[at: indexPath.section][at: indexPath.row] if let detailViewController = self.storyboard?.instantiateViewController(withIdentifier: detailViewControllerIdentifier) as? DetailViewController { detailViewController.itemDetail = StoreDetailItem(item.title, item.detailHash) detailViewController.orderDelegate = self self.navigationController?.pushViewController(detailViewController, animated: true) } } } extension ViewController: OrderDelegate { func showResult(_ orderInfo: OrderInfo) { Toast(text: orderInfo.description).show() } } <file_sep>// // StoreDataManager.swift // StoreApp // // Created by yuaming on 12/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation class StoreDataManager { private var list: [StoreItems] = [] { didSet { NotificationCenter.default.post(name: .storeList, object: nil, userInfo: [Constants.list: list]) } } convenience init() { self.init(list: []) } init(list: [StoreItems]) { self.list = list } func generateData() { if NetworkManager.shared.isConnected { requestData() } else { generateFileData() } } var numberOfSections: Int { return list.count } func numberOfCells(_ section: Int) -> Int { return list[section].count } subscript(at section: Int) -> StoreItems { return list[section] } deinit { NotificationCenter.default.removeObserver(self) } } fileprivate extension StoreDataManager { func generateFileData() { FoodType.allValues.forEach { foodType in let data = FileLoader.data(fileName: foodType.name, fileType: FileTypes.json) load(data, header: foodType) } } func requestData() { for foodType in FoodType.allValues { let url = API.shared.makeUrlInList(id: foodType.name) API.shared.sendRequest(withUrl: url) { resultType in switch resultType { case .success(let data): self.load(data, header: foodType) case .error(let error): print(error.localizedDescription) } } } } func load(_ data: Data?, header: FoodType) { if let data = data { let decodedData = JSONConverter.decode(in: data, type: [StoreItem].self) list.append(StoreItems(header: header, items: decodedData)) } } } extension Notification.Name { static let storeList = Notification.Name(Constants.storeList) } <file_sep>// // StoreItem.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct StoreItem: Decodable { let title: String let description: String let normalPrice: String? let salePrice: String let deliveryTypes: [String]? let detailHash: String let imageUrl: String let alt: String let badges: [String]? let thumbnail: Thumbnail enum CodingKeys: String, CodingKey { case title case description case normalPrice = "n_price" case salePrice = "s_price" case deliveryTypes = "delivery_type" case detailHash = "detail_hash" case imageUrl = "image" case alt case badges = "badge" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.title = try values.decode(String.self, forKey: .title) self.description = try values.decode(String.self, forKey: .description) self.normalPrice = try? values.decode(String.self, forKey: .normalPrice) self.salePrice = try values.decode(String.self, forKey: .salePrice) self.deliveryTypes = try? values.decode([String].self, forKey: .deliveryTypes) self.detailHash = try values.decode(String.self, forKey: .detailHash) self.imageUrl = try values.decode(String.self, forKey: .imageUrl) self.alt = try values.decode(String.self, forKey: .alt) self.badges = try? values.decode([String].self, forKey: .badges) self.thumbnail = Thumbnail(imageUrl) } } <file_sep>// // StoreItemCell.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit class StoreItemCell: UITableViewCell { fileprivate lazy var thumbnailImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 50 imageView.backgroundColor = .lightGray return imageView }() fileprivate lazy var itemTitleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .systemFont(ofSize: 15, weight: .bold) label.textColor = .black return label }() fileprivate lazy var itemDescriptionLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .systemFont(ofSize: 12, weight: .regular) label.textColor = .lightGray return label }() fileprivate lazy var pricesStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .fill stackView.spacing = 10 return stackView }() fileprivate lazy var normalPriceLabel: UILabel = { let label = UILabel() label.textColor = .lightGray label.font = .systemFont(ofSize: 12, weight: .regular) return label }() fileprivate lazy var salePriceLabel: UILabel = { let label = UILabel() label.textColor = .mint label.font = .systemFont(ofSize: 14, weight: .bold) return label }() fileprivate let badgeLabelInsets = UIEdgeInsets(top: 2, left: 3, bottom: 2, right: 3) fileprivate lazy var badgeLabel: UILabelWithPadding = { let label = UILabelWithPadding(frame: self.frame) label.textColor = .white label.font = .systemFont(ofSize: 10, weight: .regular) label.backgroundColor = .lightPink return label }() fileprivate lazy var badgesStackView: UIStackView = { let stackView = UIStackView() stackView.distribution = .fill stackView.spacing = 2 stackView.translatesAutoresizingMaskIntoConstraints = false return stackView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initializeLayout() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: true) } override func prepareForReuse() { super.prepareForReuse() thumbnailImageView.image = nil itemTitleLabel.text = nil itemDescriptionLabel.text = nil normalPriceLabel.text = nil salePriceLabel.text = nil pricesStackView.removeArrangedSubview(normalPriceLabel) pricesStackView.removeArrangedSubview(salePriceLabel) for case let badgeLabel as UILabelWithPadding in badgesStackView.arrangedSubviews { badgeLabel.text = nil badgeLabel.removeInsets() badgesStackView.removeArrangedSubview(badgeLabel) } } func setItem(_ data: StoreItem) { setThumbnail(data.thumbnail.image) itemTitleLabel.text = data.title itemDescriptionLabel.text = data.description if let normalPrice = data.normalPrice { normalPriceLabel.text = normalPrice normalPriceLabel.attributedText = normalPrice.throughStrike pricesStackView.addArrangedSubview(normalPriceLabel) } salePriceLabel.text = data.salePrice pricesStackView.addArrangedSubview(salePriceLabel) if let badges = data.badges { badges.forEach { badgeLabel.text = $0 badgeLabel.addInsets(badgeLabelInsets) badgesStackView.addArrangedSubview(badgeLabel) } } } fileprivate func setThumbnail(_ image: UIImage?) { DispatchQueue.main.async { self.thumbnailImageView.image = image } } fileprivate func initializeLayout() { addSubview(thumbnailImageView) addSubview(itemTitleLabel) addSubview(itemDescriptionLabel) addSubview(pricesStackView) addSubview(badgesStackView) updateCostraintsOfTitleLabel(isActive: true) updateConstraintsOfDescriptionLabel(isActive: true) updateConstraintsOfBadgesStackView(isActive: true) updateConstraintsOfThumbnailImageView(isActive: true) updateConstraintsOfPricesStackView(isActive: true) } } // MARK: - Updating constraints fileprivate extension StoreItemCell { func updateConstraintsOfThumbnailImageView(isActive: Bool) { thumbnailImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = isActive thumbnailImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5).isActive = isActive thumbnailImageView.widthAnchor.constraint(equalToConstant: 90).isActive = isActive thumbnailImageView.heightAnchor.constraint(equalTo: thumbnailImageView.widthAnchor).isActive = isActive } func updateCostraintsOfTitleLabel(isActive: Bool) { itemTitleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 4).isActive = isActive itemTitleLabel.leadingAnchor.constraint(equalTo: thumbnailImageView.trailingAnchor, constant: 10).isActive = isActive itemTitleLabel.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor, constant: 5).isActive = isActive } func updateConstraintsOfDescriptionLabel(isActive: Bool) { itemDescriptionLabel.topAnchor.constraint(equalTo: itemTitleLabel.bottomAnchor, constant: 4).isActive = isActive itemDescriptionLabel.leadingAnchor.constraint(equalTo: itemTitleLabel.leadingAnchor).isActive = isActive itemDescriptionLabel.trailingAnchor.constraint(equalTo: itemTitleLabel.trailingAnchor).isActive = isActive } func updateConstraintsOfPricesStackView(isActive: Bool) { pricesStackView.topAnchor.constraint(equalTo: itemDescriptionLabel.bottomAnchor, constant: 4).isActive = isActive pricesStackView.leadingAnchor.constraint(equalTo: itemTitleLabel.leadingAnchor).isActive = isActive pricesStackView.trailingAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.trailingAnchor, constant: 20).isActive = isActive } func updateConstraintsOfBadgesStackView(isActive: Bool) { badgesStackView.topAnchor.constraint(equalTo: pricesStackView.bottomAnchor, constant: 4).isActive = isActive badgesStackView.leadingAnchor.constraint(equalTo: itemTitleLabel.leadingAnchor).isActive = isActive badgesStackView.trailingAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.trailingAnchor, constant: 20).isActive = isActive } } <file_sep>// // StoreItems.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation class StoreItems { fileprivate let header: FoodType fileprivate let items: [StoreItem] init(header: FoodType, items: [StoreItem]) { self.header = header self.items = items } subscript(at index: Int) -> StoreItem { return items[index] } var title: String { return header.title } var subtitle: String { return header.subtitle } var count: Int { return items.count } } <file_sep>// // DetailSectionImage.swift // StoreApp // // Created by yuaming on 18/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation import UIKit class DetailSectionImage { var index: Int? var image: UIImage? { didSet { if index != nil { NotificationCenter.default.post(name: .detailSection, object: nil, userInfo: [Constants.imageIndex: index, Constants.image: image]) } } } init(_ imageUrl: String?, index: Int? = nil) { self.index = index loadImageData(imageUrl) } } extension DetailSectionImage: ImageLoaderable { } extension Notification.Name { static let detailSection = Notification.Name(Constants.detailSection) } <file_sep>// // ImageCache.swift // StoreApp // // Created by yuaming on 17/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation class ImageCache { static let shared = ImageCache() fileprivate static let cacheDirectoryUrl: URL = { return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! }() static func fetchData(_ fileName: String) -> Data? { let url = cacheDirectoryUrl.appendingPathComponent(fileName) return FileManager.default.contents(atPath: url.path) } static func store(_ fileName: String, content data: Data) { let url = cacheDirectoryUrl.appendingPathComponent(fileName) do { if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) } FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) } catch { print(error.localizedDescription) } } static func clear() { do { let contents = try FileManager.default.contentsOfDirectory(atPath: cacheDirectoryUrl.path) for fileUrl in contents { try FileManager.default.removeItem(atPath: fileUrl) } } catch { print(error.localizedDescription) } } } <file_sep>// // Thumbnail.swift // StoreApp // // Created by yuaming on 17/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation import UIKit class Thumbnail { var index: Int? var image: UIImage? { didSet { if index != nil { NotificationCenter.default.post(name: .thumbnail, object: nil, userInfo: [Constants.imageIndex: index, Constants.image: image]) } } } init(_ imageUrl: String?, index: Int? = nil) { self.index = index loadImageData(imageUrl) } } extension Thumbnail: ImageLoaderable { } extension Notification.Name { static let thumbnail = Notification.Name(Constants.thumbnail) } <file_sep>= Store === 1. 시작하기, 2. Auto Layout 적용 ===== 실행결과 image:./images/result-2-1.png[45%, 45%] image:./images/result-2-2.png[45%, 45%] image:./images/result-2-3.png[45%, 45%] image:./images/result-2-4.png[45%, 45%] ===== 학습거리 * https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types[JSON Encoding/Decoding] * https://developer.apple.com/sample-code/xcode/downloads/Auto-Layout-Cookbook.zip[Auto Layout Sample Code] * https://github.com/yuaming/TIL/blob/master/ios/auto-layout.adoc[Auto Layouot 정리] * https://github.com/yuaming/TIL/blob/master/ios/high-performance-auto-layout.adoc[High Performance Auto Layout 정리] * https://github.com/yuaming/TIL/blob/master/ios/how-to-adjust-automatic-row-height-in-table-view.adoc[TableView 동적으로 높이 조절하기 정리] === 3. Custom Header 적용 ===== 실행결과 image:./images/result-3-1.png[45%, 45%] === 4. CocoaPods 관리 ===== 실행결과 image:./images/result-4-1.png[45%, 45%] ===== 학습거리 * https://developer.apple.com/library/archive/featuredarticles/XcodeConcepts/Concept-Targets.html#//apple_ref/doc/uid/TP40009328-CH4-SW1[Xcode Concepts] ** 요약 *** Workspace **** 하나 이상 프로젝트가 포함되어 있음 **** 하나 Workspace에서 여러 프로젝트가 존재할 수 있음 *** Project **** App을 구성하는 모든 파일, 리소스, 정보가 포함되어 있음 *** Target **** 프로젝트 빌드 설정 정의함 **** 같은 프로젝트에서 서로 다른 배포판을 관리하기 위해 사용함. 예를 들어 회사 전용, 일반 전용으로 배포판을 나눌 수도 있고 배포 설정을 다르게 해서 사용할 수 있음 **** 하나 프로젝트 안에 Target이 여러 개 있을 수도 있음 *** Scheme **** Build, Test, Profile 등을 수행할 때 어떤 동작을 할지 정의함 **** An Xcode scheme defines a collection of targets to build, a configuration to use when building, and a collection of tests to execute ** *_Workspace 안에 Project A, B가 있고 정해놓은 Scheme에 따라 Target 범위가 설정됨_* === 5. Networking Programming ===== 실행결과 image:./images/result-5-1.png[45%, 45%] ===== 학습거리 * 에러 발생 ** http 통신이 되지 않아 해결책을 찾음 ** `App Transport Security` ** http://blowmj.tistory.com/entry/iOS-iOS9-App-Transport-Security-설정법[App Transport Security 설정법] > App Transport Security(이후 ATS)는 iOS 9.0또는 OS X 10.11 이상 유효하며, 응용프로그램과 웹 서비스간의 안전한 연결을 위해 사용할 수 있음. ATS가 활성화되면 HTTP를 통해 통신을 할 수 없음. 또한 Apple에서 권장하는 요구 사항을 충족하지 않는 연결은 강제로 연결 실패 처리됨. 예를 들어, Apple 권장 요구 사항을 충족하지 않는 Web 페이지를 WKWebView 에서 열려고 하면 페이지로드는 실패함 image:./images/error-5-1.png[45%, 45%] image:./images/error-5-2.png[45%, 45%] * URLSession, Alamofire ** https://developer.apple.com/documentation/foundation/url_loading_system[URL Loading System]: Apple에서 지원하는 네트워크 관련 프레임워크 ** https://github.com/Alamofire/Alamofire[Alamofire]: Apple에서 지원하는 네트워크 관련 프레임워크를 추상화한 Wrapper ** Alamofire를 사용하면 Wrapper 이기 때문에 코드는 깔끔해지지만 라이브러리 의존성이 생기기 때문에 메인테이너가 업데이트 지원하지 않을 때 문제가 발생함 ** Alamofire를 URLSession 원리를 모른 채 사용하면 네트워크 문제가 발생할 때 해결하기 힘듦 * http://kka7.tistory.com/84[읽을거리: iOS 개발자도 잘 모르는 가장 일반적인 실수 10가지] * Alamofire로 개선함 === 6. 병렬처리 ===== 실행결과 image:./images/result-6-1.png[45%, 45%] image:./images/result-6-2.png[45%, 45%] ===== 학습거리 * Alamofire, SDWebImage를 cocoapod으로 설치해서 테이블 뷰 셀에 이미지를 캐싱하고 개선함 * 병렬 처리(Parallel Processing), 동시성(Concurrency) 해결을 위한 다양한 방식에 대해 정리 ** https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008091-CH1-SW1[Concurrency Programming Guide] ** GCD, OperationQueue 차이점 * https://en.wikipedia.org/wiki/Cache_%28computing%29#Web_cache[Caching] ** NSCache *** 메모리 캐시 *** 메모리 캐시 성격상 처리 속도가 빠르고 일반적으로 용량이 적음 ** FileManager 이용 *** 디스크 캐시 *** 저장 공간은 메모리 캐시에 비해 상대적으로 크지만 파일 I/O 속도로 인해 처리 속도가 느림 ** https://erlnote.wordpress.com/2015/06/02/ios-이미지-캐시-구현하기/[iOS 이미지 캐시 구현하기] ** http://mygumi.tistory.com/275[메모리 캐시, 디스크 캐시] ** http://mygumi.tistory.com/282[Data URL, Image File] ** https://stackoverflow.com/questions/38064042/access-files-in-var-mobile-containers-data-application-without-jailbreaking-iph[실제 장비 캐시파일 확인하는 방법] * Bundle, FileManager ** https://developer.apple.com/documentation/foundation/bundle?changes=_2[Bundle] => App 내의 Bundle 접근하고 특정 파일을 찾음. 그리고, Bundle은 어떤 Target에서 Build가 되느냐에 따라 구조가 달라짐 ** https://developer.apple.com/documentation/foundation/filemanager[FileManager] => 전반적인 파일 시스템. 파일을 삭제하고 생성하고 불러거나 이동, 복사 등 작업을 할 수 있음 * DispatchQueue.global 옵션 우선순위 ** https://magi82.github.io/gcd-01/[iOS GCD] === 7. 상품 상세화면 전환 ===== 실행결과 image:./images/result-7-1.png[45%, 45%] image:./images/result-7-2.png[45%, 45%] image:./images/result-7-3.png[45%, 45%] image:./images/result-7-4.gif[45%, 45%] ===== 학습거리 * https://developer.apple.com/documentation/code_diagnostics/main_thread_checker[Main Thread Checker] ** UI 업데이트처럼 Main Thread에서만 실행해야 할 요소나 동작이 있음. 이것이 지켜지는지 안 지켜는지 Main Thread Checker가 검토함. Main Thread가 수행해야 할 UI 요소나 함수가 Background Thread에서 실행될 경우 UI 업데이트가 안되거나, 화면이 깨지거나, 데이터가 오염되거나, 앱이 죽는 경우가 발생함 image:./images/main-thread-checker-1.png[] image:./images/main-thread-checker-2.png[] * UIScrollView ** https://accounts.raywenderlich.com/v2/sso/login?sso=<KEY>bmRlcmxpY2guY29tJTJGc2Vzc2lvbiUyRmNyZWF0ZQ%253D%253D&sig=18cfac022eb70efb37aa4832befd9f760ba4d8a7e410e145fbc15c7f084da4ec[UIScrollView Tutorial: Getting Started] ** https://www.objc.io/issues/3-views/scroll-view/[Understanding Scroll Views] === 8. Reachability ===== 실행결과 image:./images/result-8-1.png[45%, 45%] image:./images/result-8-2.png[45%, 45%] ===== 학습거리 * Reachability ** https://github.com/Alamofire/Alamofire/blob/master/Source/NetworkReachabilityManager.swift[Alamofire - NetworkReachabilityManager] ** https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2[Reachability] * 앱에서 사용자 비용을 줄이기 위해 데이터 캐시를 언제 어떻게 써야할까? * 캐싱을 위해 다루는 기술 요소가 어떤 것이 있는가? <file_sep>// // StoreSectionHeader.swift // StoreApp // // Created by yuaming on 12/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit class StoreSectionHeader: UITableViewHeaderFooterView { fileprivate lazy var titleLabel: UILabelWithPadding = { let insets = UIEdgeInsets(top: 5, left: 3, bottom: 5, right: 3) let label = UILabelWithPadding(frame: self.frame, padding: insets) label.translatesAutoresizingMaskIntoConstraints = false label.font = .systemFont(ofSize: 11, weight: .regular) label.textColor = .white label.backgroundColor = .lightGray return label }() fileprivate lazy var subtitleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .systemFont(ofSize: 15, weight: .bold) label.textColor = .black return label }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) initializeLayout() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func prepareForReuse() { titleLabel.text = nil subtitleLabel.text = nil } func initializeLayout() { contentView.backgroundColor = .white contentView.layer.borderWidth = 1 contentView.layer.borderColor = UIColor.lightGray.cgColor contentView.addSubview(titleLabel) contentView.addSubview(subtitleLabel) titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 15).isActive = true subtitleLabel.centerXAnchor.constraint(equalTo: titleLabel.centerXAnchor).isActive = true subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5).isActive = true } func setContent(title: String, subtitle: String) { titleLabel.text = title subtitleLabel.text = subtitle } } <file_sep>// // FileLoader.swift // StoreApp // // Created by yuaming on 13/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct FileLoader { static func data(fileName: String, fileType: FileTypes) -> Data? { guard let path = Bundle.main.path(forResource: fileName, ofType: fileType.name) else { return nil } let url = URL(fileURLWithPath: path) guard let data = try? Data(contentsOf: url) else { return nil } return data } } <file_sep>// // UI+.swift // StoreApp // // Created by yuaming on 10/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit extension UIColor { static let lightPink = UIColor(red: 239/255, green: 169/255, blue: 199/255, alpha: 1) static let mint = UIColor(red: 80/255, green: 218/255, blue: 223/255, alpha: 1) } extension String { var throughStrike: NSMutableAttributedString { let string = NSMutableAttributedString(string: self) let range = NSRange(location: 0, length: self.count) string.addAttribute(.strikethroughStyle, value: 1, range: range) string.addAttribute(.strikethroughColor, value: UIColor.lightGray, range: range) return string } } <file_sep>// // API.swift // StoreApp // // Created by yuaming on 13/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation enum API { static let shared: APIClient = DefaultAPI() case list(String) case getImage(String) case detail(String) } extension API { var path: String { switch self { case let .list(id): return "/\(id)" case let .getImage(imagePath): return "\(imagePath)" case let .detail(hash): return "/detail/\(hash)" } } } enum ResponseResult { case success(Data?) case error(Error) } protocol APIClient { func makeUrlInList(id: String) -> URL? func makeUrl(_ urlString: String) -> URL? func makeUrlInDetail(hash: String) -> URL? } extension APIClient { typealias ResultClosure = (ResponseResult) -> Void func sendRequest(withUrl url: URL?, completionHandler: @escaping ResultClosure) { guard let url = url else { return } URLSession.shared.dataTask(with: url) { (data, response, error) in if let error = error { completionHandler(.error(error)) } else { completionHandler(.success(data)) } }.resume() } func post(withUrl url: URL?, data: Data) { guard let url = url else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = data URLSession.shared.dataTask(with: request).resume() } } class DefaultAPI: APIClient { fileprivate let host = Host.base.path func makeUrlInList(id: String) -> URL? { return URL(string: "\(host)\(API.list(id).path)") } func makeUrl(_ urlString: String) -> URL? { return URL(string: "\(urlString)") } func makeUrlInDetail(hash: String) -> URL? { return URL(string: "\(host)\(API.detail(hash).path)") } } enum Host { case base case order case apple } extension Host { var path: String { switch self { case .base: return "http://crong.codesquad.kr:8080/woowa" case .order: return "https://hooks.slack.com/services/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" case .apple: return "https://www.apple.com" } } } <file_sep>// // JSONConverter.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct JSONConverter { static func decode<T: Decodable>(in data: Data?, type: [T].Type) -> [T] { let jsonData: [T] do { guard let data = data else { return [] } jsonData = try JSONDecoder().decode(type, from: data) } catch let e { print(e) return [] } return jsonData } static func decode<T: Decodable>(in data: Data?, type: T.Type) -> T? { let jsonData: T do { guard let data = data else { return nil } jsonData = try JSONDecoder().decode(type, from: data) } catch { print(error) return nil } return jsonData } static func encode<T: Encodable>(in data: T) -> Data? { let jsonEncoder = JSONEncoder() let encodedData: Data do { encodedData = try jsonEncoder.encode(data) } catch { print(error) return nil } return encodedData } } <file_sep>// // DetailViewController.swift // StoreApp // // Created by yuaming on 17/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit protocol OrderDelegate: class { func showResult(_ orderInfo: OrderInfo) } class DetailViewController: UIViewController { @IBOutlet weak var thumbnailScrollView: UIScrollView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var pointLabel: UILabel! @IBOutlet weak var deliveryInfoLabel: UILabel! @IBOutlet weak var deliveryFeeLabel: UILabel! @IBOutlet weak var detailInfoContainer: UIView! @IBOutlet weak var sectionScrollView: UIScrollView! fileprivate let detailSectionHeight: CGFloat = 500 var orderDelegate: OrderDelegate? var itemDetail: StoreDetailItem? { willSet { self.setupObservers() } } override func viewDidLoad() { super.viewDidLoad() setup() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } fileprivate func setup() { self.itemDetail?.requestData() } fileprivate func setupObservers() { NotificationCenter.default.addObserver(self, selector: #selector(updateData(_:)), name: .detailData, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateThumbnails(_:)), name: .thumbnail, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateDetailSection(_:)), name: .detailSection, object: nil) } @objc fileprivate func updateData(_ notification: Notification) { guard let userInfo = notification.userInfo, let detailTitle = userInfo[Constants.detailTitle] as? String, let itemDetailData = userInfo[Constants.detailData] as? ItemDetailData else { return } configueSectionScrollViewSize(itemDetailData.detailSectionImageUrls.count) configueThumbnailScrollViewSize(itemDetailData.thumbnailImageUrls.count) updateDetailInfoContainer(detailTitle, itemDetailData) } @objc fileprivate func updateThumbnails(_ notification: Notification) { guard let userInfo = notification.userInfo, let index = userInfo[Constants.imageIndex] as? Int, let image = userInfo[Constants.image] as? UIImage else { return } DispatchQueue.main.async { self.updateThumbnailScrollView(index: index, image: image) } } @objc fileprivate func updateDetailSection(_ notification: Notification) { guard let userInfo = notification.userInfo, let index = userInfo[Constants.imageIndex] as? Int, let image = userInfo[Constants.image] as? UIImage else { return } DispatchQueue.main.async { self.updateDetailSectionView(index: index, image: image) } } @IBAction func orderButtonDidTapped(_ sender: UIButton) { let orderInfo = OrderInfo(name: "AMING", menu: titleLabel.text ?? "", price: priceLabel.text ?? "") guard let url = API.shared.makeUrl("\(Host.order.path)") else { return } guard let orderResultData = JSONConverter.encode(in: [Constants.text : orderInfo.description]) else { return } API.shared.post(withUrl: url, data: orderResultData) orderDelegate?.showResult(orderInfo) self.navigationController?.popViewController(animated: true) } deinit { NotificationCenter.default.removeObserver(self) } } fileprivate extension DetailViewController { func configueSectionScrollViewSize(_ count: Int) { sectionScrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: thumbnailScrollView.frame.height + detailInfoContainer.frame.height + detailSectionHeight * CGFloat(count)) } func configueThumbnailScrollViewSize(_ count: Int) { thumbnailScrollView.contentSize = CGSize(width: UIScreen.main.bounds.width * CGFloat(count), height: thumbnailScrollView.frame.height) } func updateDetailInfoContainer(_ detailTitle: String, _ data: ItemDetailData) { titleLabel.text = detailTitle descriptionLabel.text = data.productDescription priceLabel.text = data.prices.last pointLabel.text = data.point deliveryFeeLabel.text = data.deliveryFee deliveryInfoLabel.text = data.deliveryInfo } func updateThumbnailScrollView(index: Int, image: UIImage) { let xCoordinate: CGFloat = thumbnailScrollView.frame.width * CGFloat(index) let thumbnailView = UIImageView(frame: CGRect(x: xCoordinate, y: 0, width: UIScreen.main.bounds.width, height: thumbnailScrollView.frame.height)) thumbnailView.contentMode = .scaleAspectFill thumbnailView.image = image thumbnailScrollView.addSubview(thumbnailView) } func updateDetailSectionView(index: Int, image: UIImage) { let yCoordinate: CGFloat = (thumbnailScrollView.frame.height + detailInfoContainer.frame.height) + (CGFloat(index) * detailSectionHeight) let detailSectionImageView = UIImageView(frame: CGRect(x: 0, y: yCoordinate, width: UIScreen.main.bounds.width, height: detailSectionHeight)) detailSectionImageView.contentMode = .scaleAspectFit detailSectionImageView.image = image sectionScrollView.addSubview(detailSectionImageView) } } <file_sep>// // UILabelWithPadding.swift // StoreApp // // Created by yuaming on 12/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit class UILabelWithPadding: UILabel { @IBInspectable var topInset: CGFloat = 0 @IBInspectable var bottomInset: CGFloat = 0 @IBInspectable var leftInset: CGFloat = 0 @IBInspectable var rightInset: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(frame: CGRect, padding insets: UIEdgeInsets) { self.init(frame: frame) self.topInset = insets.top self.bottomInset = insets.bottom self.leftInset = insets.left self.rightInset = insets.right } override func drawText(in rect: CGRect) { let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset) super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) } override var intrinsicContentSize: CGSize { var size = super.intrinsicContentSize size.width += leftInset + rightInset size.height += topInset + bottomInset return size } func addInsets(_ insets: UIEdgeInsets) { self.topInset = insets.top self.bottomInset = insets.bottom self.leftInset = insets.left self.rightInset = insets.right } func removeInsets() { self.topInset = 0 self.bottomInset = 0 self.leftInset = 0 self.rightInset = 0 } } <file_sep>// // ImageLoaderable.swift // StoreApp // // Created by yuaming on 19/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation import UIKit protocol ImageLoaderable: class { var index: Int? { get set} var image: UIImage? { get set } } extension ImageLoaderable { func loadImageData(_ urlString: String?) { guard let urlString = urlString else { return } let dispatchQueue = DispatchQueue.global(qos: .userInitiated) dispatchQueue.async { if let cachedData = ImageCache.fetchData(urlString) { self.image = UIImage(data: cachedData) } else { self.requestImageData(urlString) } } } fileprivate func requestImageData(_ urlString: String) { guard let url = API.shared.makeUrl(urlString) else { return } API.shared.sendRequest(withUrl: url) { resultType in switch resultType { case .success(let data): guard let data = data else { return } ImageCache.store(urlString, content: data) self.image = UIImage(data: data) case .error(let error): print(error.localizedDescription) } } } } <file_sep>// // JSONConverterTests.swift // StoreAppTests // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import XCTest @testable import StoreApp class JSONConverterTest: XCTestCase { func test_JSON_파일_읽기() { let data = FileLoader.data(file: .main, fileType: .json) XCTAssert(data!.isEmpty == false) } func test_JSON_Decode_확인() { let data = FileLoader.data(file: .main, fileType: .json) let item = JSONConverter.decode(in: data!, type: [StoreItem].self) XCTAssert(item.count >= 1) } } <file_sep>// // OrderInfo.swift // StoreApp // // Created by yuaming on 19/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct OrderInfo { fileprivate let name: String fileprivate let menu: String fileprivate let price: String init(name: String, menu: String, price: String) { self.name = name self.menu = menu self.price = price } } extension OrderInfo: CustomStringConvertible { var description: String { return "\(name)이 \(menu)를(을) \(price)을 주고 구매하였습니다 :)" } } <file_sep>// // ItemDetailData.swift // StoreApp // // Created by yuaming on 17/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct ItemDetailData { let topImageUrl: String let thumbnailImageUrls: [String] let productDescription: String let point: String let deliveryInfo: String let deliveryFee: String let prices: [String] let detailSectionImageUrls: [String] var thumbnails: [Thumbnail] var detailSectionImages: [DetailSectionImage] } extension ItemDetailData: Decodable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.topImageUrl = try values.decode(String.self, forKey: .topImageUrl) self.thumbnailImageUrls = try values.decode([String].self, forKey: .thumbnailImageUrls) self.productDescription = try values.decode(String.self, forKey: .productDescription) self.point = try values.decode(String.self, forKey: .point) self.deliveryInfo = try values.decode(String.self, forKey: .deliveryInfo) self.deliveryFee = try values.decode(String.self, forKey: .deliveryFee) self.prices = try values.decode([String].self, forKey: .prices) self.detailSectionImageUrls = try values.decode([String].self, forKey: .detailSectionImageUrls) self.thumbnails = thumbnailImageUrls.enumerated().compactMap { (index, urlString) -> Thumbnail in Thumbnail(urlString, index: index) } self.detailSectionImages = detailSectionImageUrls.enumerated().compactMap { (index, urlString) -> DetailSectionImage in DetailSectionImage(urlString, index: index) } } enum CodingKeys: String, CodingKey { case topImageUrl = "top_image" case thumbnailImageUrls = "thumb_images" case productDescription = "product_description" case point case deliveryInfo = "delivery_info" case deliveryFee = "delivery_fee" case prices case detailSectionImageUrls = "detail_section" } } <file_sep>// // StoreItemDetail.swift // StoreApp // // Created by yuaming on 17/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import Foundation struct StoreDetailItem: Decodable { var title: String? var detailHash: String var detailData: ItemDetailData? init(_ title: String, _ detailHash: String) { self.title = title self.detailHash = detailHash } enum CodingKeys: String, CodingKey { case detailHash = "hash" case detailData = "data" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.detailHash = try values.decode(String.self, forKey: .detailHash) self.detailData = try values.decode(ItemDetailData.self, forKey: .detailData) } } extension StoreDetailItem { func generateFileData() { let data = FileLoader.data(fileName: "HBDEF", fileType: FileTypes.json) load(data) } func requestData() { let url = API.shared.makeUrlInDetail(hash: detailHash) API.shared.sendRequest(withUrl: url) { resultType in DispatchQueue.main.async { switch resultType { case .success(let data): self.load(data) case .error(let error): print(error.localizedDescription) } } } } fileprivate func load(_ data: Data?) { if let data = data { let decodedData = JSONConverter.decode(in: data, type: StoreDetailItem.self) NotificationCenter.default.post(name: .detailData, object: nil, userInfo: [Constants.detailTitle: title, Constants.detailData: decodedData?.detailData]) } } } extension Notification.Name { static let detailData = Notification.Name(Constants.detailData) } <file_sep>// // AppDelegate.swift // StoreApp // // Created by yuaming on 09/07/2018. // Copyright © 2018 yuaming. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { fileprivate let networkManager = NetworkManager.shared var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { NotificationCenter.default.addObserver(self, selector: #selector(updateConnectedFlag(_:)), name: Notification.Name.isConnected, object: nil) networkManager.startObserver() setStatusBarOption() return true } func applicationDidEnterBackground(_ application: UIApplication) { networkManager.stopObserver() } @objc fileprivate func updateConnectedFlag(_ notification: Notification) { guard let userInfo = notification.userInfo, let isConnected = userInfo[Constants.isConnected] as? Bool else { return } drawBorder(isConnected: isConnected) } fileprivate func drawBorder(isConnected: Bool) { let rootView = window?.rootViewController?.view rootView?.layer.borderColor = isConnected ? UIColor.green.cgColor : UIColor.red.cgColor rootView?.layer.borderWidth = 3 } fileprivate func setStatusBarOption() { if let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView { statusBar.backgroundColor = UIColor.white } } }
78530845a45142ffb4ad1e4059d2f31d88b3315f
[ "Swift", "Ruby", "AsciiDoc" ]
26
Swift
yuaming/swift-storeapp
449f5bd47c2c3c6a0411c4b6cc1cb2dda52adcd9
0487a3de79a387b9e6e2654e95083241044c3e0e
refs/heads/main
<repo_name>JimvandeVen/portfolio-sterrk<file_sep>/frontend/src/components/Tech.js import { gql, useQuery } from "@apollo/client"; import styled from "styled-components"; export const ALL_TAGS_QUERY = gql` query ALL_TAGS_QUERY { allTags { id name } } `; const StyledTech = styled.div` display: flex; max-width: 100%; margin: 0 2rem 0 2rem; flex-wrap: wrap; justify-content: flex-start; span { color: black; background-color: #ff0; border-radius: 5px; font-weight: bold; padding: 2px 5px 2px 5px; margin-top: 0.5rem; margin-right: 0.5rem; } `; export default function Tech() { const { data, error, loading } = useQuery(ALL_TAGS_QUERY); if (loading) { return <p>Loading...</p>; } if (error) { console.error(error); } return ( <> <h2 className="banner-title">Skills</h2> <StyledTech> {data.allTags.map((tag) => { return <span key={tag.id}>{tag.name}</span>; })} </StyledTech> </> ); } <file_sep>/frontend/src/components/Educations.js import styled from "styled-components"; import Education from "./Education"; const StyledEducations = styled.ul` list-style: none; padding: 0; h2 { text-decoration: underline; text-decoration-color: #ff0; } h3 { font-size: 1.2rem; font-weight: 500; } `; export default function Educations({ lang }) { return ( <StyledEducations> <h2>{lang === "en" ? "Education" : "Opleiding"}</h2> <Education></Education> </StyledEducations> ); } <file_sep>/frontend/src/components/About.js import styled from "styled-components"; import Tech from "./Tech"; const StyledAbout = styled.div` background-color: black; position: relative; h2 { color: #ff0; margin: 0 0 2rem 2rem; font-size: 4rem; } h3 { color: white; margin: 0 0 0 2rem; transform: translateY(-100%); } img { max-width: 100%; filter: grayscale(100%); } div:not(:last-of-type) { display: grid; grid-template-columns: 1fr 1fr; margin: 0 0 0 2rem; } div p { margin: 0; width: 50%; color: white; } `; export default function About({ lang }) { return ( <StyledAbout> <h2>{lang === "nl" ? "Over mij" : "About me"}</h2> <h3>Full Stack Developer</h3> <div> <p>{lang === "nl" ? "Geboren" : "Dob."}</p> <p>15/07/1990</p> </div> <div> <p>{lang === "nl" ? "Woonplaats" : "Res."}</p> <p>Amsterdam</p> </div> <div> <p>{lang === "nl" ? "Talen" : "Lang."}</p> <p>{lang === "nl" ? "Nederlands, Engels" : "Dutch, English"}</p> </div> <Tech></Tech> </StyledAbout> ); } <file_sep>/backend/schemas/Project.js const { Text, Relationship, Integer } = require("@keystonejs/fields"); module.exports = { fields: { name: { type: Text, isRequired: true, }, year: { type: Integer, isRequired: true, }, description: { type: Text, isRequired: true, }, descriptionNl: { type: Text, isRequired: true, }, tags: { type: Relationship, ref: "Tag.projects", many: true, }, }, }; <file_sep>/backend/schemas/Employer.js const { Text, CalendarDay } = require("@keystonejs/fields"); module.exports = { fields: { name: { type: Text, isRequired: true, }, description: { type: Text, isRequired: true, }, descriptionNl: { type: Text, isRequired: true, }, startDate: { type: CalendarDay, isRequired: true, }, endDate: { type: CalendarDay, }, }, }; <file_sep>/frontend/src/components/Summary.js import styled from "styled-components"; const StyledSummary = styled.div` p { font-weight: lighter; } `; export default function Summary({ lang }) { return ( <StyledSummary> {lang === "en" && ( <p> Creative Web developer with a solid background in <b>JavaScript</b>. Currently expanding my knowledge in backend, specificly <b>php</b>{" "} (Laravel). I'm a creative webdeveloper with schooling in <b>UI/UX</b>{" "} design and who centers my work around the end user. I work well in teams with different disciplines and not afraid to give my opinion and have a <b>professional</b> discussion, leading to a better product. </p> )} {lang === "nl" && ( <p> Creatieve web developer met een solide achtergrond in{" "} <b>JavaScript</b>. Momenteel ben ik bezig om mijn kennis in backend te vergroten, met name in <b>php</b> (laravel). Ik heb oog voor{" "} <b>UX/UI</b> design en centreer mijn werk op de eindgebruiker. Door mijn opleiding ben ik goed in het werken in teams met verschillende disciplines en niet bang om mijn mijn mening te geven en een{" "} <b>professionele</b> discussie te voeren, om tot een beter product te komen. </p> )} </StyledSummary> ); } <file_sep>/frontend/src/components/Employers.js import { useQuery } from "@apollo/client"; import gql from "graphql-tag"; import styled from "styled-components"; import Employer from "./Employer"; export const ALL_EMPLOYERS_QUERY = gql` query ALL_EMPLOYERS_QUERY { allEmployers(sortBy: startDate_DESC) { id name startDate endDate description descriptionNl } } `; const StyledEmployers = styled.ul` list-style: none; padding: 0; h2 { text-decoration: underline; text-decoration-color: #ff0; } h3 { font-size: 1.2rem; font-weight: 500; } `; export default function Employers({ lang }) { const { data, error, loading } = useQuery(ALL_EMPLOYERS_QUERY); if (loading) return <p>Loading...</p>; if (error) { console.error(error); } return ( <StyledEmployers> <h2>{lang === "nl" ? "Werkgevers" : "Employers"}</h2> {data.allEmployers.map((employer) => { return ( <Employer key={employer.id} employer={employer} lang={lang} ></Employer> ); })} </StyledEmployers> ); } <file_sep>/frontend/src/components/Cv.js import styled from "styled-components"; import Educations from "./Educations"; import Employers from "./Employers"; import Projects from "./Projects"; import Summary from "./Summary"; const StyledCv = styled.div` background-color: white; padding: 3rem; h3, h4 { margin-bottom: 0; margin-top: 0; } p { margin-top: 0; } h4 { font-weight: 400; } .sideline { background-color: black; height: inherit; width: 2px; position: absolute; transform: translateX(-1000%); height: 100%; } `; export default function Cv({ width, lang }) { const desktop = width <= 768 ? "hidden" : ""; const mobile = width > 768 ? "hidden" : ""; return ( <> <StyledCv className={desktop}> <h1><NAME></h1> <Summary lang={lang}></Summary> <Educations lang={lang}></Educations> <Employers lang={lang}></Employers> <Projects lang={lang}></Projects> </StyledCv> <StyledCv className={mobile}> <Summary lang={lang}></Summary> <Educations lang={lang}></Educations> <Employers lang={lang}></Employers> <Projects lang={lang}></Projects> </StyledCv> </> ); } <file_sep>/frontend/src/components/Education.js import styled from "styled-components"; const StyledEducation = styled.li` position: relative; `; export default function Education() { return ( <StyledEducation> <span className="sideline"></span> <h3>2016-2021</h3> <p>Bsc. Communication and Multimedia Design</p> </StyledEducation> ); } <file_sep>/frontend/src/components/Employer.js import styled from "styled-components"; const StyledEmployer = styled.li` position: relative; h4 { font-weight: bold; font-size: 1.3rem; } `; export default function Employer({ employer, lang }) { function endDate(lang, employer) { if (employer.endDate) { return employer.endDate; } if (lang === "nl") { return "heden"; } return "present"; } return ( <StyledEmployer> <span className="sideline"></span> <h4>{employer.name}</h4> <h3> {employer.startDate} - {endDate(lang, employer)} </h3> <p>{lang === "en" ? employer.description : employer.descriptionNl}</p> </StyledEmployer> ); } <file_sep>/README.md # portfolio-sterrk
1464053f5f218e824d8d7ed4e581e62ad601f838
[ "JavaScript", "Markdown" ]
11
JavaScript
JimvandeVen/portfolio-sterrk
352a57f978170210f6ab5bfd5e42101568eb8041
75c2412d07c426df0bb6beccf95ed4fc15454f0d
refs/heads/master
<repo_name>IlMike22/PiggyBank<file_sep>/app/src/main/java/com/mwidlok/piggybank/MainActivity.kt package com.mwidlok.piggybank import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.mwidlok.piggybank.models.Transaction import kotlinx.android.synthetic.main.activity_main.* import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var sum : Double = 0.0 var newSum : String = "" fun increaseSum(transaction : Transaction) : Double { sum += transaction.amount newSum = "%.2f Euro".format(sum) Log.i("PiggyBank","New sum is $newSum.") tvSum.setText(newSum) return sum } fun getCurrentDate() : String { val currentDate = Calendar.getInstance() return "${currentDate.get(Calendar.DAY_OF_YEAR)}.${currentDate.get(Calendar.MONTH)+1}.${currentDate.get(Calendar.YEAR)}" } btn1Cent.setOnClickListener { increaseSum(Transaction( 0.01, getCurrentDate())) } btn2Cent.setOnClickListener { increaseSum(Transaction(0.02, getCurrentDate())) } btn5Cent.setOnClickListener { increaseSum(Transaction(0.05, getCurrentDate())) } btn10Cent.setOnClickListener { increaseSum(Transaction( 0.1, getCurrentDate())) } btn20Cent.setOnClickListener { increaseSum(Transaction( 0.2, getCurrentDate())) } btn50Cent.setOnClickListener { increaseSum(Transaction(0.5, getCurrentDate())) } btn1Euro.setOnClickListener { increaseSum(Transaction(1.0, getCurrentDate())) } btn2Euro.setOnClickListener { increaseSum(Transaction(2.0, getCurrentDate())) } } } <file_sep>/app/src/main/java/com/mwidlok/piggybank/models/Transaction.kt package com.mwidlok.piggybank.models import android.util.Log import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase /** * This class offers some convenience methods for showing custom alert dialog with different user options. */ class Transaction(var amount : Double, var date : String) { init { var mDatabase: DatabaseReference mDatabase = FirebaseDatabase.getInstance().reference val key = mDatabase.child("transactions").push().key Log.i("PiggyBank","new key of value is $key") mDatabase.child("entries").child(key).setValue(this) } }
5d13fac86fe7d69f8916a38b3dfdf853e4194e2b
[ "Kotlin" ]
2
Kotlin
IlMike22/PiggyBank
4577422b5bd2146a76df7ca74ab5a93f0be9819e
bfc3d4ee67f371b7c93912c6a3eb9639e95266f7
refs/heads/main
<repo_name>zshaikhonline/GraphQL-with-Spring-Boot<file_sep>/README.md # GraphQL with Spring Boot Graphql with springboot <file_sep>/src/main/java/com/graphqlservices/graphql/model/Student.java package com.graphqlservices.graphql.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @AllArgsConstructor @NoArgsConstructor @Setter @Getter @Table @Entity public class Student { @Id private String id; private String name; private String address; } <file_sep>/src/main/java/com/graphqlservices/graphql/repository/BookRepository.java package com.graphqlservices.graphql.repository; import com.graphqlservices.graphql.model.Book; import org.springframework.data.jpa.repository.JpaRepository; public interface BookRepository extends JpaRepository<Book, String> { } <file_sep>/src/main/java/com/graphqlservices/graphql/repository/StudentRepository.java package com.graphqlservices.graphql.repository; import com.graphqlservices.graphql.model.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, String> { } <file_sep>/src/main/java/com/graphqlservices/graphql/service/datafetcher/AllStudentDataFetcher.java package com.graphqlservices.graphql.service.datafetcher; import com.graphqlservices.graphql.model.Book; import com.graphqlservices.graphql.model.Student; import com.graphqlservices.graphql.repository.StudentRepository; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class AllStudentDataFetcher implements DataFetcher<List<Student>> { @Autowired StudentRepository studentRepository; @Override public List<Student> get(DataFetchingEnvironment dataFetchingEnvironment) { return studentRepository.findAll(); } }
cc3aa3498088b817e20b3140516e814121cf8835
[ "Markdown", "Java" ]
5
Markdown
zshaikhonline/GraphQL-with-Spring-Boot
3c188b1aa3471d84d8be63f2bb6488eee3fb77ae
e10a05c0075b9efa6b697c7153de69fdd609642c
refs/heads/master
<file_sep>package AbstractClasss; abstract class figure { double dim1; double dim2; public figure(double a, double b) { dim1 = a; dim2 = b; } abstract double area(); } class rectangle extends figure { public rectangle(double a, double b) { super(a, b); // TODO Auto-generated constructor stub } @Override double area() { System.out.println("Inside area of rectangle"); return dim1 * dim2; } } class triangle extends figure { public triangle(double a, double b) { super(a, b); // TODO Auto-generated constructor stub } @Override double area() { System.out.println("Inside area of triangle"); return dim1 * dim2 / 2; } } public class AbstractClassAreas { public static void main(String[] args) { // TODO Auto-generated method stub rectangle rectangleObject = new rectangle(10, 10); triangle triangleObject = new triangle(10, 10); figure figureReference; figureReference = rectangleObject; System.out.println("Rectangle: " + figureReference.area()); figureReference = triangleObject; System.out.println("Triangle: " + figureReference.area()); } }
42b641bedcd2b1ffbf9c5959b4cb0c2b5612f01a
[ "Java" ]
1
Java
AshwiniQualityAnalyst/AbstractClasses
01b0b1df81e3cb01ed83c3c7fe4c570a830195a4
f50cd48e70eda9a03ba0206b9a6943db3941f150
refs/heads/master
<repo_name>kenzosakiyama/visao_computacional<file_sep>/utils.py import numpy as np from PIL import Image def histogram_from_grayscale(img: Image) -> np.array: histogram = np.zeros(256) # Reshape para facilitar iteração img_array = np.asarray(img).flatten() histogram, _ = np.histogram(img_array, 256, [0, 256]) return histogram def histogram_from_rgb(img: Image) -> np.array: r_channel = img.getchannel(0) g_channel = img.getchannel(1) b_channel = img.getchannel(2) r_hist = histogram_from_grayscale(r_channel) g_hist = histogram_from_grayscale(g_channel) b_hist = histogram_from_grayscale(b_channel) return np.concatenate([r_hist, g_hist, b_hist]) def luminance_gray_scale(img: Image) -> Image: img_array = np.asarray(img) output_array = np.zeros(shape=img_array.shape[:2]) # Razão de contribuição dos canais: 0.21R + 0.71G + 0.07B output_array = 0.21 * img_array[:,:,0] + 0.71 * img_array[:,:,1] + 0.07 * img_array[:,:,2] return Image.fromarray(np.uint8(output_array)) def get_pdf(img: Image, rgb: bool = False) -> np.array: if rgb: img_histogram = histogram_from_rgb(img) else: img_histogram = histogram_from_grayscale(img) n_pixels = img.size[0] * img.size[1] img_pdf = (1/n_pixels) * img_histogram return img_pdf
2a231750cb5f6facf31fd81791e30dbdabb0a89a
[ "Python" ]
1
Python
kenzosakiyama/visao_computacional
a93fbb8b109f87d41302270ebe1a89aff2d88396
48e162200057f54150a83136a37ecf9fba32a8ae
refs/heads/master
<repo_name>ethankclam/coursera-test<file_sep>/site/javascript/script.js // DOM Manipulation // console.log(document.getElementById("title")); // console.log(document instanceof HTMLDocument); // object creation // var company = new Object(); // company.name = "Facebook"; // company.ceo = new Object(); // company.ceo.firstname = "Mark"; // company.ceo.favColor = "blue"; // console.log(company); // console.log("Company CEO name is: " // + company.ceo.firstname); // console.log(company["name"]); // ompany.$stock = 110; // console.log(company); // console.log("Stock price is: " + company[stockPropNmae]); // function multiply(x, y) { // return x * y; // } // console.log(multiply(5, 3)); // multiply.version = "v.1.0.0"; // console.log(multiply.version); // alert(); // function // function go(){ // alert('hi'); // alert('hey there'); // } // go(); function call(name, age){ return name+age; } var add = call(1, 2); alert(add); var myList = ['apples', 'organge', 'bananas']; myList.forEach(function(value, index) { alert('I have '+value+' in my shopping bag'); }); //while loop var times = 0; while (times < 10) { console.log('tried it', times); times = times+1 } do { console.log('did it', times); times++; } while(times < 10); for (var i=0; i < myList.length; i++) { console.log('i is', i); } for (var i=0; i < myList.length; i++) { alert('you have '+myList[1]+' in your basket'); } // var name = "cool"; // var age = 20; // alert(name); // alert(age); //event function sayHello (event) { this.textContent = "Said it!"; var name = document.getElementById("name").value; var message = "Hello " + name + "!"; document.getElementById("content").textContent = message; }; document.querySelector("button") .addEventListener("click", sayHello); var message = "in global"; console.log("global: message = " + message); var a = function () { var message = "inside a"; console.log("a: message = " + message); b(); } function b () { console.log("b: message = " + message); } a();
2d606c9a57a1c22c416b8cf422e3a3c6461f168d
[ "JavaScript" ]
1
JavaScript
ethankclam/coursera-test
b084cd4e254cf5129b2469e64e915e07b3a8280c
296589981f28f1cce129018e093a514fc5c9115b
refs/heads/master
<file_sep>/* * Start point for application */ #include <QtGui> #include "powerstatus.h" #include "thinkpadbattery.h" int main(int argc, char *argv[]) { Q_INIT_RESOURCE(ThinkPadBattery); PowerStatus powerStatus; QApplication app(argc, argv); if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, QObject::tr("ThinkPadBattery"), QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; } QApplication::setQuitOnLastWindowClosed(false); ThinkPadBattery thinkPadBattery(&powerStatus); thinkPadBattery.hide(); powerStatus.registerLowBatterySlot(&thinkPadBattery); powerStatus.start(); return app.exec(); } <file_sep>############################################################################# # Makefile for building: ThinkpadBatteryTray # Generated by qmake (2.01a) (Qt 4.6.2) on: pt. maj 30 09:05:19 2014 # Project: ThinkpadBatteryTray.pro # Template: app # Command: /usr/bin/qmake -unix -o Makefile ThinkpadBatteryTray.pro ############################################################################# ####### Compiler, tools and options CC = gcc CXX = g++ DEFINES = -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED CFLAGS = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES) CXXFLAGS = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES) INCPATH = -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. LINK = g++ LFLAGS = -Wl,-O1 LIBS = $(SUBLIBS) -L/usr/lib -lQtGui -lQtCore -lpthread AR = ar cqs RANLIB = QMAKE = /usr/bin/qmake TAR = tar -cf COMPRESS = gzip -9f COPY = cp -f SED = sed COPY_FILE = $(COPY) COPY_DIR = $(COPY) -r STRIP = strip INSTALL_FILE = install -m 644 -p INSTALL_DIR = $(COPY_DIR) INSTALL_PROGRAM = install -m 755 -p DEL_FILE = rm -f SYMLINK = ln -f -s DEL_DIR = rmdir MOVE = mv -f CHK_DIR_EXISTS= test -d MKDIR = mkdir -p ####### Output directory OBJECTS_DIR = ./ ####### Files SOURCES = main.cpp \ thinkpadbattery.cpp \ powerstatus.cpp moc_thinkpadbattery.cpp \ moc_powerstatus.cpp \ qrc_ThinkPadBattery.cpp OBJECTS = main.o \ thinkpadbattery.o \ powerstatus.o \ moc_thinkpadbattery.o \ moc_powerstatus.o \ qrc_ThinkPadBattery.o DIST = /usr/share/qt4/mkspecs/common/g++.conf \ /usr/share/qt4/mkspecs/common/unix.conf \ /usr/share/qt4/mkspecs/common/linux.conf \ /usr/share/qt4/mkspecs/qconfig.pri \ /usr/share/qt4/mkspecs/features/qt_functions.prf \ /usr/share/qt4/mkspecs/features/qt_config.prf \ /usr/share/qt4/mkspecs/features/exclusive_builds.prf \ /usr/share/qt4/mkspecs/features/default_pre.prf \ /usr/share/qt4/mkspecs/features/release.prf \ /usr/share/qt4/mkspecs/features/default_post.prf \ /usr/share/qt4/mkspecs/features/warn_on.prf \ /usr/share/qt4/mkspecs/features/qt.prf \ /usr/share/qt4/mkspecs/features/unix/thread.prf \ /usr/share/qt4/mkspecs/features/moc.prf \ /usr/share/qt4/mkspecs/features/resources.prf \ /usr/share/qt4/mkspecs/features/uic.prf \ /usr/share/qt4/mkspecs/features/yacc.prf \ /usr/share/qt4/mkspecs/features/lex.prf \ /usr/share/qt4/mkspecs/features/include_source_dir.prf \ ThinkpadBatteryTray.pro QMAKE_TARGET = ThinkpadBatteryTray DESTDIR = TARGET = ThinkpadBatteryTray first: all ####### Implicit rules .SUFFIXES: .o .c .cpp .cc .cxx .C .cpp.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cc.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cxx.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .C.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .c.o: $(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<" ####### Build rules all: Makefile $(TARGET) $(TARGET): $(OBJECTS) $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) Makefile: ThinkpadBatteryTray.pro /usr/share/qt4/mkspecs/linux-g++/qmake.conf /usr/share/qt4/mkspecs/common/g++.conf \ /usr/share/qt4/mkspecs/common/unix.conf \ /usr/share/qt4/mkspecs/common/linux.conf \ /usr/share/qt4/mkspecs/qconfig.pri \ /usr/share/qt4/mkspecs/features/qt_functions.prf \ /usr/share/qt4/mkspecs/features/qt_config.prf \ /usr/share/qt4/mkspecs/features/exclusive_builds.prf \ /usr/share/qt4/mkspecs/features/default_pre.prf \ /usr/share/qt4/mkspecs/features/release.prf \ /usr/share/qt4/mkspecs/features/default_post.prf \ /usr/share/qt4/mkspecs/features/warn_on.prf \ /usr/share/qt4/mkspecs/features/qt.prf \ /usr/share/qt4/mkspecs/features/unix/thread.prf \ /usr/share/qt4/mkspecs/features/moc.prf \ /usr/share/qt4/mkspecs/features/resources.prf \ /usr/share/qt4/mkspecs/features/uic.prf \ /usr/share/qt4/mkspecs/features/yacc.prf \ /usr/share/qt4/mkspecs/features/lex.prf \ /usr/share/qt4/mkspecs/features/include_source_dir.prf \ /usr/lib/libQtGui.prl \ /usr/lib/libQtCore.prl $(QMAKE) -unix -o Makefile ThinkpadBatteryTray.pro /usr/share/qt4/mkspecs/common/g++.conf: /usr/share/qt4/mkspecs/common/unix.conf: /usr/share/qt4/mkspecs/common/linux.conf: /usr/share/qt4/mkspecs/qconfig.pri: /usr/share/qt4/mkspecs/features/qt_functions.prf: /usr/share/qt4/mkspecs/features/qt_config.prf: /usr/share/qt4/mkspecs/features/exclusive_builds.prf: /usr/share/qt4/mkspecs/features/default_pre.prf: /usr/share/qt4/mkspecs/features/release.prf: /usr/share/qt4/mkspecs/features/default_post.prf: /usr/share/qt4/mkspecs/features/warn_on.prf: /usr/share/qt4/mkspecs/features/qt.prf: /usr/share/qt4/mkspecs/features/unix/thread.prf: /usr/share/qt4/mkspecs/features/moc.prf: /usr/share/qt4/mkspecs/features/resources.prf: /usr/share/qt4/mkspecs/features/uic.prf: /usr/share/qt4/mkspecs/features/yacc.prf: /usr/share/qt4/mkspecs/features/lex.prf: /usr/share/qt4/mkspecs/features/include_source_dir.prf: /usr/lib/libQtGui.prl: /usr/lib/libQtCore.prl: qmake: FORCE @$(QMAKE) -unix -o Makefile ThinkpadBatteryTray.pro dist: @$(CHK_DIR_EXISTS) .tmp/ThinkpadBatteryTray1.0.0 || $(MKDIR) .tmp/ThinkpadBatteryTray1.0.0 $(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/ThinkpadBatteryTray1.0.0/ && $(COPY_FILE) --parents thinkpadbattery.h powerstatus.h .tmp/ThinkpadBatteryTray1.0.0/ && $(COPY_FILE) --parents ThinkPadBattery.qrc .tmp/ThinkpadBatteryTray1.0.0/ && $(COPY_FILE) --parents main.cpp thinkpadbattery.cpp powerstatus.cpp .tmp/ThinkpadBatteryTray1.0.0/ && (cd `dirname .tmp/ThinkpadBatteryTray1.0.0` && $(TAR) ThinkpadBatteryTray1.0.0.tar ThinkpadBatteryTray1.0.0 && $(COMPRESS) ThinkpadBatteryTray1.0.0.tar) && $(MOVE) `dirname .tmp/ThinkpadBatteryTray1.0.0`/ThinkpadBatteryTray1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/ThinkpadBatteryTray1.0.0 clean:compiler_clean -$(DEL_FILE) $(OBJECTS) -$(DEL_FILE) *~ core *.core ####### Sub-libraries distclean: clean -$(DEL_FILE) $(TARGET) -$(DEL_FILE) Makefile mocclean: compiler_moc_header_clean compiler_moc_source_clean mocables: compiler_moc_header_make_all compiler_moc_source_make_all compiler_moc_header_make_all: moc_thinkpadbattery.cpp moc_powerstatus.cpp compiler_moc_header_clean: -$(DEL_FILE) moc_thinkpadbattery.cpp moc_powerstatus.cpp moc_thinkpadbattery.cpp: thinkpadbattery.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) thinkpadbattery.h -o moc_thinkpadbattery.cpp moc_powerstatus.cpp: powerstatus.h /usr/bin/moc-qt4 $(DEFINES) $(INCPATH) powerstatus.h -o moc_powerstatus.cpp compiler_rcc_make_all: qrc_ThinkPadBattery.cpp compiler_rcc_clean: -$(DEL_FILE) qrc_ThinkPadBattery.cpp qrc_ThinkPadBattery.cpp: ThinkPadBattery.qrc \ images/bat_0.gif \ images/bat_critical.png \ images/bat_80.gif \ images/bat_100.gif \ images/bat_60.gif \ images/bat_40.gif \ images/bat_20.gif /usr/bin/rcc -name ThinkPadBattery ThinkPadBattery.qrc -o qrc_ThinkPadBattery.cpp compiler_image_collection_make_all: qmake_image_collection.cpp compiler_image_collection_clean: -$(DEL_FILE) qmake_image_collection.cpp compiler_moc_source_make_all: compiler_moc_source_clean: compiler_uic_make_all: compiler_uic_clean: compiler_yacc_decl_make_all: compiler_yacc_decl_clean: compiler_yacc_impl_make_all: compiler_yacc_impl_clean: compiler_lex_make_all: compiler_lex_clean: compiler_clean: compiler_moc_header_clean compiler_rcc_clean ####### Compile main.o: main.cpp powerstatus.h \ thinkpadbattery.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp thinkpadbattery.o: thinkpadbattery.cpp thinkpadbattery.h \ powerstatus.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o thinkpadbattery.o thinkpadbattery.cpp powerstatus.o: powerstatus.cpp powerstatus.h \ thinkpadbattery.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o powerstatus.o powerstatus.cpp moc_thinkpadbattery.o: moc_thinkpadbattery.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_thinkpadbattery.o moc_thinkpadbattery.cpp moc_powerstatus.o: moc_powerstatus.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_powerstatus.o moc_powerstatus.cpp qrc_ThinkPadBattery.o: qrc_ThinkPadBattery.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o qrc_ThinkPadBattery.o qrc_ThinkPadBattery.cpp ####### Install install: FORCE uninstall: FORCE FORCE: <file_sep>#include "powerstatus.h" #include <QFile> #include <QString> #include <QTextStream> #include <QMutexLocker> #include "thinkpadbattery.h" const QString PowerStatus::PERCENT = "/sys/devices/platform/smapi/BAT0/remaining_percent"; const QString PowerStatus::CHARGING = "/sys/devices/platform/smapi/BAT0/remaining_charging_time"; const QString PowerStatus::RUNNING = "/sys/devices/platform/smapi/BAT0/remaining_running_time_now"; PowerStatus::PowerStatus() : m_percent(0), m_charging(0), m_running(0), m_treshold(5), m_isCharging(false), m_isRunning(false), m_listener(NULL) { } void PowerStatus::registerLowBatterySlot(ThinkPadBattery* thinkPad) { m_listener = thinkPad; QObject::connect(this, SIGNAL(lowBatteryLevel()), m_listener, SLOT(showMessage())); QObject::connect(this, SIGNAL(newBatterLevel()), m_listener, SLOT(updatedTray())); } void PowerStatus::run() { for(;;) { bool ok = false; unsigned int percent, charging, running; bool isRunning, isCharging; percent = getStat(PowerStatus::PERCENT).toInt(&ok); charging = getStat(PowerStatus::CHARGING).toInt(&ok); isCharging = ok; running = getStat(PowerStatus::RUNNING).toInt(&ok); isRunning = ok; { QMutexLocker locker(&m_mutex); m_percent = percent; m_charging = charging; m_running = running; m_isCharging = isCharging; m_isRunning = isRunning; } if(m_percent <= m_treshold && !m_isCharging && m_listener) { emit lowBatteryLevel(); } emit newBatterLevel(); msleep( 10 * 1000); } } unsigned int PowerStatus::getPercent() { QMutexLocker locker(&m_mutex); return m_percent; } unsigned int PowerStatus::getCharging() { QMutexLocker locker(&m_mutex); return m_charging; } unsigned int PowerStatus::getRunning() { QMutexLocker locker(&m_mutex); return m_running; } bool PowerStatus::isCharging() { QMutexLocker locker(&m_mutex); return m_isCharging; } bool PowerStatus::isRunning() { QMutexLocker locker(&m_mutex); return m_isRunning; } QString PowerStatus::getStat(const QString& stat) { QFile statFile(stat); statFile.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream in(&statFile); return in.readLine(); } <file_sep>#ifndef THINKPADBATTERY_H #define THINKPADBATTERY_H #include <QSystemTrayIcon> #include <QVector> #include <QDialog> QT_BEGIN_NAMESPACE class QAction; class QMenu; class PowerStatus; QT_END_NAMESPACE class ThinkPadBattery : public QDialog { Q_OBJECT public: ThinkPadBattery(PowerStatus* powerStatus); public slots: void showMessage(); void updatedTray(); protected: void closeEvent(QCloseEvent *event); private slots: void iconActivated(QSystemTrayIcon::ActivationReason reason); private: void createActions(); void createTrayIcon(); QVector<QIcon> m_icon; QAction* m_quitAction; QSystemTrayIcon* m_trayIcon; QMenu* m_trayIconMenu; PowerStatus* m_powerStatus; }; #endif // THINKPADBATTERY_H <file_sep>#ifndef POWERSTATUS_H #define POWERSTATUS_H #include <QThread> #include <QMutex> #include <QObject> QT_BEGIN_NAMESPACE class QString; class ThinkPadBattery; QT_END_NAMESPACE class PowerStatus : public QThread { Q_OBJECT public: PowerStatus(); void run(); void registerLowBatterySlot(ThinkPadBattery* thinkPad); /* * Return status of battery in percantage */ unsigned int getPercent(); /* * Return remaining charging time in minutes (if is charging) */ unsigned int getCharging(); /* * Return remaining running time in minutes (if battery is used) */ unsigned int getRunning(); bool isCharging(); bool isRunning(); static const QString PERCENT; static const QString CHARGING; static const QString RUNNING; signals: void lowBatteryLevel(); void newBatterLevel(); protected: unsigned int m_percent; unsigned int m_charging; unsigned int m_running; unsigned int m_treshold; bool m_isCharging; bool m_isRunning; ThinkPadBattery* m_listener; unsigned int m_debug; QMutex m_mutex; QString getStat(const QString& stat); }; #endif // POWERSTATUS_H <file_sep>#include "thinkpadbattery.h" #include <QMenu> #include <QAction> #include <QCloseEvent> #include <QApplication> #include "powerstatus.h" ThinkPadBattery::ThinkPadBattery(PowerStatus* powerStatus) : m_powerStatus(powerStatus) { createActions(); createTrayIcon(); connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); m_icon.append(QIcon(":/images/bat_0.gif")); m_icon.append(QIcon(":/images/bat_20.gif")); m_icon.append(QIcon(":/images/bat_40.gif")); m_icon.append(QIcon(":/images/bat_60.gif")); m_icon.append(QIcon(":/images/bat_80.gif")); m_icon.append(QIcon(":/images/bat_100.gif")); m_icon.append(QIcon(":/images/bat_critical.png")); m_trayIcon->show(); // setWindowIcon(icon); // setWindowTitle(tr("ThinkPad Battery Status")); // resize(400, 300); } void ThinkPadBattery::iconActivated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::MiddleClick: showMessage(); break; default: ; } } void ThinkPadBattery::showMessage() { QString title("Battery: "); QString text("Remaning time: "); title.append(QString("%1").arg(m_powerStatus->getPercent())).append("%"); if(m_powerStatus->isCharging()) { title.append(" [charging]"); text.append(QString("%1").arg(m_powerStatus->getCharging())); } else if(m_powerStatus->isRunning()) { text.append(QString("%1").arg(m_powerStatus->getRunning())); } else text.append("Unknown"); m_trayIcon->showMessage( title, text.append(" [min]"), QSystemTrayIcon::Information, 5 * 1000); } void ThinkPadBattery::updatedTray() { const unsigned short CRITICAL_LEVEL = 6; unsigned int percent = m_powerStatus->getPercent(); m_trayIcon->setIcon(m_icon.at(percent > 5 ? percent / 20 : CRITICAL_LEVEL)); m_trayIcon->setToolTip(QString("%1 %").arg(percent)); } void ThinkPadBattery::closeEvent(QCloseEvent *event) { if (m_trayIcon->isVisible()) { hide(); event->ignore(); } } void ThinkPadBattery::createActions() { m_quitAction = new QAction(tr("&Quit"), this); connect(m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void ThinkPadBattery::createTrayIcon() { m_trayIconMenu = new QMenu(this); m_trayIconMenu->addAction(m_quitAction); m_trayIcon = new QSystemTrayIcon(this); m_trayIcon->setContextMenu(m_trayIconMenu); }
6dc41953a7e8507357043edd6106476ae78dc37b
[ "Makefile", "C++" ]
6
C++
edghto/ThinkPadBatteryTray
245270acb41813efb8c439effe0e4cab108c0968
5c4d0111314e961178be4d3a2f212bffaf4d6510