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
<repo_name>bitbybyte/fantiadl<file_sep>/README.md # FantiaDL Download media and other data from Fantia fanclubs and posts. A session cookie must be provided with the -c/--cookie argument directly or by passing the path to a legacy Netscape cookies file. Please see the [About Session Cookies](#about-session-cookies) section. ``` usage: fantiadl.py [options] url positional arguments: url fanclub or post URL options: -h, --help show this help message and exit -c SESSION_COOKIE, --cookie SESSION_COOKIE _session_id cookie or cookies.txt -q, --quiet suppress output -v, --version show program's version number and exit download options: -i, --ignore-errors continue on download errors -l #, --limit # limit the number of posts to process per fanclub (excludes -n) -o OUTPUT_PATH, --output-directory OUTPUT_PATH directory to download to -s, --use-server-filenames download using server defined filenames -r, --mark-incomplete-posts add .incomplete file to post directories that are incomplete -m, --dump-metadata store metadata to file (including fanclub icon, header, and background) -x, --parse-for-external-links parse posts for external links -t, --download-thumbnail download post thumbnails -f, --download-fanclubs download posts from all followed fanclubs -p, --download-paid-fanclubs download posts from all fanclubs backed on a paid plan -n #, --download-new-posts # download a specified number of new posts from your fanclub timeline -d %Y-%m, --download-month %Y-%m download posts only from a specific month, e.g. 2007-08 (excludes -n) --exclude EXCLUDE_FILE file containing a list of filenames to exclude from downloading ``` When parsing for external links using `-x`, a .crawljob file is created in your root directory (either the directory provided with `-o` or the directory the script is being run from) that can be parsed by [JDownloader](http://jdownloader.org/). As posts are parsed, links will be appended and assigned their appropriate post directories for download. You can import this file manually into JDownloader (File -> Load Linkcontainer) or setup the Folder Watch plugin to watch your root directory for .crawljob files. ## About Session Cookies Due to recent changes imposed by Fantia, providing an email and password to login from the command line is no longer supported. In order to login, you will need to provide the `_session_id` cookie for your Fantia login session using -c/--cookie. After logging in normally on your browser, this value can then be extracted and used with FantiaDL. This value expires and may need to be updated with some regularity. ### Mozilla Firefox 1. On https://fantia.jp, press Ctrl + Shift + I to open Developer Tools. 2. Select the Storage tab at the top. In the sidebar, select https://fantia.jp under the Cookies heading. 3. Locate the `_session_id` cookie name. Click on the value to copy it. ### Google Chrome 1. On https://fantia.jp, press Ctrl + Shift + I to open DevTools. 2. Select the Application tab at the top. In the sidebar, expand Cookies under the Storage heading and select https://fantia.jp. 3. Locate the `_session_id` cookie name. Click on the value to copy it. ### Third-Party Extensions (cookies.txt) You also have the option of passing the path to a legacy Netscape format cookies file with -c/--cookie, e.g. `-c ~/cookies.txt`. Using an extension like [cookies.txt](https://chrome.google.com/webstore/detail/cookiestxt/njabckikapfpffapmjgojcnbfjonfjfg), create a text file matching the accepted format: ``` # Netscape HTTP Cookie File # https://curl.haxx.se/rfc/cookie_spec.html # This is a generated file! Do not edit. fantia.jp FALSE / FALSE 1595755239 _session_id a1b2c3d4... ``` Only the `_session_id` cookie is required. ## Download Check the [releases page](https://github.com/bitbybyte/fantiadl/releases/latest) for the latest binaries. ## Build Requirements - Python 3.x - requests - beautifulsoup4 ## Roadmap - More robust logging <file_sep>/fantiadl.py #!/usr/bin/env python # -*- coding: utf-8 -*- """Download media and other data from Fantia""" import argparse import getpass import netrc import sys import traceback import models __author__ = "bitbybyte" __copyright__ = "Copyright 2023 bitbybyte" __license__ = "MIT" __version__ = "1.8.5" BASE_HOST = "fantia.jp" if __name__ == "__main__": cmdl_usage = "%(prog)s [options] url" cmdl_version = __version__ cmdl_parser = argparse.ArgumentParser(usage=cmdl_usage, conflict_handler="resolve") cmdl_parser.add_argument("-c", "--cookie", dest="session_arg", metavar="SESSION_COOKIE", help="_session_id cookie or cookies.txt") cmdl_parser.add_argument("-e", "--email", dest="email", metavar="EMAIL", help=argparse.SUPPRESS) cmdl_parser.add_argument("-p", "--password", dest="password", metavar="PASSWORD", help=argparse.SUPPRESS) cmdl_parser.add_argument("-n", "--netrc", action="store_true", dest="netrc", help=argparse.SUPPRESS) cmdl_parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", help="suppress output") cmdl_parser.add_argument("-v", "--version", action="version", version=cmdl_version) cmdl_parser.add_argument("url", action="store", nargs="*", help="fanclub or post URL") dl_group = cmdl_parser.add_argument_group("download options") dl_group.add_argument("-i", "--ignore-errors", action="store_true", dest="continue_on_error", help="continue on download errors") dl_group.add_argument("-l", "--limit", dest="limit", metavar="#", type=int, default=0, help="limit the number of posts to process per fanclub (excludes -n)") dl_group.add_argument("-o", "--output-directory", dest="output_path", help="directory to download to") dl_group.add_argument("-s", "--use-server-filenames", action="store_true", dest="use_server_filenames", help="download using server defined filenames") dl_group.add_argument("-r", "--mark-incomplete-posts", action="store_true", dest="mark_incomplete_posts", help="add .incomplete file to post directories that are incomplete") dl_group.add_argument("-m", "--dump-metadata", action="store_true", dest="dump_metadata", help="store metadata to file (including fanclub icon, header, and background)") dl_group.add_argument("-x", "--parse-for-external-links", action="store_true", dest="parse_for_external_links", help="parse posts for external links") dl_group.add_argument("-t", "--download-thumbnail", action="store_true", dest="download_thumb", help="download post thumbnails") dl_group.add_argument("-f", "--download-fanclubs", action="store_true", dest="download_fanclubs", help="download posts from all followed fanclubs") dl_group.add_argument("-p", "--download-paid-fanclubs", action="store_true", dest="download_paid_fanclubs", help="download posts from all fanclubs backed on a paid plan") dl_group.add_argument("-n", "--download-new-posts", dest="download_new_posts", metavar="#", type=int, help="download a specified number of new posts from your fanclub timeline") dl_group.add_argument("-d", "--download-month", dest="month_limit", metavar="%Y-%m", help="download posts only from a specific month, e.g. 2007-08 (excludes -n)") dl_group.add_argument("--exclude", dest="exclude_file", metavar="EXCLUDE_FILE", help="file containing a list of filenames to exclude from downloading") cmdl_opts = cmdl_parser.parse_args() session_arg = cmdl_opts.session_arg email = cmdl_opts.email password = cmdl_opts.password if (email or password or cmdl_opts.netrc) and not session_arg: sys.exit("Logging in from the command line is no longer supported. Please provide a session cookie using -c/--cookie. See the README for more information.") if not (cmdl_opts.download_fanclubs or cmdl_opts.download_paid_fanclubs or cmdl_opts.download_new_posts) and not cmdl_opts.url: sys.exit("Error: No valid input provided") if not session_arg: session_arg = input("Fantia session cookie (_session_id or cookies.txt path): ") # if cmdl_opts.netrc: # login = netrc.netrc().authenticators(BASE_HOST) # if login: # email = login[0] # password = <PASSWORD>] # else: # sys.exit("Error: No Fantia login found in .netrc") # else: # if not email: # email = input("Email: ") # if not password: # password = <PASSWORD>("Password: ") try: downloader = models.FantiaDownloader(session_arg=session_arg, dump_metadata=cmdl_opts.dump_metadata, parse_for_external_links=cmdl_opts.parse_for_external_links, download_thumb=cmdl_opts.download_thumb, directory=cmdl_opts.output_path, quiet=cmdl_opts.quiet, continue_on_error=cmdl_opts.continue_on_error, use_server_filenames=cmdl_opts.use_server_filenames, mark_incomplete_posts=cmdl_opts.mark_incomplete_posts, month_limit=cmdl_opts.month_limit, exclude_file=cmdl_opts.exclude_file) if cmdl_opts.download_fanclubs: try: downloader.download_followed_fanclubs(limit=cmdl_opts.limit) except KeyboardInterrupt: raise except: if cmdl_opts.continue_on_error: downloader.output("Encountered an error downloading followed fanclubs. Skipping...\n") traceback.print_exc() pass else: raise elif cmdl_opts.download_paid_fanclubs: try: downloader.download_paid_fanclubs(limit=cmdl_opts.limit) except: if cmdl_opts.continue_on_error: downloader.output("Encountered an error downloading paid fanclubs. Skipping...\n") traceback.print_exc() pass else: raise elif cmdl_opts.download_new_posts: try: downloader.download_new_posts(post_limit=cmdl_opts.download_new_posts) except: if cmdl_opts.continue_on_error: downloader.output("Encountered an error downloading new posts from timeline. Skipping...\n") traceback.print_exc() pass else: raise if cmdl_opts.url: for url in cmdl_opts.url: url_match = models.FANTIA_URL_RE.match(url) if url_match: try: url_groups = url_match.groups() if url_groups[0] == "fanclubs": fanclub = models.FantiaClub(url_groups[1]) downloader.download_fanclub(fanclub, cmdl_opts.limit) elif url_groups[0] == "posts": downloader.download_post(url_groups[1]) except KeyboardInterrupt: raise except: if cmdl_opts.continue_on_error: downloader.output("Encountered an error downloading URL. Skipping...\n") traceback.print_exc() continue else: raise else: sys.stderr.write("Error: {} is not a valid URL. Please provide a fully qualified Fantia URL (https://fantia.jp/posts/[id], https://fantia.jp/fanclubs/[id])\n".format(url)) except KeyboardInterrupt: sys.exit("Interrupted by user. Exiting...") <file_sep>/models.py #!/usr/bin/env python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup from requests.adapters import HTTPAdapter, Retry import requests from datetime import datetime as dt from urllib.parse import unquote from urllib.parse import urljoin from urllib.parse import urlparse import http.cookiejar import json import math import mimetypes import os import re import sys import time import traceback import fantiadl FANTIA_URL_RE = re.compile(r"(?:https?://(?:(?:www\.)?(?:fantia\.jp/(fanclubs|posts)/)))([0-9]+)") EXTERNAL_LINKS_RE = re.compile(r"(?:[\s]+)?((?:(?:https?://)?(?:(?:www\.)?(?:mega\.nz|mediafire\.com|(?:drive|docs)\.google\.com|youtube.com|dropbox.com)\/))[^\s]+)") DOMAIN = "fantia.jp" BASE_URL = "https://fantia.jp/" LOGIN_SIGNIN_URL = "https://fantia.jp/sessions/signin" LOGIN_SESSION_URL = "https://fantia.jp/sessions" ME_API = "https://fantia.jp/api/v1/me" FANCLUB_API = "https://fantia.jp/api/v1/fanclubs/{}" FANCLUBS_FOLLOWING_API = "https://fantia.jp/api/v1/me/fanclubs" FANCLUBS_PAID_HTML = "https://fantia.jp/mypage/users/plans?type=not_free&page={}" FANCLUB_POSTS_HTML = "https://fantia.jp/fanclubs/{}/posts?page={}" POST_API = "https://fantia.jp/api/v1/posts/{}" POST_URL = "https://fantia.jp/posts/{}" POSTS_URL = "https://fantia.jp/posts" POST_RELATIVE_URL = "/posts/" TIMELINES_API = "https://fantia.jp/api/v1/me/timelines/posts?page={}&per=24" USER_AGENT = "fantiadl/{}".format(fantiadl.__version__) CRAWLJOB_FILENAME = "external_links.crawljob" MIMETYPES = { "image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", "video/mp4": ".mp4", "video/webm": ".webm" } UNICODE_CONTROL_MAP = dict.fromkeys(range(32)) class FantiaClub: def __init__(self, fanclub_id): self.id = fanclub_id class FantiaDownloader: def __init__(self, session_arg, chunk_size=1024 * 1024 * 5, dump_metadata=False, parse_for_external_links=False, download_thumb=False, directory=None, quiet=True, continue_on_error=False, use_server_filenames=False, mark_incomplete_posts=False, month_limit=None, exclude_file=None): # self.email = email # self.password = <PASSWORD> self.session_arg = session_arg self.chunk_size = chunk_size self.dump_metadata = dump_metadata self.parse_for_external_links = parse_for_external_links self.download_thumb = download_thumb self.directory = directory or "" self.quiet = quiet self.continue_on_error = continue_on_error self.use_server_filenames = use_server_filenames self.mark_incomplete_posts = mark_incomplete_posts self.month_limit = dt.strptime(month_limit, "%Y-%m") if month_limit else None self.exclude_file = exclude_file self.exclusions = [] self.initialize_session() self.login() self.create_exclusions() def output(self, output): """Write output to the console.""" if not self.quiet: try: sys.stdout.write(output.encode(sys.stdout.encoding, errors="backslashreplace").decode(sys.stdout.encoding)) sys.stdout.flush() except (UnicodeEncodeError, UnicodeDecodeError): sys.stdout.buffer.write(output.encode("utf-8")) sys.stdout.flush() def initialize_session(self): """Initialize session with necessary headers and config.""" self.session = requests.session() self.session.headers.update({"User-Agent": USER_AGENT}) retries = Retry( total=5, connect=5, read=5, status_forcelist=[429, 500, 502, 503, 504, 507, 508], backoff_factor=2, # retry delay = {backoff factor} * (2 ** ({retry number} - 1)) raise_on_status=True ) self.session.mount("http://", HTTPAdapter(max_retries=retries)) self.session.mount("https://", HTTPAdapter(max_retries=retries)) def login(self): """Login to Fantia using the provided email and password.""" try: with open(self.session_arg, "r") as cookies_file: cookies = http.cookiejar.MozillaCookieJar(self.session_arg) cookies.load() self.session.cookies = cookies except FileNotFoundError: login_cookie = requests.cookies.create_cookie(domain=DOMAIN, name="_session_id", value=self.session_arg) self.session.cookies.set_cookie(login_cookie) check_user = self.session.get(ME_API) if not (check_user.ok or check_user.status_code == 304): sys.exit("Error: Invalid session. Please verify your session cookie") # Login flow, requires reCAPTCHA token # login_json = { # "utf8": "✓", # "button": "", # "user[email]": self.email, # "user[password]": <PASSWORD>, # } # login_session = self.session.get(LOGIN_SIGNIN_URL) # login_page = BeautifulSoup(login_session.text, "html.parser") # authenticity_token = login_page.select_one("input[name=\"authenticity_token\"]")["value"] # print(login_page.select_one("input[name=\"recaptcha_response\"]")) # login_json["authenticity_token"] = authenticity_token # login_json["recaptcha_response"] = ... # create_session = self.session.post(LOGIN_SESSION_URL, data=login_json) # if not create_session.headers.get("Location"): # sys.exit("Error: Bad login form data") # elif create_session.headers["Location"] == LOGIN_SIGNIN_URL: # sys.exit("Error: Failed to login. Please verify your username and password") # check_user = self.session.get(ME_API) # if not (check_user.ok or check_user.status_code == 304): # sys.exit("Error: Invalid session") def create_exclusions(self): """Read files to exclude from downloading.""" if self.exclude_file: with open(self.exclude_file, "r") as file: self.exclusions = [line.rstrip("\n") for line in file] def process_content_type(self, url): """Process the Content-Type from a request header and use it to build a filename.""" url_header = self.session.head(url, allow_redirects=True) mimetype = url_header.headers["Content-Type"] extension = guess_extension(mimetype, url) return extension def collect_post_titles(self, post_metadata): """Collect all post titles to check for duplicate names and rename as necessary by appending a counter.""" post_titles = [] for post in post_metadata["post_contents"]: try: potential_title = post["title"] or post["parent_post"]["title"] if not potential_title: potential_title = str(post["id"]) except KeyError: potential_title = str(post["id"]) title = potential_title counter = 2 while title in post_titles: title = potential_title + "_{}".format(counter) counter += 1 post_titles.append(title) return post_titles def download_fanclub_metadata(self, fanclub): """Download fanclub header, icon, and custom background.""" response = self.session.get(FANCLUB_API.format(fanclub.id)) response.raise_for_status() fanclub_json = json.loads(response.text) fanclub_creator = fanclub_json["fanclub"]["creator_name"] fanclub_directory = os.path.join(self.directory, sanitize_for_path(fanclub_creator)) os.makedirs(fanclub_directory, exist_ok=True) self.save_metadata(fanclub_json, fanclub_directory) header_url = fanclub_json["fanclub"]["cover"]["original"] if header_url: header_filename = os.path.join(fanclub_directory, "header" + self.process_content_type(header_url)) self.output("Downloading fanclub header...\n") self.perform_download(header_url, header_filename, use_server_filename=self.use_server_filenames) fanclub_icon_url = fanclub_json["fanclub"]["icon"]["original"] if fanclub_icon_url: fanclub_icon_filename = os.path.join(fanclub_directory, "icon" + self.process_content_type(fanclub_icon_url)) self.output("Downloading fanclub icon...\n") self.perform_download(fanclub_icon_url, fanclub_icon_filename, use_server_filename=self.use_server_filenames) background_url = fanclub_json["fanclub"]["background"] if background_url: background_filename = os.path.join(fanclub_directory, "background" + self.process_content_type(background_url)) self.output("Downloading fanclub background...\n") self.perform_download(background_url, background_filename, use_server_filename=self.use_server_filenames) def download_fanclub(self, fanclub, limit=0): """Download a fanclub.""" self.output("Downloading fanclub {}...\n".format(fanclub.id)) post_ids = self.fetch_fanclub_posts(fanclub) if self.dump_metadata: self.download_fanclub_metadata(fanclub) for post_id in post_ids if limit == 0 else post_ids[:limit]: try: self.download_post(post_id) except KeyboardInterrupt: raise except: if self.continue_on_error: self.output("Encountered an error downloading post. Skipping...\n") traceback.print_exc() continue else: raise def download_followed_fanclubs(self, limit=0): """Download all followed fanclubs.""" response = self.session.get(FANCLUBS_FOLLOWING_API) response.raise_for_status() fanclub_ids = json.loads(response.text)["fanclub_ids"] for fanclub_id in fanclub_ids: try: fanclub = FantiaClub(fanclub_id) self.download_fanclub(fanclub, limit) except KeyboardInterrupt: raise except: if self.continue_on_error: self.output("Encountered an error downloading fanclub. Skipping...\n") traceback.print_exc() continue else: raise def download_paid_fanclubs(self, limit=0): """Download all fanclubs backed on a paid plan.""" all_paid_fanclubs = [] page_number = 1 self.output("Collecting paid fanclubs...\n") while True: response = self.session.get(FANCLUBS_PAID_HTML.format(page_number)) response.raise_for_status() response_page = BeautifulSoup(response.text, "html.parser") fanclub_links = response_page.select("div.mb-5-children > div:nth-of-type(1) a[href^=\"/fanclubs\"]") for fanclub_link in fanclub_links: fanclub_id = fanclub_link["href"].lstrip("/fanclubs/") all_paid_fanclubs.append(fanclub_id) if not fanclub_links: self.output("Collected {} fanclubs.\n".format(len(all_paid_fanclubs))) break else: page_number += 1 for fanclub_id in all_paid_fanclubs: try: fanclub = FantiaClub(fanclub_id) self.download_fanclub(fanclub, limit) except: if self.continue_on_error: self.output("Encountered an error downloading fanclub. Skipping...\n") traceback.print_exc() continue else: raise def download_new_posts(self, post_limit=24): all_new_post_ids = [] total_pages = math.ceil(post_limit / 24) page_number = 1 has_next = True self.output("Downloading {} new posts...\n".format(post_limit)) while has_next and not len(all_new_post_ids) >= post_limit: response = self.session.get(TIMELINES_API.format(page_number)) response.raise_for_status() json_response = json.loads(response.text) posts = json_response["posts"] has_next = json_response["has_next"] for post in posts: if len(all_new_post_ids) >= post_limit: break post_id = post["id"] all_new_post_ids.append(post_id) page_number += 1 for post_id in all_new_post_ids: try: self.download_post(post_id) except KeyboardInterrupt: raise except: if self.continue_on_error: self.output("Encountered an error downloading post. Skipping...\n") traceback.print_exc() continue else: raise def fetch_fanclub_posts(self, fanclub): """Iterate over a fanclub's HTML pages to fetch all post IDs.""" all_posts = [] post_found = False page_number = 1 self.output("Collecting fanclub posts...\n") while True: response = self.session.get(FANCLUB_POSTS_HTML.format(fanclub.id, page_number)) response.raise_for_status() response_page = BeautifulSoup(response.text, "html.parser") posts = response_page.select("div.post") new_post_ids = [] for post in posts: link = post.select_one("a.link-block")["href"] post_id = link.lstrip(POST_RELATIVE_URL) date_string = post.select_one(".post-date .mr-5").text if post.select_one(".post-date .mr-5") else post.select_one(".post-date").text parsed_date = dt.strptime(date_string, "%Y-%m-%d %H:%M") if not self.month_limit or (parsed_date.year == self.month_limit.year and parsed_date.month == self.month_limit.month): post_found = True new_post_ids.append(post_id) all_posts += new_post_ids if not posts or (not new_post_ids and post_found): # No new posts found and we've already collected a post self.output("Collected {} posts.\n".format(len(all_posts))) return all_posts else: page_number += 1 def perform_download(self, url, filepath, use_server_filename=False): """Perform a download for the specified URL while showing progress.""" request = self.session.get(url, stream=True) if request.status_code == 404: self.output("Download URL returned 404. Skipping...\n") return request.raise_for_status() url_path = unquote(request.url.split("?", 1)[0]) server_filename = os.path.basename(url_path) filename = os.path.basename(filepath) if use_server_filename: filepath = os.path.join(os.path.dirname(filepath), server_filename) # Check if filename is in exclusion list if server_filename in self.exclusions: self.output("Server filename in exclusion list (skipping): {}\n".format(server_filename)) return elif filename in self.exclusions: self.output("Filename in exclusion list (skipping): {}\n".format(filename)) return file_size = int(request.headers["Content-Length"]) if os.path.isfile(filepath) and os.stat(filepath).st_size == file_size: self.output("File found (skipping): {}\n".format(filepath)) return self.output("File: {}\n".format(filepath)) base_filename, original_extension = os.path.splitext(filepath) incomplete_filename = base_filename + ".incomplete" downloaded = 0 with open(incomplete_filename, "wb") as file: for chunk in request.iter_content(self.chunk_size): downloaded += len(chunk) file.write(chunk) done = int(25 * downloaded / file_size) percent = int(100 * downloaded / file_size) self.output("\r|{0}{1}| {2}% ".format("\u2588" * done, " " * (25 - done), percent)) self.output("\n") if os.path.exists(filepath): os.remove(filepath) os.rename(incomplete_filename, filepath) modification_time_string = request.headers["Last-Modified"] modification_time = int(dt.strptime(modification_time_string, "%a, %d %b %Y %H:%M:%S %Z").timestamp()) if modification_time: access_time = int(time.time()) os.utime(filepath, times=(access_time, modification_time)) def download_photo(self, photo_url, photo_counter, gallery_directory): """Download a photo to the post's directory.""" extension = self.process_content_type(photo_url) filename = os.path.join(gallery_directory, str(photo_counter) + extension) if gallery_directory else str() self.perform_download(photo_url, filename, use_server_filename=self.use_server_filenames) def download_file(self, download_url, filename, post_directory): """Download a file to the post's directory.""" self.perform_download(download_url, filename, use_server_filename=True) # Force serve filenames to prevent duplicate collision def download_post_content(self, post_json, post_directory, post_title): """Parse the post's content to determine whether to save the content as a photo gallery or file.""" if post_json.get("visible_status") == "visible": if post_json.get("category") == "photo_gallery": photo_gallery = post_json["post_content_photos"] photo_counter = 0 gallery_directory = os.path.join(post_directory, sanitize_for_path(post_title)) os.makedirs(gallery_directory, exist_ok=True) for photo in photo_gallery: photo_url = photo["url"]["original"] self.download_photo(photo_url, photo_counter, gallery_directory) photo_counter += 1 elif post_json.get("category") == "file": filename = os.path.join(post_directory, post_json["filename"]) download_url = urljoin(POSTS_URL, post_json["download_uri"]) self.download_file(download_url, filename, post_directory) elif post_json.get("category") == "embed": if self.parse_for_external_links: # TODO: Check what URLs are allowed as embeds link_as_list = [post_json["embed_url"]] self.output("Adding embedded link {0} to {1}.\n".format(post_json["embed_url"], CRAWLJOB_FILENAME)) build_crawljob(link_as_list, self.directory, post_directory) elif post_json.get("category") == "blog": blog_comment = post_json["comment"] blog_json = json.loads(blog_comment) photo_counter = 0 gallery_directory = os.path.join(post_directory, sanitize_for_path(post_title)) os.makedirs(gallery_directory, exist_ok=True) for op in blog_json["ops"]: if type(op["insert"]) is dict and op["insert"].get("fantiaImage"): photo_url = urljoin(BASE_URL, op["insert"]["fantiaImage"]["original_url"]) self.download_photo(photo_url, photo_counter, gallery_directory) photo_counter += 1 else: self.output("Post content category \"{}\" is not supported. Skipping...\n".format(post_json.get("category"))) if self.parse_for_external_links: post_description = post_json["comment"] or "" self.parse_external_links(post_description, os.path.abspath(post_directory)) else: self.output("Post content not available on current plan. Skipping...\n") def download_thumbnail(self, thumb_url, post_directory): """Download a thumbnail to the post's directory.""" extension = self.process_content_type(thumb_url) filename = os.path.join(post_directory, "thumb" + extension) self.perform_download(thumb_url, filename, use_server_filename=self.use_server_filenames) def download_post(self, post_id): """Download a post to its own directory.""" self.output("Downloading post {}...\n".format(post_id)) post_html_response = self.session.get(POST_URL.format(post_id)) post_html_response.raise_for_status() post_html = BeautifulSoup(post_html_response.text, "html.parser") csrf_token = post_html.select_one("meta[name=\"csrf-token\"]")["content"] response = self.session.get(POST_API.format(post_id), headers={ "X-CSRF-Token": csrf_token, "X-Requested-With": "XMLHttpRequest" }) response.raise_for_status() post_json = json.loads(response.text)["post"] post_id = post_json["id"] post_creator = post_json["fanclub"]["creator_name"] post_title = post_json["title"] post_contents = post_json["post_contents"] post_directory_title = sanitize_for_path(str(post_id)) post_directory = os.path.join(self.directory, sanitize_for_path(post_creator), post_directory_title) os.makedirs(post_directory, exist_ok=True) post_titles = self.collect_post_titles(post_json) if self.dump_metadata: self.save_metadata(post_json, post_directory) if self.mark_incomplete_posts: self.mark_incomplete_post(post_json, post_directory) if self.download_thumb and post_json["thumb"]: self.download_thumbnail(post_json["thumb"]["original"], post_directory) if self.parse_for_external_links: # Main post post_description = post_json["comment"] or "" self.parse_external_links(post_description, os.path.abspath(post_directory)) for post_index, post in enumerate(post_contents): post_title = post_titles[post_index] self.download_post_content(post, post_directory, post_title) if not os.listdir(post_directory): self.output("No content downloaded for post {}. Deleting directory.\n".format(post_id)) os.rmdir(post_directory) def parse_external_links(self, post_description, post_directory): """Parse the post description for external links, e.g. Mega and Google Drive links.""" link_matches = EXTERNAL_LINKS_RE.findall(post_description) if link_matches: self.output("Found {} external link(s) in post. Saving...\n".format(len(link_matches))) build_crawljob(link_matches, self.directory, post_directory) def save_metadata(self, metadata, directory): """Save the metadata for a post to the post's directory.""" filename = os.path.join(directory, "metadata.json") with open(filename, "w") as file: json.dump(metadata, file, sort_keys=True, indent=4) def mark_incomplete_post(self, post_metadata, post_directory): """Mark incomplete posts with a .incomplete file.""" is_incomplete = False incomplete_filename = os.path.join(post_directory, ".incomplete") for post in post_metadata["post_contents"]: if post["visible_status"] != "visible": is_incomplete = True break if is_incomplete: if not os.path.exists(incomplete_filename): open(incomplete_filename, 'a').close() else: if os.path.exists(incomplete_filename): os.remove(incomplete_filename) def guess_extension(mimetype, download_url): """ Guess the file extension from the mimetype or force a specific extension for certain mimetypes. If the mimetype returns no found extension, guess based on the download URL. """ extension = MIMETYPES.get(mimetype) or mimetypes.guess_extension(mimetype, strict=True) if not extension: try: path = urlparse(download_url).path extension = os.path.splitext(path)[1] except IndexError: extension = ".unknown" return extension def sanitize_for_path(value, replace=' '): """Remove potentially illegal characters from a path.""" sanitized = re.sub(r'[<>\"\?\\\/\*:|]', replace, value) sanitized = sanitized.translate(UNICODE_CONTROL_MAP) return re.sub(r'[\s.]+$', '', sanitized) def build_crawljob(links, root_directory, post_directory): """Append to a root .crawljob file with external links gathered from a post.""" filename = os.path.join(root_directory, CRAWLJOB_FILENAME) with open(filename, "a", encoding="utf-8") as file: for link in links: crawl_dict = { "packageName": "Fantia", "text": link, "downloadFolder": post_directory, "enabled": "true", "autoStart": "true", "forcedStart": "true", "autoConfirm": "true", "addOfflineLink": "true", "extractAfterDownload": "false" } for key, value in crawl_dict.items(): file.write(key + "=" + value + "\n") file.write("\n")
0a9a5027e043808d9556a1b88394e1c631276a51
[ "Markdown", "Python" ]
3
Markdown
bitbybyte/fantiadl
f56ed851888f96ade25affefd164fe717f95852a
7b6a40b13b8ce9917432095afcee2dda23d23268
refs/heads/master
<repo_name>x5engine/genetic-beats<file_sep>/generateComponent.sh #!/bin/bash path='./src/components/'${1} continue=false # If no argument provided if [ -z "$1" ] then echo "Provide a component name" else #If the component folder already exists if [ -e $path ]; then echo "Component $1 already exists!" #Prompt the user while true; do read -p "Do you wish to delete the component and make a new one? [y/n]: " yn case $yn in [Yy]* ) rm -rf $path; continue=true; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done fi if [ ! -f $path ] || [ $continue=true ]; then mkdir $path jsPath=$path/$1.js cssPath=$path/$1.css packagePath=$path/package.json jsContent="import React from 'react';\nimport classNames from 'classnames/bind';\nimport withStyles from 'isomorphic-style-loader/lib/withStyles';\nimport s from './${1}.css';\nimport PropTypes from 'prop-types';\n// import cx from 'classnames';\n// let cx = classNames.bind(s);\n\nfunction ${1}() {\n return (\n <div className={s.root}>\n </div>\n );\n}\n\n${1}.propTypes = {};\n\nexport default withStyles(s)(${1});" cssContent="@import '../variables.css';\n\n.root {\n}" packageContent="{\n \"name\": \"${1}\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"main\": \"./${1}.js\"\n}" #echo $jsContent echo -e "$jsContent" > $jsPath echo -e "$cssContent" > $cssPath echo -e "$packageContent" > $packagePath fi fi <file_sep>/src/reducers/beatInfo.js /* eslint-disable import/prefer-default-export */ import { HIDE_WELCOME_INFO } from '../constants'; export const beatInfoObj = { noOfBeats: 8, noOfTicks: 16, welcomeInfoVisible: true, }; export default function beatInfo(state = beatInfoObj, action) { switch (action.type) { case HIDE_WELCOME_INFO: { const newState = Object.assign({}, state); newState.welcomeInfoVisible = false; return newState; } default: return state; } } <file_sep>/src/components/Lines/Lines.js import React from 'react'; import classNames from 'classnames/bind'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import PropTypes from 'prop-types'; import s from './Lines.css'; import { mapRange } from '../../utils'; // import cx from 'classnames'; // let cx = classNames.bind(s); class Lines extends React.Component { static propTypes = { domNodes: PropTypes.array, beatInfo: PropTypes.object, evolutionPairs: PropTypes.array, }; componentDidMount() { this.addFilter(); } // Render or unrender the lines depending on Redux props componentWillReceiveProps(nextProps) { // Only render lines if the domNodes of the boxes and the evolution pairs exists. if (nextProps.domNodes && nextProps.evolutionPairs) this.renderLines(nextProps); // Only unrender lines for the first generation, when we click the reset beats. if (!nextProps.evolutionPairs && nextProps.timeLineIndex === 0) this.unrenderLines(nextProps); } /* Get the center coordinates for a DOM element */ getCenterCoords = (el) => { const coords = {}; coords.x = el.offsetLeft + (el.offsetWidth / 2); coords.y = el.offsetTop + (el.offsetHeight / 2); return coords; }; /* Add lines to the DOM */ addLines = (props) => { const { beatInfo, timeLineIndex, beatList, evolutionPairs } = props; const lines = []; const colors = ['#5C429B', '#81DFEF', '#1D2DBF', '#6D0F3A', '#FFFFFF', '#8FDD76', '#F286B1', '#EDDA54']; if (beatInfo) { for (let j = 0; j < beatInfo.noOfBeats; j++) { let score = 0; if(beatList && evolutionPairs) { const score1 = beatList[evolutionPairs[j].parent1].props.beat.score; const score2 = beatList[evolutionPairs[j].parent2].props.beat.score; score = (score1 + score2) / 2; } const strokeWidth = mapRange(score, 1.5, 5, 1, 8); lines.push(<path id={'line' + timeLineIndex + '' + j} stroke={colors[j]} strokeWidth={strokeWidth} className={s.line} key={'line' + timeLineIndex + '' + j} fill="transparent" />); } } return lines; }; // Doesn't work yet. Should add a glow-effect to the lines. addFilter = () => { const svg = document.getElementById('svg'); if (svg) { const defs = svg.append('defs'); // // Filter for the outside glow // const filter = defs.append('filter').attr('id', 'glow'); // filter.append('feGaussianBlur').attr('stdDeviation', '3.5').attr('result', 'coloredBlur'); // // const feMerge = filter.append('feMerge'); // feMerge.append('feMergeNode').attr('in', 'coloredBlur'); // feMerge.append('feMergeNode').attr('in', 'SourceGraphic'); } } applyGlow = () => { //d3.selectAll(".class-of-elements").style("filter", "url(#glow)"); } /* Reset all lines */ unrenderLines = (props) => { const { beatInfo, timeLineIndex } = props; for (let i = 0; i < beatInfo.noOfBeats; i++) { document.getElementById('line' + timeLineIndex + '' + i).setAttribute('d', 'M0 0 C 0 0, 0 0, 0 0'); } } /* Calculate the x, y-coordinates for the lines and draw them out */ renderLines(props) { const { evolutionPairs, beatInfo, domNodes, timeLineIndex } = props; for (let i = 0; i < beatInfo.noOfBeats; i++) { const parent1 = evolutionPairs[i].parent1; const parent2 = evolutionPairs[i].parent2; const el1 = domNodes[parent1]; const el2 = domNodes[parent2]; const coords1 = this.getCenterCoords(el1); const coords2 = this.getCenterCoords(el2); const sx1 = coords1.x + 300; const sy1 = coords1.y + 150; const sx2 = coords2.x - 200; const sy2 = coords2.y - 150; // Bezier curve coords const d = 'M' + coords1.x + ' ' + coords1.y + ' C ' + sx1 + ' ' + sy1 + ', ' + sx2 + ' ' + sy2 + ', ' + coords2.x + ' ' + coords2.y; document.getElementById('line' + timeLineIndex + '' + i).setAttribute('d', d); } } render() { return ( <div className={s.root}> <svg id="svg"> { this.addLines(this.props) } </svg> </div> ); } } export default withStyles(s)(Lines); <file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import runtime from './runtime'; import beatTimeline from './beatTimeline'; import beatInfo from './beatInfo'; import evolutionPairs from './evolutionPairs'; export default combineReducers({ runtime, beatTimeline, beatInfo, evolutionPairs, }); <file_sep>/src/reducers/evolutionPairs.js import { ADD_NEW_EVOLUTION_PAIRS, RESET_EVOLUTION_PAIRS } from '../constants'; /* Reducer of the selected pairs for each generation made during the genetic algorithm */ export default function evolutionPairs(state = [], action) { switch (action.type) { case ADD_NEW_EVOLUTION_PAIRS: { const newState = state.slice(); newState.push(action.selectedPairs); return newState; } case RESET_EVOLUTION_PAIRS: return []; default: return state; } } <file_sep>/src/components/BeatList/BeatList.js import React from 'react'; import classNames from 'classnames/bind'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import PropTypes from 'prop-types'; import * as ga from './GeneticAlgorithm'; import s from './BeatList.css'; import { initializeBeat, startBeat, stopBeat } from './playBeat'; import Box from '../Box'; import Lines from '../Lines'; const cx = classNames.bind(s); /* Bealist component. Displays a list of beats that can be votable. */ class BeatList extends React.Component { static propTypes = { beats: PropTypes.array, beatInfo: PropTypes.object, scoreBeat: PropTypes.func, addNewPopulation: PropTypes.func, resetBeats: PropTypes.func, timelineIndex: PropTypes.number, storeDomNodes: PropTypes.func, domNodes: PropTypes.array, evolutionPairs: PropTypes.array, }; static defaultProps = { beats: [], beatInfo: {}, scoreBeat: () => {}, addNewPopulation: () => {}, resetBeats: () => {}, timelineIndex: 0, storeDomNodes: () => {}, } /* Populate the array at init */ componentWillMount() { this.setState({ clickedPlay: [], sequences: [], higherGenerationExists: false, scoreZeroExists: false, allInfoActive: false, showArrow: false, }); } /* Require the Tone.js lib and set it to the state. Can only be loaded once * the component did mount, so we set the state here. */ componentDidMount() { const Tone = require('tone'); this.populateBeatArray(this.props); this.setState({ Tone }, () => this.populateSequenceArray(this.props.beats)); } /* Populate the beat array and the sequence array on new props from redux * Don't update the sequence array when the score is changed. */ componentWillReceiveProps(nextProps) { const nextBeats = nextProps.beats; const beats = this.props.beats; // Reset the clickedPlay array this.setState({ clickedPlay: [] }); let scoreIsSame = true; let allScoreZero = true; /* Since setState is asynchronus. When resetting beats, we need to know if higher generations exists to pass to the box component and score component */ let higherGenerationExists = false; // Check if the score has changed for (let i = 0; i < nextBeats.length; i++) { if (!Object.is(nextBeats[i].score, beats[i].score)) scoreIsSame = false; if (nextBeats[i].score !== 0) allScoreZero = false; } /* Only update the sequence array if the score has changed, or when we * have a new population with zero score */ if (!scoreIsSame || allScoreZero) { this.populateSequenceArray(nextProps.beats); } // If we have a beatlist with a higher index than this, update state. // Used to disable the run-button and scorer if (nextProps.timelineIndex !== nextProps.noOfGenerations - 1) { this.setState({ higherGenerationExists: true }); higherGenerationExists = true; } else { this.setState({ higherGenerationExists: false }); higherGenerationExists = false; }; this.populateBeatArray(nextProps, higherGenerationExists); } /* When clicking the beat to play */ onPlayClick(index) { const { Tone, sequences } = this.state; // Update the state with the clicked state of the beat const clickedPlay = this.state.clickedPlay.slice(); clickedPlay[index] = !clickedPlay[index]; this.setState({ clickedPlay }); // Stop all beats first, then play. sequences.forEach((seq, i) => stopBeat(sequences[i])); if (clickedPlay[index]) startBeat(sequences[index]); } /* When clicking the button that runs the genetic algorithm. Check for score * of the beat first. */ onGenesisClick() { const scoreZeroExists = this.props.beats.map(beat => beat.score).includes(0); this.setState({ scoreZeroExists }); // Remove the tooltip after 3 seconds setTimeout(() => {this.setState({scoreZeroExists: false})}, 3000); // Reset the scorer check after new population has been made. if (!scoreZeroExists) ga.newPopulation(this.props, () => { this.setState({scoreZeroExists: false}); // Set a timer for the arrow tooltip if(this.props.timelineIndex === 0) { this.setState({showArrow: true}); setTimeout(() => this.setState({showArrow: false}), 6000); } }); } /* Click on all box refs and display their info */ onBeatInfoClick = () => { let allInfoActiveState = this.state.allInfoActive; this.setState({ allInfoActive: !allInfoActiveState }); allInfoActiveState = this.state.allInfoActive; if (allInfoActiveState) { for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) { this[`box${i}`].hideInfo(); } } else { for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) { this[`box${i}`].showInfo(); } } } /* Initialize sequences and put in the state to be able to play them. */ populateSequenceArray(newBeats) { const sequences = this.state.sequences; for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) { sequences[i] = (initializeBeat(this.state.Tone, newBeats, this.props.beatInfo, i, this.props.timelineIndex)); } this.setState({ sequences }); } /* Populate the beatlist with Box components. Used when updating from redux. */ populateBeatArray(props, higherGenerationExists) { const { beats, scoreBeat, timelineIndex, storeDomNodes, evolutionPairs, beatInfo, noOfGenerations } = props; this.beatList = []; beats.forEach((beat, index) => { this.beatList.push( <Box id={'beat' + timelineIndex + '' + index} beat={beat} index={index} timelineIndex={timelineIndex} scoreBeat={scoreBeat} key={beat.id} onPlayClick={this.onPlayClick.bind(this)} storeDomNodes={storeDomNodes} evolutionPairs={evolutionPairs} onRef={ref => (this[`box${index}`] = ref)} noOfGenerations={noOfGenerations} higherGenerationExists={higherGenerationExists} />); }); } render() { const runButtonClass = cx('runButton', { hidden: this.state.higherGenerationExists }); const overlayClass = cx('overlay', { active: this.state.scoreZeroExists }); const arrowDownTooltipClass = cx('arrowDownTooltip', { active: this.state.showArrow && this.props.timelineIndex === 0 }); return ( <div className={s.root} id="beatList"> { this.beatList } <section className={s.buttons}> <div className={s.flexGrow}> <div className={s.beatInfoButton} onClick={this.onBeatInfoClick.bind(this)} tabIndex={-10} role="button" >i</div> </div> <div className={runButtonClass} onClick={() => this.onGenesisClick()} role="button" tabIndex="-1" >BEAT GENESIS</div> <div className={arrowDownTooltipClass} /> <div className={overlayClass}> Please score all beats <div className={s.triangle} /> </div> </section> <Lines domNodes={this.props.domNodes} beatInfo={this.props.beatInfo} evolutionPairs={this.props.evolutionPairs} timeLineIndex={this.props.timelineIndex} beatList={this.beatList} /> </div> ); } } export default withStyles(s)(BeatList); <file_sep>/src/constants/index.js /* eslint-disable import/prefer-default-export */ export const SET_RUNTIME_VARIABLE = 'SET_RUNTIME_VARIABLE'; export const ADD_NEW_POPULATION = 'ADD_NEW_POPULATION'; export const SCORE_BEAT = 'SCORE_BEAT'; export const RESET_BEATS = 'RESET_BEATS'; export const ADD_NEW_EVOLUTION_PAIRS = 'ADD_NEW_EVOLUTION_PAIRS'; export const RESET_EVOLUTION_PAIRS = 'RESET_EVOLUTION_PAIRS'; export const HIDE_WELCOME_INFO = 'HIDE_WELCOME_INFO'; <file_sep>/src/actions/beats.js /* eslint-disable import/prefer-default-export */ import { ADD_NEW_POPULATION, SCORE_BEAT, UNSCORE_BEAT, RESET_BEATS } from '../constants'; /* Adds a new population, newBeats is an array */ export function addNewPopulation(newBeats) { return { type: ADD_NEW_POPULATION, newBeats, }; } export function scoreBeat(timelineIndex, index, score) { return { type: SCORE_BEAT, timelineIndex, index, score, }; } export function resetBeats() { return { type: RESET_BEATS, }; } <file_sep>/src/components/WelcomeInfo/WelcomeInfo.js import React from 'react'; import classNames from 'classnames/bind'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './WelcomeInfo.css'; import PropTypes from 'prop-types'; const cx = classNames.bind(s); const WelcomeInfo = (props) => { return ( <div className={s.root} id="welcomeInfo"> <div className={s.container}> <div className={s.top}> <h1>THIS IS</h1> <div className={s.logo} /> </div> <div> <div className={s.beats}/> <div className={s.middle}> <div className={s.item}> <h2>1. LISTEN TO BEATS AND SCORE THEM</h2> </div> <div className={s.item}> <h2>2. NEW BEATS WILL BE GENERATED FROM THE BEST ONES</h2> </div> <div className={s.item}> <h2>3. REPEAT STEP 1 AND 2, UNTIL YOU FIND SOMETHING YOU LIKE</h2> </div> </div> </div> <div className={s.bottom}> <div className={s.goButton} onClick={() => props.hideWelcomeInfo()} role="button" tabIndex="-10"> GO! </div> </div> </div> </div> ); } // // <p>This is a tool for creatives to discover new types of musical beats // created with AI.</p> // // <p>What you will be using is a <span>genetic algorithm</span> that takes inspiration // from evolutionary biology to make new generations of beats, the next better // than the previous one.</p> // // <p>By scoring the beats which are given, the algorithm can figure out which // ones that are the best, and create new beats based on their scoring.</p> WelcomeInfo.propTypes = {}; export default withStyles(s)(WelcomeInfo); <file_sep>/src/components/BeatTimeline/BeatTimeline.js import React from 'react'; import { connect } from 'react-redux'; import classNames from 'classnames/bind'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './BeatTimeline.css'; import PropTypes from 'prop-types'; import { addNewPopulation, scoreBeat, resetBeats } from '../../actions/beats'; import { addNewSelectedPairs, resetSelectedPairs } from '../../actions/evolutionPairs'; import { hideWelcomeInfo } from '../../actions/beatInfo'; import BeatList from '../BeatList'; import Timeline from '../Timeline'; import Menu from '../Menu'; import WelcomeInfo from '../WelcomeInfo'; const cx = classNames.bind(s); /* Populate the beatlist with Box components. Used when updating from redux. */ class BeatTimeline extends React.Component { static propTypes = { }; componentWillMount() { this.setState({ domNodesTimeline: [], linesTimeline: [], }); this.storeDomNodes = this.storeDomNodes.bind(this); } componentDidMount() { this.showHideWelcomeInfo(this.props.beatInfo.welcomeInfoVisible); } componentWillReceiveProps(nextProps) { this.showHideWelcomeInfo(nextProps.beatInfo.welcomeInfoVisible); } showHideWelcomeInfo = (welcomeInfoVisible) => { const welcomeInfoDiv = document.getElementById('welcomeInfo'); if (welcomeInfoVisible) welcomeInfoDiv.style.visibility = 'visible'; else welcomeInfoDiv.style.visibility = 'hidden'; } /* Store DOM-nodes of the boxes in the beatlist */ storeDomNodes(domNode, timelineIndex) { const domNodesTimeline = this.state.domNodesTimeline; if (!domNodesTimeline[timelineIndex]) { const domNodes = []; domNodes.push(domNode); domNodesTimeline.push(domNodes); this.setState({ domNodesTimeline }); } else { domNodesTimeline[timelineIndex].push(domNode); this.setState({ domNodesTimeline }); } } storeLines(lines) { this.setState({ lines }); } /* Populate the beat timeline array with beatlist components */ populateTimelineArray() { const { beatTimeline, evolutionPairs } = this.props; const beatTimelineArray = []; beatTimeline.forEach((generation, index) => { beatTimelineArray.push( <BeatList {...this.props} beats={beatTimeline[index]} timelineIndex={index} storeDomNodes={(domNode, timelineIndex) => this.storeDomNodes(domNode, timelineIndex)} domNodes={this.state.domNodesTimeline[index]} noOfGenerations={beatTimeline.length} key={'generation' + index} evolutionPairs={evolutionPairs[index]} />, ); }); return beatTimelineArray; } render() { return ( <div className={s.root}> <WelcomeInfo hideWelcomeInfo={this.props.hideWelcomeInfo} /> <Menu resetSelectedPairs={this.props.resetSelectedPairs} resetBeats={this.props.resetBeats} /> { this.populateTimelineArray() } <Timeline noOfGenerations={this.props.beatTimeline.length} /> </div> ); } } BeatTimeline.propTypes = {}; const mapState = state => ({ beatTimeline: state.beatTimeline, beatInfo: state.beatInfo, evolutionPairs: state.evolutionPairs, }); const mapDispatch = dispatch => ({ scoreBeat: (timelineIndex, index, score) => dispatch(scoreBeat(timelineIndex, index, score)), addNewPopulation: newBeats => dispatch(addNewPopulation(newBeats)), resetBeats: () => {dispatch(resetBeats())}, addNewSelectedPairs: (selectedPairs, timelineIndex) => dispatch(addNewSelectedPairs(selectedPairs, timelineIndex)), resetSelectedPairs: () => dispatch(resetSelectedPairs()), hideWelcomeInfo: () => dispatch(hideWelcomeInfo()), }); export default connect(mapState, mapDispatch)(withStyles(s)(BeatTimeline)); <file_sep>/README.md ![Genetic Beats](genetic-beats-overview2.png) # genetic-beats Genetic Beats is an application for artists, musicians and dj’s who want to create musical beats in a new way. It’s made to be a creative tool that generates ideas to get inspiration from when making music. Under the hood is a genetic algorithm that improves the beats as the user votes for their favorites. ## Requirements * Install the latest LTS version of [Node](https://nodejs.org/en/) on your computer. * Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) on your computer to be able to clone the repository. ## Installation Open your computers terminal and clone this repository to your computer. Type: ```git clone https://github.com/fgrhlt/genetic-beats.git``` Move to the newly cloned repository ```cd genetic-beats``` Install node_modules that are needed to run the application: ```npm install``` Run the application ```npm start``` This will open the application in your browser on port 3000. ## Demo A demo is located on [Heroku](https://genetic-beats.herokuapp.com/) My portfolio is located [Issuu](https://issuu.com/asppp/docs/simonasp-portfolio2018) <file_sep>/src/components/Scorer/Scorer.js import React from 'react'; import classNames from 'classnames/bind'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import PropTypes from 'prop-types'; import s from './Scorer.css'; const cx = classNames.bind(s); const scoreBeatCheck = (props, i) => { const { index, scoreBeat, higherGenerationExists, timelineIndex } = props; if(!higherGenerationExists) { scoreBeat(timelineIndex, index, i + 1); } } /* Scorer function, renders stars that can be clickable */ function Scorer(props) { const { index, beat, scoreBeat, timelineIndex, noOfGenerations, higherGenerationExists } = props; const stars = []; for (let i = 0; i < 5; i++) { const starClass = cx('score', { filled: beat.score >= i + 1, dark: higherGenerationExists, }); stars.push( <div className={starClass} onClick={() => scoreBeatCheck(props, i)} role="button" tabIndex={0} key={i} />); } return ( <div className={s.root}> { stars } </div> ); } Scorer.propTypes = { index: PropTypes.number.isRequired, }; export default withStyles(s)(Scorer); <file_sep>/src/components/BeatList/playBeat.js import { getInstrumentKeys } from '../../utils/utils'; /* Creates an array with ticks */ const createTickArray = (noTicks) => { const tickArray = []; for (let i = 0; i < noTicks; i++) tickArray.push(i); return tickArray; }; /* Function to play beats */ export function initializeBeat(Tone, beats, beatInfo, index, timelineIndex) { const instrumentKeys = getInstrumentKeys(beats[0]); const noTicks = beatInfo.noOfTicks; const tickArray = createTickArray(noTicks); // console.log(Tone.Transport); Tone.Transport.cancel(); const instruments = new Tone.Players({ kick: require('./sounds/kick.wav'), clap: require('./sounds/clap.wav'), closedhat: require('./sounds/closedhat.wav'), openhat: require('./sounds/openhat.wav'), }, { volume: 0, }).toMaster(); Tone.Transport.bpm.value = 106; const colors = ['deeppink', 'blue', 'gold', 'aqua']; let counter = 0; const sequence = new Tone.Sequence((time, tick) => { instrumentKeys.forEach((key) => { if (beats[index][key][tick] === 1) instruments.get(key).start(); }); // Make the boxes glow at certain ticks counter = Math.ceil(tick / 4) - 1; if (tick === 3 || tick === 7 || tick === 11 || tick === 15) { document.getElementById('beat' + timelineIndex + '' + index).style.boxShadow = '0px 0px 26px 1px ' + colors[counter]; } // Remove the glow at certain ticks else if (tick === 1 || tick === 5 || tick === 9 || tick === 13) { document.getElementById('beat' + timelineIndex + '' + index).style.boxShadow = '0px 5px 5px 1px rgba(0,0,0,0.15)'; } }, tickArray, '16n'); sequence.loop = 4; Tone.Transport.start('+0.1'); return sequence; } // Stop the beat export function stopBeat(loop) { loop.stop(); } // Start the beat export function startBeat(loop) { loop.start(); } // document.getElementById('playToggle').addEventListener("click", function(){ // Tone.Transport.start('+0.1'); // });
725bb3a6c33b651ee5e7afe54286d6ccda27f051
[ "JavaScript", "Markdown", "Shell" ]
13
Shell
x5engine/genetic-beats
4258f5ab0af03181eaf645be6bf9532f1602a919
7ad700d3d9f848207a826db255f4af541e643e80
refs/heads/master
<repo_name>prineshkumar/BE<file_sep>/BE.Entities/Employee.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BE.Entities { public class Employee { public int EmployeeID { get; set; } public string EmployeeName { get; set; } public string EmployeeEmail { get; set; } public string EmployeePhoneNumber { get; set; } public DateTime EmployeeDOB { get; set; } public double EmployeeSalary { get; set; } public string EmployeeStatus { get; set; } public Branch BranchDetails { get; set; } public string LoginPassword { get; set; } public Employee() { BranchDetails = new Branch(); } } } <file_sep>/BE.Data/BranchOperations.cs using BE.Entities; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BE.Data { public class BranchOperations : IDisposable { public IEnumerable<Branch> GetBranchDetailsByEmployee(int EmployeeID) { List<Branch> _branchDetails = null; using (DBConnection dbCon = new Data.DBConnection()) { SqlParameter[] sqlParams = new SqlParameter[] { new SqlParameter(parameterName: "EmployeeID", value: EmployeeID) }; DataSet dsBranchDetails = dbCon.ExecuteReader("BE_Get_BranchDetailsbyEmployee", sqlParams); if (dsBranchDetails != null && dsBranchDetails.Tables.Count > 0 && dsBranchDetails.Tables[0].Rows.Count > 0) { _branchDetails = new List<Branch>(); Branch _branch = null; foreach (DataRow drBranch in dsBranchDetails.Tables[0].Rows) { _branch = new Branch(); _branch.BranchID = Convert.ToInt32(drBranch["BranchID"]); _branch.BranchName = Convert.ToString(drBranch["BranchName"]); _branch.City = Convert.ToString(drBranch["City"]); _branch.BranchAddress = Convert.ToString(drBranch["BranchAddress"]); _branch.EmailAddress = Convert.ToString(drBranch["EmailAddress"]); _branch.Gender = Convert.ToString(drBranch["Gender"]); _branch.PhoneNumber = Convert.ToString(drBranch["PhoneNumber"]); _branch.BranchStatus = Convert.ToString(drBranch["BranchStatus"]); _branchDetails.Add(_branch); } } } return _branchDetails; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~BranchOperations() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } } <file_sep>/BE_WebAPI/Controllers/ManagerController.cs using BE.Data; using BE.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace BE_WebAPI.Controllers { [RoutePrefix("api/manager")] public class ManagerController : ApiController { [HttpGet] [Route("GetComplaints/{id}")] public IHttpActionResult GetComplaints(string id) { using (UserOperations _userOperation = new UserOperations()) { IEnumerable<Complaint> _complaintDetails = _userOperation.GetComplaintDetailsByEmployee(Convert.ToInt32(id)); if (_complaintDetails == null || _complaintDetails.Count() == 0) return NotFound(); else return Ok(_complaintDetails); } } } }<file_sep>/BE_WebAPI/Controllers/BranchOpsController.cs using BE.Data; using BE.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web; using System.Web.Http; namespace BE_WebAPI.Controllersid { [RoutePrefix("api/branch")] public class BranchOpsController : ApiController { [HttpGet] [Route("getbranch/{id}")] public IHttpActionResult GetBranchDetails(string id) { IEnumerable<Branch> _lstBranchDetails = null; using (BranchOperations _branchOperation = new BranchOperations()) { _lstBranchDetails = _branchOperation.GetBranchDetailsByEmployee(Convert.ToInt32(id)); } return Ok(_lstBranchDetails); } [Route("addbranch")] [HttpPost] public IHttpActionResult AddNewBranch() { return Ok(""); } [Route("updatebranch")] [HttpPut] public IHttpActionResult UpdateBranch() { return Ok(""); } [Route("addroom")] [HttpPut] public IHttpActionResult AddNewRoom() { return Ok(""); } [Route("updateroom")] [HttpPut] public IHttpActionResult UpdateRoom() { return Ok(""); } [HttpOptions] public void Options() { } } }<file_sep>/BE.Entities/Complaint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BE.Entities { public class Complaint { public int ComplaintID { get; set; } public int TenantID { get; set; } public string ComplaintDescription { get; set; } public DateTime ComplaintRaisedDate { get; set; } public string ComplaintStatus { get; set; } public DateTime ComplaintLastModifiedDate { get; set; } public Tenant TenantDetails { get; set; } public Branch BranchDetails { get; set; } public Complaint() { TenantDetails = new Tenant(); BranchDetails = new Branch(); } } }
94bc74a4068d74aed72553be3b2b4298e5953ccd
[ "C#" ]
5
C#
prineshkumar/BE
f5e80c9e080d0a622d9b396d61398905558de4e6
d47efb132bc34cc9ff5f6e08770c1ed40f61b9a6
refs/heads/master
<repo_name>WildGenie/PictureViewer<file_sep>/PictureViewer/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCvSharp; using OpenCvSharp.Blob; using VideoInputSharp; using System.Diagnostics; using System.Threading; using System.Net.Sockets; using System.Net; using System.Runtime.InteropServices; using System.IO; namespace PictureViewer { public partial class Form1 : Form { //状態を表す定数 const int TRUE = 0; const int FALSE = 1; //上の2つ状態を保持します int ImgSaveFlag = FALSE ; //状態を表す定数 const int STOP = 0; const int START = 1; const int SAVE = 2; // MT3導入動作中 //上の2つ状態を保持します int States = 0; int MT3Status = STOP; //状態を表す定数 const int LOST = 0; const int FISH_DETECT = 1; // Fisheye等他で検出 const int MyDETECT = 2; // 自分で検出 const int PID_TEST = 3; //上の2つ状態を保持します int FishMode = LOST ; int PvMode = LOST; int DarkMode = FALSE; // 時刻基準(BCB互換) DateTime TBASE = new DateTime(1899, 12, 30, 0, 0, 0); // メイン装置光軸座標 int xoa_mes = 320 ; int yoa_mes = 240 ; int roa = 5; //中心マーク長さ int row = 60; //width 半値幅 int roh = 40; //Height 半値幅 double xoad, yoad; int xoa = 334; int yoa = 223; // test double test_start_id = 0; double xoa_test_start = 70; double yoa_test_start = 70; double xoa_test_step = 1; double yoa_test_step = 1; // 観測開始からのフレーム番号 int id = 0; // 検出条件 const int Low_Limit = 40; double gx, gy, max_area; const int MaxFrame = 256; const int WIDTH = 640; const int HEIGHT = 480 ; ImageData imgdata = new ImageData(WIDTH, HEIGHT); CircularBuffer fifo = new CircularBuffer(MaxFrame,WIDTH,HEIGHT); private BackgroundWorker worker; private BackgroundWorker worker_udp; IplImage imgLabel = new IplImage(WIDTH, HEIGHT, CvBlobLib.DepthLabel, 1); CvBlobs blobs = new CvBlobs(); int threshold_blob = 64; // 検出閾値(0-255) double threshold_min_area = 0.25; // 最小エリア閾値(最大値x0.25) CvPoint2D64f max_centroid; uint max_label; CvBlob maxBlob; double distance, distance_min, d_val; FSI_PID_DATA pid_data = new FSI_PID_DATA(); MT_MONITOR_DATA mtmon_data = new MT_MONITOR_DATA(); int mmFsiUdpPortMT3PV = 24404; // MT3PV (受信) int mmFsiUdpPortMT3PVs = 24405; // MT3PVS (送信) int mmFsiUdpPortMTmonitor = 24415; string mmFsiCore_i5 = "192.168.1.211"; int mmFsiUdpPortSpCam = 24410; // SpCam(受信) string mmFsiSC440 = "192.168.1.206"; System.Net.Sockets.UdpClient udpc3 = null; DriveInfo cDrive = new DriveInfo("C"); long diskspace; public Form1() { InitializeComponent(); worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); worker_udp = new BackgroundWorker(); worker_udp.WorkerReportsProgress = true; worker_udp.WorkerSupportsCancellation = true; worker_udp.DoWork += new DoWorkEventHandler(worker_udp_DoWork); worker_udp.ProgressChanged += new ProgressChangedEventHandler(worker_udp_ProgressChanged); Pid_Data_Send_Init(); } private void Form1_Load(object sender, EventArgs e) { this.worker_udp.RunWorkerAsync(); } #region UDP // 別スレッド処理(UDP) private void worker_udp_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bw = (BackgroundWorker)sender; //バインドするローカルポート番号 int localPort = 24404; System.Net.Sockets.UdpClient udpc = null; ; try { udpc = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } //文字コードを指定する System.Text.Encoding enc = System.Text.Encoding.UTF8; //データを送信するリモートホストとポート番号 //string remoteHost = "localhost"; // string remoteHost = "192.168.1.204"; // int remotePort = 24404; //送信するデータを読み込む string sendMsg = "test送信するデータ"; byte[] sendBytes = enc.GetBytes(sendMsg); //リモートホストを指定してデータを送信する // udpc.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); string str; MOTOR_DATA_KV_SP kmd3 = new MOTOR_DATA_KV_SP(); int size = Marshal.SizeOf(kmd3); //データを受信する System.Net.IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, localPort); while (bw.CancellationPending == false) { byte[] rcvBytes = udpc.Receive(ref remoteEP); if (rcvBytes.Length == size) { kmd3 = ToStruct(rcvBytes); if (kmd3.cmd == 1) //mmMove:1 { FishMode = FISH_DETECT; MT3Status = SAVE; this.Invoke(new dlgSetColor(SetTimer), new object[] { timerSaveMainTime, START }); //timerSaveMainTime.Start(); buttonSave_Click(sender, e) ; } else if (kmd3.cmd == 16) //mmLost:16 { FishMode = LOST; //ButtonSaveEnd_Click(sender, e); //匿名デリゲートで表示する this.Invoke(new dlgSetColor(SetTimer), new object[] { timerSaveMainTime, STOP }); this.Invoke(new dlgSetColor(SetTimer), new object[] { timerSavePostTime, START }); //timerSavePostTime.Start(); } else if (kmd3.cmd == 17) //mmMoveEnd:17 { MT3Status = STOP ; } str = "受信したデータ(kmd3):" + kmd3.cmd + ":" + kmd3.t + ":" +kmd3.az + "\n"; this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, str }); bw.ReportProgress(0, kmd3); } else { string rcvMsg = enc.GetString(rcvBytes); str = "受信したデータ:[" +rcvMsg +"]\n" ; this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, str }); } str = "送信元アドレス:{0}/ポート番号:{1}/Size:{2}\n" + remoteEP.Address + "/" + remoteEP.Port + "/" + rcvBytes.Length ; this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, str }); } //UDP接続を終了 udpc.Close(); } //メインスレッドでの処理 private void worker_udp_ProgressChanged(object sender, ProgressChangedEventArgs e) { // 画面表示 if ((id % 1) == 0) { MOTOR_DATA_KV_SP kmd3 = (MOTOR_DATA_KV_SP)e.UserState; string s = string.Format("worker_udp_ProgressChanged:[{0} {1} az:{2} alt:{3}]\n", kmd3.cmd ,kmd3.t,kmd3.az, kmd3.alt); textBox1.AppendText(s); } } static byte[] ToBytes(MOTOR_DATA_KV_SP obj) { int size = Marshal.SizeOf(typeof(MOTOR_DATA_KV_SP)); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(obj, ptr, false); byte[] bytes = new byte[size]; Marshal.Copy(ptr, bytes, 0, size); Marshal.FreeHGlobal(ptr); return bytes; } static byte[] ToBytes(FSI_PID_DATA obj) { int size = Marshal.SizeOf(typeof(FSI_PID_DATA)); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(obj, ptr, false); byte[] bytes = new byte[size]; Marshal.Copy(ptr, bytes, 0, size); Marshal.FreeHGlobal(ptr); return bytes; } public static MOTOR_DATA_KV_SP ToStruct(byte[] bytes) { GCHandle gch = GCHandle.Alloc(bytes, GCHandleType.Pinned); MOTOR_DATA_KV_SP result = (MOTOR_DATA_KV_SP)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(MOTOR_DATA_KV_SP)); gch.Free(); return result; } #endregion #region キャプチャー // 別スレッド処理(キャプチャー) private void worker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bw = (BackgroundWorker)sender; Stopwatch sw = new Stopwatch() ; string str; id = 0; //PID送信用UDP //バインドするローカルポート番号 // FSI_PID_DATA pid_data = new FSI_PID_DATA(); int localPort = mmFsiUdpPortMT3PV; System.Net.Sockets.UdpClient udpc2 = null; ; /* try { udpc2 = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } */ //videoInputオブジェクト const int DeviceID = 0;// 0; // 3 (pro), 4(piccolo) 7(DMK) const int CaptureFps = 30; // 30 int interval = (int)(1000 / CaptureFps/10); const int CaptureWidth = 640; const int CaptureHeight = 480; // 画像保存枚数 int mmFsiPostRec = 60; int save_counter = mmFsiPostRec; using (VideoInput vi = new VideoInput()) { vi.SetIdealFramerate(DeviceID, CaptureFps); vi.SetupDevice(DeviceID, CaptureWidth, CaptureHeight); int width = vi.GetWidth(DeviceID); int height = vi.GetHeight(DeviceID); using (IplImage img = new IplImage(width, height, BitDepth.U8, 3)) using (IplImage img_dark8 = Cv.LoadImage(@"C:\piccolo\MT3V_dark.bmp", LoadMode.GrayScale)) //using (IplImage img_dark = new IplImage(width, height, BitDepth.U8, 3)) using (IplImage img_mono = new IplImage(width, height, BitDepth.U8, 1)) using (IplImage img2 = new IplImage(width, height, BitDepth.U8, 1)) // using (Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb)) using (CvFont font = new CvFont(FontFace.HersheyComplex, 0.45, 0.45)) //using (CvWindow window0 = new CvWindow("FIFO0", WindowMode.AutoSize)) { //this.Size = new Size(width + 12, height + 148); double min_val, max_val; CvPoint min_loc, max_loc; int size = 15 ; int size2x = size/2 ; int size2y = size/2 ; int crop = 20; double sigma = 3; long elapsed0 =0, elapsed1 =0; double framerate0=0, framerate1=0; double alfa_fr=0.99; sw.Start(); while (bw.CancellationPending == false) { if (vi.IsFrameNew(DeviceID)) { DateTime dn = DateTime.Now; //取得時刻 vi.GetPixels(DeviceID, img.ImageData, false, true); // 画面time表示 str = String.Format("Wide ID:{0:D2} ", id) + dn.ToString("yyyyMMdd_HHmmss_fff");// +String.Format(" ({0,000:F2},{1,000:F2}) ({2,000:0},{3,000:0})({4,0:F1})", gx, gy, max_loc.X, max_loc.Y, max_val); img.PutText(str, new CvPoint(10, 475), font, new CvColor(0, 100, 40)); Cv.CvtColor(img, img_mono, ColorConversion.BgrToGray); Cv.Sub(img_mono, img_dark8, imgdata.img); // dark減算 imgdata.id = ++id; imgdata.t = dn; imgdata.ImgSaveFlag = !(ImgSaveFlag != 0); //int->bool変換 if (fifo.Count == MaxFrame - 1) fifo.EraseLast(); fifo.InsertFirst(imgdata); #region 位置検出1 //MinMaxLoc /*// 位置検出 Cv.Smooth(imgdata.img, img2, SmoothType.Gaussian, size, 0, sigma, 0); CvRect rect; if (PvMode == MyDETECT) { rect = new CvRect( (int)(gx+0.5) - size, (int)(gy+0.5) - size, size*2, size*2); Cv.SetImageROI(img2, rect); Cv.MinMaxLoc(img2, out min_val, out max_val, out min_loc, out max_loc, null); Cv.ResetImageROI(img2); max_loc.X += (int)(gx + 0.5) - size; // 基準点が(1,1)のため+1 max_loc.Y += (int)(gy + 0.5) - size; } else { rect = new CvRect(crop, crop, width - (crop + crop), height - (crop + crop)); Cv.SetImageROI(img2, rect); Cv.MinMaxLoc(img2, out min_val, out max_val, out min_loc, out max_loc, null); Cv.ResetImageROI(img2); max_loc.X += crop; // 基準点が(1,1)のため+1 max_loc.Y += crop; } window0.ShowImage(img2); double m00, m10, m01; size2x = size2y = size / 2; if (max_loc.X - size2x < 0) size2x = max_loc.X; if (max_loc.Y - size2y < 0) size2y = max_loc.Y; if (max_loc.X + size2x >= width ) size2x = width -max_loc.X -1; if (max_loc.Y + size2y >= height) size2y = height -max_loc.Y -1; rect = new CvRect(max_loc.X - size2x, max_loc.Y - size2y, size, size); CvMoments moments; Cv.SetImageROI(img2, rect); Cv.Moments(img2, out moments, false); Cv.ResetImageROI(img2); m00 = Cv.GetSpatialMoment(moments, 0, 0); m10 = Cv.GetSpatialMoment(moments, 1, 0); m01 = Cv.GetSpatialMoment(moments, 0, 1); gx = max_loc.X - size2x + m10 / m00; gy = max_loc.Y - size2y + m01 / m00; */ #endregion #region 位置検出2 //Blob Cv.Threshold(imgdata.img, img2, threshold_blob, 255, ThresholdType.Binary); //2ms blobs.Label(img2, imgLabel); //1.4ms max_label = blobs.GreaterBlob(); elapsed1 = sw.ElapsedTicks; //1.3ms if (blobs.Count > 1 && gx >= 0) { uint min_area = (uint)(threshold_min_area * blobs[max_label].Area); blobs.FilterByArea(min_area, uint.MaxValue); //0.001ms // 最適blobの選定(area大 かつ 前回からの距離小) double x = blobs[max_label].Centroid.X; double y = blobs[max_label].Centroid.Y; uint area = blobs[max_label].Area; //CvRect rect; distance_min = ((x - gx) * (x - gx) + (y - gy) * (y - gy)); //Math.Sqrt() foreach (var item in blobs) { //Console.WriteLine("{0} | Centroid:{1} Area:{2}", item.Key, item.Value.Centroid, item.Value.Area); x = item.Value.Centroid.X; y = item.Value.Centroid.Y; //rect = item.Value.Rect; distance = ((x - gx) * (x - gx) + (y - gy) * (y - gy)); //将来はマハラノビス距離 if (distance < distance_min) { d_val = (item.Value.Area) / max_area; if (distance <= 25) //近距離(5pix) { if (d_val >= 0.4)//&& d_val <= 1.2) { max_label = item.Key; distance_min = distance; } } else { if (d_val >= 0.8 && d_val <= 1.5) { max_label = item.Key; distance_min = distance; } } } //w.WriteLine("{0} {1} {2} {3} {4}", dis, dv, i, item.Key, item.Value.Area); } //gx = x; gy = y; max_val = area; } if (max_label > 0) { maxBlob = blobs[max_label]; max_centroid = maxBlob.Centroid; gx = max_centroid.X; gy = max_centroid.Y; max_area = maxBlob.Area; if (this.States == SAVE) { Pid_Data_Send(); timerSavePostTime.Stop(); timerSaveMainTime.Stop(); timerSaveMainTime.Start(); } } else { gx = gy = 0; max_area = 0; } #endregion // 画面表示 str = String.Format("ID:{0:D2} ", id) + dn.ToString("yyyyMMdd_HHmmss_fff") + String.Format(" ({0,000:F2},{1,000:F2}) ({2,000:0},{3,000:0})({4,0:F1})", gx,gy, xoa, yoa, max_area); if (imgdata.ImgSaveFlag) str += " True"; img.PutText(str, new CvPoint(10, 20), font, new CvColor(0, 255, 100)); img.Circle(new CvPoint((int)gx,(int)gy), 10, new CvColor(255, 255, 100)); bw.ReportProgress(0, img); // 処理速度 elapsed0 = sw.ElapsedTicks - elapsed1 ; // 1frameのticks elapsed1 = sw.ElapsedTicks; framerate0 = alfa_fr * framerate1 + (1 - alfa_fr) * (Stopwatch.Frequency / (double)elapsed0); framerate1 = framerate0; str = String.Format("fr time = {0}({1}){2:F1}", sw.Elapsed, id, framerate0); //," ", sw.ElapsedMilliseconds); //匿名デリゲートで現在の時間をラベルに表示する this.Invoke(new dlgSetString(ShowText), new object[] { textBox1, str }); //img.ToBitmap(bitmap); //pictureBox1.Refresh(); } Application.DoEvents(); Thread.Sleep(interval); } this.States = STOP; this.Invoke(new dlgSetColor(SetColor), new object[] { ObsStart, this.States }); this.Invoke(new dlgSetColor(SetColor), new object[] { ObsEndButton, this.States }); vi.StopDevice(DeviceID); //udpc2.Close(); } } } //BCB互換TDatetime値に変換 private double TDateTimeDouble(DateTime t) { TimeSpan ts = t - TBASE ; // BCB 1899/12/30 0:0:0 からの経過日数 return (ts.TotalDays); } //現在の時刻の表示と、タイマーの表示に使用されるデリゲート delegate void dlgSetString(object lbl, string text); //ボタンのカラー変更に使用されるデリゲート delegate void dlgSetColor(object lbl, int state); //デリゲートで別スレッドから呼ばれてラベルに現在の時間又は //ストップウオッチの時間を表示する private void ShowRText(object sender, string str) { RichTextBox rtb = (RichTextBox)sender; //objectをキャストする rtb.AppendText(str); } private void ShowText(object sender, string str) { TextBox rtb = (TextBox)sender; //objectをキャストする rtb.Text = str; } private void SetColor(object sender, int sta) { Button rtb = (Button)sender; //objectをキャストする if (sta == START) { rtb.BackColor = Color.Red; } else if (sta == STOP) { rtb.BackColor = Color.FromKnownColor(KnownColor.Control); } } private void SetTimer(object sender, int sta) { System.Windows.Forms.Timer tim = (System.Windows.Forms.Timer)sender; //objectをキャストする if (sta == START) { tim.Start(); } else if (sta == STOP) { tim.Stop(); } } private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // 画面表示 if ((id % 1) == 0) { IplImage image = (IplImage)e.UserState; //Cv.Circle(image, new CvPoint(xoa, yoa), roa, new CvColor(0, 255, 0)); Cv.Rectangle(image, new CvRect(xoa-row, yoa-roh,row+row,roh+roh), new CvColor(0, 255, 0)); Cv.Line( image, new CvPoint(xoa + roa, yoa + roa), new CvPoint(xoa - roa, yoa - roa), new CvColor(0, 255, 0)); Cv.Line( image, new CvPoint(xoa - roa, yoa + roa), new CvPoint(xoa + roa, yoa - roa), new CvColor(0, 255, 0)); pictureBox1.Image = image.ToBitmap(); } } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { MessageBox.Show(e.Error.Message); } else if (e.Cancelled) { // Next, handle the case where the user canceled // the operation. // Note that due to a race condition in // the DoWork event handler, the Cancelled // flag may not have been set, even though // CancelAsync was called. this.ObsStart.BackColor = Color.FromKnownColor(KnownColor.Control); this.ObsEndButton.BackColor = Color.FromKnownColor(KnownColor.Control); } this.States = STOP; } #endregion private void Form1_FormClosing(object sender, FormClosingEventArgs e) { } private void ShowButton_Click(object sender, EventArgs e) { /* if (openFileDialog1.ShowDialog() == DialogResult.OK) { pictureBox1.Load(openFileDialog1.FileName); } */ Pid_Data_Send(); return; //testルーチン double gx = 1; double gy = 2; //PID送信用UDP //バインドするローカルポート番号 FSI_PID_DATA pid_data = new FSI_PID_DATA(); int localPort = 24407; System.Net.Sockets.UdpClient udpc3 = null; ; try { udpc3 = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } //データを送信するリモートホストとポート番号 string remoteHost = "192.168.1.206"; int remotePort = 24410; //送信するデータを読み込む ++(pid_data.id); pid_data.swid = 24402; // 仮 mmFsiUdpPortFSI2 pid_data.t = TDateTimeDouble(DateTime.Now); pid_data.dx = (float)(gx); pid_data.dy = (float)(gy); pid_data.vmax = 123 ; byte[] sendBytes = ToBytes(pid_data); //リモートホストを指定してデータを送信する udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); if (udpc3 != null) udpc3.Close(); } private void CloseButton_Click(object sender, EventArgs e) { this.Close(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { /* if (checkBox1.Checked) pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; else pictureBox1.SizeMode = PictureBoxSizeMode.Normal; */ } private void ObsEndButton_Click(object sender, EventArgs e) { // BackgroundWorkerを停止. if (worker.IsBusy) { this.worker.CancelAsync(); this.ObsEndButton.BackColor = Color.Red; } } private void ObsStart_Click(object sender, EventArgs e) { // BackgroundWorkerを開始 if (!worker.IsBusy) { this.worker.RunWorkerAsync(); this.ObsStart.BackColor = Color.Red; this.States = START; } } private void buttonSave_Click(object sender, EventArgs e) { ImgSaveFlag = TRUE; this.buttonSave.BackColor = Color.Red; } private void ButtonSaveEnd_Click(object sender, EventArgs e) { ImgSaveFlag = FALSE; this.buttonSave.BackColor = Color.FromKnownColor(KnownColor.Control); } private void timerSavePostTime_Tick(object sender, EventArgs e) { timerSaveMainTime.Stop(); timerSavePostTime.Stop(); ButtonSaveEnd_Click(sender, e); } private void timerSaveMainTime_Tick(object sender, EventArgs e) { timerSaveMainTime.Stop(); timerSavePostTime.Start(); } private void buttonMakeDark_Click(object sender, EventArgs e) { if (checkBox1.Checked) { checkBox1.Checked = false; DarkMode = TRUE; timerMakeDark.Enabled = true; } } private void timerMakeDark_Tick(object sender, EventArgs e) { timerMakeDark.Enabled = false; DarkMode = FALSE; } private void timerObsOnOff_Tick(object sender, EventArgs e) { TimeSpan nowtime = DateTime.Now - DateTime.Today; TimeSpan endtime = new TimeSpan( 7, 0, 0); TimeSpan starttime = new TimeSpan(17, 0, 0); if (nowtime.CompareTo(endtime) >= 0 && nowtime.CompareTo(starttime) <= 0) { // DayTime if (this.States == START && checkBoxObsAuto.Checked) { ObsEndButton_Click(sender, e); } } else { //NightTime if (this.States == STOP && checkBoxObsAuto.Checked) { ObsStart_Click(sender, e); } } } // PID data送信ルーチン private void Pid_Data_Send_Init() { //PID送信用UDP //バインドするローカルポート番号 //FSI_PID_DATA pid_data = new FSI_PID_DATA(); int localPort = mmFsiUdpPortMT3PVs; // 24405 mmFsiUdpPortMT3PVs //System.Net.Sockets.UdpClient udpc3 = null ; try { udpc3 = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } } // PID data送信ルーチン private void Pid_Data_Send() { // PID data send for UDP //データを送信するリモートホストとポート番号 string remoteHost = mmFsiSC440; int remotePort = mmFsiUdpPortSpCam; // KV1000SpCam //送信するデータを読み込む ++(pid_data.id); //pid_data.swid = (ushort)mmFsiUdpPortMT3IDS2s;// 24417; //mmFsiUdpPortMT3WideS pid_data.swid = (ushort)id;// mmFsiUdpPortMT3IDS2s;// 24417; //mmFsiUdpPortMT3WideS pid_data.t =TDateTimeDouble(DateTime.Now); //TDateTimeDouble(imageInfo.TimestampSystem); //LiveStartTime.AddSeconds(CurrentBuffer.SampleEndTime));//(DateTime.Now); if (PvMode == PID_TEST) { xoad = xoa_test_start + xoa_test_step * (pid_data.id - test_start_id); yoad = yoa_test_start + yoa_test_step * (pid_data.id - test_start_id); } else { xoad = xoa_mes; yoad = yoa_mes; } pid_data.dx = (float)(gx - xoad); pid_data.dy = (float)(gy - yoad); pid_data.vmax = (ushort)(max_area); byte[] sendBytes = ToBytes(pid_data); try { //リモートホストを指定してデータを送信する udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } } /// <summary> /// MTmon status 送信ルーチン /// </summary> /// <remarks> /// MTmon status send /// </remarks> private void MTmon_Data_Send(object sender) { // MTmon status for UDP //データを送信するリモートホストとポート番号 string remoteHost = mmFsiCore_i5; int remotePort = mmFsiUdpPortMTmonitor; //送信するデータを読み込む mtmon_data.id = 6; //PictureViewer mtmon_data.diskspace = (int)(diskspace / (1024 * 1024 * 1024)); mtmon_data.obs = (byte)this.States; //mtmon_data.obs = this.States ; byte[] sendBytes = ToBytes(mtmon_data); try { //リモートホストを指定してデータを送信する udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } } static byte[] ToBytes(MT_MONITOR_DATA obj) { int size = Marshal.SizeOf(typeof(MT_MONITOR_DATA)); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(obj, ptr, false); byte[] bytes = new byte[size]; Marshal.Copy(ptr, bytes, 0, size); Marshal.FreeHGlobal(ptr); return bytes; } private void timerMTmonSend_Tick(object sender, EventArgs e) { MTmon_Data_Send(sender); } private void timer1min_Tick(object sender, EventArgs e) { diskspace = cDrive.TotalFreeSpace; } } }
20fd501a3206327ea07c392d4b50656922b2e568
[ "C#" ]
1
C#
WildGenie/PictureViewer
6c0185908c137574080220ed8557ae1cf949410c
cf0eb0b510fffe748017b05b0efa3b8353a45200
refs/heads/master
<file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/Biblioteca.cpp" "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/cmake-build-debug/CMakeFiles/Agregacion_y_Herencia.dir/Biblioteca.cpp.o" "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/Biblioteca_test.cpp" "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/cmake-build-debug/CMakeFiles/Agregacion_y_Herencia.dir/Biblioteca_test.cpp.o" "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/main.cpp" "/home/ariana/UTEC/POO 2/CLASES/Clase_5/agregacion-y-herencia-ArianaVillegas/Agregacion_y_Herencia/cmake-build-debug/CMakeFiles/Agregacion_y_Herencia.dir/main.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>// // Created by ariana on 3/05/19. // #include "catch.hpp" #include "Biblioteca.h" SCENARIO("BIBLIOTECA"){ GIVEN("Existen 3 libros y 3 revistas"){ WHEN("Incluir 3 libros y 3 revistas dentro de la librería"){ Biblioteca b; b.incluir('L',"El anticristo"); b.incluir('R',"Hola"); b.incluir('R',"Caretas"); b.incluir('L',"Así habló Saratustra"); b.incluir('R',"Nature"); b.incluir('L',"Más allá del bien y del mal"); THEN("Comprobar que la biblioteca tenga 6 volumenes"){ REQUIRE(b.tamano()==6); } } } }<file_sep>// // Created by ariana on 3/05/19. // #include <iostream> #include "Biblioteca.h" void Libro::mostrar() { std::cout<<"\nVolumen #"<<num_volumen<<": Libro #"<<num_libro<<" Título: \""<<nombre<<'\"'; } void Revista::mostrar() { std::cout<<"\nVolumen #"<<num_volumen<<": Revista #"<<num_revista<<" Título: \""<<nombre<<'\"'; } Biblioteca::Biblioteca() { numLibro=0; numRevista=0; } void Biblioteca::mostrarBiblioteca() { for (int i=0; i<numLibro+numRevista; i++){ biblioteca[i]->mostrar(); } } void Biblioteca::incluir(char tipo, std::string nombre) { switch (tipo){ case 'L':{ numLibro++; Libro* l=new Libro(numLibro,numRevista+numLibro,nombre); biblioteca.push_back(l); break; } case 'R':{ numRevista++; Revista* r=new Revista(numRevista,numRevista+numLibro,nombre); biblioteca.push_back(r); break; } } } Biblioteca::~Biblioteca() { biblioteca.clear(); }<file_sep>file(REMOVE_RECURSE "CMakeFiles/Agregacion_y_Herencia.dir/main.cpp.o" "CMakeFiles/Agregacion_y_Herencia.dir/Biblioteca.cpp.o" "CMakeFiles/Agregacion_y_Herencia.dir/Biblioteca_test.cpp.o" "Agregacion_y_Herencia.pdb" "Agregacion_y_Herencia" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Agregacion_y_Herencia.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>cmake_minimum_required(VERSION 3.13) project(Agregacion_y_Herencia) set(CMAKE_CXX_STANDARD 14) add_executable(Agregacion_y_Herencia main.cpp Biblioteca.cpp Biblioteca.h Biblioteca_test.cpp)<file_sep>// // Created by ariana on 3/05/19. // #ifndef AGREGACION_Y_HERENCIA_BIBLIOTECA_H #define AGREGACION_Y_HERENCIA_BIBLIOTECA_H #include <string> #include <vector> class Volumen{ protected: int num_volumen; std::string nombre; public: Volumen(int num_volumen,std::string nombre):num_volumen(num_volumen),nombre(nombre){} virtual void mostrar()=0; }; class Libro:public Volumen{ int num_libro; public: Libro(int num_libro,int num_volumen,std::string nombre):Volumen(num_volumen, nombre),num_libro(num_libro){}; void mostrar()override; }; class Revista:public Volumen{ int num_revista; public: Revista(int num_revista,int num_volumen,std::string nombre):Volumen(num_volumen, nombre),num_revista(num_revista){}; void mostrar()override; }; class Biblioteca{ std::vector <Volumen*> biblioteca; int numLibro; int numRevista; public: Biblioteca(); void mostrarBiblioteca(); int tamano(){ return numLibro+numRevista;}; void incluir(char tipo, std::string nombre); ~Biblioteca(); }; #endif //AGREGACION_Y_HERENCIA_BIBLIOTECA_H <file_sep>#include <iostream> #include "Biblioteca.h" #define CATCH_CONFIG_MAIN #include "catch.hpp" #ifndef CATCH_CONFIG_MAIN int main() { Biblioteca b; b.incluir('L',"El anticristo"); b.incluir('R',"Hola"); b.incluir('R',"Caretas"); b.incluir('L',"Así habló Saratustra"); b.mostrarBiblioteca(); return 0; } #endif
c2975a22fa5c304cef24a8731eb5b16b70d196c0
[ "CMake", "C++" ]
7
CMake
utec-cs1103-2019-01/agregacion-y-herencia-ArianaVillegas
ca4586b4f001642989dfc4420e19a62ab327a3b0
18b6cc34c70cf521af326dea4c072f3e5a99e760
refs/heads/main
<repo_name>johnhorsema/flatend-quickstart<file_sep>/index.js const { Node } = require("flatend"); const main = async () => { const node = await Node.start({ addrs: [`0.0.0.0:9000`], services: { index: (ctx) => ctx.json({root: true}), }, }); } main().catch(err => console.error(err)); <file_sep>/config.toml addr = "127.0.0.1:9000" [[http]] https = false addr = ":8080" [http.max] header_size = 1048576 body_size = 1048576 [[http.routes]] path = "GET /" service = "index"
7c599a512084ff8021178bd8a77adbd1e2b2634a
[ "JavaScript", "TOML" ]
2
JavaScript
johnhorsema/flatend-quickstart
d92201e2c254866970f4e268a4e1412c5c6cbcd6
9c62728dd27c3762ef8ad252b35f1bbadf4067d2
refs/heads/master
<repo_name>leoliuasia/pokedex<file_sep>/pokedex/Pokemon.swift // // Pokemon.swift // pokedex // // Created by Leo on 15/12/22. // Copyright © 2015年 LeoLiu. All rights reserved. // import Foundation class Pokemon { private var _name: String! private var _pokedexId: Int! var name: String { return _name } var pokedexId: Int { return _pokedexId } init(name: String, pokedexId: Int) { self._name = name self._pokedexId = pokedexId } } <file_sep>/pokedex/ViewController.swift // // ViewController.swift // pokedex // // Created by Leo on 15/12/22. // Copyright © 2015年 LeoLiu. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Collection View DataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 718 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PokemonCell", forIndexPath: indexPath) as? PokemonCell { cell.configureCell(Pokemon(name: "\(indexPath.row+1)", pokedexId: indexPath.row + 1)) return cell } else { let cell = PokemonCell() cell.configureCell(Pokemon(name: "\(indexPath.row+1)", pokedexId: indexPath.row + 1)) return cell } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSizeMake(105, 105) } } <file_sep>/pokedex/PokemonCell.swift // // PokemonCell.swift // pokedex // // Created by Leo on 15/12/22. // Copyright © 2015年 LeoLiu. All rights reserved. // import UIKit class PokemonCell: UICollectionViewCell { @IBOutlet weak var thumbImg: UIImageView! @IBOutlet weak var nameLbl: UILabel! var pokemon: Pokemon! override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 5.0 self.clipsToBounds = true } func configureCell(pokemon: Pokemon) { self.pokemon = pokemon self.thumbImg.image = UIImage(named: "\(self.pokemon.pokedexId)") self.nameLbl.text = self.pokemon.name } }
ea12b3ceabbec0f08e0446f4a2b04267c09b738f
[ "Swift" ]
3
Swift
leoliuasia/pokedex
90013343982897120769eb59e39c29e8233a0046
64a0ffc4a8a4d678a72dd201e6bf2a5ec026db09
refs/heads/master
<file_sep>import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) throws IOException { // write your code here if(args.length==0){ System.out.println("Please provide input filname"); return; } HashMap<Character,Integer> hm = new HashMap<Character, Integer>(); File inputFile = new File(args[0]); FileReader fr = new FileReader(inputFile); int i; while ((i=fr.read())!=-1){ Character c = (char)i; if(hm.containsKey(c)){ hm.put(c,hm.get(c)+1); } else{ hm.put(c,1); } } FileWriter outputFile = new FileWriter("result.txt"); for (Map.Entry<Character,Integer> e: hm.entrySet()){ System.out.println(String.valueOf(e.getKey())+" "+ String.valueOf(e.getValue())); outputFile.write(String.valueOf(e.getKey())+" "+ String.valueOf(e.getValue())+"\n"); } outputFile.close(); } }
44f52da495148910cc44545f11f35b84c369355c
[ "Java" ]
1
Java
Srujana-K/File-IO-Assignment
4742369d1d71e56b16b24e52ce6bab5c53622037
83a24f04ff482eb0c711821c282eff4a55ee6188
refs/heads/master
<repo_name>blacksun1/hapi-fan-club<file_sep>/server/api/index.js 'use strict'; exports.plugin = { pkg: require('./package.json'), register: function (server, options) { server.route({ method: 'GET', path: '/', handler: function (request, h) { return { message: 'Welcome to the plot device.' }; } }); } }; <file_sep>/server/proxytest/index.js 'use strict'; exports.plugin = { pkg: require('./package.json'), register: function (server, options) { server.route({ method: 'GET', path: '/testproxy', handler: async function (requiest, h) { return await h.proxy({ uri: 'https://www.blacksun.cx/' }); } }); } }; <file_sep>/test/server/api/index.js 'use strict'; const Lab = require('@hapi/lab'); const Code = require('@hapi/code'); const Config = require('../../../config'); const Hapi = require('@hapi/hapi'); const IndexPlugin = require('../../../server/api/index'); const lab = exports.lab = Lab.script(); let request; let server; lab.beforeEach(async () => { const plugins = [IndexPlugin]; server = Hapi.Server({ port: Config.get('/port/ ') }); return await server.register(plugins); }); lab.experiment('Index Plugin', () => { lab.beforeEach(() => { request = { method: 'GET', url: '/' }; }); lab.test('it returns the default message', () => { return; server.inject(request, (response) => { Code.expect(response.result.message).to.match(/welcome to the plot device/i); Code.expect(response.statusCode).to.equal(200); }); }); }); <file_sep>/manifest.js 'use strict'; const Confidence = require('confidence'); const Config = require('./config'); const criteria = { env: process.env.NODE_ENV }; const manifest = { $meta: 'This file defines the plot device.', server: { routes: { security: true }, debug: { request: ['error'] }, port: Config.get('/port/api') }, register: { plugins: [ { plugin: './server/api/index' }, { plugin: './server/proxytest/index' }, { plugin: '@hapi/h2o2' }, { plugin: '@hapi/good', options: { ops: { interval: 30000 }, reporters: { console: [ { module: '@hapi/good-squeeze', name: 'Squeeze', args: [{ log: '*', response: '*', ops: '*' }] }, { module: '@hapi/good-console' }, 'stdout' ] } } } ] } }; const store = new Confidence.Store(manifest); exports.get = function (key) { return store.get(key, criteria); }; exports.meta = function (key) { return store.meta(key, criteria); }; <file_sep>/README.md # hapi-fan-club Just an example of using HAPI with [Glue](https://www.npmjs.com/package/glue) and [Confidence](https://www.npmjs.com/package/confidence). Mostly based on a [yo](http://yeoman.io/) template called [Hapi Style](https://github.com/jedireza/generator-hapi-style). Now upgraded to use the latest version of everything Hapi. ## Usage ```bash $ npm test $ npm start ``` ## License MIT <file_sep>/.eslintrc.js 'use strict'; module.exports = { extends: require.resolve('@hapi/eslint-config-hapi'), parserOptions: { loc: true, comment: true, range: true, ecmaVersion: 2019 } }; <file_sep>/server.js 'use strict'; const Composer = require('./index'); const main = async () => { try { const server = await Composer(); await server.start(); console.log('Started the plot device on port ' + server.info.port); } catch (err) { console.error('Application has crashed and burned'); console.error(err); process.exit(); } }; main();
e03494ecaaeab72933d65c519382fa70d404e37c
[ "JavaScript", "Markdown" ]
7
JavaScript
blacksun1/hapi-fan-club
650b25cec1e68af921b27ae1ce9873b410fcbb4c
b87b13a5e6bd05f2abff959f7862346378b19910
refs/heads/master
<file_sep>package yitgogo.consumer.suning.ui; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.main.ui.MainActivity; import yitgogo.consumer.suning.model.GetNewSignature; import yitgogo.consumer.suning.model.ModelProductClass; import yitgogo.consumer.suning.model.SuningManager; import yitgogo.consumer.tools.API; import yitgogo.consumer.view.Notify; /** * Created by Tiger on 2015-10-21. */ public abstract class SuningClassesFragment extends BaseNotifyFragment { private SwipeRefreshLayout refreshLayout; private ListView listView; private List<ModelProductClass> productClasses; private ProductClassAdapter productClassAdapter; private ModelProductClass selectedProductClass = new ModelProductClass(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_suning_classes); init(); findViews(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(SuningClassesFragment.class.getName()); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(SuningClassesFragment.class.getName()); if (productClasses.isEmpty()) { if (!TextUtils.isEmpty(SuningManager.getSuningAreas().getTown().getCode())) { new GetClasses().execute(); } else { MainActivity.switchTab(0); } } } private void init() { productClasses = new ArrayList<>(); productClassAdapter = new ProductClassAdapter(); } @Override protected void findViews() { refreshLayout = (SwipeRefreshLayout) contentView.findViewById(R.id.suning_classes_refresh); listView = (ListView) contentView.findViewById(R.id.suning_classes); initViews(); registerViews(); } @Override protected void initViews() { listView.setAdapter(productClassAdapter); } @Override protected void registerViews() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { select(productClasses.get(i)); } }); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new GetClasses().execute(); } }); } private void select(ModelProductClass productClass) { selectedProductClass = productClass; productClassAdapter.notifyDataSetChanged(); onClassSelected(selectedProductClass); } public abstract void onClassSelected(ModelProductClass selectedProductClass); class GetClasses extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); productClasses.clear(); productClassAdapter.notifyDataSetChanged(); } @Override protected String doInBackground(Void... params) { JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); return netUtil.postWithoutCookie(API.API_SUNING_PRODUCT_CALSSES, nameValuePairs, true, true); } @Override protected void onPostExecute(String s) { hideLoading(); refreshLayout.setRefreshing(false); if (SuningManager.isSignatureOutOfDate(s)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetClasses().execute(); } } }; getNewSignature.execute(); return; } if (!TextUtils.isEmpty(s)) { try { JSONObject object = new JSONObject(s); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("result"); if (array != null) { for (int i = 0; i < array.length(); i++) { productClasses.add(new ModelProductClass(array.optJSONObject(i))); } if (!productClasses.isEmpty()) { select(productClasses.get(0)); } } return; } Notify.show(object.optString("returnMsg")); } catch (JSONException e) { e.printStackTrace(); } } } } class ProductClassAdapter extends BaseAdapter { @Override public int getCount() { return productClasses.size(); } @Override public Object getItem(int position) { return productClasses.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_local_business_class, null); viewHolder.selector = convertView .findViewById(R.id.local_business_class_selector); viewHolder.className = (TextView) convertView .findViewById(R.id.local_business_class_name); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.className.setText(productClasses.get(position).getName()); if (productClasses.get(position).getCategoryId().equals(selectedProductClass.getCategoryId())) { viewHolder.selector .setBackgroundResource(R.color.textColorCompany); viewHolder.className.setTextColor(getResources() .getColor(R.color.textColorCompany)); } else { viewHolder.selector.setBackgroundResource(android.R.color.transparent); viewHolder.className.setTextColor(getResources() .getColor(R.color.textColorSecond)); } return convertView; } class ViewHolder { TextView className; View selector; } } } <file_sep>package yitgogo.consumer.tools; import android.content.Context; import com.squareup.okhttp.ConnectionPool; import com.squareup.okhttp.OkHttpClient; import java.util.concurrent.TimeUnit; /** * Created by Tiger on 2015-11-13. */ public class MissionController { private static OkHttpClient okHttpClient; // private static Map<Context, List<Call>> calls = Collections // .synchronizedMap(new WeakHashMap<Context, List<Call>>()); public static void init(Context context) { okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(5, TimeUnit.SECONDS); okHttpClient.setWriteTimeout(5, TimeUnit.SECONDS); okHttpClient.setReadTimeout(5, TimeUnit.SECONDS); okHttpClient.setConnectionPool(new ConnectionPool(5, 15 * 1000)); } public static void cancelNetworkMission(Context context) { okHttpClient.cancel(context); } public static OkHttpClient getOkHttpClient() { return okHttpClient; } // private static void syncCalls(Context context, Call call) { // List<Call> contextCalls = new ArrayList<>(); // synchronized (calls) { // contextCalls = calls.get(context); // if (contextCalls == null) { // contextCalls = Collections // .synchronizedList(new LinkedList<Call>()); // calls.put(context, contextCalls); // } // } // contextCalls.add(call); // Iterator<Call> iterator = contextCalls.iterator(); // while (iterator.hasNext()) { // if (iterator.next().isCanceled()) { // iterator.remove(); // } // } // } // // public static void cancelMissions(Context context) { // List<Call> contextCalls = new ArrayList<>(); // if (calls.containsKey(context)) { // contextCalls = calls.get(context); // calls.remove(context); // if (contextCalls != null) { // for (Call call : contextCalls) { // if (call != null) { // if (!call.isCanceled()) { // call.cancel(); // } // } // } // } // } // } } <file_sep>package yitgogo.consumer.order.ui; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.Notify; public class PlatformProductBuyFragment extends BaseNotifyFragment { ImageView imageView; TextView providerTextView, nameTextView, attrTextView, countTextView, priceTextView, freightTextView; FrameLayout addressLayout, paymentLayout; TextView totalMoneyTextView, confirmButton; String supplierId = ""; String supplierName = ""; String productId = ""; String productNumber = ""; String productAttr = ""; String name = ""; String image = ""; int isIntegralMall = 0; double price = 0; int buyCount = 0; HashMap<String, Double> freightMap; OrderConfirmPartAddressFragment addressFragment; OrderConfirmPartPaymentFragment paymentFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_confirm_order_sale); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(PlatformProductBuyFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(PlatformProductBuyFragment.class.getName()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getFragmentManager().beginTransaction() .replace(R.id.platform_product_buy_address, addressFragment) .replace(R.id.platform_product_buy_payment, paymentFragment) .commit(); } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("supplierId")) { supplierId = bundle.getString("supplierId"); } if (bundle.containsKey("supplierName")) { supplierName = bundle.getString("supplierName"); } if (bundle.containsKey("productId")) { productId = bundle.getString("productId"); } if (bundle.containsKey("productNumber")) { productNumber = bundle.getString("productNumber"); } if (bundle.containsKey("name")) { name = bundle.getString("name"); } if (bundle.containsKey("productAttr")) { productAttr = bundle.getString("productAttr"); } if (bundle.containsKey("image")) { image = bundle.getString("image"); } if (bundle.containsKey("isIntegralMall")) { isIntegralMall = bundle.getInt("isIntegralMall"); } if (bundle.containsKey("price")) { price = bundle.getDouble("price"); } if (bundle.containsKey("buyCount")) { buyCount = bundle.getInt("buyCount"); } } freightMap = new HashMap<>(); addressFragment = new OrderConfirmPartAddressFragment(); paymentFragment = new OrderConfirmPartPaymentFragment(true, false); addressFragment.setOnSetAddressListener(new OrderConfirmPartAddressFragment.OnSetAddressListener() { @Override public void onSetAddress() { new GetFreight().execute(); } }); } protected void findViews() { imageView = (ImageView) contentView.findViewById(R.id.platform_product_buy_image); providerTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_provider); nameTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_name); attrTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_attr); countTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_count); priceTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_price); freightTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_freight); addressLayout = (FrameLayout) contentView.findViewById(R.id.platform_product_buy_address); paymentLayout = (FrameLayout) contentView.findViewById(R.id.platform_product_buy_payment); totalMoneyTextView = (TextView) contentView.findViewById(R.id.platform_product_buy_money); confirmButton = (TextView) contentView.findViewById(R.id.platform_product_buy_ok); initViews(); registerViews(); } @Override protected void initViews() { ImageLoader.getInstance().displayImage(getSmallImageUrl(image), imageView); providerTextView.setText(supplierName); nameTextView.setText(name); attrTextView.setText(productAttr); priceTextView.setText("单价:" + Parameters.CONSTANT_RMB + decimalFormat.format(price)); countTextView.setText("数量:" + String.valueOf(buyCount)); } @Override protected void registerViews() { confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addOrder(); } }); } private void addOrder() { if (buyCount * price > 0) { if (freightMap.containsKey(supplierId)) { if (addressFragment.getAddress() == null) { Notify.show("收货人信息有误"); } else { new AddOrder().execute(); } } else { Notify.show("查询运费失败,不能购买"); } } else { Notify.show("商品信息有误,不能购买"); } } /** * 促销产品下单 * * @author Tiger * @Result {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[{ * "zhekouhou" * :"34.0","zongzhekou":"0.0","fuwuZuoji":"028-2356895623" * ,"zongjine":"34.0","productInfo": * "[{\"spname\":\"韵思家具 法式田园抽屉储物六斗柜 欧式复古白色五斗柜 4斗柜 KSDG01\",\"price\":\"34.0\",\"Amount\":\"34.0\",\"num\":\"1\"}]" * ,"ordernumber":"YT5431669380","totalIntegral":"0","fuwushang": * "测试运营中心一" * ,"shijian":"2015-07-31","fuwuPhone":"15878978945"}],"totalCount" * :1,"dataMap":{},"object":null} */ class AddOrder extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... arg0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userNumber", User.getUser().getUseraccount())); nameValuePairs.add(new BasicNameValuePair("customerName", addressFragment.getAddress().getPersonName())); nameValuePairs.add(new BasicNameValuePair("phone", addressFragment.getAddress().getPhone())); nameValuePairs.add(new BasicNameValuePair("shippingaddress", addressFragment.getAddress().getAreaAddress() + addressFragment.getAddress().getDetailedAddress())); nameValuePairs.add(new BasicNameValuePair("totalMoney", decimalFormat.format(buyCount * price))); nameValuePairs.add(new BasicNameValuePair("sex", User.getUser().getSex())); nameValuePairs.add(new BasicNameValuePair("age", User.getUser().getAge())); nameValuePairs.add(new BasicNameValuePair("address", Store.getStore().getStoreArea())); nameValuePairs.add(new BasicNameValuePair("jmdId", Store.getStore().getStoreId())); nameValuePairs.add(new BasicNameValuePair("orderType", "0")); try { JSONArray dataArray = new JSONArray(); JSONObject object = new JSONObject(); object.put("productIds", productId); object.put("shopNum", buyCount); object.put("price", price); object.put("isIntegralMall", isIntegralMall); dataArray.put(object); nameValuePairs.add(new BasicNameValuePair("data", dataArray.toString())); JSONArray freightArray = new JSONArray(); JSONObject freightObject = new JSONObject(); freightObject.put("supplyId", supplierId); freightObject.put("freight", freightMap.get(supplierId)); freightArray.put(freightObject); nameValuePairs.add(new BasicNameValuePair("freights", freightArray.toString())); } catch (JSONException e) { e.printStackTrace(); } return netUtil.postWithoutCookie(API.API_ORDER_ADD_CENTER, nameValuePairs, false, false); } @Override protected void onPostExecute(String result) { if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { Toast.makeText(getActivity(), "下单成功", Toast.LENGTH_SHORT).show(); if (paymentFragment.getPaymentType() == OrderConfirmPartPaymentFragment.PAY_TYPE_CODE_ONLINE) { payMoney(object.optJSONArray("object")); getActivity().finish(); return; } showOrder(PayFragment.ORDER_TYPE_YY); getActivity().finish(); return; } else { hideLoading(); Notify.show(object.optString("message")); return; } } catch (JSONException e) { hideLoading(); Notify.show("下单失败"); e.printStackTrace(); return; } } hideLoading(); Notify.show("下单失败"); } } class GetFreight extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); freightMap.clear(); } @Override protected String doInBackground(Void... params) { List<NameValuePair> valuePairs = new ArrayList<>(); valuePairs.add(new BasicNameValuePair("productNumber", productNumber + "-" + buyCount)); valuePairs.add(new BasicNameValuePair("areaid", addressFragment.getAddress().getAreaId())); valuePairs.add(new BasicNameValuePair("spid", Store.getStore().getStoreId())); return netUtil.postWithCookie(API.API_PRODUCT_FREIGHT, valuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONArray jsonArray = object.optJSONArray("dataList"); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.optJSONObject(i); if (jsonObject != null) { Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); freightMap.put(key, jsonObject.optDouble(key)); } } } if (freightMap.containsKey(supplierId)) { freightTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(freightMap.get(supplierId))); totalMoneyTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format((buyCount * price) + freightMap.get(supplierId))); } } return; } Notify.show(object.optString("message")); } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.user.ui; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.user.model.ModelRecommend; import yitgogo.consumer.user.model.User; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class UserRecommendFragment extends BaseNotifyFragment { ListView recommendListView; TextView countTextView, moneyTextView; List<ModelRecommend> recommends; RecommendAdapter recommendAdapter; Statistics statistics = new Statistics(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_recommend); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserRecommendFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserRecommendFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetStatistics().execute(); new GetRecommendList().execute(); } private void init() { recommends = new ArrayList<ModelRecommend>(); recommendAdapter = new RecommendAdapter(); } @Override protected void findViews() { recommendListView = (ListView) contentView .findViewById(R.id.recommend_list); countTextView = (TextView) contentView .findViewById(R.id.recommend_count); moneyTextView = (TextView) contentView .findViewById(R.id.recommend_money); initViews(); registerViews(); } @Override protected void initViews() { recommendListView.setAdapter(recommendAdapter); } @Override protected void registerViews() { } private void showStatistics() { countTextView.setText(statistics.getNum() + ""); moneyTextView.setText(statistics.getBonus() + ""); } class RecommendAdapter extends BaseAdapter { @Override public int getCount() { return recommends.size(); } @Override public Object getItem(int position) { return recommends.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_recommend, null); holder = new ViewHolder(); holder.accountTextView = (TextView) convertView .findViewById(R.id.list_recommend_account); holder.scoreTextView = (TextView) convertView .findViewById(R.id.list_recommend_score); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelRecommend recommend = recommends.get(position); holder.accountTextView.setText(recommend.getMemberAccount()); holder.scoreTextView.setText(recommend.getTotalBonus()); return convertView; } class ViewHolder { TextView accountTextView, scoreTextView; } } /** * 获取我推荐的会员总人数和会员消费总金额 * * @author Tiger * * @Result {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[], * "totalCount":1,"dataMap":{"num":0,"bonus":0},"object":null} */ class GetStatistics extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("memberAccount", User .getUser().getUseraccount())); return netUtil.postWithCookie(API.API_USER_RECOMMEND_STATISTICS, nameValuePairs); } @Override protected void onPostExecute(String result) { statistics = new Statistics(result); showStatistics(); } } /** * @author Tiger * * @Result * {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[{"id" * :null, "totalBonus" * :0,"memberAccount":"15882972602"}],"totalCount":1,"dataMap":{} * ,"object":null} * */ class GetRecommendList extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { recommends.clear(); recommendAdapter.notifyDataSetChanged(); } @Override protected String doInBackground(Void... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("memberAccount", User .getUser().getUseraccount())); return netUtil.postWithCookie(API.API_USER_RECOMMEND_LIST, nameValuePairs); } @Override protected void onPostExecute(String result) { if (result.length() > 0) { try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.getString("state").equalsIgnoreCase( "SUCCESS")) { JSONArray array = jsonObject.optJSONArray("dataList"); if (array != null) { for (int i = 0; i < array.length(); i++) { recommends.add(new ModelRecommend(array .optJSONObject(i))); } recommendAdapter.notifyDataSetChanged(); } } } catch (JSONException e) { e.printStackTrace(); } } } } class Statistics { long num = 0; long bonus = 0; public Statistics() { } public Statistics(String result) { if (result.length() > 0) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject jsonObject = object.getJSONObject("dataMap"); if (jsonObject != null) { num = jsonObject.optLong("num"); bonus = jsonObject.optLong("bonus"); } } } catch (JSONException e) { e.printStackTrace(); } } } public long getNum() { return num; } public long getBonus() { return bonus; } @Override public String toString() { return "Statistics [num=" + num + ", bonus=" + bonus + "]"; } } } <file_sep>package yitgogo.consumer.user.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.local.model.ModelAddress; import yitgogo.consumer.store.ui.StoreAreaFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; /** * 用户收货地址管理(添加/修改) * * @author Tiger */ public class UserAddressEditFragment extends BaseNetworkFragment { EditText nameEditText, phoneEditText, addressEditText, telephoneEditText, postcodeEditText, emailEditText; TextView areaTextView; Button addButton; String addressId = ""; public static String areaName = "", areaId = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_address_edit); init(); findViews(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserAddressEditFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getAddressDetail(); } @Override protected void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("addressId")) { addressId = bundle.getString("addressId"); } } } @Override public void onDestroy() { areaName = ""; areaId = ""; super.onDestroy(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserAddressEditFragment.class.getName()); areaTextView.setText(areaName); } @Override protected void findViews() { nameEditText = (EditText) contentView .findViewById(R.id.address_add_name); phoneEditText = (EditText) contentView .findViewById(R.id.address_add_phone); addressEditText = (EditText) contentView .findViewById(R.id.address_add_address); telephoneEditText = (EditText) contentView .findViewById(R.id.address_add_telephone); postcodeEditText = (EditText) contentView .findViewById(R.id.address_add_postcode); emailEditText = (EditText) contentView .findViewById(R.id.address_add_email); areaTextView = (TextView) contentView .findViewById(R.id.address_add_area); addButton = (Button) contentView.findViewById(R.id.address_add_add); initViews(); registerViews(); } @Override protected void initViews() { if (addressId.length() > 0) { addButton.setText("修改"); } } @Override protected void registerViews() { areaTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putBoolean("getArea", true); jump(StoreAreaFragment.class.getName(), "选择收货区域", bundle); } }); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editAddress(); } }); } private void editAddress() { if (nameEditText.length() <= 0) { ApplicationTool.showToast("请输入收货人姓名"); } else if (phoneEditText.length() <= 0) { ApplicationTool.showToast("请输入收货人手机号"); } else if (!isPhoneNumber(phoneEditText.getText().toString())) { ApplicationTool.showToast("请输入正确的手机号"); } else if (areaId.length() <= 0) { ApplicationTool.showToast("请选择收货区域"); } else if (addressEditText.length() <= 0) { ApplicationTool.showToast("请输入详细收货地址"); } else if (telephoneEditText.length() > 0 & telephoneEditText.length() < 11) { ApplicationTool.showToast("请输入正确的固定电话号码"); } else if (postcodeEditText.length() > 0 & postcodeEditText.length() < 6) { ApplicationTool.showToast("请输入正确的邮政编码"); } else { if (addressId.length() > 0) { modifyAddress(); } else { addAddress(); } } } private void addAddress() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("memberAccount", User.getUser().getUseraccount())); requestParams.add(new RequestParam("personName", nameEditText.getText().toString())); requestParams.add(new RequestParam("phone", phoneEditText.getText().toString())); requestParams.add(new RequestParam("areaAddress", areaName)); requestParams.add(new RequestParam("areaId", areaId)); requestParams.add(new RequestParam("detailedAddress", addressEditText.getText().toString())); requestParams.add(new RequestParam("fixPhone", telephoneEditText.getText().toString())); requestParams.add(new RequestParam("postcode", postcodeEditText.getText().toString())); requestParams.add(new RequestParam("email", emailEditText.getText().toString())); post(API.API_USER_ADDRESS_ADD, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { ApplicationTool.showToast("添加成功"); getActivity().finish(); } else { ApplicationTool.showToast(object.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getAddressDetail() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("id", addressId)); post(API.API_USER_ADDRESS_DETAIL, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { ModelAddress address = new ModelAddress(dataMap.optJSONObject("updateMemberAddress")); nameEditText.setText(address.getPersonName()); areaTextView.setText(address.getAreaAddress()); addressEditText.setText(address.getDetailedAddress()); phoneEditText.setText(address.getPhone()); telephoneEditText.setText(address.getFixPhone()); postcodeEditText.setText(address.getPostcode()); emailEditText.setText(address.getEmail()); } } } catch (JSONException e) { e.printStackTrace(); } } } }); } /** * 获取地址详情对象 * * @author Tiger * @Json {"message":"ok","state":"SUCCESS" * ,"cacheKey":null,"dataList":[],"totalCount" * :1,"dataMap":{"updateMemberAddress" * :{"id":3,"personName":"赵晋","areaId":2421 * ,"areaAddress":"四川省成都市金牛区","detailedAddress" * :"解放路二段6号凤凰大厦","phone":"18584182653" * ,"fixPhone":"","postcode":"","email":"" * ,"isDefault":1,"memberAccount":"18584182653" * ,"millis":1438598019428},"secondId" * :269,"thirdId":2421,"firstId":23},"object":null} */ private void modifyAddress() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("id", addressId)); requestParams.add(new RequestParam("personName", nameEditText.getText().toString())); requestParams.add(new RequestParam("phone", phoneEditText.getText().toString())); requestParams.add(new RequestParam("areaAddress", areaName)); requestParams.add(new RequestParam("areaId", areaId)); requestParams.add(new RequestParam("detailedAddress", addressEditText.getText().toString())); requestParams.add(new RequestParam("fixPhone", telephoneEditText.getText().toString())); requestParams.add(new RequestParam("postcode", postcodeEditText.getText().toString())); requestParams.add(new RequestParam("email", emailEditText.getText().toString())); post(API.API_USER_ADDRESS_MODIFY, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { ApplicationTool.showToast("修改成功"); getActivity().finish(); } else { Toast.makeText(getActivity(), object.getString("message"), Toast.LENGTH_SHORT) .show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.net.ConnectivityManager; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Base64; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.dtr.zxing.activity.CaptureActivity; import com.smartown.yitian.gogo.R; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.bianmin.ModelBianminOrderResult; import yitgogo.consumer.bianmin.phoneCharge.ui.PhoneChargeFragment; import yitgogo.consumer.local.model.ModelLocalCar; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.order.model.ModelOrderResult; import yitgogo.consumer.order.model.ModelStorePostInfo; import yitgogo.consumer.order.ui.OrderFragment; import yitgogo.consumer.product.ui.ProductDetailFragment; import yitgogo.consumer.product.ui.ProductListFragment; import yitgogo.consumer.tools.MD5; import yitgogo.consumer.tools.NetUtil; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.ScreenUtil; /** * 有通知功能的fragment * * @author Tiger */ public class BaseNotifyFragment extends Fragment { public LayoutInflater layoutInflater; public NetUtil netUtil; public int screenWidth = 0, screenHeight = 0; public int pagenum = 0, pagesize = 12; public DecimalFormat decimalFormat; public SimpleDateFormat simpleDateFormat; public boolean showConnectionState = true; public boolean useCache = true; LinearLayout emptyLayout; ImageView emptyImage; TextView emptyText; LinearLayout failLayout; Button failButton; TextView failText; LinearLayout disconnectLayout; TextView disconnectText; View disconnectMargin; LinearLayout loadingLayout; ProgressBar loadingProgressBar; TextView loadingText; FrameLayout contentLayout; public View contentView; BroadcastReceiver broadcastReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); } private void init() { layoutInflater = LayoutInflater.from(getActivity()); netUtil = NetUtil.getInstance(); decimalFormat = new DecimalFormat("0.00"); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup base_fragment, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_base, null); findView(view); return view; } @Override public void onDestroy() { getActivity().unregisterReceiver(broadcastReceiver); super.onDestroy(); } private void findView(View view) { contentLayout = (FrameLayout) view .findViewById(R.id.base_fragment_content); emptyLayout = (LinearLayout) view .findViewById(R.id.base_fragment_empty); failLayout = (LinearLayout) view.findViewById(R.id.base_fragment_fail); disconnectLayout = (LinearLayout) view .findViewById(R.id.base_fragment_disconnect); disconnectMargin = view .findViewById(R.id.base_fragment_disconnect_margin); loadingLayout = (LinearLayout) view .findViewById(R.id.base_fragment_loading); emptyImage = (ImageView) view .findViewById(R.id.base_fragment_empty_image); emptyText = (TextView) view.findViewById(R.id.base_fragment_empty_text); failText = (TextView) view.findViewById(R.id.base_fragment_fail_text); disconnectText = (TextView) view .findViewById(R.id.base_fragment_disconnect_text); loadingText = (TextView) view .findViewById(R.id.base_fragment_loading_text); failButton = (Button) view.findViewById(R.id.base_fragment_fail_button); loadingProgressBar = (ProgressBar) view .findViewById(R.id.base_fragment_loading_progressbar); disconnectText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); } }); showContentView(); initReceiver(); } protected void findViews() { } protected void initViews() { } protected void registerViews() { } protected void reload() { failButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { reload(); } }); } private void initReceiver() { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { if (showConnectionState) { checkConnection(); } } } }; IntentFilter intentFilter = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); getActivity().registerReceiver(broadcastReceiver, intentFilter); } protected void showContentView() { if (contentLayout.getChildCount() > 0) { contentLayout.removeAllViews(); } if (contentView != null) { contentLayout.addView(contentView); } } protected void setContentView(int layoutId) { contentView = layoutInflater.inflate(layoutId, null); } protected View getContentView() { return contentView; } protected void setShowConnectionState(boolean showConnectionState) { this.showConnectionState = showConnectionState; } protected void showDisconnectMargin() { disconnectMargin.setVisibility(View.VISIBLE); } private void checkConnection() { if (isConnected()) { disconnectLayout.setVisibility(View.GONE); } else { disconnectLayout.setVisibility(View.VISIBLE); } } protected void showLoading() { loadingText.setText("请稍候..."); emptyLayout.setVisibility(View.GONE); failLayout.setVisibility(View.GONE); loadingLayout.setVisibility(View.VISIBLE); } protected void showLoading(String text) { loadingText.setText(text); emptyLayout.setVisibility(View.GONE); failLayout.setVisibility(View.GONE); loadingLayout.setVisibility(View.VISIBLE); } protected void hideLoading() { loadingLayout.setVisibility(View.GONE); } protected void loadingEmpty() { emptyText.setText("暂无数据"); emptyLayout.setVisibility(View.VISIBLE); } protected void loadingEmpty(String text) { emptyText.setText(text); emptyLayout.setVisibility(View.VISIBLE); } protected void loadingFailed() { failLayout.setVisibility(View.VISIBLE); } /** * 带参数的fragment跳转 * * @param fragmentName * @param fragmentTitle * @param parameters */ protected void jumpFull(String fragmentName, String fragmentTitle, Bundle parameters) { Intent intent = new Intent(getActivity(), ContainerFullActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBundle("parameters", parameters); intent.putExtras(bundle); startActivity(intent); } protected void jump(String fragmentName, String fragmentTitle) { if (fragmentName.equals(PhoneChargeFragment.class.getName())) { jump(fragmentName, fragmentTitle, true); return; } Intent intent = new Intent(getActivity(), ContainerActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); intent.putExtras(bundle); startActivity(intent); } protected void jumpForResult(String fragmentName, String fragmentTitle, Bundle parameters, int requestCode) { Intent intent = new Intent(getActivity(), ContainerActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBundle("parameters", parameters); intent.putExtras(bundle); startActivityForResult(intent, requestCode); } /** * 可隐藏container标题栏的跳转 * * @param fragmentName * @param fragmentTitle * @param hideTitle */ protected void jump(String fragmentName, String fragmentTitle, boolean hideTitle) { Intent intent = new Intent(getActivity(), ContainerActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBoolean("hideTitle", hideTitle); intent.putExtras(bundle); startActivity(intent); } /** * 带参数的fragment跳转 * * @param fragmentName * @param fragmentTitle * @param parameters */ protected void jump(String fragmentName, String fragmentTitle, Bundle parameters) { Intent intent = new Intent(getActivity(), ContainerActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBundle("parameters", parameters); intent.putExtras(bundle); startActivity(intent); } /** * 带参数的fragment跳转 * * @param fragmentName * @param fragmentTitle * @param hideTitle */ protected void jump(String fragmentName, String fragmentTitle, Bundle parameters, boolean hideTitle) { Intent intent = new Intent(getActivity(), ContainerActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBundle("parameters", parameters); bundle.putBoolean("hideTitle", hideTitle); intent.putExtras(bundle); startActivity(intent); } /** * 显示商品列表 * * @param fragmentTitle 标题 * @param value 参数值 * @param type 参数类型/产品类型 */ protected void jumpProductList(String fragmentTitle, String value, int type) { Bundle bundle = new Bundle(); bundle.putString("value", value); bundle.putInt("type", type); jump(ProductListFragment.class.getName(), fragmentTitle, bundle); } protected void showOrder(int orderType) { Bundle bundle = new Bundle(); bundle.putInt("orderType", orderType); jump(OrderFragment.class.getName(), "我的订单", bundle); } protected void showProductDetail(String productId, String productName, int saleType) { Bundle bundle = new Bundle(); bundle.putString("productId", productId); bundle.putInt("saleType", saleType); jump(ProductDetailFragment.class.getName(), productName, bundle); } protected void measureScreen() { DisplayMetrics metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay() .getMetrics(metrics); screenHeight = metrics.heightPixels; screenWidth = metrics.widthPixels; } protected void addImageButton(int imageResId, String tag, OnClickListener onClickListener) { getContainerActivity().addImageButton(imageResId, tag, onClickListener); } protected void addTextButton(String text, OnClickListener onClickListener) { getContainerActivity().addTextButton(text, onClickListener); } /** * fragment设置返回按钮点击事件 * * @param onClickListener */ protected void onBackButtonClick(OnClickListener onClickListener) { getContainerActivity().onBackButtonClick(onClickListener); } private ContainerActivity getContainerActivity() { ContainerActivity containerActivity = (ContainerActivity) getActivity(); return containerActivity; } /** * 获取圆角位图的方法 * * @param bitmap 需要转化成圆角的位图 * @param pixels 圆角的度数,数值越大,圆角越大 * @return 处理后的圆角位图 */ protected Bitmap getRoundCornerBitmap(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); RectF rectF = new RectF(rect); float roundPx = pixels; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } /** * @param originalUrl json得到的图片链接 * @return formatedUrl 切图链接 * @author Tiger */ protected String getSmallImageUrl(String originalUrl) { String formatedUrl = ""; if (!TextUtils.isEmpty(originalUrl)) { formatedUrl = originalUrl; if (originalUrl.contains("images.")) { formatedUrl = originalUrl.replace("images.", "imageprocess.") + "@!350"; } } return formatedUrl; } /** * @param originalUrl json得到的图片链接 * @return formatedUrl 切图链接 * @author Tiger */ protected String getBigImageUrl(String originalUrl) { String formatedUrl = ""; if (!TextUtils.isEmpty(originalUrl)) { formatedUrl = originalUrl; if (originalUrl.contains("images.")) { formatedUrl = originalUrl.replace("images.", "imageprocess.") + "@!600"; } } return formatedUrl; } /** * 通过接口地址和参数组成唯一字符串,作为用于缓存数据的键 * * @param api_url 接口地址 * @param parameters 网络请求参数 * @return 缓存数据的键 */ protected String getCacheKey(String api_url, List<NameValuePair> parameters) { // TODO Auto-generated method stub StringBuilder builder = new StringBuilder(); builder.append(api_url); if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { if (i == 0) { builder.append("?"); } else { builder.append("&"); } builder.append(parameters.get(i).getName()); builder.append("="); builder.append(parameters.get(i).getValue()); } } return builder.toString(); } /** * 验证手机格式 */ protected boolean isPhoneNumber(String number) { if (TextUtils.isEmpty(number)) { return false; } else { return number.length() == 11; } } /** * 判断是否连接网络 * * @return */ protected boolean isConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager.getActiveNetworkInfo() != null) { if (connectivityManager.getActiveNetworkInfo().isAvailable()) { return true; } else { return false; } } else { return false; } } protected String getHtmlFormated(String baseHtml) { String head = "<head>" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " + "<style>img{max-width: 100%; width:auto; height:auto;}</style>" + "</head>"; return "<html>" + head + "<body>" + baseHtml + "</body></html>"; } protected String getEncodedPassWord(String password) { return MD5.GetMD5Code(password + "{<PASSWORD>}"); } protected String getSecretCardNuber(String cardNumber) { if (cardNumber.length() > 4) { return "**** **** **** " + cardNumber.substring(cardNumber.length() - 4, cardNumber.length()); } return "**** **** **** " + cardNumber; } protected void payMoney(ModelBianminOrderResult bianminOrderResult) { ArrayList<String> orderNumbers = new ArrayList<String>(); orderNumbers.add(bianminOrderResult.getOrderNumber()); payMoney(orderNumbers, bianminOrderResult.getSellPrice(), PayFragment.ORDER_TYPE_BM); } protected void payMoney(String orderNumber, double totalMoney, int orderType) { ArrayList<String> orderNumbers = new ArrayList<String>(); orderNumbers.add(orderNumber); payMoney(orderNumbers, totalMoney, orderType); } protected void payMoney(ArrayList<String> orderNumbers, double totalMoney, int orderType) { Bundle bundle = new Bundle(); bundle.putStringArrayList("orderNumbers", orderNumbers); bundle.putDouble("totalMoney", totalMoney); bundle.putInt("orderType", orderType); // bundle.putInt("productCount", productCount); jump(PayFragment.class.getName(), "订单支付", bundle); } /** * 易田商城下单成功后支付 * * @param platformOrderResult 下单返回订单的结果 */ protected void payMoney(JSONArray platformOrderResult) { if (platformOrderResult != null) { if (platformOrderResult != null) { double payPrice = 0; ArrayList<String> orderNumbers = new ArrayList<String>(); for (int i = 0; i < platformOrderResult.length(); i++) { ModelOrderResult orderResult = new ModelOrderResult( platformOrderResult.optJSONObject(i)); orderNumbers.add(orderResult.getOrdernumber()); payPrice += orderResult.getZhekouhou(); payPrice += orderResult.getFreight(); } if (orderNumbers.size() > 0) { if (payPrice > 0) { payMoney(orderNumbers, payPrice, PayFragment.ORDER_TYPE_YY); } } } } } protected ContentValues getShareCodeContent(String userAccount, String userCode) throws JSONException { JSONObject object = new JSONObject(); object.put("codeType", CaptureActivity.CODE_TYPE_SHARE); JSONObject dataObject = new JSONObject(); dataObject.put("userAccount", userAccount); dataObject.put("userCode", userCode); object.put("data", dataObject); ContentValues contentValues = new ContentValues(); contentValues.put("content", Base64.encodeToString(object.toString() .getBytes(), Base64.DEFAULT)); contentValues.put("imageWidth", ScreenUtil.getScreenWidth() / 2); return contentValues; } protected String getStorePostInfoString(ModelStorePostInfo storePostInfo) { return "配送费:" + Parameters.CONSTANT_RMB + decimalFormat.format(storePostInfo.getPostage()) + ",店铺购物满" + Parameters.CONSTANT_RMB + decimalFormat.format(storePostInfo.getHawManyPackages()) + "免配送费"; } protected String getMoneyDetailString(double goodsMoney, double postFee) { return "商品:" + Parameters.CONSTANT_RMB + decimalFormat.format(goodsMoney) + "+配送费:" + Parameters.CONSTANT_RMB + decimalFormat.format(postFee); } protected String getDiliverPayString(ModelLocalCar localCar) { return localCar.getDiliver().getName() + "、" + localCar.getPayment().getName(); } } <file_sep>package yitgogo.consumer.money.ui; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.activity.ActivityFragment; import yitgogo.consumer.bianmin.game.ui.GameFilterFragment; import yitgogo.consumer.bianmin.phoneCharge.ui.PhoneChargeFragment; import yitgogo.consumer.bianmin.qq.ui.QQChargeFragment; import yitgogo.consumer.bianmin.telephone.ui.TelePhoneChargeFragment; import yitgogo.consumer.bianmin.traffic.ui.TraffictSearchFragment; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.money.task.GetBankCards; import yitgogo.consumer.money.task.HavePayPasswordTask; import yitgogo.consumer.money.task.LoginMoneyTask; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.view.Notify; import android.os.AsyncTask.Status; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class MoneyHomeFragment extends BaseNotifyFragment { FrameLayout cashLayout, bankCardLayout, takeOutButton, bianminPhoneButton, bianminKuandaiButton, bianminQQButton, bianminGameButton, bianminTrafficButton, changePayPassword, findPayPassword, shakeButton; LinearLayout accountLayout, bianminLayout; TextView cashTextView, bankCardTextView, passwordTextView; LoginMoneyTask loginMoneyTask; GetBankCards getBankCards; HavePayPasswordTask havePayPasswordTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_home); init(); findViews(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(MoneyHomeFragment.class.getName()); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(MoneyHomeFragment.class.getName()); loginMoney(); } @Override public void onDestroy() { stopAsyncTasks(); super.onDestroy(); } private void init() { measureScreen(); } @Override protected void findViews() { cashLayout = (FrameLayout) contentView .findViewById(R.id.money_account_cash_layout); accountLayout = (LinearLayout) contentView .findViewById(R.id.money_account_layout); cashTextView = (TextView) contentView .findViewById(R.id.money_account_cash); bankCardLayout = (FrameLayout) contentView .findViewById(R.id.money_account_bankcard_layout); bankCardTextView = (TextView) contentView .findViewById(R.id.money_account_bankcard); takeOutButton = (FrameLayout) contentView .findViewById(R.id.money_home_take_out); bianminPhoneButton = (FrameLayout) contentView .findViewById(R.id.money_bianmin_phone); bianminKuandaiButton = (FrameLayout) contentView .findViewById(R.id.money_bianmin_kuandai); bianminQQButton = (FrameLayout) contentView .findViewById(R.id.money_bianmin_qq); bianminGameButton = (FrameLayout) contentView .findViewById(R.id.money_bianmin_game); bianminTrafficButton = (FrameLayout) contentView .findViewById(R.id.money_bianmin_traffic); changePayPassword = (FrameLayout) contentView .findViewById(R.id.money_pay_password_change); passwordTextView = (TextView) contentView .findViewById(R.id.money_pay_password_change_lable); findPayPassword = (FrameLayout) contentView .findViewById(R.id.money_pay_password_find); bianminLayout = (LinearLayout) contentView .findViewById(R.id.money_bianmin_layout); shakeButton = (FrameLayout) contentView.findViewById(R.id.money_shake); initViews(); registerViews(); } @Override protected void initViews() { LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, screenWidth); bianminLayout.setLayoutParams(layoutParams); LayoutParams accountLayoutParams = new LayoutParams( LayoutParams.MATCH_PARENT, screenWidth / 2); accountLayout.setLayoutParams(accountLayoutParams); } @Override protected void registerViews() { cashLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(TradeHistoryFragment.class.getName(), "余额交易明细"); } }); bankCardLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(BankCardFragment.class.getName(), "我的银行卡"); } }); takeOutButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(TakeOutFragment.class.getName(), "提现"); } }); bianminPhoneButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(PhoneChargeFragment.class.getName(), "手机充值"); } }); bianminKuandaiButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(TelePhoneChargeFragment.class.getName(), "固话宽带充值"); } }); bianminQQButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(QQChargeFragment.class.getName(), "QQ充值"); } }); bianminGameButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(GameFilterFragment.class.getName(), "游戏充值"); } }); bianminTrafficButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(TraffictSearchFragment.class.getName(), "违章查询"); } }); shakeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(ActivityFragment.class.getName(), "摇一摇"); } }); } private void stopAsyncTasks() { if (loginMoneyTask != null) { if (loginMoneyTask.getStatus() == Status.RUNNING) { loginMoneyTask.cancel(true); } } if (getBankCards != null) { if (getBankCards.getStatus() == Status.RUNNING) { getBankCards.cancel(true); } } if (havePayPasswordTask != null) { if (havePayPasswordTask.getStatus() == Status.RUNNING) { havePayPasswordTask.cancel(true); } } } private void loginMoney() { if (loginMoneyTask != null) { if (loginMoneyTask.getStatus() == Status.RUNNING) { return; } } loginMoneyTask = new LoginMoneyTask() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(String result) { hideLoading(); super.onPostExecute(result); if (MoneyAccount.getMoneyAccount().isLogin()) { cashTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(MoneyAccount .getMoneyAccount().getBalance())); getBankCards(); havePayPassword(); } else { getActivity().finish(); } } }; loginMoneyTask.execute(); } private void getBankCards() { if (getBankCards != null) { if (getBankCards.getStatus() == Status.RUNNING) { return; } } getBankCards = new GetBankCards() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(String result) { hideLoading(); super.onPostExecute(result); bankCardTextView.setText(MoneyAccount.getMoneyAccount() .getBankCards().size() + ""); } }; getBankCards.execute(); } private void havePayPassword() { if (havePayPasswordTask != null) { if (havePayPasswordTask.getStatus() == Status.RUNNING) { return; } } havePayPasswordTask = new HavePayPasswordTask() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(String result) { hideLoading(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase( "success")) { JSONObject jsonObject = object .optJSONObject("databody"); if (jsonObject != null) { if (jsonObject.optBoolean("pwd")) { // 已设置支付密码 findPayPassword.setVisibility(View.VISIBLE); findPayPassword .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(PayPasswordFindFragment.class .getName(), "找回支付密码"); } }); passwordTextView.setText("修改支付密码"); changePayPassword .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(PayPasswordChangeFragment.class .getName(), "修改支付密码"); } }); } else { // 未设置支付密码 findPayPassword .setVisibility(View.INVISIBLE); findPayPassword .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); passwordTextView.setText("设置支付密码"); changePayPassword .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(PayPasswordSetFragment.class .getName(), "设置支付密码"); } }); } return; } } } catch (JSONException e) { e.printStackTrace(); } } } }; havePayPasswordTask.execute(); } } <file_sep>package yitgogo.consumer.user.ui; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; public class ModifySecret extends BaseNetworkFragment { Button modify; TextView accountText, secretOld, secretNew, secretVerify; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_secret); findViews(); } @Override protected void init() { } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(ModifySecret.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(ModifySecret.class.getName()); } protected void findViews() { accountText = (TextView) contentView .findViewById(R.id.user_info_secret_account); secretOld = (TextView) contentView .findViewById(R.id.user_info_secret_old); secretNew = (TextView) contentView .findViewById(R.id.user_info_secret_new); secretVerify = (TextView) contentView .findViewById(R.id.user_info_secret_verify); modify = (Button) contentView.findViewById(R.id.user_secret_modify); initViews(); registerViews(); } @Override protected void initViews() { accountText.setText(User.getUser().getUseraccount()); } @Override protected void registerViews() { modify.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { modify(); } }); } private void modify() { String oldpassword = secretOld.getText().toString().trim(); String newpassword = secretNew.getText().toString().trim(); String renewpassword = secretVerify.getText().toString().trim(); if (TextUtils.isEmpty(oldpassword)) { ApplicationTool.showToast("请输入旧密码"); } else if (TextUtils.isEmpty(newpassword)) { ApplicationTool.showToast("请输入新密码"); } else if (TextUtils.isEmpty(renewpassword)) { ApplicationTool.showToast("请确认新密码"); } else if (newpassword.equalsIgnoreCase(oldpassword)) { ApplicationTool.showToast("新密码与旧密码相同"); } else if (!newpassword.equalsIgnoreCase(renewpassword)) { ApplicationTool.showToast("两次输入的新密码不相同"); } else { modifySecret(oldpassword, newpassword); } } private void modifySecret(String oldpassword, String newpassword) { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("useraccount", User.getUser().getUseraccount())); requestParams.add(new RequestParam("oldpassword", getEncodedPassWord(oldpassword))); requestParams.add(new RequestParam("newpassword", getEncodedPassWord(newpassword))); post(API.API_USER_MODIFY_SECRET, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { Content.removeContent(Parameters.CACHE_KEY_USER_JSON); Content.removeContent(Parameters.CACHE_KEY_USER_PASSWORD); Content.removeContent(Parameters.CACHE_KEY_COOKIE); User.init(getActivity()); ApplicationTool.showToast("修改成功,请重新登录"); jump(UserLoginFragment.class.getName(), "会员登录"); getActivity().finish(); } else { ApplicationTool.showToast(object.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } } }); } } <file_sep>package yitgogo.consumer.home.task; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import android.os.AsyncTask; public class GetStore extends AsyncTask<Boolean, Void, String> { @Override protected String doInBackground(Boolean... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("storeId", Store.getStore() .getStoreId())); return NetUtil.getInstance().postWithoutCookie( API.API_LOCAL_STORE_LIST, nameValuePairs, params[0], true); } } <file_sep>package yitgogo.consumer.user.ui; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; public class UserScoreFragment extends BaseNetworkFragment { TextView scoreTotalTextView, signButton; LinearLayout detailButton, shareButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_score); findViews(); } @Override protected void init() { } @Override protected void initViews() { } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserScoreFragment.class.getName()); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserScoreFragment.class.getName()); if (User.getUser().isLogin()) { getUserScore(); getSignState(); } } @Override protected void findViews() { scoreTotalTextView = (TextView) contentView .findViewById(R.id.score_total); signButton = (TextView) contentView.findViewById(R.id.score_sign); detailButton = (LinearLayout) contentView .findViewById(R.id.score_detail); shareButton = (LinearLayout) contentView.findViewById(R.id.score_share); registerViews(); } @Override protected void registerViews() { signButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { userSignUp(); } }); detailButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(UserScoreDetailFragment.class.getName(), "积分详情"); } }); shareButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(UserShareFragment.class.getName(), "推荐好友"); } }); } private void getUserScore() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("memberAccount", User.getUser().getUseraccount())); post(API.API_USER_JIFEN, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONObject jifenObject = object.optJSONObject("object"); if (jifenObject != null) { String score = jifenObject.optString("totalBonus"); if (!score.equalsIgnoreCase("null")) { scoreTotalTextView.setText(score); } else { scoreTotalTextView.setText("0"); } } } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getSignState() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("userAccount", User.getUser().getUseraccount())); post(API.API_USER_SIGN_STATE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONObject jsonObject = object.getJSONObject("object"); String isSign = jsonObject.getString("isSign"); if (!isSign.equals("0")) { signButton.setText("今日已签到"); signButton.setTextColor(getResources().getColor( R.color.textColorThird)); signButton.setClickable(false); } else { signButton.setText("签到领积分"); signButton.setTextColor(getResources().getColor( R.color.textColorSecond)); signButton.setClickable(true); } } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void userSignUp() { signButton.setText("今日已签到"); signButton.setTextColor(getResources().getColor(R.color.textColorThird)); signButton.setClickable(false); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("userAccount", User.getUser().getUseraccount())); post(API.API_USER_SIGN, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { getSignState(); getUserScore(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer.order.ui; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.home.model.ModelListPrice; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.order.model.ModelOrderResult; import yitgogo.consumer.product.model.ModelCar; import yitgogo.consumer.product.model.ModelProduct; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.InnerListView; public class PlatformOrderConfirmFragment extends BaseNetworkFragment { InnerListView productListView; FrameLayout addressLayout, paymentLayout; TextView totalPriceTextView, confirmButton; List<ModelCar> modelCars; HashMap<String, ModelListPrice> priceMap; ProductAdapter productAdapter; double totalPrice = 0; List<ModelOrderResult> orderResults; OrderConfirmPartAddressFragment addressFragment; OrderConfirmPartPaymentFragment paymentFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_confirm_order); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(PlatformOrderConfirmFragment.class.getName()); getOrderProduct(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(PlatformOrderConfirmFragment.class.getName()); } @Override protected void init() { modelCars = new ArrayList<>(); priceMap = new HashMap<>(); productAdapter = new ProductAdapter(); orderResults = new ArrayList<>(); addressFragment = new OrderConfirmPartAddressFragment(); paymentFragment = new OrderConfirmPartPaymentFragment(true, false); } protected void findViews() { productListView = (InnerListView) contentView .findViewById(R.id.platform_order_confirm_products); addressLayout = (FrameLayout) contentView .findViewById(R.id.platform_order_confirm_part_address); paymentLayout = (FrameLayout) contentView .findViewById(R.id.platform_order_confirm_part_payment); totalPriceTextView = (TextView) contentView .findViewById(R.id.platform_order_confirm_total_money); confirmButton = (TextView) contentView .findViewById(R.id.platform_order_confirm); initViews(); registerViews(); } @Override protected void initViews() { getFragmentManager() .beginTransaction() .replace(R.id.platform_order_confirm_part_address, addressFragment) .replace(R.id.platform_order_confirm_part_payment, paymentFragment).commit(); productListView.setAdapter(productAdapter); } @Override protected void registerViews() { confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addOrder(); } }); } private void getOrderProduct() { modelCars.clear(); productAdapter.notifyDataSetChanged(); totalPriceTextView.setText(""); try { JSONArray orderArray = new JSONArray(Content.getStringContent( Parameters.CACHE_KEY_ORDER_PRODUCT, "[]")); for (int i = 0; i < orderArray.length(); i++) { modelCars.add(new ModelCar(orderArray.getJSONObject(i))); } productAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } if (modelCars.size() > 0) { if (priceMap.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < modelCars.size(); i++) { if (i > 0) { stringBuilder.append(","); } stringBuilder.append(modelCars.get(i).getProduct().getId()); } getPriceList(stringBuilder.toString()); } else { countTotalPrice(); productAdapter.notifyDataSetChanged(); } } else { missionNodata(); } } private void countTotalPrice() { totalPrice = 0; for (int i = 0; i < modelCars.size(); i++) { if (modelCars.get(i).isSelected()) { ModelProduct product = modelCars.get(i).getProduct(); if (priceMap.containsKey(product.getId())) { double price = priceMap.get(product.getId()).getPrice(); long count = modelCars.get(i).getProductCount(); if (price > 0) { totalPrice += count * price; } } } } totalPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(totalPrice)); } private void addOrder() { for (int i = 0; i < modelCars.size(); i++) { ModelProduct product = modelCars.get(i).getProduct(); if (priceMap.containsKey(product.getId())) { ModelListPrice price = priceMap.get(product.getId()); if (price.getPrice() > 0) { if (price.getNum() < modelCars.get(i).getProductCount()) { ApplicationTool.showToast("商品库存不足,无法下单"); return; } } else { ApplicationTool.showToast("有商品信息错误,无法下单"); return; } } else { ApplicationTool.showToast("有商品信息错误,无法下单"); return; } } if (addressFragment.getAddress() == null) { ApplicationTool.showToast("收货人信息有误"); } else { buy(); } } class ProductAdapter extends BaseAdapter { @Override public int getCount() { return modelCars.size(); } @Override public Object getItem(int position) { return modelCars.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_order_product, null); viewHolder = new ViewHolder(); viewHolder.attr = (TextView) convertView .findViewById(R.id.list_product_attr); viewHolder.price = (TextView) convertView .findViewById(R.id.list_product_price); viewHolder.count = (TextView) convertView .findViewById(R.id.list_product_count); viewHolder.name = (TextView) convertView .findViewById(R.id.list_product_name); viewHolder.img = (ImageView) convertView .findViewById(R.id.list_product_img); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ModelCar modelCar = modelCars.get(position); ModelProduct product = modelCar.getProduct(); ImageLoader.getInstance().displayImage(product.getImg(), viewHolder.img); viewHolder.count.setText(" × " + modelCar.getProductCount()); viewHolder.name.setText(product.getProductName()); viewHolder.attr.setText(product.getAttName()); if (priceMap.containsKey(product.getId())) { ModelListPrice price = priceMap.get(product.getId()); viewHolder.price.setText("¥" + decimalFormat.format(price.getPrice())); if (price.getNum() <= 0) { viewHolder.price.setText("无货"); } } return convertView; } class ViewHolder { ImageView img; TextView name, price, count, attr; } } private void buy() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("userNumber", User .getUser().getUseraccount())); requestParams.add(new RequestParam("customerName", addressFragment.getAddress().getPersonName())); requestParams.add(new RequestParam("phone", addressFragment .getAddress().getPhone())); requestParams .add(new RequestParam("shippingaddress", addressFragment.getAddress().getAreaAddress() + addressFragment.getAddress() .getDetailedAddress())); requestParams.add(new RequestParam("totalMoney", totalPrice + "")); requestParams.add(new RequestParam("sex", User.getUser() .getSex())); requestParams.add(new RequestParam("age", User.getUser() .getAge())); requestParams.add(new RequestParam("address", Store .getStore().getStoreArea())); requestParams.add(new RequestParam("jmdId", Store.getStore() .getStoreId())); requestParams.add(new RequestParam("orderType", "0")); JSONArray orderArray = new JSONArray(); try { for (int i = 0; i < modelCars.size(); i++) { ModelProduct product = modelCars.get(i).getProduct(); if (priceMap.containsKey(product.getId())) { JSONObject object = new JSONObject(); object.put("productIds", product.getId()); object.put("shopNum", modelCars.get(i) .getProductCount()); object.put("price", product.getPrice()); object.put("isIntegralMall", 0); orderArray.put(object); } } } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", orderArray .toString())); post(API.API_ORDER_ADD_CENTER, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { ApplicationTool.showToast("下单成功"); if (paymentFragment.getPaymentType() == OrderConfirmPartPaymentFragment.PAY_TYPE_CODE_ONLINE) { payMoney(object.optJSONArray("object")); getActivity().finish(); return; } showOrder(PayFragment.ORDER_TYPE_YY); getActivity().finish(); return; } ApplicationTool.showToast(object.optString("message")); return; } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("下单失败"); } }); } private void getPriceList(String productId) { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("jmdId", Store.getStore() .getStoreId())); requestParams.add(new RequestParam("productId", productId)); post(API.API_PRICE_LIST, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONArray priceArray = object.optJSONArray("dataList"); if (priceArray != null) { for (int i = 0; i < priceArray.length(); i++) { ModelListPrice priceList = new ModelListPrice( priceArray.getJSONObject(i)); priceMap.put(priceList.getProductId(), priceList); } countTotalPrice(); productAdapter.notifyDataSetChanged(); } } } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer.store.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.main.ui.MainActivity; import yitgogo.consumer.store.model.ModelArea; import yitgogo.consumer.store.model.ModelStoreSelected; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.ui.UserAddressEditFragment; import yitgogo.consumer.view.InnerGridView; public class StoreAreaFragment extends BaseNetworkFragment { ListView listView; InnerGridView gridView; List<ModelArea> listAreas, gridAreas; List<ModelStoreSelected> stores; AreaListAdapter areaListAdapter; AreaGridAdapter areaGridAdapter; StoreAdapter storeAdapter; boolean getArea = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_store_select_area); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(StoreAreaFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(StoreAreaFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getArea(null); } @Override protected void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("getArea")) { getArea = bundle.getBoolean("getArea"); } } listAreas = new ArrayList<>(); gridAreas = new ArrayList<>(); stores = new ArrayList<>(); areaGridAdapter = new AreaGridAdapter(); areaListAdapter = new AreaListAdapter(); storeAdapter = new StoreAdapter(); } @Override protected void findViews() { listView = (ListView) contentView .findViewById(R.id.store_select_selected); gridView = (InnerGridView) contentView .findViewById(R.id.store_select_selection); initViews(); } @Override protected void initViews() { listView.setAdapter(areaListAdapter); gridView.setAdapter(areaGridAdapter); } @Override protected void registerViews() { } private void getLocalBusinessState() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("organizationId", Store.getStore().getStoreId())); post(API.API_LOCAL_BUSINESS_STATE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { boolean showLocalBusiness = false; if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { showLocalBusiness = dataMap.optInt("returnNum") != 0; } } } catch (JSONException e) { e.printStackTrace(); } } Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra("showLocalBusiness", showLocalBusiness); startActivity(intent); getActivity().finish(); } }); } class AreaListAdapter extends BaseAdapter { @Override public int getCount() { return listAreas.size(); } @Override public Object getItem(int position) { return listAreas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final int index = position; ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_area_selected, null); holder = new ViewHolder(); holder.textView = (TextView) convertView .findViewById(R.id.list_area_selected); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.textView.setText(listAreas.get(position).getValuename()); holder.textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getArea(listAreas.get(index).getId()); listAreas = listAreas.subList(0, index + 1); areaListAdapter.notifyDataSetChanged(); } }); return convertView; } class ViewHolder { TextView textView; } } class AreaGridAdapter extends BaseAdapter { @Override public int getCount() { return gridAreas.size(); } @Override public Object getItem(int position) { return gridAreas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_area_selection, null); holder = new ViewHolder(); holder.textView = (TextView) convertView .findViewById(R.id.list_area_selection); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final ModelArea modelArea = gridAreas.get(position); holder.textView.setText(modelArea.getValuename()); holder.textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listAreas.add(modelArea); areaListAdapter.notifyDataSetChanged(); getArea(modelArea.getId()); } }); return convertView; } class ViewHolder { TextView textView; } } class StoreAdapter extends BaseAdapter { @Override public int getCount() { return stores.size(); } @Override public Object getItem(int position) { return stores.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_store_selected, null); holder = new ViewHolder(); holder.nameTextView = (TextView) convertView .findViewById(R.id.list_store_name); holder.addressTextView = (TextView) convertView .findViewById(R.id.list_store_address); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final ModelStoreSelected storeSelected = stores.get(position); holder.nameTextView.setText(storeSelected.getServicename()); holder.addressTextView.setText(storeSelected.getServiceaddress()); convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Content.saveIntContent(Parameters.CACHE_KEY_STORE_TYPE, Parameters.CACHE_VALUE_STORE_TYPE_SELECTED); Content.saveStringContent( Parameters.CACHE_KEY_STORE_JSONSTRING, storeSelected.getJsonObject().toString()); Store.init(getActivity()); getLocalBusinessState(); } }); return convertView; } class ViewHolder { TextView nameTextView, addressTextView; } } private void getArea(String aid) { stores.clear(); storeAdapter.notifyDataSetChanged(); gridAreas.clear(); areaGridAdapter.notifyDataSetChanged(); gridView.setNumColumns(3); gridView.setAdapter(areaGridAdapter); List<RequestParam> requestParams = new ArrayList<>(); if (!TextUtils.isEmpty(aid)) { requestParams.add(new RequestParam("aid", aid)); } post(API.API_STORE_AREA, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONArray array = object.optJSONArray("dataList"); if (array != null) { for (int i = 0; i < array.length(); i++) { gridAreas.add(new ModelArea(array .getJSONObject(i))); } if (gridAreas.size() > 0) { areaGridAdapter.notifyDataSetChanged(); return; } } String areaId = listAreas.get(listAreas.size() - 1) .getId(); if (getArea) { String areaName = ""; for (int i = 0; i < listAreas.size(); i++) { if (i > 0) { areaName += ">"; } areaName += listAreas.get(i).getValuename(); } UserAddressEditFragment.areaId = areaId; UserAddressEditFragment.areaName = areaName; getActivity().finish(); return; } getStore(areaId); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getStore(String areaId) { stores.clear(); storeAdapter.notifyDataSetChanged(); gridAreas.clear(); areaGridAdapter.notifyDataSetChanged(); gridView.setNumColumns(1); gridView.setAdapter(storeAdapter); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("areaId", areaId)); post(API.API_STORE_LIST, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONArray array = object.optJSONArray("dataList"); if (array != null) { for (int i = 0; i < array.length(); i++) { stores.add(new ModelStoreSelected(array .getJSONObject(i))); } if (stores.size() > 0) { storeAdapter.notifyDataSetChanged(); } else { missionNodata(); } } } } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer.money.ui; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.RequestParam; public class PayPasswordFindFragment extends BaseNetworkFragment { TextView getCodeButton; EditText idcardEditText, smsCodeEditText; Button button; List<RequestParam> requestParams = new ArrayList<>(); Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj != null) { getCodeButton.setText(msg.obj + "s"); } else { getCodeButton.setClickable(true); getCodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getCodeButton.setText("获取验证码"); } } ; }; boolean isFinish = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_password_find); findViews(); } @Override protected void init() { } @Override protected void initViews() { } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(PayPasswordFindFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(PayPasswordFindFragment.class.getName()); } @Override public void onDestroy() { super.onDestroy(); isFinish = true; } @Override protected void findViews() { idcardEditText = (EditText) contentView .findViewById(R.id.find_pay_password_idcard); getCodeButton = (TextView) contentView .findViewById(R.id.find_pay_password_smscode_get); smsCodeEditText = (EditText) contentView .findViewById(R.id.find_pay_password_smscode); button = (Button) contentView.findViewById(R.id.find_pay_password_ok); registerViews(); } @Override protected void registerViews() { getCodeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getSmsCode(); } }); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { findPassword(); } }); } private void findPassword() { requestParams.clear(); if (TextUtils.isEmpty(idcardEditText.getText().toString().trim())) { ApplicationTool.showToast("请输入您的身份证号码"); } else if (TextUtils.isEmpty(smsCodeEditText.getText().toString() .trim())) { ApplicationTool.showToast("请输入您收到的验证码"); } else { requestParams.add(new RequestParam("seckey", MoneyAccount.getMoneyAccount().getSeckey())); requestParams.add(new RequestParam("cardid", idcardEditText.getText().toString().trim())); requestParams.add(new RequestParam("mcode", smsCodeEditText.getText().toString().trim())); PayPasswordDialog newPasswordDialog = new PayPasswordDialog("请输入新支付密码", false) { public void onDismiss(DialogInterface dialog) { if (!TextUtils.isEmpty(payPassword)) { requestParams.add(new RequestParam("newpaypwd", payPassword)); findPayPassword(); } super.onDismiss(dialog); } }; newPasswordDialog.show(getFragmentManager(), null); } } private void findPayPassword() { post(API.MONEY_PAY_PASSWORD_FIND, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { requestParams.clear(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject databody = object.optJSONObject("databody"); if (databody != null) { if (databody.optString("paypwd").equalsIgnoreCase( "ok")) { ApplicationTool.showToast("修改支付密码成功"); getActivity().finish(); return; } } ApplicationTool.showToast("修改支付密码失败"); return; } ApplicationTool.showToast(object.optString("msg")); return; } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("修改支付密码失败"); } }); } private void getSmsCode() { post(API.MONEY_SMS_CODE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject databody = object.optJSONObject("databody"); if (databody != null) { if (databody.optString("send").equalsIgnoreCase( "ok")) { getCodeButton.setClickable(false); new Thread(new Runnable() { @Override public void run() { int time = 60; while (time > -1) { if (isFinish) { break; } try { Message message = new Message(); if (time > 0) { message.obj = time; } handler.sendMessage(message); Thread.sleep(1000); time--; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); ApplicationTool.showToast("已将验证码发送至尾号为 " + databody.optString("mobile") + " 的手机"); return; } } } ApplicationTool.showToast(object.optString("msg")); } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer.order.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.dtr.zxing.activity.CaptureActivity; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.product.model.ModelProduct; import yitgogo.consumer.product.model.ModelSaleDetailMiaosha; import yitgogo.consumer.product.model.ModelSaleDetailTejia; import yitgogo.consumer.product.model.ModelSaleDetailTime; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; public class SaleProductOrderConfirmFragment extends BaseNetworkFragment { ImageView imageView; TextView nameTextView, priceTextView, countTextView, countAddButton, countDeleteButton, additionTextView; FrameLayout addressLayout, paymentLayout; TextView totalPriceTextView, confirmButton; String productId = ""; int saleType = CaptureActivity.SALE_TYPE_NONE; ModelProduct product = new ModelProduct(); ModelOrderProduct orderProduct = new ModelOrderProduct(); OrderConfirmPartAddressFragment addressFragment; OrderConfirmPartPaymentFragment paymentFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_confirm_order_sale); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(SaleProductOrderConfirmFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(SaleProductOrderConfirmFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getProductDetail(); } @Override protected void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("productId")) { productId = bundle.getString("productId"); } if (bundle.containsKey("saleType")) { saleType = bundle.getInt("saleType"); } } addressFragment = new OrderConfirmPartAddressFragment(); paymentFragment = new OrderConfirmPartPaymentFragment(true, false); } protected void findViews() { imageView = (ImageView) contentView .findViewById(R.id.order_confirm_sale_image); nameTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_name); priceTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_price); countTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_count); countDeleteButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_count_delete); countAddButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_count_add); additionTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_addition); addressLayout = (FrameLayout) contentView .findViewById(R.id.order_confirm_sale_address); paymentLayout = (FrameLayout) contentView .findViewById(R.id.order_confirm_sale_payment); totalPriceTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_total_money); confirmButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_confirm); initViews(); registerViews(); } @Override protected void initViews() { getFragmentManager().beginTransaction() .replace(R.id.order_confirm_sale_address, addressFragment) .replace(R.id.order_confirm_sale_payment, paymentFragment) .commit(); } @Override protected void registerViews() { confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addOrder(); } }); countDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { deleteCount(); } }); countAddButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addCount(); } }); } private void showProductInfo() { ImageLoader.getInstance().displayImage(product.getImg(), imageView); nameTextView.setText(product.getProductName()); if (orderProduct.isSale()) { priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(orderProduct.getSalePrice())); } else { priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(product.getPrice())); } countTextView.setText(orderProduct.getBuyCount() + ""); additionTextView.setText(orderProduct.getAddition()); totalPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(countTotalPrice())); } private void deleteCount() { if (orderProduct.getBuyCount() > 1) { orderProduct.setBuyCount(orderProduct.getBuyCount() - 1); } if (orderProduct.getBuyCount() == 1) { countDeleteButton.setClickable(false); } countAddButton.setClickable(true); countTextView.setText(orderProduct.getBuyCount() + ""); totalPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(countTotalPrice())); } private void addCount() { if (orderProduct.isSale()) { if (orderProduct.getMaxBuyCount() > 0) { if (orderProduct.getMaxBuyCount() > orderProduct.getStock()) { if (orderProduct.getBuyCount() < orderProduct.getStock()) { orderProduct .setBuyCount(orderProduct.getBuyCount() + 1); } if (orderProduct.getBuyCount() == orderProduct.getStock()) { countAddButton.setClickable(false); } } else { if (orderProduct.getBuyCount() < orderProduct .getMaxBuyCount()) { orderProduct .setBuyCount(orderProduct.getBuyCount() + 1); } if (orderProduct.getBuyCount() == orderProduct .getMaxBuyCount()) { countAddButton.setClickable(false); } } } else if (orderProduct.getStock() > 0) { if (orderProduct.getBuyCount() < orderProduct.getStock()) { orderProduct.setBuyCount(orderProduct.getBuyCount() + 1); } if (orderProduct.getBuyCount() == orderProduct.getStock()) { countAddButton.setClickable(false); } } else { if (orderProduct.getBuyCount() < product.getNum()) { orderProduct.setBuyCount(orderProduct.getBuyCount() + 1); } if (orderProduct.getBuyCount() == product.getNum()) { countAddButton.setClickable(false); } } } else { if (orderProduct.getBuyCount() < product.getNum()) { orderProduct.setBuyCount(orderProduct.getBuyCount() + 1); } if (orderProduct.getBuyCount() == product.getNum()) { countAddButton.setClickable(false); } } countDeleteButton.setClickable(true); countTextView.setText(orderProduct.getBuyCount() + ""); totalPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(countTotalPrice())); } private void getProductSaleInfo() { switch (saleType) { case CaptureActivity.SALE_TYPE_MIAOSHA: getMiaoshaSaleDetail(); break; case CaptureActivity.SALE_TYPE_TEJIA: getTejiaSaleDetail(); break; case CaptureActivity.SALE_TYPE_TIME: getTimeSaleDetail(); break; default: showProductInfo(); break; } } private double countTotalPrice() { double totalPrice = 0; if (orderProduct.isSale()) { totalPrice = orderProduct.getSalePrice() * orderProduct.getBuyCount(); } else { totalPrice = product.getPrice() * orderProduct.getBuyCount(); } return totalPrice; } private void addOrder() { if (addressFragment.getAddress() == null) { ApplicationTool.showToast("收货人信息有误"); } else { buy(); } } private void buy() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("userNumber", User .getUser().getUseraccount())); requestParams.add(new RequestParam("customerName", addressFragment.getAddress().getPersonName())); requestParams.add(new RequestParam("phone", addressFragment .getAddress().getPhone())); requestParams .add(new RequestParam("shippingaddress", addressFragment.getAddress().getAreaAddress() + addressFragment.getAddress() .getDetailedAddress())); requestParams.add(new RequestParam("totalMoney", countTotalPrice() + "")); requestParams.add(new RequestParam("sex", User.getUser() .getSex())); requestParams.add(new RequestParam("age", User.getUser() .getAge())); requestParams.add(new RequestParam("address", Store .getStore().getStoreArea())); requestParams.add(new RequestParam("jmdId", Store.getStore() .getStoreId())); requestParams.add(new RequestParam("orderType", "0")); JSONArray orderArray = new JSONArray(); try { JSONObject object = new JSONObject(); object.put("productIds", productId); object.put("shopNum", orderProduct.getBuyCount()); if (orderProduct.isSale()) { object.put("price", orderProduct.getSalePrice()); } else { object.put("price", product.getPrice()); } switch (saleType) { case CaptureActivity.SALE_TYPE_MIAOSHA: object.put("isIntegralMall", 2); break; default: object.put("isIntegralMall", 0); break; } orderArray.put(object); } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", orderArray .toString())); post(API.API_ORDER_ADD_CENTER, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { Toast.makeText(getActivity(), "下单成功", Toast.LENGTH_SHORT).show(); if (paymentFragment.getPaymentType() == OrderConfirmPartPaymentFragment.PAY_TYPE_CODE_ONLINE) { payMoney(object.optJSONArray("object")); getActivity().finish(); return; } showOrder(PayFragment.ORDER_TYPE_YY); getActivity().finish(); return; } else { ApplicationTool.showToast(object.optString("message")); return; } } catch (JSONException e) { ApplicationTool.showToast("下单失败"); e.printStackTrace(); return; } } ApplicationTool.showToast("下单失败"); } }); } private void getProductDetail() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("jmdId", Store.getStore() .getStoreId())); requestParams.add(new RequestParam("productId", productId)); post(API.API_PRODUCT_DETAIL, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase( "SUCCESS")) { JSONObject detailObject = object .optJSONObject("dataMap"); if (detailObject != null) { product = new ModelProduct(detailObject); getProductSaleInfo(); } } } catch (JSONException e) { e.printStackTrace(); } } } } }); } private void getMiaoshaSaleDetail() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("productId", productId)); post(API.API_SALE_MIAOSHA_DETAIL, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { try { ModelSaleDetailMiaosha saleDetailMiaosha = new ModelSaleDetailMiaosha( result); if (saleDetailMiaosha != null) { orderProduct = new ModelOrderProduct(saleDetailMiaosha); showProductInfo(); } } catch (JSONException e) { e.printStackTrace(); } } }); } private void getTimeSaleDetail() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("productId", productId)); post(API.API_SALE_TIME_DETAIL, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { try { ModelSaleDetailTime saleDetailTime = new ModelSaleDetailTime( result); if (saleDetailTime != null) { orderProduct = new ModelOrderProduct(saleDetailTime); showProductInfo(); } } catch (JSONException e) { e.printStackTrace(); } } }); } private void getTejiaSaleDetail() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("productId", productId)); post(API.API_SALE_TEJIA_DETAIL, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { try { ModelSaleDetailTejia saleDetailTejia = new ModelSaleDetailTejia( result); if (saleDetailTejia != null) { orderProduct = new ModelOrderProduct(saleDetailTejia); showProductInfo(); } } catch (JSONException e) { e.printStackTrace(); } } }); } class ModelOrderProduct { double salePrice = -1, price = -1; boolean isSale = false; long buyCount = 1, stock = -1, maxBuyCount = -1; String addition = ""; public ModelOrderProduct(ModelSaleDetailMiaosha saleDetailMiaosha) { if (saleDetailMiaosha != null) { salePrice = saleDetailMiaosha.getSeckillPrice(); price = saleDetailMiaosha.getPrice(); if (saleDetailMiaosha.getSeckillPrice() > 0) { // 开始时间<=当前时间,活动已开始 if (saleDetailMiaosha.getStartTime() <= Calendar .getInstance().getTime().getTime()) { // 剩余秒杀数量>0,显示秒杀信息 if (saleDetailMiaosha.getSeckillNUmber() > 0) { isSale = true; stock = saleDetailMiaosha.getSeckillNUmber(); maxBuyCount = saleDetailMiaosha.getMemberNumber(); addition = "剩余" + stock + "件,限购" + maxBuyCount + "件"; } else { isSale = false; addition = "秒杀结束,按原价购买"; } } else { // 开始时间>当前时间,活动未开始,显示预告 isSale = false; addition = "秒杀未开始,按原价购买"; } } } } public ModelOrderProduct(ModelSaleDetailTejia saleDetailTejia) { if (saleDetailTejia != null) { salePrice = saleDetailTejia.getSalePrice(); price = saleDetailTejia.getPrice(); if (saleDetailTejia.getSalePrice() > 0) { if (saleDetailTejia.getNumbers() > 0) { isSale = true; stock = saleDetailTejia.getNumbers(); } else { isSale = false; addition = "活动已结束,按原价购买"; } } } } public ModelOrderProduct(ModelSaleDetailTime saleDetailTime) { if (saleDetailTime != null) { salePrice = saleDetailTime.getPromotionPrice(); price = saleDetailTime.getPrice(); if (saleDetailTime.getPromotionPrice() > 0) { // 开始时间>当前时间,未开始,显示活动预告 if (saleDetailTime.getStartTime() > Calendar.getInstance() .getTime().getTime()) { isSale = false; addition = "活动未开始,按原价购买"; } else if (saleDetailTime.getEndTime() > Calendar .getInstance().getTime().getTime()) { // 开始时间<=当前时间,结束时间>当前时间,已开始未结束,活动进行时 isSale = true; } else { // 活动结束 isSale = false; addition = "活动已结束,按原价购买"; } } } } public ModelOrderProduct() { } public double getSalePrice() { return salePrice; } public double getPrice() { return price; } public boolean isSale() { return isSale; } public long getBuyCount() { return buyCount; } public long getStock() { return stock; } public long getMaxBuyCount() { return maxBuyCount; } public String getAddition() { return addition; } public void setBuyCount(long buyCount) { this.buyCount = buyCount; } } } <file_sep>package yitgogo.consumer.user.ui; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.Notify; import android.os.AsyncTask; import android.os.Bundle; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class UserLoginFragment extends BaseNotifyFragment implements OnClickListener { EditText nameEdit, passwordEdit; Button loginButton; TextView registerButton, passwordButton; ImageView showPassword; boolean isShown = false; String phone = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_login); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserLoginFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserLoginFragment.class.getName()); } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("phone")) { phone = bundle.getString("phone"); } } } @Override protected void findViews() { nameEdit = (EditText) contentView.findViewById(R.id.user_login_name); passwordEdit = (EditText) contentView .findViewById(R.id.user_login_password); loginButton = (Button) contentView.findViewById(R.id.user_login_login); registerButton = (TextView) contentView .findViewById(R.id.user_login_register); passwordButton = (TextView) contentView .findViewById(R.id.user_login_findpassword); showPassword = (ImageView) contentView .findViewById(R.id.user_login_password_show); initViews(); registerViews(); } @Override protected void initViews() { nameEdit.setText(phone); } @Override protected void registerViews() { loginButton.setOnClickListener(this); registerButton.setOnClickListener(this); passwordButton.setOnClickListener(this); showPassword.setOnClickListener(this); } private void login() { if (!isPhoneNumber(nameEdit.getText().toString())) { Notify.show("请输入正确的手机号"); } else if (passwordEdit.length() == 0) { Notify.show("请输入密码"); } else { new Login().execute(); } } private void showPassword() { if (isShown) { passwordEdit.setTransformationMethod(PasswordTransformationMethod .getInstance()); } else { passwordEdit .setTransformationMethod(HideReturnsTransformationMethod .getInstance()); } isShown = !isShown; if (isShown) { showPassword.setImageResource(R.drawable.ic_hide); } else { showPassword.setImageResource(R.drawable.ic_show); } } class Login extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading("正在登录..."); } @Override protected String doInBackground(Void... arg0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("phone", nameEdit .getText().toString())); nameValuePairs .add(new BasicNameValuePair("password", getEncodedPassWord(passwordEdit.getText() .toString().trim()))); return netUtil .postAndSaveCookie(API.API_USER_LOGIN, nameValuePairs); } @Override protected void onPostExecute(String result) { // {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[],"totalCount":1,"dataMap":{},"object":{"id":470,"useraccount":"13032889558","realname":"Tiger","phone":"13032889558","area":null,"address":"凤凰大厦","uImg":null,"addtime":"2014-11-10 16:43:09","email":"<EMAIL>","sex":"男","age":"21","birthday":755971200000,"idcard":"513030199311056012","spid":"0","memtype":"手机"}} // {"message":"登陆失败,账号或密码错误!","state":"ERROR"} hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { Notify.show("登录成功"); Content.saveStringContent( Parameters.CACHE_KEY_MONEY_SN, object.optString("cacheKey")); JSONObject userObject = object.optJSONObject("object"); if (userObject != null) { Content.saveStringContent( Parameters.CACHE_KEY_USER_JSON, userObject.toString()); Content.saveStringContent( Parameters.CACHE_KEY_USER_PASSWORD, getEncodedPassWord(passwordEdit.getText() .toString().trim())); User.init(getActivity()); } getActivity().finish(); } else { Notify.show(object.optString("message")); } } catch (JSONException e) { Notify.show("登录失败"); e.printStackTrace(); } } else { Notify.show("登录失败"); } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.user_login_login: login(); break; case R.id.user_login_register: jump(UserRegisterFragment.class.getName(), "注册"); getActivity().finish(); break; case R.id.user_login_password_show: showPassword(); break; case R.id.user_login_findpassword: jump(UserFindPasswordFragment.class.getName(), "重设密码"); break; default: break; } } } <file_sep>package yitgogo.consumer.money.ui; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.money.model.ModelBankCard; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.InnerListView; public class BankCardFragment extends BaseNetworkFragment { LinearLayout addButton; InnerListView cardListView; List<ModelBankCard> bankCards; BandCardAdapter bandCardAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_backcard_list); init(); findViews(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(BankCardFragment.class.getName()); } @Override protected void init() { bankCards = new ArrayList<>(); bandCardAdapter = new BandCardAdapter(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(BankCardFragment.class.getName()); getBankCards(); } @Override protected void findViews() { cardListView = (InnerListView) contentView .findViewById(R.id.bank_card_list); addButton = (LinearLayout) contentView.findViewById(R.id.bank_card_add); addImageButton(R.drawable.address_add, "添加银行卡", new OnClickListener() { @Override public void onClick(View v) { havePayPassword(); } }); initViews(); registerViews(); } @Override protected void initViews() { cardListView.setAdapter(bandCardAdapter); } @Override protected void registerViews() { addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { havePayPassword(); } }); cardListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Bundle bundle = new Bundle(); bundle.putString("bankCard", bankCards.get(arg2) .getJsonObject().toString()); jump(BankCardDetailFragment.class.getName(), "我的银行卡", bundle); } }); } class BandCardAdapter extends BaseAdapter { @Override public int getCount() { return bankCards.size(); } @Override public Object getItem(int position) { return bankCards.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_money_bank_card, null); viewHolder.imageView = (ImageView) convertView .findViewById(R.id.bank_card_bank_image); viewHolder.cardNumberTextView = (TextView) convertView .findViewById(R.id.bank_card_number); viewHolder.cardTypeTextView = (TextView) convertView .findViewById(R.id.bank_card_type); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ImageLoader.getInstance().displayImage( bankCards.get(position).getBank().getIcon(), viewHolder.imageView); viewHolder.cardNumberTextView.setText(getSecretCardNuber(bankCards .get(position).getBanknumber())); viewHolder.cardTypeTextView.setText(bankCards.get(position) .getBank().getName() + " " + bankCards.get(position).getCardType()); return convertView; } class ViewHolder { ImageView imageView; TextView cardNumberTextView, cardTypeTextView; } } private void havePayPassword() { post(API.MONEY_PAY_PASSWORD_STATE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject jsonObject = object.optJSONObject("databody"); if (jsonObject != null) { if (jsonObject.optBoolean("pwd")) { // 已设置支付密码 jump(BankCardBindFragment.class.getName(), "添加银行卡"); } else { // 未设置支付密码 ApplicationTool.showToast("请先设置支付密码"); jump(PayPasswordSetFragment.class.getName(), "设置支付密码"); } return; } } } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("访问服务器失败,请稍候再试!"); } }); } private void getBankCards() { MoneyAccount.getMoneyAccount().getBankCards().clear(); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("sn", User.getUser().getCacheKey())); requestParams.add(new RequestParam("memberid", User.getUser().getUseraccount())); post(API.MONEY_BANK_BINDED, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { initbankCards(result); bankCards = MoneyAccount.getMoneyAccount().getBankCards(); bandCardAdapter.notifyDataSetChanged(); } }); } private void initbankCards(String result) { MoneyAccount.getMoneyAccount().getBankCards().clear(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONArray array = object.optJSONArray("databody"); if (array != null) { List<ModelBankCard> bankCards = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { bankCards.add(new ModelBankCard(array.optJSONObject(i))); } MoneyAccount.getMoneyAccount().setGetBankCardFailed( false); MoneyAccount.getMoneyAccount().setBankCards(bankCards); return; } } MoneyAccount.getMoneyAccount().setGetBankCardFailed(true); ApplicationTool.showToast(object.optString("msg")); return; } catch (JSONException e) { e.printStackTrace(); } } MoneyAccount.getMoneyAccount().setGetBankCardFailed(true); ApplicationTool.showToast("获取绑定的银行卡信息失败!"); return; } } <file_sep>package yitgogo.consumer.order.ui; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.order.model.ModelWuliu; import yitgogo.consumer.order.model.ModelWuliuDetail; import yitgogo.consumer.tools.API; import yitgogo.consumer.view.InnerListView; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ScrollView; import android.widget.TextView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class OrderWuliuFragment extends BaseNotifyFragment { PullToRefreshScrollView refreshScrollView; TextView wuliuStateText; InnerListView wuliuList; List<ModelWuliu> wulius; WuliuAdapter wuliuAdapter; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss"); String orderNumber = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_order_wuliu); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(OrderWuliuFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(OrderWuliuFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetOrderWuliu().execute(); } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("orderNumber")) { orderNumber = bundle.getString("orderNumber"); } } wulius = new ArrayList<ModelWuliu>(); wuliuAdapter = new WuliuAdapter(); } @Override protected void findViews() { refreshScrollView = (PullToRefreshScrollView) contentView .findViewById(R.id.wuliu_refresh); wuliuStateText = (TextView) contentView.findViewById(R.id.wuliu_state); wuliuList = (InnerListView) contentView.findViewById(R.id.wuliu_list); initViews(); registerViews(); } @Override protected void initViews() { wuliuList.setAdapter(wuliuAdapter); refreshScrollView.setMode(Mode.PULL_FROM_START); } @Override protected void registerViews() { refreshScrollView .setOnRefreshListener(new OnRefreshListener<ScrollView>() { @Override public void onRefresh( PullToRefreshBase<ScrollView> refreshView) { new GetOrderWuliu().execute(); } }); } class WuliuAdapter extends BaseAdapter { @Override public int getCount() { return wulius.size(); } @Override public Object getItem(int position) { return wulius.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_wuliu_item, null); holder = new ViewHolder(); holder.companyNameText = (TextView) convertView .findViewById(R.id.wuliu_item_company); holder.numberText = (TextView) convertView .findViewById(R.id.wuliu_item_number); holder.senderText = (TextView) convertView .findViewById(R.id.wuliu_item_sender); holder.stateText = (TextView) convertView .findViewById(R.id.wuliu_item_state); holder.dateText = (TextView) convertView .findViewById(R.id.wuliu_item_date); holder.detailList = (InnerListView) convertView .findViewById(R.id.wuliu_item_list); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelWuliu wuliu = wulius.get(position); holder.companyNameText.setText(wuliu.getCompanyName()); holder.numberText.setText(wuliu.getWayBill()); holder.senderText.setText("发货商家:" + wuliu.getPerson() + "\n商家电话:" + wuliu.getPersonPhone() + "\n发货时间:" + wuliu.getDeliveryTime()); if (wuliu.isSuceess()) { holder.stateText.setText(wuliu.getWuliuObject().getStatus()); holder.detailList.setAdapter(new WuliuDetailAdapter(wuliu .getWuliuObject().getWuliuDetails())); } else { holder.dateText.setText(wuliu.getMessage()); } return convertView; } class ViewHolder { TextView companyNameText, numberText, senderText, stateText, dateText; InnerListView detailList; } } class WuliuDetailAdapter extends BaseAdapter { List<ModelWuliuDetail> wuliuDetails; public WuliuDetailAdapter(List<ModelWuliuDetail> wuliuDetails) { this.wuliuDetails = wuliuDetails; } @Override public int getCount() { return wuliuDetails.size(); } @Override public Object getItem(int position) { return wuliuDetails.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_wuliu_detail, null); holder = new ViewHolder(); holder.detailText = (TextView) convertView .findViewById(R.id.wuliu_detail_text); holder.timeText = (TextView) convertView .findViewById(R.id.wuliu_detail_time); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelWuliuDetail wuliu = wuliuDetails.get(position); holder.timeText.setText(wuliu.getTime()); holder.detailText.setText(wuliu.getContext()); return convertView; } class ViewHolder { TextView timeText, detailText; } } class GetOrderWuliu extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); wulius.clear(); wuliuAdapter.notifyDataSetChanged(); } @Override protected String doInBackground(Void... arg0) { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("orderNumber", orderNumber)); return netUtil.postWithoutCookie(API.API_ORDER_WULIU, parameters, false, false); } @Override protected void onPostExecute(String result) { hideLoading(); refreshScrollView.onRefreshComplete(); if (result.length() > 0) { try { JSONObject object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONArray wuliuArray = object.optJSONArray("dataList"); if (wuliuArray != null) { for (int i = 0; i < wuliuArray.length(); i++) { JSONObject wuliuObject = wuliuArray .optJSONObject(i); if (wuliuObject != null) { wulius.add(new ModelWuliu(wuliuObject)); } } } if (wulius.size() > 0) { wuliuStateText.setText("有" + wulius.size() + "条物流信息"); wuliuAdapter.notifyDataSetChanged(); } else { wuliuStateText.setText("暂无物流信息"); } } else { wuliuStateText.setText("暂无物流信息"); } } catch (JSONException e) { wuliuStateText.setText("暂无物流信息"); e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.order.ui; import android.os.Bundle; import com.smartown.yitian.gogo.R; import yitgogo.consumer.BaseNetworkFragment; /** * Created by Tiger on 2015-11-26. */ public class OrderPlatformReturnCommitedFragment extends BaseNetworkFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_platform_order_return_commited); } @Override protected void findViews() { } @Override protected void init() { } @Override protected void initViews() { } @Override protected void registerViews() { } } <file_sep>package yitgogo.smart.suning.model; import org.json.JSONObject; /** * Created by Tiger on 2015-10-19. */ public class ModelProductPool { String commonPartnum = "", sku = ""; JSONObject jsonObject = new JSONObject(); public ModelProductPool() { } public ModelProductPool(JSONObject object) { if (object != null) { jsonObject = object; if (object.has("commonPartnum")) { if (!object.optString("commonPartnum").equalsIgnoreCase("null")) { commonPartnum = object.optString("commonPartnum"); } } if (object.has("sku")) { if (!object.optString("sku").equalsIgnoreCase("null")) { sku = object.optString("sku"); } } } } public String getCommonPartnum() { return commonPartnum; } public String getSku() { return sku; } public JSONObject getJsonObject() { return jsonObject; } } <file_sep>package yitgogo.consumer.user.ui; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.store.SelectAreaFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.Notify; /** * 用户收货地址管理(添加/修改) * * @author Tiger */ public class UserAddressEditFragment extends BaseNotifyFragment { EditText nameEditText, phoneEditText, addressEditText, telephoneEditText, postcodeEditText, emailEditText; TextView areaTextView; Button addButton; String addressId = ""; String areaName = "", areaId = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_address_edit); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserAddressEditFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserAddressEditFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetAddressDetail().execute(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 22) { if (resultCode == 23) { areaName = data.getStringExtra("name"); areaId = data.getStringExtra("id"); areaTextView.setText(areaName); } } } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("addressId")) { addressId = bundle.getString("addressId"); } } } @Override protected void findViews() { nameEditText = (EditText) contentView .findViewById(R.id.address_add_name); phoneEditText = (EditText) contentView .findViewById(R.id.address_add_phone); addressEditText = (EditText) contentView .findViewById(R.id.address_add_address); telephoneEditText = (EditText) contentView .findViewById(R.id.address_add_telephone); postcodeEditText = (EditText) contentView .findViewById(R.id.address_add_postcode); emailEditText = (EditText) contentView .findViewById(R.id.address_add_email); areaTextView = (TextView) contentView .findViewById(R.id.address_add_area); addButton = (Button) contentView.findViewById(R.id.address_add_add); initViews(); registerViews(); } @Override protected void initViews() { if (addressId.length() > 0) { addButton.setText("修改"); } } @Override protected void registerViews() { areaTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putInt("type", SelectAreaFragment.TYPE_GET_AREA); jumpForResult(SelectAreaFragment.class.getName(), "选择区域", bundle, 22); } }); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editAddress(); } }); } private void editAddress() { if (nameEditText.length() <= 0) { Notify.show("请输入收货人姓名"); } else if (phoneEditText.length() <= 0) { Notify.show("请输入收货人手机号"); } else if (!isPhoneNumber(phoneEditText.getText().toString())) { Notify.show("请输入正确的手机号"); } else if (areaId.length() <= 0) { Notify.show("请选择收货区域"); } else if (addressEditText.length() <= 0) { Notify.show("请输入详细收货地址"); } else if (telephoneEditText.length() > 0 & telephoneEditText.length() < 11) { Notify.show("请输入正确的固定电话号码"); } else if (postcodeEditText.length() > 0 & postcodeEditText.length() < 6) { Notify.show("请输入正确的邮政编码"); } else { if (addressId.length() > 0) { new ModifyAddress().execute(); } else { new AddAdress().execute(); } } } /** * 添加收货地址 */ class AddAdress extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("memberAccount", User .getUser().getUseraccount())); nameValuePairs.add(new BasicNameValuePair("personName", nameEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("phone", phoneEditText .getText().toString())); nameValuePairs.add(new BasicNameValuePair("areaAddress", areaName)); nameValuePairs.add(new BasicNameValuePair("areaId", areaId)); nameValuePairs.add(new BasicNameValuePair("detailedAddress", addressEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("fixPhone", telephoneEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("postcode", postcodeEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("email", emailEditText .getText().toString())); return netUtil.postWithCookie(API.API_USER_ADDRESS_ADD, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { Notify.show("添加成功"); getActivity().finish(); } else { Toast.makeText(getActivity(), object.getString("message"), Toast.LENGTH_SHORT) .show(); } } catch (JSONException e) { e.printStackTrace(); } } } } /** * 获取地址详情对象 * * @author Tiger * @Json {"message":"ok","state":"SUCCESS" * ,"cacheKey":null,"dataList":[],"totalCount" * :1,"dataMap":{"updateMemberAddress" * :{"id":3,"personName":"赵晋","areaId":2421 * ,"areaAddress":"四川省成都市金牛区","detailedAddress" * :"解放路二段6号凤凰大厦","phone":"18584182653" * ,"fixPhone":"","postcode":"","email":"" * ,"isDefault":1,"memberAccount":"18584182653" * ,"millis":1438598019428},"secondId" * :269,"thirdId":2421,"firstId":23},"object":null} */ class GetAddressDetail extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("id", addressId)); return netUtil.postWithCookie(API.API_USER_ADDRESS_DETAIL, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { JSONObject updateMemberAddress = dataMap .optJSONObject("updateMemberAddress"); if (updateMemberAddress != null) { if (updateMemberAddress.has("personName")) { if (!updateMemberAddress.optString( "personName").equalsIgnoreCase( "null")) { nameEditText .setText(updateMemberAddress .optString("personName")); } } if (updateMemberAddress.has("areaAddress")) { if (!updateMemberAddress.optString( "areaAddress").equalsIgnoreCase( "null")) { areaName = updateMemberAddress .optString("areaAddress"); areaTextView.setText(areaName); } } if (updateMemberAddress.has("areaId")) { if (!updateMemberAddress .optString("areaId") .equalsIgnoreCase("null")) { areaId = updateMemberAddress .optString("areaId"); } } if (updateMemberAddress.has("detailedAddress")) { if (!updateMemberAddress.optString( "detailedAddress") .equalsIgnoreCase("null")) { addressEditText .setText(updateMemberAddress .optString("detailedAddress")); } } if (updateMemberAddress.has("phone")) { if (!updateMemberAddress.optString("phone") .equalsIgnoreCase("null")) { phoneEditText .setText(updateMemberAddress .optString("phone")); } } if (updateMemberAddress.has("fixPhone")) { if (!updateMemberAddress.optString( "fixPhone") .equalsIgnoreCase("null")) { telephoneEditText .setText(updateMemberAddress .optString("fixPhone")); } } if (updateMemberAddress.has("postcode")) { if (!updateMemberAddress.optString( "postcode") .equalsIgnoreCase("null")) { postcodeEditText .setText(updateMemberAddress .optString("postcode")); } } if (updateMemberAddress.has("email")) { if (!updateMemberAddress.optString("email") .equalsIgnoreCase("null")) { emailEditText .setText(updateMemberAddress .optString("email")); } } } } } } catch (JSONException e) { e.printStackTrace(); } } } } /** * 修改地址信息 * * @author Tiger */ class ModifyAddress extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("id", addressId)); nameValuePairs.add(new BasicNameValuePair("personName", nameEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("phone", phoneEditText .getText().toString())); nameValuePairs.add(new BasicNameValuePair("areaAddress", areaName)); nameValuePairs.add(new BasicNameValuePair("areaId", areaId)); nameValuePairs.add(new BasicNameValuePair("detailedAddress", addressEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("fixPhone", telephoneEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("postcode", postcodeEditText.getText().toString())); nameValuePairs.add(new BasicNameValuePair("email", emailEditText .getText().toString())); return netUtil.postWithCookie(API.API_USER_ADDRESS_MODIFY, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { Notify.show("修改成功"); getActivity().finish(); } else { Toast.makeText(getActivity(), object.getString("message"), Toast.LENGTH_SHORT) .show(); } } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.home.task; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import android.os.AsyncTask; public class GetLoveFresh extends AsyncTask<Boolean, Void, String> { @Override protected String doInBackground(Boolean... params) { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("pageNo", "1")); parameters.add(new BasicNameValuePair("pageSize", "5")); parameters.add(new BasicNameValuePair("organizationId", Store .getStore().getStoreId())); return NetUtil.getInstance().postWithoutCookie( API.API_LOCAL_BUSINESS_SERVICE_FRESH, parameters, params[0], true); } } <file_sep>package yitgogo.consumer.product.ui; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.local.ui.LocalGoodsSearchFragment; import yitgogo.consumer.local.ui.LocalServiceSearchFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; public class ProductSearchFragment extends BaseNetworkFragment { public static final int SEARCH_TYPE_PLATFORM = 1; public static final int SEARCH_TYPE_LOCAL_PRODUCT = 2; public static final int SEARCH_TYPE_LOCAL_SERVICE = 3; ImageView backButton, searchButton; EditText wordsEdit; TextView searchTypeTextView; List<SearchType> searchTypes; SearchTypeAdapter searchTypeAdapter; SearchType searchType; GridView hotSearchGridView; List<String> searchWords; HotSearchAdapter hotSearchAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_product_search); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(ProductSearchFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(ProductSearchFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getHotSearch(); } @Override protected void init() { searchWords = new ArrayList<>(); hotSearchAdapter = new HotSearchAdapter(); searchTypes = new ArrayList<>(); searchTypes.add(new SearchType(SEARCH_TYPE_PLATFORM, "易商城")); searchTypes.add(new SearchType(SEARCH_TYPE_LOCAL_PRODUCT, "本地商品")); searchTypes.add(new SearchType(SEARCH_TYPE_LOCAL_SERVICE, "本地服务")); searchTypeAdapter = new SearchTypeAdapter(); } @Override protected void findViews() { backButton = (ImageView) contentView.findViewById(R.id.search_back); searchTypeTextView = (TextView) contentView .findViewById(R.id.search_type); searchButton = (ImageView) contentView.findViewById(R.id.search_search); wordsEdit = (EditText) contentView.findViewById(R.id.search_edit); hotSearchGridView = (GridView) contentView .findViewById(R.id.search_hot); initViews(); registerViews(); } @Override protected void initViews() { selectSearchType(0); hotSearchGridView.setAdapter(hotSearchAdapter); } @Override protected void registerViews() { hotSearchGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { search(searchWords.get(arg2)); } }); searchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { search(wordsEdit.getText().toString()); } }); backButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getActivity().finish(); } }); searchTypeTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { new SearchTypeDialog().show(getFragmentManager(), null); } }); } private void getHotSearch() { searchWords.clear(); hotSearchAdapter.notifyDataSetChanged(); post(API.API_PRODUCT_SEARCH_HOT, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); JSONArray array = object.optJSONArray("dataList"); if (array != null) { for (int i = 0; i < array.length(); i++) { JSONObject object2 = array.optJSONObject(i); if (object2 != null) { searchWords .add(object2.optString("searchName")); } } hotSearchAdapter.notifyDataSetChanged(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void search(String words) { if (words.length() > 0) { switch (searchType.getType()) { case SEARCH_TYPE_PLATFORM: jumpProductList("搜索\"" + words + "\"", words, ProductListFragment.TYPE_NAME); break; case SEARCH_TYPE_LOCAL_PRODUCT: Bundle bundle1 = new Bundle(); bundle1.putString("productName", words); jump(LocalGoodsSearchFragment.class.getName(), "搜索\"" + words + "\"", bundle1); break; case SEARCH_TYPE_LOCAL_SERVICE: Bundle bundle2 = new Bundle(); bundle2.putString("productName", words); jump(LocalServiceSearchFragment.class.getName(), "搜索\"" + words + "\"", bundle2); break; default: jumpProductList("搜索\"" + words + "\"", words, ProductListFragment.TYPE_NAME); break; } getActivity().finish(); } else { ApplicationTool.showToast("请输入关键字"); } } class HotSearchAdapter extends BaseAdapter { @Override public int getCount() { return searchWords.size(); } @Override public Object getItem(int position) { return searchWords.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.list_class_min, null); holder.nameText = (TextView) convertView .findViewById(R.id.class_min_name); holder.nameText.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, ApplicationTool .dip2px(36))); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.nameText.setText(searchWords.get(position)); return convertView; } class ViewHolder { TextView nameText; } } class SearchTypeDialog extends DialogFragment { View dialogView; ListView listView; TextView titleTextView, button; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); findViews(); } @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity()); dialog.getWindow().setBackgroundDrawableResource(R.color.divider); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(dialogView, new LayoutParams( LayoutParams.MATCH_PARENT, ApplicationTool.getScreenWidth())); return dialog; } private void findViews() { dialogView = layoutInflater.inflate(R.layout.dialog_list, null); titleTextView = (TextView) dialogView .findViewById(R.id.dialog_title); button = (TextView) dialogView.findViewById(R.id.dialog_button); listView = (ListView) dialogView.findViewById(R.id.dialog_list); initViews(); } private void initViews() { titleTextView.setText("选择搜索类型"); button.setText("取消"); listView.setAdapter(searchTypeAdapter); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { selectSearchType(arg2); dismiss(); } }); } } private void selectSearchType(int position) { if (searchTypes.size() > position) { searchType = searchTypes.get(position); searchTypeTextView.setText(searchType.getName()); } } class SearchTypeAdapter extends BaseAdapter { @Override public int getCount() { return searchTypes.size(); } @Override public Object getItem(int position) { return searchTypes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.list_class_main, null); holder.textView = (TextView) convertView .findViewById(R.id.class_main_name); holder.textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); holder.textView.setGravity(Gravity.CENTER_VERTICAL); holder.textView.setPadding(ApplicationTool.dip2px(24), 0, ApplicationTool.dip2px(24), 0); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, ApplicationTool.dip2px(48)); holder.textView.setLayoutParams(layoutParams); convertView .setBackgroundResource(R.drawable.selector_trans_divider); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.textView.setText(searchTypes.get(position).getName()); return convertView; } class ViewHolder { TextView textView; } } class SearchType { int type = 0; String name = ""; public SearchType(int type, String name) { this.name = name; this.type = type; } public int getType() { return type; } public String getName() { return name; } } } <file_sep>package yitgogo.smart; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import com.smartown.yitgogo.smart.R; public class AlertDialogActivity extends BaseActivity { private TextView titleTextView; private ImageView closeButton; private TextView disconnectTextView; private String fragmentName = "", title = ""; private Bundle parameters; private Fragment fragment; private Bundle bundle; BroadcastReceiver broadcastReceiver; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); neverShowAds(); View view = LayoutInflater.from(this).inflate( R.layout.activity_dialog_alert, null); LayoutParams layoutParams = new LayoutParams(880, LayoutParams.WRAP_CONTENT); setContentView(view, layoutParams); init(); findViews(); } @Override protected void onResume() { initReceiver(); super.onResume(); } @Override protected void onPause() { unregisterReceiver(broadcastReceiver); super.onPause(); } private void init() { bundle = getIntent().getExtras(); if (bundle != null) { if (bundle.containsKey("fragmentName")) { fragmentName = bundle.getString("fragmentName"); } if (bundle.containsKey("title")) { title = bundle.getString("title"); } if (bundle.containsKey("parameters")) { parameters = bundle.getBundle("parameters"); } } if (fragmentName.length() > 0) { try { fragment = (Fragment) Class.forName(fragmentName).newInstance(); if (parameters != null) { fragment.setArguments(parameters); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } @Override protected void findViews() { titleTextView = (TextView) findViewById(R.id.dialog_activity_title); closeButton = (ImageView) findViewById(R.id.dialog_activity_close); disconnectTextView = (TextView) findViewById(R.id.dialog_activity_disconnect); initViews(); registerViews(); } @Override protected void initViews() { titleTextView.setText(title); if (fragment != null) { getSupportFragmentManager().beginTransaction() .replace(R.id.dialog_activity_content, fragment).commit(); } } @Override protected void registerViews() { closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); disconnectTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); } }); } private void initReceiver() { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { checkConnection(); } } }; IntentFilter intentFilter = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(broadcastReceiver, intentFilter); } /** * 判断是否连接网络 * * @return */ protected boolean isConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager.getActiveNetworkInfo() != null) { if (connectivityManager.getActiveNetworkInfo().isAvailable()) { return true; } else { return false; } } else { return false; } } private void checkConnection() { if (isConnected()) { disconnectTextView.setVisibility(View.GONE); } else { disconnectTextView.setVisibility(View.VISIBLE); } } } <file_sep>package yitgogo.consumer.money.task; import android.os.AsyncTask; import android.text.TextUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import yitgogo.consumer.user.model.User; /** * @author Tiger * @Url http://192.168.8.2:8030/api/member/account/validatepaypwd * @Parameters [sn=3473404ae106951e8e3e9244b5f3d80d, payaccount=15081818130001, * paypwd=<PASSWORD>] * @Put_Cookie JSESSIONID=D2AF3DDA2FE8EDEB9F4308E0DD126B38 * @Result {"state":"success","msg":"操作成功","databody":{"vli":true}} */ public class VerifyPayPasswordTask extends AsyncTask<String, Void, String> { public boolean passwordIsRight = false; @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("sn", User.getUser() .getCacheKey())); nameValuePairs.add(new BasicNameValuePair("payaccount", MoneyAccount .getMoneyAccount().getPayaccount())); nameValuePairs.add(new BasicNameValuePair("paypwd", params[0])); return NetUtil.getInstance().postWithCookie( API.MONEY_PAY_PASSWORD_VALIDATE, nameValuePairs); } @Override protected void onPostExecute(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject jsonObject = object.optJSONObject("databody"); if (jsonObject != null) { passwordIsRight = jsonObject.optBoolean("vli"); } } } catch (JSONException e) { e.printStackTrace(); } } } } <file_sep>package yitgogo.consumer.bianmin.qq.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.bianmin.ModelBianminOrderResult; import yitgogo.consumer.bianmin.ModelChargeInfo; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; public class QQChargeFragment extends BaseNetworkFragment { TextView priceTextView; EditText accountEditText, amountEditText; Button chargeButton; ModelChargeInfo chargeInfo = new ModelChargeInfo(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_bianmin_qq_charge); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(QQChargeFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(QQChargeFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override protected void init() { } @Override protected void initViews() { } @Override protected void findViews() { priceTextView = (TextView) contentView .findViewById(R.id.qq_charge_price); accountEditText = (EditText) contentView .findViewById(R.id.qq_charge_account); amountEditText = (EditText) contentView .findViewById(R.id.qq_charge_amount); chargeButton = (Button) contentView.findViewById(R.id.qq_charge_charge); initViews(); registerViews(); } @Override protected void registerViews() { amountEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { getPrice(); } }); chargeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { charge(); } }); } private void getPrice() { if (amountEditText.length() > 0) { getChargePrice(); } else { priceTextView.setText(""); } } private void charge() { if (amountEditText.length() <= 0) { ApplicationTool.showToast("请输入充值数量"); } else if (accountEditText.length() <= 0) { ApplicationTool.showToast("请输入要充值的QQ号"); } else { if (chargeInfo.getSellprice() > 0) { qqCharge(); } } } private void getChargePrice(){ List<RequestParam> requestParams = new ArrayList<>(); if (amountEditText.length() > 0) { requestParams.add(new RequestParam("num", amountEditText.getText().toString().trim())); } else { return; } post(API.API_BIANMIN_QQ_INFO, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject infoObject = object.optJSONObject("object"); chargeInfo = new ModelChargeInfo(infoObject); if (amountEditText.length() > 0) { if (chargeInfo.getSellprice() > 0) { priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(chargeInfo .getSellprice())); return; } } } priceTextView.setText(""); return; } catch (JSONException e) { e.printStackTrace(); } } priceTextView.setText(""); } }); } private void qqCharge() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("cardid", chargeInfo .getCardid())); requestParams.add(new RequestParam("game_userid", accountEditText.getText().toString().trim())); requestParams.add(new RequestParam("cardnum", amountEditText.getText().toString().trim())); if (User.getUser().isLogin()) { requestParams.add(new RequestParam("memberAccount", User.getUser().getUseraccount())); } post(API.API_BIANMIN_GAME_QQ_CHARGE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); ModelBianminOrderResult orderResult = new ModelBianminOrderResult( dataMap); if (orderResult != null) { if (orderResult.getSellPrice() > 0) { payMoney(orderResult); getActivity().finish(); return; } } } ApplicationTool.showToast(object.optString("message")); return; } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("充值失败"); } }); } } <file_sep>package yitgogo.consumer.home.task; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import android.os.AsyncTask; public class GetBrand extends AsyncTask<Boolean, Void, String> { @Override protected String doInBackground(Boolean... params) { return NetUtil.getInstance().postWithoutCookie(API.API_HOME_BRAND, null, params[0], true); } } <file_sep>package yitgogo.consumer; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import com.dtr.zxing.activity.CaptureActivity; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.bianmin.ModelBianminOrderResult; import yitgogo.consumer.local.model.ModelLocalCar; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.order.model.ModelOrderResult; import yitgogo.consumer.order.model.ModelStorePostInfo; import yitgogo.consumer.order.ui.OrderFragment; import yitgogo.consumer.product.ui.PlatformProductDetailFragment; import yitgogo.consumer.product.ui.ProductDetailFragment; import yitgogo.consumer.product.ui.ProductListFragment; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.MD5; import yitgogo.consumer.tools.Parameters; public abstract class BaseFragment extends Fragment { public LayoutInflater layoutInflater; public DecimalFormat decimalFormat; public int pagenum = 0, pagesize = 12; public SimpleDateFormat simpleDateFormat; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layoutInflater = LayoutInflater.from(getActivity()); decimalFormat = new DecimalFormat("0.00"); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } /** * 数据初始化 */ protected abstract void init(); protected void findViews(View view) { } /** * 初始化UI */ protected abstract void initViews(); /** * 注册监听UI */ protected abstract void registerViews(); /** * jump ui * * @param fragment */ protected void jump(String fragment) { jump(fragment, ""); } protected void jump(String fragment, String title) { jump(fragment, title, null); } protected void jump(String fragment, String title, Bundle bundle) { Intent intent = new Intent(getActivity(), ContainerActivity.class); if (!TextUtils.isEmpty(fragment)) { intent.putExtra("fragment", fragment); } if (!TextUtils.isEmpty(title)) { intent.putExtra("title", title); } if (bundle != null) { intent.putExtra("bundle", bundle); } startActivity(intent); } /** * 显示商品列表 * * @param title 标题 * @param value 参数值 * @param type 参数类型/产品类型 */ protected void jumpProductList(String title, String value, int type) { Bundle bundle = new Bundle(); bundle.putString("value", value); bundle.putInt("type", type); jump(ProductListFragment.class.getName(), title, bundle); } protected void showProductDetail(String productId, String productName, int saleType) { Bundle bundle = new Bundle(); bundle.putString("productId", productId); if (saleType == CaptureActivity.SALE_TYPE_NONE) { jump(PlatformProductDetailFragment.class.getName(), productName, bundle); return; } bundle.putInt("saleType", saleType); jump(ProductDetailFragment.class.getName(), productName, bundle); } private ContainerActivity getContainerActivity() { ContainerActivity containerActivity = (ContainerActivity) getActivity(); return containerActivity; } protected void addImageButton(int imageResId, String tag, OnClickListener onClickListener) { getContainerActivity().addImageButton(imageResId, tag, onClickListener); } protected void addTextButton(String text, OnClickListener onClickListener) { getContainerActivity().addTextButton(text, onClickListener); } /** * fragment设置返回按钮点击事件 * * @param onClickListener */ protected void onBackButtonClick(OnClickListener onClickListener) { getContainerActivity().onBackButtonClick(onClickListener); } /** * @param originalUrl json得到的图片链接 * @return 切图链接 * @author Tiger */ protected String getSmallImageUrl(String originalUrl) { String formatedUrl = ""; if (!TextUtils.isEmpty(originalUrl)) { formatedUrl = originalUrl; if (originalUrl.contains("images.")) { formatedUrl = originalUrl.replace("images.", "imageprocess.") + "@!350"; } } return formatedUrl; } /** * @param originalUrl json得到的图片链接 * @return 切图链接 * @author Tiger */ protected String getBigImageUrl(String originalUrl) { String formatedUrl = ""; if (!TextUtils.isEmpty(originalUrl)) { formatedUrl = originalUrl; if (originalUrl.contains("images.")) { formatedUrl = originalUrl.replace("images.", "imageprocess.") + "@!600"; } } return formatedUrl; } /** * 通过接口地址和参数组成唯一字符串,作为用于缓存数据的键 * * @param api_url 接口地址 * @param parameters 网络请求参数 * @return 缓存数据的键 */ protected String getCacheKey(String api_url, List<NameValuePair> parameters) { StringBuilder builder = new StringBuilder(); builder.append(api_url); if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { if (i == 0) { builder.append("?"); } else { builder.append("&"); } builder.append(parameters.get(i).getName()); builder.append("="); builder.append(parameters.get(i).getValue()); } } return builder.toString(); } /** * 验证手机格式 */ protected boolean isPhoneNumber(String number) { /* * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 */ // "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 // String telRegex = "[1][3578]\\d{9}"; // if (TextUtils.isEmpty(number)) // return false; // else // return number.matches(telRegex); if (TextUtils.isEmpty(number)) { return false; } else { return number.length() == 11; } } /** * 判断是否连接网络 * * @return */ protected boolean isConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager.getActiveNetworkInfo() != null) { if (connectivityManager.getActiveNetworkInfo().isAvailable()) { return true; } else { return false; } } else { return false; } } protected String getHtmlFormated(String baseHtml) { String head = "<head>" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " + "<style>img{max-width: 100%; width:auto; height:auto;}</style>" + "</head>"; return "<html>" + head + "<body>" + baseHtml + "</body></html>"; } protected String getEncodedPassWord(String password) { return MD5.GetMD5Code(password + "{<PASSWORD>}"); } protected void payMoney(ModelBianminOrderResult bianminOrderResult) { ArrayList<String> orderNumbers = new ArrayList<String>(); orderNumbers.add(bianminOrderResult.getOrderNumber()); payMoney(orderNumbers, bianminOrderResult.getSellPrice(), PayFragment.ORDER_TYPE_BM); } protected void payMoney(String orderNumber, double totalMoney, int orderType) { ArrayList<String> orderNumbers = new ArrayList<String>(); orderNumbers.add(orderNumber); payMoney(orderNumbers, totalMoney, orderType); } protected void payMoney(ArrayList<String> orderNumbers, double totalMoney, int orderType) { Bundle bundle = new Bundle(); bundle.putStringArrayList("orderNumbers", orderNumbers); bundle.putDouble("totalMoney", totalMoney); bundle.putInt("orderType", orderType); // bundle.putInt("productCount", productCount); jump(PayFragment.class.getName(), "订单支付", bundle); } /** * 易田商城下单成功后支付 * * @param platformOrderResult 下单返回订单的结果 */ protected void payMoney(JSONArray platformOrderResult) { if (platformOrderResult != null) { if (platformOrderResult != null) { double payPrice = 0; int productCount = 0; ArrayList<String> orderNumbers = new ArrayList<String>(); for (int i = 0; i < platformOrderResult.length(); i++) { ModelOrderResult orderResult = new ModelOrderResult( platformOrderResult.optJSONObject(i)); orderNumbers.add(orderResult.getOrdernumber()); payPrice += orderResult.getZhekouhou(); // productCount+= orderResult.get } if (orderNumbers.size() > 0) { if (payPrice > 0) { payMoney(orderNumbers, payPrice, PayFragment.ORDER_TYPE_YY); } } } } } /** * 带参数的fragment跳转 * * @param fragmentName * @param fragmentTitle * @param parameters */ protected void jumpFull(String fragmentName, String fragmentTitle, Bundle parameters) { Intent intent = new Intent(getActivity(), ContainerFullActivity.class); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("fragmentTitle", fragmentTitle); bundle.putBundle("parameters", parameters); intent.putExtras(bundle); startActivity(intent); } protected void showOrder(int orderType) { Bundle bundle = new Bundle(); bundle.putInt("orderType", orderType); jump(OrderFragment.class.getName(), "我的订单", bundle); } /** * 获取圆角位图的方法 * * @param bitmap 需要转化成圆角的位图 * @param pixels 圆角的度数,数值越大,圆角越大 * @return 处理后的圆角位图 */ protected Bitmap getRoundCornerBitmap(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); RectF rectF = new RectF(rect); float roundPx = pixels; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } protected String getSecretPhone(String phone) { int length = phone.length(); if (length > 3) { String string = ""; if (length < 8) { string = phone.substring(0, 3) + "****"; } else { string = phone.substring(0, 3) + "****" + phone.substring(7, length); } return string; } return "***"; } protected String getSecretCardNuber(String cardNumber) { if (cardNumber.length() > 4) { return "**** **** **** " + cardNumber.substring(cardNumber.length() - 4, cardNumber.length()); } return "**** **** **** " + cardNumber; } protected ContentValues getShareCodeContent(String userAccount, String userCode) throws JSONException { JSONObject object = new JSONObject(); object.put("codeType", CaptureActivity.CODE_TYPE_SHARE); JSONObject dataObject = new JSONObject(); dataObject.put("userAccount", userAccount); dataObject.put("userCode", userCode); object.put("data", dataObject); ContentValues contentValues = new ContentValues(); contentValues.put("content", Base64.encodeToString(object.toString() .getBytes(), Base64.DEFAULT)); contentValues.put("imageWidth", ApplicationTool.getScreenWidth() / 2); return contentValues; } protected String getStorePostInfoString(ModelStorePostInfo storePostInfo) { return "配送费:" + Parameters.CONSTANT_RMB + decimalFormat.format(storePostInfo.getPostage()) + ",店铺购物满" + Parameters.CONSTANT_RMB + decimalFormat.format(storePostInfo.getHawManyPackages()) + "免配送费"; } protected String getMoneyDetailString(double goodsMoney, double postFee) { return "商品:" + Parameters.CONSTANT_RMB + decimalFormat.format(goodsMoney) + "+配送费:" + Parameters.CONSTANT_RMB + decimalFormat.format(postFee); } protected String getDiliverPayString(ModelLocalCar localCar) { return localCar.getDiliver().getName() + "、" + localCar.getPayment().getName(); } } <file_sep>package yitgogo.consumer.money.ui; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; public class PayPasswordChangeFragment extends BaseNetworkFragment { TextView phoneTextView, getCodeButton; EditText smsCodeEditText; Button button; List<RequestParam> requestParams = new ArrayList<>(); Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj != null) { getCodeButton.setText(msg.obj + "s"); } else { getCodeButton.setClickable(true); getCodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getCodeButton.setText("获取验证码"); } } ; }; boolean isFinish = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_password_change); findViews(); } @Override protected void init() { } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(PayPasswordChangeFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(PayPasswordChangeFragment.class.getName()); } @Override public void onDestroy() { super.onDestroy(); isFinish = true; } @Override protected void findViews() { phoneTextView = (TextView) contentView .findViewById(R.id.change_pay_password_phone); getCodeButton = (TextView) contentView .findViewById(R.id.change_pay_password_smscode_get); smsCodeEditText = (EditText) contentView .findViewById(R.id.change_pay_password_smscode); button = (Button) contentView.findViewById(R.id.change_pay_password_ok); initViews(); registerViews(); } @Override protected void initViews() { phoneTextView.setText(User.getUser().getPhone()); } @Override protected void registerViews() { getCodeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getSmsCode(); } }); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { changePassword(); } }); } private void changePassword() { if (TextUtils.isEmpty(smsCodeEditText.getText().toString().trim())) { ApplicationTool.showToast("请输入您收到的验证码"); } else { requestParams.add(new RequestParam("mcode", smsCodeEditText.getText().toString().trim())); PayPasswordDialog oldPasswordDialog = new PayPasswordDialog( "请输入旧支付密码", false) { public void onDismiss(DialogInterface dialog) { if (!TextUtils.isEmpty(payPassword)) { requestParams.add(new RequestParam("paypwd", payPassword)); PayPasswordDialog newPasswordDialog = new PayPasswordDialog("请输入新支付密码", false) { public void onDismiss(DialogInterface dialog) { if (!TextUtils.isEmpty(payPassword)) { requestParams.add(new RequestParam("newpaypwd", payPassword)); changePayPassword(); } super.onDismiss(dialog); } }; newPasswordDialog.show(getFragmentManager(), null); } super.onDismiss(dialog); } }; oldPasswordDialog.show(getFragmentManager(), null); } } private void changePayPassword() { post(API.MONEY_PAY_PASSWORD_MODIFY, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject databody = object.optJSONObject("databody"); if (databody != null) { if (databody.optString("modpwd").equalsIgnoreCase("ok")) { ApplicationTool.showToast("修改支付密码成功"); getActivity().finish(); return; } } } ApplicationTool.showToast(object.optString("msg")); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getSmsCode() { post(API.MONEY_SMS_CODE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject databody = object.optJSONObject("databody"); if (databody != null) { if (databody.optString("send").equalsIgnoreCase( "ok")) { getCodeButton.setClickable(false); new Thread(new Runnable() { @Override public void run() { int time = 60; while (time > -1) { if (isFinish) { break; } try { Message message = new Message(); if (time > 0) { message.obj = time; } handler.sendMessage(message); Thread.sleep(1000); time--; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); ApplicationTool.showToast("已将验证码发送至尾号为 " + databody.optString("mobile") + " 的手机"); return; } } } ApplicationTool.showToast(object.optString("msg")); } catch (JSONException e) { e.printStackTrace(); } } } }); } } <file_sep>package yitgogo.consumer.user.ui; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.dtr.zxing.activity.CaptureActivity; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.RequestParam; public class UserRegisterFragment extends BaseNetworkFragment implements OnClickListener { EditText phoneEdit, smscodeEdit, passwordEdit, passwordConfirmEdit, inviteCodeEditText; TextView getSmscodeButton; ImageView showPassword, scanButton; Button registerButton; boolean isShown = false, isFinish = false; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj != null) { getSmscodeButton.setText(msg.obj + "s"); } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); } } ; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_register); findViews(); } @Override protected void init() { } @Override protected void initViews() { } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserRegisterFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserRegisterFragment.class.getName()); } @Override public void onDestroy() { isFinish = true; super.onDestroy(); } @Override protected void findViews() { phoneEdit = (EditText) contentView .findViewById(R.id.user_register_phone); smscodeEdit = (EditText) contentView .findViewById(R.id.user_register_smscode); passwordEdit = (EditText) contentView .findViewById(R.id.user_register_password); passwordConfirmEdit = (EditText) contentView .findViewById(R.id.user_register_password_confirm); inviteCodeEditText = (EditText) contentView .findViewById(R.id.user_register_invitecode); scanButton = (ImageView) contentView .findViewById(R.id.user_register_invitecode_scan); getSmscodeButton = (TextView) contentView .findViewById(R.id.user_register_smscode_get); registerButton = (Button) contentView .findViewById(R.id.user_register_enter); showPassword = (ImageView) contentView .findViewById(R.id.user_register_password_show); registerViews(); } @Override protected void registerViews() { getSmscodeButton.setOnClickListener(this); registerButton.setOnClickListener(this); showPassword.setOnClickListener(this); onBackButtonClick(new OnClickListener() { @Override public void onClick(View v) { jump(UserLoginFragment.class.getName(), "会员登录"); getActivity().finish(); } }); scanButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), CaptureActivity.class); startActivityForResult(intent, 5); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 5) { if (data != null) { Bundle bundle = data.getExtras(); if (bundle != null) { if (bundle.containsKey("userCode")) { inviteCodeEditText .setText(bundle.getString("userCode")); } } } } } private void register() { if (!isPhoneNumber(phoneEdit.getText().toString())) { ApplicationTool.showToast("请输入正确的手机号"); } else if (smscodeEdit.length() != 6) { ApplicationTool.showToast("请输入您收到的验证码"); } else if (passwordEdit.length() == 0) { ApplicationTool.showToast("请输入密码"); } else if (passwordConfirmEdit.length() == 0) { ApplicationTool.showToast("请确认密码"); } else if (!passwordEdit.getText().toString() .equals(passwordConfirmEdit.getText().toString())) { ApplicationTool.showToast("两次输入的密码不相同 "); } else { userRegister(); } } private void showPassword() { if (isShown) { passwordEdit.setTransformationMethod(PasswordTransformationMethod .getInstance()); passwordConfirmEdit .setTransformationMethod(PasswordTransformationMethod .getInstance()); } else { passwordEdit .setTransformationMethod(HideReturnsTransformationMethod .getInstance()); passwordConfirmEdit .setTransformationMethod(HideReturnsTransformationMethod .getInstance()); } isShown = !isShown; if (isShown) { showPassword.setImageResource(R.drawable.ic_hide); } else { showPassword.setImageResource(R.drawable.ic_show); } } private void userRegister() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("phone", phoneEdit.getText().toString())); requestParams.add(new RequestParam("smsCode", smscodeEdit.getText().toString())); requestParams.add(new RequestParam("password", getEncodedPassWord(passwordEdit.getText().toString().trim()))); requestParams.add(new RequestParam("refereeCode", inviteCodeEditText.getText().toString())); requestParams.add(new RequestParam("spNo", Store.getStore().getStoreNumber())); post(API.API_USER_REGISTER, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { ApplicationTool.showToast("注册成功"); Bundle bundle = new Bundle(); bundle.putString("phone", phoneEdit.getText().toString()); jump(UserLoginFragment.class.getName(), "会员登录", bundle); getActivity().finish(); } else { ApplicationTool.showToast(object.optString("message")); } } catch (JSONException e) { ApplicationTool.showToast("注册失败"); e.printStackTrace(); } } else { ApplicationTool.showToast("注册失败"); } } }); } private void getSmscode() { if (!isPhoneNumber(phoneEdit.getText().toString())) { ApplicationTool.showToast("请输入正确的手机号"); return; } getSmscodeButton.setEnabled(false); getSmscodeButton.setTextColor(getResources().getColor(R.color.textColorThird)); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("phone", phoneEdit.getText().toString())); post(API.API_USER_REGISTER_SMSCODE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { ApplicationTool.showToast("验证码已发送至您的手机"); new Thread(new Runnable() { @Override public void run() { int time = 60; while (time > -1) { if (isFinish) { break; } try { Message message = new Message(); if (time > 0) { message.obj = time; } handler.sendMessage(message); Thread.sleep(1000); time--; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); ApplicationTool.showToast(object.optString("message")); } } catch (JSONException e) { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); ApplicationTool.showToast("获取验证码失败"); e.printStackTrace(); } } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); ApplicationTool.showToast("获取验证码失败"); } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.user_register_smscode_get: getSmscode(); break; case R.id.user_register_enter: register(); break; case R.id.user_register_password_show: showPassword(); break; default: break; } } } <file_sep>package yitgogo.consumer.user.ui; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.user.model.User; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class ModifyIdCard extends BaseNotifyFragment { LinearLayout editor; Button modify; TextView accountText, idOld, idNew; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_idcard); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(ModifyIdCard.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(ModifyIdCard.class.getName()); } protected void findViews() { accountText = (TextView) contentView .findViewById(R.id.user_info_idcard_account); idOld = (TextView) contentView.findViewById(R.id.user_info_idcard_old); idNew = (TextView) contentView.findViewById(R.id.user_info_idcard_new); modify = (Button) contentView.findViewById(R.id.user_idcard_modify); initViews(); registerViews(); } @Override protected void initViews() { accountText.setText(User.getUser().getUseraccount()); idOld.setText(User.getUser().getIdcard()); } @Override protected void registerViews() { modify.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { modify(); } }); } @SuppressWarnings("unchecked") private void modify() { String idcard = idNew.getText().toString().trim(); if (TextUtils.isEmpty(idcard)) { Toast.makeText(getActivity(), "请输入要绑定的身份证号码", Toast.LENGTH_SHORT) .show(); } else if (idcard.length() != 15 & idcard.length() != 18) { Toast.makeText(getActivity(), "身份证号码格式不正确", Toast.LENGTH_SHORT) .show(); } else { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("account", User.getUser() .getUseraccount())); nameValuePairs.add(new BasicNameValuePair("idcard", idcard)); new Modify().execute(nameValuePairs); } } class Modify extends AsyncTask<List<NameValuePair>, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(List<NameValuePair>... arg0) { return netUtil.postWithCookie(API.API_USER_MODIFY_IDCARD, arg0[0]); } @Override protected void onPostExecute(String result) { hideLoading(); JSONObject data; try { data = new JSONObject(result); if (data.getString("state").equalsIgnoreCase("SUCCESS")) { Toast.makeText(getActivity(), "绑定身份证成功", Toast.LENGTH_SHORT) .show(); getActivity().finish(); } else { Toast.makeText(getActivity(), data.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } } <file_sep>package yitgogo.consumer; import android.os.AsyncTask; import android.text.TextUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; /** * Created by Tiger on 2015-10-29. * * @Result {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[],"totalCount":1,"dataMap":{"returnNum":0},"object":null} */ public class GetLocalBusinessState extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... voids) { return false; } }<file_sep>package yitgogo.smart.suning.ui; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.smartown.yitgogo.smart.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.smart.BaseNotifyFragment; import yitgogo.smart.suning.model.API_SUNING; import yitgogo.smart.suning.model.GetNewSignature; import yitgogo.smart.suning.model.ModelProductDetail; import yitgogo.smart.suning.model.ModelProductImage; import yitgogo.smart.suning.model.ModelProductPrice; import yitgogo.smart.suning.model.SuningCarController; import yitgogo.smart.suning.model.SuningManager; import yitgogo.smart.tools.MissionController; import yitgogo.smart.tools.Parameters; import yitgogo.smart.tools.ScreenUtil; import yitgogo.smart.view.Notify; public class ProductDetailFragment extends BaseNotifyFragment { ViewPager imagePager; TextView nameTextView, brandTextView, modelTextView, stateTextView, priceTextView; ImageView lastImageButton, nextImageButton; TextView imageIndexText; TextView carButton, buyButton; WebView webView; ProgressBar progressBar; ImageAdapter imageAdapter; ModelProductDetail productDetail = new ModelProductDetail(); ModelProductPrice productPrice = new ModelProductPrice(); List<ModelProductImage> productImages = new ArrayList<>(); Bundle bundle = new Bundle(); String state = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_suning_product_detail); try { init(); } catch (JSONException e) { e.printStackTrace(); } findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(ProductDetailFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(ProductDetailFragment.class.getName()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetProductStock().execute(); new GetProductImages().execute(); } private void init() throws JSONException { measureScreen(); bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("product")) { productDetail = new ModelProductDetail(new JSONObject(bundle.getString("product"))); } if (bundle.containsKey("price")) { productPrice = new ModelProductPrice(new JSONObject(bundle.getString("price"))); } } imageAdapter = new ImageAdapter(); } protected void findViews() { imagePager = (ViewPager) contentView .findViewById(R.id.product_detail_images); lastImageButton = (ImageView) contentView .findViewById(R.id.product_detail_image_last); nextImageButton = (ImageView) contentView .findViewById(R.id.product_detail_image_next); imageIndexText = (TextView) contentView .findViewById(R.id.product_detail_image_index); nameTextView = (TextView) contentView .findViewById(R.id.product_detail_name); brandTextView = (TextView) contentView .findViewById(R.id.product_detail_brand); modelTextView = (TextView) contentView .findViewById(R.id.product_detail_model); stateTextView = (TextView) contentView .findViewById(R.id.product_detail_state); priceTextView = (TextView) contentView .findViewById(R.id.product_detail_price); carButton = (TextView) contentView .findViewById(R.id.product_detail_car); buyButton = (TextView) contentView .findViewById(R.id.product_detail_buy); webView = (WebView) contentView.findViewById(R.id.web_webview); progressBar = (ProgressBar) contentView.findViewById(R.id.web_progress); initViews(); registerViews(); } protected void initViews() { FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, ScreenUtil.getScreenWidth() / 3); imagePager.setLayoutParams(layoutParams); imagePager.setAdapter(imageAdapter); nameTextView.setText(productDetail.getName()); priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(productPrice.getPrice())); brandTextView.setText(productDetail.getBrand()); modelTextView.setText(productDetail.getModel()); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar.setVisibility(View.GONE); } else { if (progressBar.getVisibility() == View.GONE) progressBar.setVisibility(View.VISIBLE); progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); WebSettings settings = webView.getSettings(); settings.setDefaultTextEncodingName("utf-8"); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); settings.setUseWideViewPort(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); settings.setLoadWithOverviewMode(true); settings.setCacheMode(WebSettings.LOAD_DEFAULT); settings.setDomStorageEnabled(true); settings.setDatabaseEnabled(true); settings.setAppCachePath(getActivity().getCacheDir().getPath()); settings.setAppCacheEnabled(true); webView.loadData(productDetail.getIntroduction(), "text/html; charset=utf-8", "utf-8"); } @SuppressWarnings("deprecation") @Override protected void registerViews() { lastImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageAdapter.getCount() > 0) { if (imagePager.getCurrentItem() == 0) { setImagePosition(imageAdapter.getCount() - 1); } else { setImagePosition(imagePager.getCurrentItem() - 1); } } } }); nextImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageAdapter.getCount() > 0) { if (imagePager.getCurrentItem() == imageAdapter.getCount() - 1) { setImagePosition(0); } else { setImagePosition(imagePager.getCurrentItem() + 1); } } } }); imagePager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { imageIndexText.setText((imagePager.getCurrentItem() + 1) + "/" + imageAdapter.getCount()); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); carButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (state.equals("00")) { if (productPrice.getPrice() > 0) { if (SuningCarController.addProduct(productDetail)) { Notify.show("添加到购物车成功"); } else { Notify.show("已添加过此商品"); } } else { Notify.show("商品信息有误,不能购买"); } } else { Notify.show("此商品暂不能购买"); } } }); buyButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (state.equals("00")) { if (productPrice.getPrice() > 0) { openWindow(SuningProductBuyFragment.class.getName(), productDetail.getName(), bundle); } else { Notify.show("商品信息有误,不能购买"); } } else { Notify.show("此商品暂不能购买"); } } }); } /** * 点击左右导航按钮切换图片 * * @param imagePosition */ private void setImagePosition(int imagePosition) { imagePager.setCurrentItem(imagePosition, true); imageIndexText.setText((imagePosition + 1) + "/" + imageAdapter.getCount()); } /** * viewpager适配器 */ private class ImageAdapter extends PagerAdapter { @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return productImages.size(); } @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = layoutInflater.inflate( R.layout.adapter_viewpager, view, false); assert imageLayout != null; ImageView imageView = (ImageView) imageLayout .findViewById(R.id.view_pager_img); final ProgressBar spinner = (ProgressBar) imageLayout .findViewById(R.id.view_pager_loading); ImageLoader.getInstance().displayImage(productImages.get(position).getPath(), imageView, new SimpleImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { spinner.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { spinner.setVisibility(View.GONE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { spinner.setVisibility(View.GONE); } }); view.addView(imageLayout, 0); return imageLayout; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public Parcelable saveState() { return null; } } class GetProductImages extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { JSONArray dataArray = new JSONArray(); dataArray.put(productDetail.getSku()); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("sku", dataArray); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); /** *{"result":[{"skuId":"108246148","price":15000.00}],"isSuccess":true,"returnMsg":"查询成功。"} */ return MissionController.post(API_SUNING.API_PRODUCT_IMAGES, nameValuePairs); } @Override protected void onPostExecute(String result) { if (SuningManager.isSignatureOutOfDate(result)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetProductImages().execute(); } } }; getNewSignature.execute(); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("result"); if (array != null) { if (array.length() > 0) { JSONObject imageObject = array.optJSONObject(0); if (imageObject != null) { JSONArray imageArray = imageObject.optJSONArray("urls"); if (imageArray != null) { for (int i = 0; i < imageArray.length(); i++) { productImages.add(new ModelProductImage(imageArray.optJSONObject(i))); } imageAdapter.notifyDataSetChanged(); imageIndexText.setText("1/" + imageAdapter.getCount()); } } } } } } catch (JSONException e) { e.printStackTrace(); } } } } class GetProductStock extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("cityId", SuningManager.getSuningAreas().getCity().getCode()); data.put("countyId", SuningManager.getSuningAreas().getDistrict().getCode()); data.put("sku", productDetail.getSku()); data.put("num", 1); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); return MissionController.post(API_SUNING.API_PRODUCT_STOCK, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (SuningManager.isSignatureOutOfDate(result)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetProductStock().execute(); } } }; getNewSignature.execute(); return; } /** * {"sku":null,"state":null,"isSuccess":false,"returnMsg":"无货"} */ if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { state = object.optString("state"); if (state.equals("00")) { stateTextView.setText("有货"); } else if (state.equals("01")) { stateTextView.setText("暂不销售"); } else { stateTextView.setText("无货"); } } } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.activity.model; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.store.model.ModelStoreSelected; /** * * @author Tiger * * @Json { "id": 4, "activityName": "七夕时刻", "activityImg": * "http://192.168.8.98:8087/images/public/20150819/55901439975585460.jpg" * , "titleImg": * "http://images.yitos.net/images/public/20150819/54901439975595835.jpg,http://192.168.8.98:8087/images/public/20150819/54901439975595835.jpg" * , "totalMoney": 5000, "surplusMoney": 5000, "lowestMoney": 100, * "highestMoney": 500, "activityNum": "489799", "activityState": "启用", * "activityStartTime": "2015-08-20 08:00:46", "progress": 1, "addUser": * "测试一", "service": { "id": 1, "no": "YT613630259926", "brevitycode": * "scytsmyxgs", "servicename": "四川易田商贸有限公司", "businessno": * "VB11122220000", "contacts": "易田", "cardnumber": "111111111111111111", * "serviceaddress": "成都市金牛区", "contactphone": "13076063079", * "contacttelephone": "028-83222680", "email": "<EMAIL>", "reva": { * "id": 3253, "valuename": "中国", "valuetype": { "id": 1, "typename": "国" * }, "onid": 0, "onname": null, "brevitycode": null }, "contractno": * "SC11111100000", "contractannex": "", "onservice": null, "state": "启用", * "addtime": "2014-09-04 16:01:36", "starttime": 1409760000000, "sptype": * "1", "endtime": 1457712000000, "supply": true, "imghead": "", * "longitude": null, "latitude": null }, "addTime": * "2015-08-19 17:13:59", "winExtent": 50, "winNum": 10 } */ public class ModelActivity { String id = "", activityName = "", activityImg = "", titleImg = "", activityNum = "", activityState = "", activityStartTime = "", progress = "", addUser = "", addTime = ""; double totalMoney = 0, surplusMoney = 0, lowestMoney = 0, highestMoney = 0; ModelStoreSelected service = new ModelStoreSelected(); int winExtent = 0, winNum = 0; JSONObject jsonObject = new JSONObject(); public ModelActivity() { } public ModelActivity(JSONObject object) throws JSONException { if (object != null) { jsonObject = object; if (object.has("id")) { if (!object.optString("id").equalsIgnoreCase("null")) { id = object.optString("id"); } } if (object.has("activityName")) { if (!object.optString("activityName").equalsIgnoreCase("null")) { activityName = object.optString("activityName"); } } if (object.has("activityImg")) { if (!object.optString("activityImg").equalsIgnoreCase("null")) { activityImg = object.optString("activityImg"); } } if (object.has("titleImg")) { if (!object.optString("titleImg").equalsIgnoreCase("null")) { titleImg = object.optString("titleImg"); } } if (object.has("activityNum")) { if (!object.optString("activityNum").equalsIgnoreCase("null")) { activityNum = object.optString("activityNum"); } } if (object.has("activityState")) { if (!object.optString("activityState").equalsIgnoreCase("null")) { activityState = object.optString("activityState"); } } if (object.has("activityStartTime")) { if (!object.optString("activityStartTime").equalsIgnoreCase( "null")) { activityStartTime = object.optString("activityStartTime"); } } if (object.has("progress")) { if (!object.optString("progress").equalsIgnoreCase("null")) { progress = object.optString("progress"); } } if (object.has("addUser")) { if (!object.optString("addUser").equalsIgnoreCase("null")) { addUser = object.optString("addUser"); } } if (object.has("addTime")) { if (!object.optString("addTime").equalsIgnoreCase("null")) { addTime = object.optString("addTime"); } } if (object.has("totalMoney")) { if (!object.optString("totalMoney").equalsIgnoreCase("null")) { totalMoney = object.optDouble("totalMoney"); } } if (object.has("surplusMoney")) { if (!object.optString("surplusMoney").equalsIgnoreCase("null")) { surplusMoney = object.optDouble("surplusMoney"); } } if (object.has("lowestMoney")) { if (!object.optString("lowestMoney").equalsIgnoreCase("null")) { lowestMoney = object.optDouble("lowestMoney"); } } if (object.has("highestMoney")) { if (!object.optString("highestMoney").equalsIgnoreCase("null")) { highestMoney = object.optDouble("highestMoney"); } } service = new ModelStoreSelected(object.optJSONObject("service")); winExtent = object.optInt("winExtent"); winNum = object.optInt("winNum"); } } public String getId() { return id; } public String getActivityName() { return activityName; } public String getActivityImg() { return activityImg; } public String getTitleImg() { return titleImg; } public String getActivityNum() { return activityNum; } public String getActivityState() { return activityState; } public String getActivityStartTime() { return activityStartTime; } public String getProgress() { return progress; } public String getAddUser() { return addUser; } public String getAddTime() { return addTime; } public double getTotalMoney() { return totalMoney; } public double getSurplusMoney() { return surplusMoney; } public double getLowestMoney() { return lowestMoney; } public double getHighestMoney() { return highestMoney; } public ModelStoreSelected getService() { return service; } public int getWinExtent() { return winExtent; } public int getWinNum() { return winNum; } public JSONObject getJsonObject() { return jsonObject; } } <file_sep>package yitgogo.consumer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.util.List; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.MissionController; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; /** * 有通知功能的fragment * * @author Tiger */ public abstract class BaseNetworkFragment extends BaseFragment { LinearLayout emptyLayout; ImageView emptyImage; TextView emptyText; LinearLayout failLayout; Button failButton; TextView failText; LinearLayout disconnectLayout; TextView disconnectText; View disconnectMargin; LinearLayout loadingLayout; ProgressBar loadingProgressBar; TextView loadingText; FrameLayout contentLayout; public View contentView; BroadcastReceiver broadcastReceiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup base_fragment, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_base, null); findView(view); return view; } @Override public void onDestroy() { getActivity().unregisterReceiver(broadcastReceiver); MissionController.cancelNetworkMission(getActivity()); super.onDestroy(); } /** * 绑定UI */ protected abstract void findViews(); private void findView(View view) { contentLayout = (FrameLayout) view .findViewById(R.id.base_fragment_content); emptyLayout = (LinearLayout) view .findViewById(R.id.base_fragment_empty); failLayout = (LinearLayout) view.findViewById(R.id.base_fragment_fail); disconnectLayout = (LinearLayout) view .findViewById(R.id.base_fragment_disconnect); disconnectMargin = view .findViewById(R.id.base_fragment_disconnect_margin); loadingLayout = (LinearLayout) view .findViewById(R.id.base_fragment_loading); emptyImage = (ImageView) view .findViewById(R.id.base_fragment_empty_image); emptyText = (TextView) view.findViewById(R.id.base_fragment_empty_text); failText = (TextView) view.findViewById(R.id.base_fragment_fail_text); disconnectText = (TextView) view .findViewById(R.id.base_fragment_disconnect_text); loadingText = (TextView) view .findViewById(R.id.base_fragment_loading_text); failButton = (Button) view.findViewById(R.id.base_fragment_fail_button); loadingProgressBar = (ProgressBar) view .findViewById(R.id.base_fragment_loading_progressbar); disconnectText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); } }); showContentView(); initReceiver(); } private void initReceiver() { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { checkConnection(); // if (showConnectionState) { // } } } }; failButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { reload(); } }); IntentFilter intentFilter = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); getActivity().registerReceiver(broadcastReceiver, intentFilter); } protected View findViewById(int viewId) { return contentView.findViewById(viewId); } protected void showContentView() { if (contentLayout.getChildCount() > 0) { contentLayout.removeAllViews(); } if (contentView != null) { contentLayout.addView(contentView); } } protected void setContentView(int layoutId) { contentView = layoutInflater.inflate(layoutId, null); } protected View getContentView() { return contentView; } private void checkConnection() { if (isConnected()) { disconnectLayout.setVisibility(View.GONE); } else { disconnectLayout.setVisibility(View.VISIBLE); } } protected void reload() { } /** * network mission start */ protected void missionStart() { loadingLayout.setVisibility(View.VISIBLE); failLayout.setVisibility(View.GONE); emptyLayout.setVisibility(View.GONE); } /** * network mission finished */ protected void missionComplete() { loadingLayout.setVisibility(View.GONE); failLayout.setVisibility(View.GONE); emptyLayout.setVisibility(View.GONE); } /** * network mission finished on fail */ protected void missionFailed() { loadingLayout.setVisibility(View.GONE); failLayout.setVisibility(View.VISIBLE); emptyLayout.setVisibility(View.GONE); } /** * network mission finished but not contain useable data */ protected void missionNodata() { loadingLayout.setVisibility(View.GONE); failLayout.setVisibility(View.GONE); emptyLayout.setVisibility(View.VISIBLE); } protected String post(String url, List<RequestParam> requestParams) { if (!isConnected()) { ApplicationTool.log("ApplicationTool", "Request disconnect"); return ""; } ApplicationTool.log("ApplicationTool", "Request url=" + url); ApplicationTool.log("ApplicationTool", "Request requestParams=" + requestParams); Request.Builder builder = new Request.Builder(); builder.tag(getActivity()); builder.url(url); FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); if (requestParams != null) { for (int i = 0; i < requestParams.size(); i++) { formEncodingBuilder.add(requestParams.get(i).getKey(), requestParams.get(i).getValue()); } } builder.post(formEncodingBuilder.build()); Request request = builder.build(); try { Response response = MissionController.getOkHttpClient().newCall(request).execute(); if (response != null) { String result = response.body().string(); ApplicationTool.log("ApplicationTool", "Request onResponse=" + result); return result; } } catch (IOException e) { e.printStackTrace(); } return ""; } /** * add a new post network mission */ protected void post(String url, OnNetworkListener onNetworkListener) { post(url, null, onNetworkListener); } /** * add a new post network mission */ protected void post(String url, List<RequestParam> requestParams, OnNetworkListener onNetworkListener) { // if (!isConnected()) { // ApplicationTool.log("ApplicationTool", "Request disconnect"); // return; // } ApplicationTool.log("ApplicationTool", "Request url=" + url); ApplicationTool.log("ApplicationTool", "Request requestParams=" + requestParams); Request.Builder builder = new Request.Builder(); builder.header("version", ApplicationTool.getVersionName()); if (url.startsWith(API.IP_PUBLIC)) { builder.header("cookie", Content.getStringContent(Parameters.CACHE_KEY_COOKIE, "")); } else if (url.startsWith(API.IP_MONEY)) { builder.header("cookie", Content.getStringContent(Parameters.CACHE_KEY_COOKIE_MONEY, "")); } builder.tag(getActivity()); builder.url(url); FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); if (requestParams != null) { for (int i = 0; i < requestParams.size(); i++) { formEncodingBuilder.add(requestParams.get(i).getKey(), requestParams.get(i).getValue()); } } builder.post(formEncodingBuilder.build()); Request request = builder.build(); startNetworkMission(request, onNetworkListener); } private void startNetworkMission(final Request request, final OnNetworkListener onNetworkListener) { if (loadingLayout.getVisibility() != View.VISIBLE) { missionStart(); } Call call = MissionController.getOkHttpClient().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { onNetworkListener.onFailure(request); } @Override public void onResponse(Response response) throws IOException { if (response != null) { // if (response.body() != null) { // String result = response.body().string(); // if (result.contains("NAUTH")) { // ApplicationTool.log("ApplicationTool", "会话过期" + request.urlString()); // Content.removeContent(Parameters.CACHE_KEY_USER_JSON); // Content.removeContent(Parameters.CACHE_KEY_USER_PASSWORD); // Content.removeContent(Parameters.CACHE_KEY_COOKIE); // Content.removeContent(Parameters.CACHE_KEY_MONEY_SN); // User.init(getActivity()); // MoneyAccount.init(null); // } // } if (response.headers() != null) { if (response.headers().toMultimap().containsKey("Set-Cookie")) { ApplicationTool.log("ApplicationTool", response.headers().toString()); if (response.request().urlString().equals(API.API_USER_LOGIN)) { Content.saveStringContent(Parameters.CACHE_KEY_COOKIE, response.headers().toMultimap().get("Set-Cookie").toString()); } else if (response.request().urlString().equals(API.MONEY_LOGIN)) { Content.saveStringContent(Parameters.CACHE_KEY_COOKIE_MONEY, response.headers().toMultimap().get("Set-Cookie").toString()); } } } } onNetworkListener.onResponse(response); } }); } public abstract class OnNetworkListener { public static final int FLAG_FAIL = 0; public static final int FLAG_SUCCESS = 1; Handler handler = new Handler(Looper.getMainLooper()) { public void handleMessage(Message msg) { switch (msg.what) { case FLAG_FAIL: onFailure((String) msg.obj); break; case FLAG_SUCCESS: onResponse((String) msg.obj); break; default: break; } } }; public void onFailure(Request request) { handler.sendMessage(Message.obtain(handler, FLAG_FAIL, "Called when the request could not be executed due to cancellation, a connectivity problem or timeout.")); } public void onResponse(Response response) { if (response.code() >= 400 && response.code() <= 599) { handler.sendMessage(Message.obtain(handler, FLAG_FAIL, "ResponseCode " + response.code())); return; } try { handler.sendMessage(Message.obtain(handler, FLAG_SUCCESS, response.body().string())); } catch (IOException e) { handler.sendMessage(Message.obtain(handler, FLAG_FAIL, e.getMessage())); } } private void onFailure(String failReason) { ApplicationTool.log("ApplicationTool", "Request onFailure=" + failReason); // missionFailed(); missionComplete(); onSuccess(""); } private void onResponse(String result) { ApplicationTool.log("ApplicationTool", "Request onResponse=" + result); missionComplete(); onSuccess(result); } public abstract void onSuccess(String result); } } <file_sep>package yitgogo.consumer.order.ui; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.smartown.yitian.gogo.R; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.view.Notify; /** * Created by Tiger on 2015-11-26. */ public class OrderPlatformReturnFragment extends BaseNotifyFragment { TextView productNameTextView, productPriceTextView, contactPhoneTextView; EditText reasonEditText; Button commitButton; String productName = ""; double productPrice = 0; String saleId = ""; String supplierId = ""; String orderNumber = ""; String productInfo = ""; int buyCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_platform_order_return); init(); findViews(); } @Override protected void findViews() { productNameTextView = (TextView) contentView.findViewById(R.id.fragment_platform_return_product_name); productPriceTextView = (TextView) contentView.findViewById(R.id.fragment_platform_return_product_price); contactPhoneTextView = (TextView) contentView.findViewById(R.id.fragment_platform_return_phone); reasonEditText = (EditText) contentView.findViewById(R.id.fragment_platform_return_reason); commitButton = (Button) contentView.findViewById(R.id.fragment_platform_return_commit); initViews(); registerViews(); } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("productName")) { productName = bundle.getString("productName"); } if (bundle.containsKey("productPrice")) { productPrice = bundle.getDouble("productPrice"); } if (bundle.containsKey("saleId")) { saleId = bundle.getString("saleId"); } if (bundle.containsKey("supplierId")) { supplierId = bundle.getString("supplierId"); } if (bundle.containsKey("orderNumber")) { orderNumber = bundle.getString("orderNumber"); } if (bundle.containsKey("productInfo")) { productInfo = bundle.getString("productInfo"); } if (bundle.containsKey("buyCount")) { buyCount = bundle.getInt("buyCount"); } } } @Override protected void initViews() { productNameTextView.setText(productName); productPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(productPrice) + " ×" + buyCount); } @Override protected void registerViews() { commitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!TextUtils.isEmpty(reasonEditText.getText().toString())) { new ReturnProduct().execute(); } else { Notify.show("请填写退货原因"); } } }); } class ReturnProduct extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... voids) { List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("saleId", saleId)); nameValuePairs.add(new BasicNameValuePair("supplierId", supplierId)); nameValuePairs.add(new BasicNameValuePair("orderNumber", orderNumber)); nameValuePairs.add(new BasicNameValuePair("productInfo", productInfo)); nameValuePairs.add(new BasicNameValuePair("reason", reasonEditText.getText().toString())); return NetUtil.getInstance().postWithCookie(API.API_ORDER_RETURN, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { jump(OrderPlatformReturnCommitedFragment.class.getName(), "申请退货"); getActivity().finish(); } else { Notify.show(object.optString("message")); } return; } catch (JSONException e) { e.printStackTrace(); } } Notify.show("申请退货失败"); } } } <file_sep>package yitgogo.consumer.store.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.location.LocationClientOption.LocationMode; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.main.ui.MainActivity; import yitgogo.consumer.store.model.ModelStoreLocated; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.view.InnerListView; public class StoreLocateFragment extends BaseNetworkFragment { InnerListView storeListView; ImageView refreshButton; TextView locationText; LocationClient locationClient; List<ModelStoreLocated> storeLocateds; StoreAdapter storeAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_store_select_locate); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(StoreLocateFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(StoreLocateFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); locate(); } @Override protected void init() { initLocationTool(); storeLocateds = new ArrayList<>(); storeAdapter = new StoreAdapter(); } @Override protected void findViews() { storeListView = (InnerListView) contentView .findViewById(R.id.locate_stores); refreshButton = (ImageView) contentView .findViewById(R.id.locate_refresh); locationText = (TextView) contentView .findViewById(R.id.locate_location); initViews(); registerViews(); } @Override protected void initViews() { storeListView.setAdapter(storeAdapter); } @Override protected void registerViews() { refreshButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { locate(); } }); } private void getLocalBusinessState() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("organizationId", Store.getStore().getStoreId())); post(API.API_LOCAL_BUSINESS_STATE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { boolean showLocalBusiness = false; if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { showLocalBusiness = dataMap.optInt("returnNum") != 0; } } } catch (JSONException e) { e.printStackTrace(); } } Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra("showLocalBusiness", showLocalBusiness); startActivity(intent); getActivity().finish(); } }); } class StoreAdapter extends BaseAdapter { @Override public int getCount() { return storeLocateds.size(); } @Override public Object getItem(int position) { return storeLocateds.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_store_selected, null); holder = new ViewHolder(); holder.nameTextView = (TextView) convertView .findViewById(R.id.list_store_name); holder.addressTextView = (TextView) convertView .findViewById(R.id.list_store_address); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final ModelStoreLocated storeLocated = storeLocateds.get(position); holder.nameTextView.setText(storeLocated.getTitle()); holder.addressTextView.setText(storeLocated.getAddress()); convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Content.saveIntContent(Parameters.CACHE_KEY_STORE_TYPE, Parameters.CACHE_VALUE_STORE_TYPE_LOCATED); Content.saveStringContent( Parameters.CACHE_KEY_STORE_JSONSTRING, storeLocated .getJsonObject().toString()); Store.init(getActivity()); getLocalBusinessState(); } }); return convertView; } class ViewHolder { TextView nameTextView, addressTextView; } } private void initLocationTool() { locationClient = new LocationClient(getActivity()); LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式 option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02 option.setIsNeedAddress(true);// 返回的定位结果包含地址信息 // option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms // option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向 locationClient.setLocOption(option); locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(BDLocation bdLocation) { // locateTime++; // // 防止重复定位,locateTime>1 表示已经定位过,无需再定位 // if (locateTime > 1) { // return; // } if (bdLocation != null) { if (bdLocation.getLocType() == 61 || bdLocation.getLocType() == 65 || bdLocation.getLocType() == 161) { locationText.setText(bdLocation.getAddrStr()); getNearestStore(bdLocation); } else { locationText.setText("定位失败"); } } else { locationText.setText("定位失败"); } locationClient.stop(); } }); } private void locate() { locationClient.start(); locationClient.requestLocation(); } private void getNearestStore(BDLocation location) { storeLocateds.clear(); storeAdapter.notifyDataSetChanged(); RequestParams requestParams = new RequestParams(); requestParams.add("ak", Parameters.CONSTANT_LBS_AK); requestParams.add("geotable_id", Parameters.CONSTANT_LBS_TABLE); requestParams.add("sortby", "distance:1"); requestParams.add("radius", "100000"); requestParams.add("page_index", "0"); requestParams.add("page_size", "100"); requestParams.add("location", location.getLongitude() + "," + location.getLatitude()); AsyncHttpClient httpClient = new AsyncHttpClient(); httpClient.get(API.API_LBS_NEARBY, requestParams, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // {"total":102,"contents":[{"uid":723032242,"tags":"","coord_type":3,"jmdNo":"YT445572733429","phone":"15123568974","weight":0,"location":[104.0866308,30.68404769],"jmdId":"7","type":0,"city":"成都市","distance":49,"title":"易田测试加盟店五","geotable_id":96314,"address":"解放路二段六号凤凰大厦","province":"四川省","create_time":1427430737,"icon_style_id":"sid1","bossName":"张帅的","district":"金牛区"}],"status":0,"size":1} if (statusCode == 200) { if (response != null) { JSONArray array; try { array = response.getJSONArray("contents"); if (array.length() > 0) { for (int i = 0; i < array.length(); i++) { storeLocateds.add(new ModelStoreLocated( array.optJSONObject(i))); } storeAdapter.notifyDataSetChanged(); // 自动定位到到最近加盟店,跳转到主页 return; } } catch (JSONException e) { e.printStackTrace(); } } } // 执行到这里说明没有自动定位到到最近加盟店,需要手选 } }); } } <file_sep>include ':pullToRefresh' include ':smart' <file_sep>package yitgogo.smart; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitgogo.smart.R; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.List; import yitgogo.smart.home.model.ModelAds; import yitgogo.smart.home.model.ModelAdsImage; /** * Created by Tiger on 2015-10-29. */ public class AdsActivity extends Activity { ImageView imageView; public static List<ModelAds> adses = new ArrayList<>(); List<ModelAdsImage> adsImages = new ArrayList<>(); int count = 0; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { ImageLoader.getInstance().displayImage(adsImages.get(count % adsImages.size()).getAdverImg(), imageView); count++; handler.sendEmptyMessageDelayed(0, 10000); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_ads); for (int i = 0; i < adses.size(); i++) { if (adses.get(i).getAdsImages().isEmpty()) { if (!TextUtils.isEmpty(adses.get(i).getDefaultadver())) { adsImages.add(new ModelAdsImage(adses.get(i).getDefaultadver())); } } else { adsImages.addAll(adses.get(i).getAdsImages()); } } if (adsImages.isEmpty()) { adsImages.add(new ModelAdsImage("drawable://" + R.drawable.ads)); } findViews(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); MobclickAgent.onPageStart(AdsActivity.class.getName()); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); MobclickAgent.onPageEnd(AdsActivity.class.getName()); } private void findViews() { imageView = (ImageView) findViewById(R.id.ads_image); initViews(); } private void initViews() { imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); handler.sendEmptyMessage(0); } } <file_sep>include ':consumer' include ':pullToRefresh' include ':ViewPagerIndicator' <file_sep>package yitgogo.consumer.home.task; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import android.os.AsyncTask; public class GetSaleTimes extends AsyncTask<Boolean, Void, String> { @Override protected String doInBackground(Boolean... params) { List<NameValuePair> activity = new ArrayList<NameValuePair>(); activity.add(new BasicNameValuePair("strno", Store.getStore() .getStoreNumber())); activity.add(new BasicNameValuePair("flag", "1")); return NetUtil.getInstance().postWithoutCookie(API.API_SALE_CLASS, activity, params[0], true); } } <file_sep>package yitgogo.consumer; import android.app.Application; import android.graphics.Bitmap; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.utils.L; import com.smartown.controller.shoppingcart.DataBaseHelper; import com.smartown.yitian.gogo.R; import com.tencent.bugly.crashreport.CrashReport; import com.umeng.analytics.AnalyticsConfig; import com.umeng.analytics.MobclickAgent; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.suning.model.SuningCarController; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.LogUtil; import yitgogo.consumer.tools.NetUtil; import yitgogo.consumer.tools.PackageTool; import yitgogo.consumer.tools.ScreenUtil; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.Notify; public class YitgogoApplication extends Application { @Override public void onCreate() { super.onCreate(); init(); } private void init() { DataBaseHelper.init(this); PackageTool.init(this); LogUtil.setLogEnable(false); SuningCarController.init(this); Notify.init(this); NetUtil.init(this); Content.init(this); User.init(this); Store.init(this); ScreenUtil.init(this); CrashReport.initCrashReport(this, "900003445", false); initImageLoader(); initUmeng(); } private void initImageLoader() { L.writeDebugLogs(false); L.writeLogs(false); DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.loading_default) .showImageForEmptyUri(R.drawable.loading_default) .showImageOnFail(R.drawable.loading_default) .resetViewBeforeLoading(true).cacheInMemory(false) .cacheOnDisk(true).considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565).build(); ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder( this).memoryCache(new WeakMemoryCache()) .denyCacheImageMultipleSizesInMemory() .defaultDisplayImageOptions(options).build(); ImageLoader.getInstance().init(configuration); } private void initUmeng() { //Edit in AndroidManifest.xml // AnalyticsConfig.setAppkey(this, "564143c067e58e7902003900"); //Tencent 腾讯应用宝 Qihu 360手机助手 Baidu 百度手机助手 Wandoujia 豌豆荚 Update 自动更新 // AnalyticsConfig.setChannel("Update"); //session超时 MobclickAgent.setSessionContinueMillis(2 * 60 * 1000); //账号统计 if (User.getUser().isLogin()) { MobclickAgent.onProfileSignIn(User.getUser().getUseraccount()); // MobclickAgent.onProfileSignIn("QQ","userid"); } /** * 账号登出时需调用此接口,调用之后不再发送账号相关内容。 */ // MobclickAgent.onProfileSignOff(); /** * 禁止默认的页面统计方式,这样将不会再自动统计Activity。 * 然后需要做两步集成: 1. 使用 onResume 和 onPause 方法统计时长, 这和基本统计中的情况一样(针对Activity) 2. 使用 onPageStart 和 onPageEnd 方法统计页面(针对页面,页面可能是Activity 也可能是Fragment或View) */ MobclickAgent.openActivityDurationTrack(false); /** 设置是否对日志信息进行加密, 默认false(不加密). */ AnalyticsConfig.enableEncrypt(true); MobclickAgent.setDebugMode(false); } } <file_sep>package yitgogo.smart; import android.app.Application; import android.graphics.Bitmap; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.utils.L; import com.smartown.yitgogo.smart.R; import com.umeng.analytics.AnalyticsConfig; import com.umeng.analytics.MobclickAgent; import smartown.controller.shoppingcart.DataBaseHelper; import yitgogo.smart.suning.model.SuningCarController; import yitgogo.smart.tools.Content; import yitgogo.smart.tools.Device; import yitgogo.smart.tools.LogUtil; import yitgogo.smart.tools.PackageTool; import yitgogo.smart.tools.ScreenUtil; import yitgogo.smart.view.Notify; public class YitgogoApplication extends Application { @Override public void onCreate() { super.onCreate(); init(); } private void init() { DataBaseHelper.init(this); PackageTool.init(this); Device.init(); Notify.init(this); Content.init(this); ScreenUtil.init(this); SuningCarController.init(this); LogUtil.setLogEnable(true); initImageLoader(); initUmeng(); } private void initImageLoader() { L.writeDebugLogs(false); L.writeLogs(false); DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.loading_default) .showImageForEmptyUri(R.drawable.loading_default) .showImageOnFail(R.drawable.loading_default) .resetViewBeforeLoading(true).cacheInMemory(false) .cacheOnDisk(true).considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565).build(); ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder( this).memoryCache(new WeakMemoryCache()) .denyCacheImageMultipleSizesInMemory() .defaultDisplayImageOptions(options).build(); ImageLoader.getInstance().init(configuration); } private void initUmeng() { //Edit in AndroidManifest.xml AnalyticsConfig.setAppkey(this, "<KEY>"); //Tencent 腾讯应用宝 Qihu 360手机助手 Baidu 百度手机助手 Wandoujia 豌豆荚 Update 自动更新 AnalyticsConfig.setChannel("Official"); //session超时 MobclickAgent.setSessionContinueMillis(2 * 60 * 1000); //账号统计 MobclickAgent.onProfileSignIn(Device.getDeviceCode()); // MobclickAgent.onProfileSignIn("QQ","userid"); /** * 账号登出时需调用此接口,调用之后不再发送账号相关内容。 */ // MobclickAgent.onProfileSignOff(); /** * 禁止默认的页面统计方式,这样将不会再自动统计Activity。 * 然后需要做两步集成: 1. 使用 onResume 和 onPause 方法统计时长, 这和基本统计中的情况一样(针对Activity) 2. 使用 onPageStart 和 onPageEnd 方法统计页面(针对页面,页面可能是Activity 也可能是Fragment或View) */ MobclickAgent.openActivityDurationTrack(false); /** 设置是否对日志信息进行加密, 默认false(不加密). */ AnalyticsConfig.enableEncrypt(true); MobclickAgent.setDebugMode(true); } } <file_sep>package yitgogo.smart; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.smartown.yitgogo.smart.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import yitgogo.smart.home.HomeFragment; import yitgogo.smart.model.VersionInfo; import yitgogo.smart.task.CommonTask; import yitgogo.smart.tools.NetworkMissionMessage; import yitgogo.smart.tools.OnNetworkListener; import yitgogo.smart.tools.PackageTool; import yitgogo.smart.view.DownloadDialog; public class EntranceActivity extends BaseActivity { LinearLayout loadingLayout; TextView loadingTextView, versionTextView; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); neverShowAds(); setContentView(R.layout.fragment_entrance); findViews(); checkUpdate(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); MobclickAgent.onPageStart(EntranceActivity.class.getName()); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); MobclickAgent.onPageEnd(EntranceActivity.class.getName()); } @Override protected void findViews() { loadingLayout = (LinearLayout) findViewById(R.id.entrance_loading_layout); loadingTextView = (TextView) findViewById(R.id.entrance_loading_text); versionTextView = (TextView) findViewById(R.id.entrance_version_text); initViews(); } @Override protected void initViews() { versionTextView.setText("版本:" + PackageTool.getVersionName() + "(" + PackageTool.getVersionCode() + ")"); } private void showLoading(String text) { loadingLayout.setVisibility(View.VISIBLE); loadingTextView.setText(text); } private void hideLoading() { loadingLayout.setVisibility(View.GONE); } private void activeSuccess() { jump(HomeFragment.class.getName(), "", null); finish(); } private void checkUpdate() { CommonTask.checkUpdate(this, new OnNetworkListener() { @Override public void onStart() { super.onStart(); showLoading("正在检查更新..."); } @Override public void onSuccess(NetworkMissionMessage message) { super.onSuccess(message); VersionInfo versionInfo = new VersionInfo(message.getResult()); if (versionInfo.getVerCode() > PackageTool.getVersionCode()) { // 网络上的版本大于此安装版本,需要更新 DownloadDialog downloadDialog = new DownloadDialog( versionInfo) { @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); getMachineState(); } }; downloadDialog.show(getSupportFragmentManager(), null); return; } getMachineState(); } @Override public void onFail(NetworkMissionMessage message) { super.onFail(message); getMachineState(); } @Override public void onFinish() { super.onFinish(); hideLoading(); } }); } private void getMachineState() { CommonTask.getMachineState(this, new OnNetworkListener() { @Override public void onStart() { super.onStart(); showLoading("查询设备状态中,请稍候..."); } @Override public void onSuccess(NetworkMissionMessage message) { super.onSuccess(message); if (TextUtils.isEmpty(message.getResult())) { alert("访问服务器出现异常", "访问服务器出现异常,请检查网络连接或联系客服人员!"); } else { try { JSONObject object = new JSONObject(message.getResult()); if (object.optString("message").equals("stop")) { alert("此设备已被停用", "此设备已被停用!"); } else if (object.optString("message").equals("noexit")) { new MachineActiveFragment().show( getSupportFragmentManager(), null); } else if (object.optString("message").equals("ok")) { activeSuccess(); } else { alert("访问出错!", "访问出错!" + object.optString("message")); } } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onFail(NetworkMissionMessage message) { super.onFail(message); alert("访问出错!", message.getMessage()); } @Override public void onFinish() { super.onFinish(); hideLoading(); } }); } } <file_sep>package yitgogo.consumer.money.ui; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.money.model.ModelBankCard; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; import yitgogo.consumer.user.ui.UserLoginFragment; import yitgogo.consumer.view.CodeEditDialog; import yitgogo.consumer.view.InnerListView; public class PayFragment extends BaseNetworkFragment { /** * 订单数据 */ String orderNumbers = ""; double totalMoney = 0; int orderType = 1; int productCount = 1; String serialNumber = ""; public static final int ORDER_TYPE_YY = 1; public static final int ORDER_TYPE_YD = 2; public static final int ORDER_TYPE_LP = 3; public static final int ORDER_TYPE_LS = 4; public static final int ORDER_TYPE_BM = 5; public static final int ORDER_TYPE_SN = 6; InnerListView bankCardListView; TextView orderNumberTextView, amountTextView, payButton; SimpleDateFormat serialNumberFormat = new SimpleDateFormat( "yyyyMMddHHmmssSSS"); ModelBankCard selectedBankCard = new ModelBankCard(); BindResult bindResult = new BindResult(); List<ModelBankCard> bankCards; BandCardAdapter bandCardAdapter; LinearLayout addBankCardButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_pay); init(); findViews(); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(PayFragment.class.getName()); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(PayFragment.class.getName()); if (User.getUser().isLogin()) { loginMoney(); } else { jump(UserLoginFragment.class.getName(), "会员登录"); getActivity().finish(); } } @Override protected void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("orderNumbers")) { List<String> orderNumbers = bundle.getStringArrayList("orderNumbers"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < orderNumbers.size(); i++) { if (i > 0) { builder.append(","); } builder.append(orderNumbers.get(i)); } this.orderNumbers = builder.toString(); } if (bundle.containsKey("totalMoney")) { totalMoney = bundle.getDouble("totalMoney"); } if (bundle.containsKey("orderType")) { orderType = bundle.getInt("orderType"); } if (bundle.containsKey("productCount")) { productCount = bundle.getInt("productCount"); } } bankCards = new ArrayList<>(); bandCardAdapter = new BandCardAdapter(); } protected void findViews() { orderNumberTextView = (TextView) contentView.findViewById(R.id.pay_order_number); bankCardListView = (InnerListView) contentView.findViewById(R.id.pay_bankcards); amountTextView = (TextView) contentView.findViewById(R.id.pay_amount); payButton = (TextView) contentView.findViewById(R.id.pay_pay); addBankCardButton = (LinearLayout) layoutInflater.inflate(R.layout.list_pay_bank_card_add, null); initViews(); registerViews(); } @Override protected void initViews() { orderNumberTextView.setText(orderNumbers.toString()); amountTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(totalMoney)); bankCardListView.addFooterView(addBankCardButton); bankCardListView.setAdapter(bandCardAdapter); } @Override protected void registerViews() { bankCardListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { selectedBankCard = bankCards.get(arg2); bandCardAdapter.notifyDataSetChanged(); } }); payButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (totalMoney > 0) { if (TextUtils.isEmpty(selectedBankCard.getId())) { ApplicationTool.showToast("请选择付款方式"); } else { if (selectedBankCard.getCardType().contains("储蓄")) { inputPayPassword(1); } else if (selectedBankCard.getCardType() .contains("信用")) { new CreditInfoDialog().show(getFragmentManager(), null); } else if (selectedBankCard.getCardType().contains( "钱袋子")) { inputPayPassword(2); } } } } }); addBankCardButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(BankCardBindFragment.class.getName(), "绑定银行卡"); } }); } private void pay() { serialNumber = serialNumberFormat.format(new Date(System.currentTimeMillis())); getSmsCode(); } /** * @param type 1:银行卡支付 * <p> * 2:钱袋子月支付 */ private void inputPayPassword(int type) { final int payType = type; PayPasswordDialog passwordDialog = new PayPasswordDialog("请输入支付密码", false) { @Override public void onDismiss(DialogInterface dialog) { if (!TextUtils.isEmpty(payPassword)) { switch (payType) { case 1: verifyPayPassword(payPassword); break; case 2: payBalance(payPassword); break; default: break; } } super.onDismiss(dialog); } }; passwordDialog.show(getFragmentManager(), null); } private void getSmsCode() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("pan", selectedBankCard.getBanknumber())); // requestParams.add(new RequestParam("pan", // "6225881285953427")); requestParams.add(new RequestParam("expiredDate", selectedBankCard.getExpiredDate())); requestParams.add(new RequestParam("cvv2", selectedBankCard.getCvv2())); requestParams.add(new RequestParam("amount", decimalFormat.format(totalMoney))); requestParams.add(new RequestParam("externalRefNumber", serialNumber)); requestParams.add(new RequestParam("customerId", selectedBankCard.getOrg())); // requestParams.add(new RequestParam("customerId", // "HY048566511863")); requestParams.add(new RequestParam("cardHolderName", selectedBankCard.getCradname())); requestParams.add(new RequestParam("cardHolderId", selectedBankCard.getIdCard())); requestParams.add(new RequestParam("phoneNO", selectedBankCard.getMobile())); requestParams.add(new RequestParam("bankCode", selectedBankCard.getBank().getCode())); if (selectedBankCard.getCardType().equalsIgnoreCase("储蓄卡")) { requestParams.add(new RequestParam("isBankType", "1")); } else { requestParams.add(new RequestParam("isBankType", "2")); } post(API.API_PAY_BIND, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { bindResult = new BindResult(dataMap); if (bindResult.getResponseCode().equals("00")) { new SmsDialog().show(getFragmentManager(), null); return; } if (TextUtils.isEmpty(bindResult .getResponseTextMessage())) { ApplicationTool.showToast("获取验证码失败"); } else { ApplicationTool.showToast(bindResult.getResponseTextMessage()); } return; } } } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("获取验证码失败"); } }); } private void showSmsCodeDialog() { CodeEditDialog codeEditDialog = new CodeEditDialog("请输入验证码", false) { @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { return super.onCreateDialog(savedInstanceState); } @Override public void onDismiss(DialogInterface dialog) { if (ok) { if (selectedBankCard.isValidation()) { paySecondTime(code); } else { payFirstTime(code); } } super.onDismiss(dialog); } }; } private void payFirstTime(String validCode) { List<RequestParam> requestParams = new ArrayList<RequestParam>(); requestParams.add(new RequestParam("payInfoType", orderType + "")); requestParams.add(new RequestParam("orderNumber", orderNumbers)); requestParams.add(new RequestParam("cardNo", selectedBankCard.getBanknumber())); requestParams.add(new RequestParam("externalRefNumber", serialNumber)); requestParams.add(new RequestParam("storableCardNo", getShortCardNumber(selectedBankCard.getBanknumber()))); requestParams.add(new RequestParam("expiredDate", selectedBankCard.getExpiredDate())); requestParams.add(new RequestParam("cvv2", selectedBankCard.getCvv2())); requestParams.add(new RequestParam("amount", decimalFormat.format(totalMoney))); requestParams.add(new RequestParam("customerId", selectedBankCard.getOrg())); requestParams.add(new RequestParam("cardHolderName", selectedBankCard.getCradname())); requestParams.add(new RequestParam("cardHolderId", selectedBankCard.getIdCard())); requestParams.add(new RequestParam("phone", selectedBankCard.getMobile())); requestParams.add(new RequestParam("validCode", validCode)); if (!TextUtils.isEmpty(bindResult.getToken())) { requestParams.add(new RequestParam("token", bindResult.getToken())); } requestParams.add(new RequestParam("bankCode", selectedBankCard.getBank().getCode())); if (selectedBankCard.getCardType().equalsIgnoreCase("储蓄卡")) { requestParams.add(new RequestParam("isBankType", "1")); } else { requestParams.add(new RequestParam("isBankType", "2")); } post(API.API_PAY_FIRST_TIME, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { BindResult payResult = new BindResult(dataMap); if (payResult.getResponseCode().equals("00")) { paySuccess(); return; } if (TextUtils.isEmpty(payResult .getResponseTextMessage())) { ApplicationTool.showToast("付款失败"); } else { ApplicationTool.showToast(payResult.getResponseTextMessage()); } return; } } } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("付款失败"); } }); } private void paySecondTime(String validCode) { List<RequestParam> requestParams = new ArrayList<RequestParam>(); requestParams.add(new RequestParam("payInfoType", orderType + "")); requestParams.add(new RequestParam("orderNumber", orderNumbers)); requestParams.add(new RequestParam("storableCardNo", getShortCardNumber(selectedBankCard.getBanknumber()))); requestParams.add(new RequestParam("externalRefNumber", serialNumber)); requestParams.add(new RequestParam("amount", decimalFormat.format(totalMoney))); requestParams.add(new RequestParam("customerId", selectedBankCard.getOrg())); requestParams.add(new RequestParam("phone", selectedBankCard.getMobile())); requestParams.add(new RequestParam("validCode", validCode)); requestParams.add(new RequestParam("token", bindResult.getToken())); post(API.API_PAY_SECOND_TIME, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { BindResult payResult = new BindResult(dataMap); if (payResult.getResponseCode().equals("00")) { paySuccess(); return; } } } } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("付款失败"); } }); } private void payBalance(String pwd) { List<RequestParam> requestParams = new ArrayList<RequestParam>(); requestParams.add(new RequestParam("memberAccount", User.getUser().getUseraccount())); requestParams.add(new RequestParam("orderType", orderType + "")); requestParams.add(new RequestParam("orderNumbers", orderNumbers)); requestParams.add(new RequestParam("customerName", User.getUser().getRealname())); requestParams.add(new RequestParam("apAmount", decimalFormat.format(totalMoney))); requestParams.add(new RequestParam("pwd", pwd)); post(API.API_PAY_BALANCE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); if (dataMap != null) { if (dataMap.optString("status").equalsIgnoreCase( "ok")) { paySuccess(); return; } else { ApplicationTool.showToast(dataMap.optString("msg")); return; } } } else { ApplicationTool.showToast(object.optString("message")); return; } } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("付款失败"); } }); } private void paySuccess() { ApplicationTool.showToast("付款成功"); showOrder(orderType); getActivity().finish(); } private String getShortCardNumber(String cardNumber) { if (cardNumber.length() > 10) { return cardNumber.substring(0, 6) + cardNumber.substring(cardNumber.length() - 4, cardNumber.length()); } return ""; } class BandCardAdapter extends BaseAdapter { @Override public int getCount() { return bankCards.size(); } @Override public Object getItem(int position) { return bankCards.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_pay_bank_card, null); viewHolder.selected = (ImageView) convertView .findViewById(R.id.bank_card_bank_selection); viewHolder.bankImageView = (ImageView) convertView .findViewById(R.id.bank_card_bank_image); viewHolder.cardNumberTextView = (TextView) convertView .findViewById(R.id.bank_card_number); viewHolder.cardTypeTextView = (TextView) convertView .findViewById(R.id.bank_card_type); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ModelBankCard bankCard = bankCards.get(position); if (bankCard.getId().equals(selectedBankCard.getId())) { viewHolder.selected .setImageResource(R.drawable.iconfont_check_checked); } else { viewHolder.selected .setImageResource(R.drawable.iconfont_check_normal); } ImageLoader.getInstance().displayImage( bankCard.getBank().getIcon(), viewHolder.bankImageView); if (bankCard.getCardType().contains("钱袋子")) { viewHolder.cardNumberTextView.setText("钱袋子余额"); viewHolder.cardTypeTextView.setText("剩余:" + Parameters.CONSTANT_RMB + decimalFormat.format(MoneyAccount.getMoneyAccount() .getBalance())); } else { viewHolder.cardNumberTextView .setText(getSecretCardNuber(bankCard.getBanknumber())); viewHolder.cardTypeTextView.setText(bankCard.getBank() .getName() + " " + bankCard.getCardType()); } return convertView; } class ViewHolder { ImageView selected, bankImageView; TextView cardNumberTextView, cardTypeTextView; } } /** * @author Tiger * @Json "dataMap":{"responseCode":"00", "customerId" * :"zhaojin1992","token":"<PASSWORD>","merchantId": "104110045112012" * ,"storablePan":"6225883427"} */ class BindResult { String responseCode = "", responseTextMessage = "", customerId = "", token = "", merchantId = "", storablePan = ""; public BindResult() { } public BindResult(JSONObject object) { if (object != null) { if (object.has("responseCode")) { if (!object.optString("responseCode").equalsIgnoreCase( "null")) { responseCode = object.optString("responseCode"); } } if (object.has("responseTextMessage")) { if (!object.optString("responseTextMessage") .equalsIgnoreCase("null")) { responseTextMessage = object .optString("responseTextMessage"); } } if (object.has("customerId")) { if (!object.optString("customerId") .equalsIgnoreCase("null")) { customerId = object.optString("customerId"); } } if (object.has("token")) { if (!object.optString("token").equalsIgnoreCase("null")) { token = object.optString("token"); } } if (object.has("merchantId")) { if (!object.optString("merchantId") .equalsIgnoreCase("null")) { merchantId = object.optString("merchantId"); } } if (object.has("storablePan")) { if (!object.optString("storablePan").equalsIgnoreCase( "null")) { storablePan = object.optString("storablePan"); } } } } public String getResponseCode() { return responseCode; } public String getCustomerId() { return customerId; } public String getToken() { return token; } public String getMerchantId() { return merchantId; } public String getStorablePan() { return storablePan; } public String getResponseTextMessage() { return responseTextMessage; } } class SmsDialog extends DialogFragment { View dialogView; TextView okButton, getCodeButton; EditText smscodeEditText; ImageView closeButton; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj != null) { getCodeButton.setText(msg.obj + "s"); } else { getCodeButton.setEnabled(true); getCodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getCodeButton.setText("获取验证码"); } } ; }; boolean isFinish = false; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); findViews(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); isFinish = true; } private void init() { setCancelable(false); new Thread(new Runnable() { @Override public void run() { int time = 60; while (time > -1) { if (isFinish) { break; } try { Message message = new Message(); if (time > 0) { message.obj = time; } handler.sendMessage(message); Thread.sleep(1000); time--; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity()); dialog.getWindow().setBackgroundDrawableResource(R.color.divider); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(dialogView, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); return dialog; } private void findViews() { dialogView = layoutInflater.inflate(R.layout.dialog_pay_smscode, null); closeButton = (ImageView) dialogView .findViewById(R.id.pay_sms_close); smscodeEditText = (EditText) dialogView .findViewById(R.id.pay_sms_code); getCodeButton = (TextView) dialogView .findViewById(R.id.pay_sms_get); okButton = (TextView) dialogView.findViewById(R.id.pay_sms_ok); getCodeButton.setEnabled(false); okButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(smscodeEditText.getText().toString() .trim())) { ApplicationTool.showToast("请输入验证码"); } else { if (selectedBankCard.isValidation()) { paySecondTime(smscodeEditText.getText().toString()); } else { payFirstTime(smscodeEditText.getText().toString()); } dismiss(); } } }); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); getCodeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getSmsCode(); dismiss(); } }); } } class CreditInfoDialog extends DialogFragment { View dialogView; TextView okButton, cancelButton; EditText timeEditText, codeEditText; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); findViews(); } private void init() { setCancelable(false); } @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity()); dialog.getWindow().setBackgroundDrawableResource(R.color.divider); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(dialogView, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); return dialog; } private void findViews() { dialogView = layoutInflater.inflate(R.layout.dialog_credit_edit, null); timeEditText = (EditText) dialogView .findViewById(R.id.pay_credit_card_time); codeEditText = (EditText) dialogView .findViewById(R.id.pay_credit_card_code); cancelButton = (TextView) dialogView .findViewById(R.id.pay_credit_card_cancel); okButton = (TextView) dialogView .findViewById(R.id.pay_credit_card_ok); okButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(timeEditText.getText().toString() .trim())) { ApplicationTool.showToast("请输入信用卡有效期"); } else if (TextUtils.isEmpty(codeEditText.getText() .toString().trim())) { ApplicationTool.showToast("请输入信用卡校验码"); } else { selectedBankCard.setExpiredDate(timeEditText.getText() .toString().trim()); selectedBankCard.setCvv2(codeEditText.getText() .toString().trim()); inputPayPassword(1); dismiss(); } } }); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } } private void verifyPayPassword(String paypwd) { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("sn", User.getUser().getCacheKey())); requestParams.add(new RequestParam("payaccount", MoneyAccount.getMoneyAccount().getPayaccount())); requestParams.add(new RequestParam("paypwd", paypwd)); post(API.MONEY_PAY_PASSWORD_VALIDATE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (passwordIsRight(result)) { pay(); } else { ApplicationTool.showToast("支付密码错误"); } } }); } private boolean passwordIsRight(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject jsonObject = object.optJSONObject("databody"); if (jsonObject != null) { return jsonObject.optBoolean("vli"); } } } catch (JSONException e) { e.printStackTrace(); } } return false; } private void loginMoney() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("sn", User.getUser().getCacheKey())); post(API.MONEY_LOGIN, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { initMoney(result); if (MoneyAccount.getMoneyAccount().isLogin()) { getBankCards(); } else { getActivity().finish(); } } }); } private void initMoney(String result) { MoneyAccount.init(null); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { MoneyAccount.init(object.optJSONObject("databody")); return; } ApplicationTool.showToast(object.optString("msg")); return; } catch (JSONException e) { e.printStackTrace(); } } ApplicationTool.showToast("暂无法进入钱袋子,请稍候再试"); return; } private void getBankCards() { MoneyAccount.getMoneyAccount().getBankCards().clear(); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("sn", User.getUser().getCacheKey())); requestParams.add(new RequestParam("memberid", User.getUser().getUseraccount())); post(API.MONEY_BANK_BINDED, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { initbankCards(result); if (MoneyAccount.getMoneyAccount().isGetBankCardFailed()) { getActivity().finish(); } else { bankCards = MoneyAccount.getMoneyAccount().getBankCards(); ModelBankCard bankCard = new ModelBankCard("钱袋子余额"); bankCards.add(0, bankCard); bandCardAdapter.notifyDataSetChanged(); } } }); } private void initbankCards(String result) { MoneyAccount.getMoneyAccount().getBankCards().clear(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONArray array = object.optJSONArray("databody"); if (array != null) { List<ModelBankCard> bankCards = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { bankCards.add(new ModelBankCard(array.optJSONObject(i))); } MoneyAccount.getMoneyAccount().setGetBankCardFailed( false); MoneyAccount.getMoneyAccount().setBankCards(bankCards); return; } } MoneyAccount.getMoneyAccount().setGetBankCardFailed(true); ApplicationTool.showToast(object.optString("msg")); return; } catch (JSONException e) { e.printStackTrace(); } } MoneyAccount.getMoneyAccount().setGetBankCardFailed(true); ApplicationTool.showToast("获取绑定的银行卡信息失败!"); return; } } <file_sep>package yitgogo.consumer.home.task; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.NetUtil; import android.os.AsyncTask; public class GetSaleTimes extends AsyncTask<Boolean, Void, String> { @Override protected String doInBackground(Boolean... params) { List<NameValuePair> activity = new ArrayList<NameValuePair>(); activity.add(new BasicNameValuePair("strno", Store.getStore() .getStoreNumber())); activity.add(new BasicNameValuePair("flag", "1")); return NetUtil.getInstance().postWithoutCookie(API.API_SALE_CLASS, activity, params[0], true); } } <file_sep>package yitgogo.consumer.money.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.money.model.ModelBankCard; import yitgogo.consumer.money.model.ModelTakeOutHistory; import yitgogo.consumer.money.model.MoneyAccount; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.view.InnerListView; public class TakeOutHistoryFragment extends BaseNetworkFragment { DrawerLayout drawerLayout; PullToRefreshScrollView refreshScrollView; InnerListView dataListView, bankCardsListView; TextView clearButton, selectButton; List<ModelTakeOutHistory> takeOutHistories; TakeOutHistoryAdapter historyAdapter; BandCardAdapter bandCardAdapter; ModelBankCard selectedBankCard = new ModelBankCard(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_takeout_list); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(TakeOutHistoryFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(TakeOutHistoryFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); reload(); } @Override protected void init() { takeOutHistories = new ArrayList<>(); historyAdapter = new TakeOutHistoryAdapter(); bandCardAdapter = new BandCardAdapter(); } @Override protected void findViews() { drawerLayout = (DrawerLayout) contentView .findViewById(R.id.takeout_drawer); refreshScrollView = (PullToRefreshScrollView) contentView .findViewById(R.id.takeout_refresh); dataListView = (InnerListView) contentView .findViewById(R.id.takeout_list); bankCardsListView = (InnerListView) contentView .findViewById(R.id.takeout_list_selector_bankcards); clearButton = (TextView) contentView .findViewById(R.id.takeout_list_selector_clear); selectButton = (TextView) contentView .findViewById(R.id.takeout_list_selector_select); initViews(); registerViews(); } @Override protected void initViews() { dataListView.setAdapter(historyAdapter); bankCardsListView.setAdapter(bandCardAdapter); refreshScrollView.setMode(Mode.BOTH); } @Override protected void registerViews() { addTextButton("筛选", new OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(Gravity.RIGHT); } }); refreshScrollView .setOnRefreshListener(new OnRefreshListener2<ScrollView>() { @Override public void onPullDownToRefresh( PullToRefreshBase<ScrollView> refreshView) { reload(); } @Override public void onPullUpToRefresh( PullToRefreshBase<ScrollView> refreshView) { pagenum++; getTakeOutHistory(); } }); bankCardsListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { selectedBankCard = MoneyAccount.getMoneyAccount() .getBankCards().get(arg2); bandCardAdapter.notifyDataSetChanged(); } }); clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { drawerLayout.closeDrawers(); selectedBankCard = new ModelBankCard(); bandCardAdapter.notifyDataSetChanged(); reload(); } }); selectButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { drawerLayout.closeDrawers(); reload(); } }); } @Override protected void reload() { refreshScrollView.setMode(Mode.BOTH); pagenum = 0; takeOutHistories.clear(); historyAdapter.notifyDataSetChanged(); pagenum++; getTakeOutHistory(); } private void getTakeOutHistory() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("pageindex", pagenum + "")); requestParams.add(new RequestParam("pagecount", pagesize + "")); if (!TextUtils.isEmpty(selectedBankCard.getId())) { requestParams.add(new RequestParam("bankcardid", selectedBankCard.getId())); } post(API.MONEY_BANK_TAKEOUT_HISTORY, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { refreshScrollView.onRefreshComplete(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject jsonObject = object .optJSONObject("databody"); if (jsonObject != null) { JSONArray array = jsonObject.optJSONArray("data"); if (array != null) { if (array.length() < pagesize) { refreshScrollView .setMode(Mode.PULL_FROM_START); } for (int i = 0; i < array.length(); i++) { takeOutHistories .add(new ModelTakeOutHistory(array .optJSONObject(i))); } if (!takeOutHistories.isEmpty()) { historyAdapter.notifyDataSetChanged(); return; } } } } ApplicationTool.showToast(object.optString("msg")); } catch (JSONException e) { e.printStackTrace(); } } refreshScrollView.setMode(Mode.PULL_FROM_START); if (takeOutHistories.isEmpty()) { missionNodata(); } } }); } class TakeOutHistoryAdapter extends BaseAdapter { @Override public int getCount() { return takeOutHistories.size(); } @Override public Object getItem(int position) { return takeOutHistories.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_money_take_out_history, null); viewHolder.amountTextView = (TextView) convertView .findViewById(R.id.list_takeout_amount); viewHolder.stateTextView = (TextView) convertView .findViewById(R.id.list_takeout_state); viewHolder.bankTextView = (TextView) convertView .findViewById(R.id.list_takeout_bank); viewHolder.dateTextView = (TextView) convertView .findViewById(R.id.list_takeout_time); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ModelTakeOutHistory takeOutHistory = takeOutHistories.get(position); viewHolder.amountTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(takeOutHistory.getAmount())); viewHolder.bankTextView.setText(takeOutHistory.getUserbank() + "(尾号" + takeOutHistory.getUserbankid().substring( takeOutHistory.getUserbankid().length() - 4, takeOutHistory.getUserbankid().length()) + ")"); viewHolder.dateTextView.setText(takeOutHistory.getDatatime()); viewHolder.stateTextView.setText(takeOutHistory.getState()); return convertView; } class ViewHolder { TextView amountTextView, stateTextView, bankTextView, dateTextView; } } class BandCardAdapter extends BaseAdapter { @Override public int getCount() { return MoneyAccount.getMoneyAccount().getBankCards().size(); } @Override public Object getItem(int position) { return MoneyAccount.getMoneyAccount().getBankCards().get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_pay_bank_card, null); viewHolder.selected = (ImageView) convertView .findViewById(R.id.bank_card_bank_selection); viewHolder.bankImageView = (ImageView) convertView .findViewById(R.id.bank_card_bank_image); viewHolder.cardNumberTextView = (TextView) convertView .findViewById(R.id.bank_card_number); viewHolder.cardTypeTextView = (TextView) convertView .findViewById(R.id.bank_card_type); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ModelBankCard bankCard = MoneyAccount.getMoneyAccount() .getBankCards().get(position); if (bankCard.getId().equals(selectedBankCard.getId())) { viewHolder.selected .setImageResource(R.drawable.iconfont_check_checked); } else { viewHolder.selected .setImageResource(R.drawable.iconfont_check_normal); } ImageLoader.getInstance().displayImage( bankCard.getBank().getIcon(), viewHolder.bankImageView); viewHolder.cardNumberTextView.setText(getSecretCardNuber(bankCard .getBanknumber())); viewHolder.cardTypeTextView.setText(bankCard.getBank().getName() + " " + bankCard.getCardType()); return convertView; } class ViewHolder { ImageView selected, bankImageView; TextView cardNumberTextView, cardTypeTextView; } } } <file_sep>package yitgogo.consumer.local.ui; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.local.model.LocalCarController; import yitgogo.consumer.local.model.ModelLocalCar; import yitgogo.consumer.local.model.ModelLocalCarGoods; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.order.model.ModelDiliver; import yitgogo.consumer.order.model.ModelLocalGoodsOrderResult; import yitgogo.consumer.order.model.ModelPayment; import yitgogo.consumer.order.ui.OrderConfirmPartAddressFragment; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.InnerListView; public class LocalCarBuyFragment extends BaseNetworkFragment { InnerListView listView; TextView totalMoneyTextView, confirmButton; List<ModelLocalCar> localCars; CarAdapter carAdapter; double totalMoney = 0; OrderConfirmPartAddressFragment addressFragment = new OrderConfirmPartAddressFragment(); ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_confirm_order_local_car); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(LocalCarBuyFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(LocalCarBuyFragment.class.getName()); } @Override protected void init() { localCars = LocalCarController.getSelectedLocalCars(); carAdapter = new CarAdapter(); } @Override protected void findViews() { listView = (InnerListView) contentView .findViewById(R.id.order_confirm_products); totalMoneyTextView = (TextView) contentView .findViewById(R.id.order_confirm_total_money); confirmButton = (TextView) contentView .findViewById(R.id.order_confirm_ok); initViews(); registerViews(); } @Override protected void initViews() { getFragmentManager().beginTransaction() .replace(R.id.order_confirm_part_address, addressFragment) .commit(); listView.setAdapter(carAdapter); countTotalPrice(); } @Override protected void registerViews() { confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { confirmOrder(); } }); } private void countTotalPrice() { totalMoney = 0; for (int i = 0; i < localCars.size(); i++) { totalMoney += localCars.get(i).getTotalMoney(); } totalMoneyTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(totalMoney)); } private void confirmOrder() { if (totalMoney <= 0) { ApplicationTool.showToast("商品信息有误"); } else if (addressFragment.getAddress() == null) { ApplicationTool.showToast("收货人地址有误"); } else { addLocalGoodsOrder(); } } private void addLocalGoodsOrder() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("serviceProvidID", Store .getStore().getStoreId())); requestParams.add(new RequestParam("memberAccount", User .getUser().getUseraccount())); requestParams.add(new RequestParam("customerName", addressFragment.getAddress().getPersonName())); requestParams.add(new RequestParam("customerPhone", addressFragment.getAddress().getPhone())); requestParams.add(new RequestParam("retailOrderPrice", totalMoney + "")); JSONArray data = new JSONArray(); JSONArray deliveryInfo = new JSONArray(); try { for (int i = 0; i < localCars.size(); i++) { JSONObject deliveryInfoObject = new JSONObject(); deliveryInfoObject.put("supplyId", localCars.get(i) .getStore().getId()); deliveryInfoObject.put("deliveryType", localCars.get(i) .getDiliver().getName()); switch (localCars.get(i).getDiliver().getType()) { case ModelDiliver.TYPE_HOME: deliveryInfoObject.put("address", addressFragment .getAddress().getAreaAddress() + addressFragment.getAddress() .getDetailedAddress()); break; case ModelDiliver.TYPE_SELF: deliveryInfoObject.put("address", localCars.get(i) .getStore().getServiceaddress()); break; default: break; } deliveryInfoObject.put("paymentType", localCars.get(i) .getPayment().getType()); deliveryInfo.put(deliveryInfoObject); for (int j = 0; j < localCars.get(i).getCarGoods().size(); j++) { JSONObject dataObject = new JSONObject(); ModelLocalCarGoods dataGoods = localCars.get(i) .getCarGoods().get(j); dataObject.put("retailProductManagerID", dataGoods .getGoods().getId()); dataObject.put("orderType", "0"); dataObject.put("shopNum", dataGoods.getGoodsCount()); dataObject.put("productPrice", dataGoods.getGoods() .getRetailPrice()); data.put(dataObject); } } } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", data.toString())); requestParams.add(new RequestParam("deliveryInfo", deliveryInfo .toString())); post(API.API_LOCAL_BUSINESS_GOODS_ORDER_ADD, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { LocalCarController.deleteSelectedGoods(); ApplicationTool.showToast("下单成功"); JSONArray orderArray = object.optJSONArray("dataList"); if (orderArray != null) { double payPrice = 0; ArrayList<String> orderNumbers = new ArrayList<String>(); for (int i = 0; i < orderArray.length(); i++) { ModelLocalGoodsOrderResult orderResult = new ModelLocalGoodsOrderResult( orderArray.optJSONObject(i)); if (orderResult.getPaymentType() == ModelPayment.TYPE_ONLINE) { orderNumbers.add(orderResult .getOrdernumber()); payPrice += orderResult.getOrderPrice(); } } if (orderNumbers.size() > 0) { if (payPrice > 0) { payMoney(orderNumbers, payPrice, PayFragment.ORDER_TYPE_LP); getActivity().finish(); return; } } } showOrder(PayFragment.ORDER_TYPE_LP); getActivity().finish(); return; } else { ApplicationTool.showToast(object.optString("message")); return; } } catch (JSONException e) { ApplicationTool.showToast("下单失败"); e.printStackTrace(); return; } } ApplicationTool.showToast("下单失败"); } }); } class CarAdapter extends BaseAdapter { @Override public int getCount() { return localCars.size(); } @Override public Object getItem(int position) { return localCars.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate( R.layout.list_local_car_buy, null); holder = new ViewHolder(); holder.storeTextView = (TextView) convertView .findViewById(R.id.local_car_store_name); holder.goodsListView = (InnerListView) convertView .findViewById(R.id.local_car_goods); holder.diliverTextView = (TextView) convertView .findViewById(R.id.local_car_store_diliver); holder.paymentTextView = (TextView) convertView .findViewById(R.id.local_car_store_pay); holder.moneyTextView = (TextView) convertView .findViewById(R.id.local_car_store_money); holder.moneyDetailTextView = (TextView) convertView .findViewById(R.id.local_car_store_money_detail); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelLocalCar localCar = localCars.get(position); holder.storeTextView.setText(localCar.getStore().getServicename()); holder.goodsListView.setAdapter(new CarGoodsAdapter(localCar)); holder.diliverTextView.setText(localCar.getDiliver().getName()); holder.paymentTextView.setText(localCar.getPayment().getName()); holder.moneyTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(localCar.getTotalMoney())); holder.moneyDetailTextView.setText(getMoneyDetailString( localCar.getGoodsMoney(), localCar.getPostFee())); return convertView; } class ViewHolder { TextView storeTextView, moneyTextView, moneyDetailTextView, diliverTextView, paymentTextView; InnerListView goodsListView; } } class CarGoodsAdapter extends BaseAdapter { ModelLocalCar localCar = new ModelLocalCar(); public CarGoodsAdapter(ModelLocalCar localCar) { this.localCar = localCar; } @Override public int getCount() { return localCar.getCarGoods().size(); } @Override public Object getItem(int position) { return localCar.getCarGoods().get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_car_buy, null); holder = new ViewHolder(); holder.goodNameText = (TextView) convertView .findViewById(R.id.list_car_title); holder.goodsImageView = (ImageView) convertView .findViewById(R.id.list_car_image); holder.goodsPriceText = (TextView) convertView .findViewById(R.id.list_car_price); holder.guigeText = (TextView) convertView .findViewById(R.id.list_car_guige); holder.stateText = (TextView) convertView .findViewById(R.id.list_car_state); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelLocalCarGoods goods = localCar.getCarGoods().get(position); ImageLoader.getInstance().displayImage( getSmallImageUrl(goods.getGoods().getBigImgUrl()), holder.goodsImageView); holder.goodNameText.setText(goods.getGoods() .getRetailProdManagerName()); holder.goodsPriceText.setText("¥" + decimalFormat.format(goods.getGoods().getRetailPrice())); holder.stateText.setText("×" + goods.getGoodsCount()); return convertView; } class ViewHolder { ImageView goodsImageView; TextView goodNameText, goodsPriceText, guigeText, stateText; } } } <file_sep>package yitgogo.consumer.suning.ui; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.suning.model.ModelSuningArea; import yitgogo.consumer.suning.model.ModelSuningAreas; import yitgogo.consumer.suning.model.SuningManager; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Content; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; public class SuningAreaSelectFragment extends BaseNetworkFragment { TextView provinceTextView, cityTextView, districtTextView, townTextView; GridView areaGridView; HashMap<String, List<ModelSuningArea>> suningAreaHashMap = new HashMap<>(); ModelSuningArea province = new ModelSuningArea(); ModelSuningArea city = new ModelSuningArea(); ModelSuningArea district = new ModelSuningArea(); ModelSuningArea town = new ModelSuningArea(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_suning_area); findViews(); } @Override protected void init() { } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(SuningAreaSelectFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(SuningAreaSelectFragment.class.getName()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); selectProvince(); } protected void findViews() { provinceTextView = (TextView) contentView .findViewById(R.id.suning_area_province); cityTextView = (TextView) contentView .findViewById(R.id.suning_area_city); districtTextView = (TextView) contentView .findViewById(R.id.suning_area_district); townTextView = (TextView) contentView .findViewById(R.id.suning_area_town); areaGridView = (GridView) contentView .findViewById(R.id.suning_area_selection); initViews(); } protected void initViews() { addTextButton("确定", new View.OnClickListener() { @Override public void onClick(View view) { if (TextUtils.isEmpty(province.getCode())) { ApplicationTool.showToast("请选择所在省"); } else if (TextUtils.isEmpty(city.getCode())) { ApplicationTool.showToast("请选择所在市"); } else if (TextUtils.isEmpty(district.getCode())) { ApplicationTool.showToast("请选择所在区县"); } else if (TextUtils.isEmpty(town.getCode())) { ApplicationTool.showToast("请选择所在乡镇或街道"); } else { ModelSuningAreas suningAreas = SuningManager.getSuningAreas(); suningAreas.setProvince(province); suningAreas.setCity(city); suningAreas.setDistrict(district); suningAreas.setTown(town); suningAreas.save(); getActivity().finish(); } } }); provinceTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectProvince(); } }); cityTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(province.getCode())) { ApplicationTool.showToast("请选择所在省"); return; } selectCity(); } }); districtTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(city.getCode())) { ApplicationTool.showToast("请选择所在市"); return; } selectDistrict(); } }); townTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(district.getCode())) { ApplicationTool.showToast("请选择所在区县"); return; } selectTown(); } }); } @Override protected void registerViews() { } private void selectProvince() { provinceTextView.setBackgroundResource(R.drawable.back_white_rec_border_orange); cityTextView.setBackgroundResource(R.drawable.back_white_rec_border); districtTextView.setBackgroundResource(R.drawable.back_white_rec_border); townTextView.setBackgroundResource(R.drawable.back_white_rec_border); areaGridView.setAdapter(new AreaAdapter(new ArrayList<ModelSuningArea>(), 0)); if (suningAreaHashMap.containsKey("province")) { areaGridView.setAdapter(new AreaAdapter(suningAreaHashMap.get("province"), 0)); } else { getSuningProvince(); } } private void selectCity() { provinceTextView.setBackgroundResource(R.drawable.back_white_rec_border); cityTextView.setBackgroundResource(R.drawable.back_white_rec_border_orange); districtTextView.setBackgroundResource(R.drawable.back_white_rec_border); townTextView.setBackgroundResource(R.drawable.back_white_rec_border); areaGridView.setAdapter(new AreaAdapter(new ArrayList<ModelSuningArea>(), 0)); if (suningAreaHashMap.containsKey(province.getCode())) { areaGridView.setAdapter(new AreaAdapter(suningAreaHashMap.get(province.getCode()), 1)); } else { getSuningCity(); } } private void selectDistrict() { provinceTextView.setBackgroundResource(R.drawable.back_white_rec_border); cityTextView.setBackgroundResource(R.drawable.back_white_rec_border); districtTextView.setBackgroundResource(R.drawable.back_white_rec_border_orange); townTextView.setBackgroundResource(R.drawable.back_white_rec_border); areaGridView.setAdapter(new AreaAdapter(new ArrayList<ModelSuningArea>(), 0)); if (suningAreaHashMap.containsKey(city.getCode())) { areaGridView.setAdapter(new AreaAdapter(suningAreaHashMap.get(city.getCode()), 2)); } else { getSuningDistrict(); } } private void selectTown() { provinceTextView.setBackgroundResource(R.drawable.back_white_rec_border); cityTextView.setBackgroundResource(R.drawable.back_white_rec_border); districtTextView.setBackgroundResource(R.drawable.back_white_rec_border); townTextView.setBackgroundResource(R.drawable.back_white_rec_border_orange); areaGridView.setAdapter(new AreaAdapter(new ArrayList<ModelSuningArea>(), 0)); if (suningAreaHashMap.containsKey(district.getCode())) { areaGridView.setAdapter(new AreaAdapter(suningAreaHashMap.get(district.getCode()), 3)); } else { getSuningTown(); } } private void getSuningProvince() { List<RequestParam> requestParams = new ArrayList<>(); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", data.toString())); post(API.API_SUNING_AREA_PROVINCE, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (SuningManager.isSignatureOutOfDate(result)) { post(API.API_SUNING_SIGNATURE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); Content.saveStringContent(Parameters.CACHE_KEY_SUNING_SIGNATURE, dataMap.toString()); getSuningProvince(); return; } ApplicationTool.showToast(object.optString("message")); } catch (JSONException e) { e.printStackTrace(); } } } }); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("province"); if (array != null) { List<ModelSuningArea> provinceAreas = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { provinceAreas.add(new ModelSuningArea(array.optJSONObject(i))); } suningAreaHashMap.put("province", provinceAreas); areaGridView.setAdapter(new AreaAdapter(provinceAreas, 0)); } return; } ApplicationTool.showToast(object.optString("returnMsg")); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getSuningCity() { showSuningAreas(); List<RequestParam> requestParams = new ArrayList<>(); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("provinceId", province.getCode()); } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", data.toString())); post(API.API_SUNING_AREA_CITY, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (SuningManager.isSignatureOutOfDate(result)) { post(API.API_SUNING_SIGNATURE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); Content.saveStringContent(Parameters.CACHE_KEY_SUNING_SIGNATURE, dataMap.toString()); getSuningCity(); return; } ApplicationTool.showToast(object.optString("message")); } catch (JSONException e) { e.printStackTrace(); } } } }); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("city"); if (array != null) { List<ModelSuningArea> cityAreas = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { cityAreas.add(new ModelSuningArea(array.optJSONObject(i))); } suningAreaHashMap.put(province.getCode(), cityAreas); areaGridView.setAdapter(new AreaAdapter(cityAreas, 1)); return; } ApplicationTool.showToast(object.optString("returnMsg")); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getSuningDistrict() { showSuningAreas(); List<RequestParam> requestParams = new ArrayList<>(); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("cityId", city.getCode()); } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", data.toString())); post(API.API_SUNING_AREA_DISTRICT, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (SuningManager.isSignatureOutOfDate(result)) { post(API.API_SUNING_SIGNATURE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); Content.saveStringContent(Parameters.CACHE_KEY_SUNING_SIGNATURE, dataMap.toString()); getSuningDistrict(); return; } ApplicationTool.showToast(object.optString("message")); } catch (JSONException e) { e.printStackTrace(); } } } }); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("district"); if (array != null) { List<ModelSuningArea> districtAreas = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { districtAreas.add(new ModelSuningArea(array.optJSONObject(i))); } suningAreaHashMap.put(city.getCode(), districtAreas); areaGridView.setAdapter(new AreaAdapter(districtAreas, 2)); return; } ApplicationTool.showToast(object.optString("returnMsg")); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getSuningTown() { showSuningAreas(); List<RequestParam> requestParams = new ArrayList<>(); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("cityId", city.getCode()); data.put("countyId", district.getCode()); } catch (JSONException e) { e.printStackTrace(); } requestParams.add(new RequestParam("data", data.toString())); post(API.API_SUNING_AREA_TOWN, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (SuningManager.isSignatureOutOfDate(result)) { post(API.API_SUNING_SIGNATURE, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONObject dataMap = object.optJSONObject("dataMap"); Content.saveStringContent(Parameters.CACHE_KEY_SUNING_SIGNATURE, dataMap.toString()); getSuningTown(); return; } ApplicationTool.showToast(object.optString("message")); } catch (JSONException e) { e.printStackTrace(); } } } }); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("town"); if (array != null) { List<ModelSuningArea> townAreas = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { townAreas.add(new ModelSuningArea(array.optJSONObject(i))); } suningAreaHashMap.put(district.getCode(), townAreas); areaGridView.setAdapter(new AreaAdapter(townAreas, 3)); return; } ApplicationTool.showToast(object.optString("returnMsg")); } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void showSuningAreas() { if (!TextUtils.isEmpty(province.getName())) { provinceTextView.setText(province.getName()); if (!TextUtils.isEmpty(city.getName())) { cityTextView.setText(city.getName()); if (!TextUtils.isEmpty(district.getName())) { districtTextView.setText(district.getName()); if (!TextUtils.isEmpty(town.getName())) { townTextView.setText(town.getName()); } } } } } private class AreaAdapter extends BaseAdapter { List<ModelSuningArea> areas = new ArrayList<>(); int level = 0; public AreaAdapter(List<ModelSuningArea> areas, int level) { this.areas = areas; this.level = level; } @Override public int getCount() { return areas.size(); } @Override public Object getItem(int i) { return areas.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { final int position = i; ViewHolder viewHolder; if (view == null) { view = layoutInflater.inflate(R.layout.list_suning_area, null); viewHolder = new ViewHolder(); viewHolder.textView = (TextView) view.findViewById(R.id.suning_area); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } viewHolder.textView.setText(areas.get(i).getName()); viewHolder.textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (level) { case 0: province = areas.get(position); city = new ModelSuningArea(); district = new ModelSuningArea(); town = new ModelSuningArea(); provinceTextView.setText(province.getName()); cityTextView.setText(""); districtTextView.setText(""); townTextView.setText(""); selectCity(); break; case 1: city = areas.get(position); district = new ModelSuningArea(); town = new ModelSuningArea(); cityTextView.setText(city.getName()); districtTextView.setText(""); townTextView.setText(""); selectDistrict(); break; case 2: district = areas.get(position); town = new ModelSuningArea(); districtTextView.setText(district.getName()); townTextView.setText(""); selectTown(); break; case 3: town = areas.get(position); townTextView.setText(town.getName()); break; default: break; } } }); return view; } } private class ViewHolder { TextView textView; } }<file_sep>package yitgogo.consumer.suning.ui; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.product.ui.WebFragment; import yitgogo.consumer.suning.model.GetNewSignature; import yitgogo.consumer.suning.model.ModelProductDetail; import yitgogo.consumer.suning.model.ModelProductImage; import yitgogo.consumer.suning.model.ModelProductPrice; import yitgogo.consumer.suning.model.SuningCarController; import yitgogo.consumer.suning.model.SuningManager; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.user.model.User; import yitgogo.consumer.user.ui.UserLoginFragment; import yitgogo.consumer.view.Notify; public class ProductDetailFragment extends BaseNotifyFragment { ViewPager imagePager; LinearLayout htmlButton; TextView nameTextView, brandTextView, modelTextView, stateTextView, priceTextView, serviceTextView; ImageView lastImageButton, nextImageButton; TextView imageIndexText; TextView carButton, buyButton; ImageAdapter imageAdapter; ModelProductDetail productDetail = new ModelProductDetail(); ModelProductPrice productPrice = new ModelProductPrice(); List<ModelProductImage> productImages = new ArrayList<>(); Bundle bundle = new Bundle(); String state = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_product_suning_detail); try { init(); } catch (JSONException e) { e.printStackTrace(); } findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(ProductDetailFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(ProductDetailFragment.class.getName()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetProductStock().execute(); new GetProductImages().execute(); } private void init() throws JSONException { measureScreen(); bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("product")) { productDetail = new ModelProductDetail(new JSONObject(bundle.getString("product"))); } if (bundle.containsKey("price")) { productPrice = new ModelProductPrice(new JSONObject(bundle.getString("price"))); } } imageAdapter = new ImageAdapter(); } protected void findViews() { imagePager = (ViewPager) contentView .findViewById(R.id.product_detail_images); lastImageButton = (ImageView) contentView .findViewById(R.id.product_detail_image_last); nextImageButton = (ImageView) contentView .findViewById(R.id.product_detail_image_next); imageIndexText = (TextView) contentView .findViewById(R.id.product_detail_image_index); nameTextView = (TextView) contentView .findViewById(R.id.product_detail_name); brandTextView = (TextView) contentView .findViewById(R.id.product_detail_brand); modelTextView = (TextView) contentView .findViewById(R.id.product_detail_model); stateTextView = (TextView) contentView .findViewById(R.id.product_detail_state); htmlButton = (LinearLayout) contentView .findViewById(R.id.product_detail_html); serviceTextView = (TextView) contentView .findViewById(R.id.product_detail_service); priceTextView = (TextView) contentView .findViewById(R.id.product_detail_price); carButton = (TextView) contentView .findViewById(R.id.product_detail_car); buyButton = (TextView) contentView .findViewById(R.id.product_detail_buy); addImageButton(R.drawable.iconfont_cart, "购物车", new OnClickListener() { @Override public void onClick(View v) { jump(ShoppingCarFragment.class.getName(), "云商城购物车"); } }); initViews(); registerViews(); } protected void initViews() { FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( screenWidth, screenWidth); imagePager.setLayoutParams(layoutParams); imagePager.setAdapter(imageAdapter); nameTextView.setText(productDetail.getName()); priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(productPrice.getPrice())); brandTextView.setText(productDetail.getBrand()); modelTextView.setText(productDetail.getModel()); serviceTextView.setText(Html.fromHtml(productDetail.getService())); } @SuppressWarnings("deprecation") @Override protected void registerViews() { htmlButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Bundle bundle = new Bundle(); bundle.putString("html", productDetail.getIntroduction()); bundle.putInt("type", WebFragment.TYPE_HTML); jump(WebFragment.class.getName(), productDetail.getName(), bundle); } }); lastImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageAdapter.getCount() > 0) { if (imagePager.getCurrentItem() == 0) { setImagePosition(imageAdapter.getCount() - 1); } else { setImagePosition(imagePager.getCurrentItem() - 1); } } } }); nextImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageAdapter.getCount() > 0) { if (imagePager.getCurrentItem() == imageAdapter.getCount() - 1) { setImagePosition(0); } else { setImagePosition(imagePager.getCurrentItem() + 1); } } } }); imagePager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { imageIndexText.setText((imagePager.getCurrentItem() + 1) + "/" + imageAdapter.getCount()); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); carButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (state.equals("00")) { if (productPrice.getPrice() > 0) { if (SuningCarController.addProduct(productDetail)) { Notify.show("添加到购物车成功"); } else { Notify.show("已添加过此商品"); } } else { Notify.show("商品信息有误,不能购买"); } } else { Notify.show("此商品暂不能购买"); } } }); buyButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (state.equals("00")) { if (productPrice.getPrice() > 0) { if (User.getUser().isLogin()) { jump(SuningProductBuyFragment.class.getName(), "确认订单", bundle); } else { Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show(); jump(UserLoginFragment.class.getName(), "会员登录"); } } else { Notify.show("商品信息有误,不能购买"); } } else { Notify.show("此商品暂不能购买"); } } }); } /** * 点击左右导航按钮切换图片 * * @param imagePosition */ private void setImagePosition(int imagePosition) { imagePager.setCurrentItem(imagePosition, true); imageIndexText.setText((imagePosition + 1) + "/" + imageAdapter.getCount()); } /** * viewpager适配器 */ private class ImageAdapter extends PagerAdapter { @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return productImages.size(); } @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = layoutInflater.inflate( R.layout.adapter_viewpager, view, false); assert imageLayout != null; ImageView imageView = (ImageView) imageLayout .findViewById(R.id.view_pager_img); final ProgressBar spinner = (ProgressBar) imageLayout .findViewById(R.id.view_pager_loading); ImageLoader.getInstance().displayImage(productImages.get(position).getPath(), imageView, new SimpleImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { spinner.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { spinner.setVisibility(View.GONE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { spinner.setVisibility(View.GONE); } }); view.addView(imageLayout, 0); return imageLayout; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public Parcelable saveState() { return null; } } class GetProductImages extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { JSONArray dataArray = new JSONArray(); dataArray.put(productDetail.getSku()); JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("sku", dataArray); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); /** *{"result":[{"skuId":"108246148","price":15000.00}],"isSuccess":true,"returnMsg":"查询成功。"} */ return netUtil.postWithoutCookie(API.API_SUNING_PRODUCT_IMAGES, nameValuePairs, false, false); } @Override protected void onPostExecute(String result) { if (SuningManager.isSignatureOutOfDate(result)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetProductImages().execute(); } } }; getNewSignature.execute(); return; } if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { JSONArray array = object.optJSONArray("result"); if (array != null) { if (array.length() > 0) { JSONObject imageObject = array.optJSONObject(0); if (imageObject != null) { JSONArray imageArray = imageObject.optJSONArray("urls"); if (imageArray != null) { for (int i = 0; i < imageArray.length(); i++) { productImages.add(new ModelProductImage(imageArray.optJSONObject(i))); } imageAdapter.notifyDataSetChanged(); imageIndexText.setText("1/" + imageAdapter.getCount()); } } } } } } catch (JSONException e) { e.printStackTrace(); } } } } class GetProductStock extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("cityId", SuningManager.getSuningAreas().getCity().getCode()); data.put("countyId", SuningManager.getSuningAreas().getDistrict().getCode()); data.put("sku", productDetail.getSku()); data.put("num", 1); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); return netUtil.postWithoutCookie(API.API_SUNING_PRODUCT_STOCK, nameValuePairs, false, false); } @Override protected void onPostExecute(String result) { hideLoading(); if (SuningManager.isSignatureOutOfDate(result)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetProductStock().execute(); } } }; getNewSignature.execute(); return; } /** * {"sku":null,"state":null,"isSuccess":false,"returnMsg":"无货"} */ if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { state = object.optString("state"); if (state.equals("00")) { stateTextView.setText("有货"); } else if (state.equals("01")) { stateTextView.setText("暂不销售"); } else { stateTextView.setText("无货"); } } } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.money.tools; public interface PayAPI { public String API_IP = "http://yitos.net"; // public String API_IP = "http://192.168.8.8:8050"; // public String API_IP = "http://192.168.8.36:8080"; /** * 短信验证码接口 * <p/> * 参数: (第一次绑卡):pan // 卡号 expiredDate // 卡效期// 格式是:MMYY cvv2 // * 安全校验值,CVV2或CVC2 // 对于银联和VISA卡,对应卡片背面的CVV2数字;对于MasterCard卡,对应卡片背面的CVC2数字 * Amount // 交易金额 // 以元为单位,小数点后最多两位 externalRefNumber// 流水号(商家自己的订单号) * customerId// 客户号 cardHolderName// 客户姓名 cardHolderId// 客户身份证号 phoneNO// * 手机号码 * <p/> * 返回数据:{responseCode=00, customerId=11999, token=<PASSWORD>, * merchantId=104110045112012} */ public String API_PAY_BIND = API_IP + "/api/settlement/kuaiqian/getAuthCodeApi"; /** * 快捷支付(首次) * <p/> * payInfoType:订单类型(1-运营中心订单 2-易店订单 3-本地产品订单 4-本地服务订单5-便民服务) orderNumber:订单号 * cardNo// 卡号 externalRefNumber// 流水号(商家自己的订单号) storableCardNo// 短卡号 * expiredDate// 卡效期,格式是:MMYY cvv2// 安全校验值,CVV2或CVC2 // * 对于银联和VISA卡,对应卡片背面的CVV2数字;对于MasterCard卡,对应卡片背面的CVC2数字 amount// * 交易金额,以元为单位,小数点后最多两位 customerId// 客户号 cardHolderName// 客户姓名 cardHolderId// * 客户身份证号 phone// 手机号码 validCode// 手机验证码 token// 手机令牌码 * <p/> * {responseCode=00, responseTextMessage=交易成功, * externalRefNumber=20150814110720} */ public String API_PAY_FIRST_TIME = API_IP + "/api/settlement/kuaiqian/payDataFirstApi"; /** * 快捷支付(非首次) * <p/> * payInfoType:订单类型(1-运营中心订单 2-易店订单 3-本地产品订单 4-本地服务订单) orderNumber:订单号 * <p/> * storableCardNo// 短卡号 amount// 交易金额,以元为单位,小数点后最多两位 externalRefNumber// * 流水号(商家自己的订单号) customerId// 客户号 phone// 手机号码 validCode// 手机验证码 token// * 手机令牌码 * <p/> * {responseCode=00, responseTextMessage=交易成功, * externalRefNumber=20150814110720} */ public String API_PAY_SECOND_TIME = API_IP + "/api/settlement/kuaiqian/payDataTwiceApi"; /** * 钱袋子余额支付 * <p/> * String memberAccount 会员账号 * <p/> * String customerName 会员姓名(可选) * <p/> * String pwd <PASSWORD>(需加密) * <p/> * String orderNumbers 订单编号,多个订单以”,”拼接 * <p/> * String orderType 订单类型 1-运营中心订单 2-易店订单 3-本地产品订单 4-本地服务订单 * <p/> * String apAmount 订单金额 */ public String API_PAY_BALANCE = API_IP + "/api/settlement/member/payMemberAccount"; } <file_sep>package yitgogo.consumer.suning.ui; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.money.ui.PayFragment; import yitgogo.consumer.order.ui.OrderConfirmPartAddressFragment; import yitgogo.consumer.order.ui.OrderConfirmPartPaymentFragment; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.suning.model.GetNewSignature; import yitgogo.consumer.suning.model.ModelProductDetail; import yitgogo.consumer.suning.model.ModelProductPrice; import yitgogo.consumer.suning.model.ModelSuningOrderResult; import yitgogo.consumer.suning.model.SuningManager; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.user.model.User; import yitgogo.consumer.view.Notify; public class SuningProductBuyFragment extends BaseNotifyFragment { ImageView imageView; TextView nameTextView, priceTextView, countTextView, countAddButton, countDeleteButton, additionTextView; FrameLayout addressLayout, paymentLayout; TextView totalPriceTextView, confirmButton; ModelProductDetail productDetail = new ModelProductDetail(); ModelProductPrice productPrice = new ModelProductPrice(); OrderConfirmPartAddressFragment addressFragment; OrderConfirmPartPaymentFragment paymentFragment; int buyCount = 1; double goodsMoney = 0; String state = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_confirm_order_suning); try { init(); } catch (JSONException e) { e.printStackTrace(); } findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(SuningProductBuyFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(SuningProductBuyFragment.class.getName()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new GetProductStock().execute(); } private void init() throws JSONException { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("product")) { productDetail = new ModelProductDetail(new JSONObject(bundle.getString("product"))); } if (bundle.containsKey("price")) { productPrice = new ModelProductPrice(new JSONObject(bundle.getString("price"))); } } addressFragment = new OrderConfirmPartAddressFragment(); paymentFragment = new OrderConfirmPartPaymentFragment(true, true, false); } protected void findViews() { imageView = (ImageView) contentView .findViewById(R.id.order_confirm_sale_image); nameTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_name); priceTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_price); countTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_count); countDeleteButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_count_delete); countAddButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_count_add); additionTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_addition); addressLayout = (FrameLayout) contentView .findViewById(R.id.order_confirm_sale_address); paymentLayout = (FrameLayout) contentView .findViewById(R.id.order_confirm_sale_payment); totalPriceTextView = (TextView) contentView .findViewById(R.id.order_confirm_sale_total_money); confirmButton = (TextView) contentView .findViewById(R.id.order_confirm_sale_confirm); initViews(); registerViews(); } @Override protected void initViews() { showProductInfo(); getFragmentManager().beginTransaction() .replace(R.id.order_confirm_sale_address, addressFragment) .replace(R.id.order_confirm_sale_payment, paymentFragment) .commit(); } @Override protected void registerViews() { confirmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { buy(); } }); countDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { deleteCount(); } }); countAddButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addCount(); } }); } private void showProductInfo() { ImageLoader.getInstance().displayImage(productDetail.getImage(), imageView); nameTextView.setText(productDetail.getName()); priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(productPrice.getPrice())); countTextView.setText(buyCount + ""); countTotalPrice(); } private void deleteCount() { if (buyCount > 1) { buyCount--; countTotalPrice(); new GetProductStock().execute(); } } private void addCount() { buyCount++; countTotalPrice(); new GetProductStock().execute(); } private void countTotalPrice() { goodsMoney = 0; double sendMoney = 0; goodsMoney = productPrice.getPrice() * buyCount; if (goodsMoney > 0 & goodsMoney < 69) { sendMoney = 5; } countTextView.setText(buyCount + ""); totalPriceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(goodsMoney + sendMoney)); } private void buy() { if (addressFragment.getAddress() == null) { Notify.show("收货人信息有误"); } else { if (state.equals("00")) { if (goodsMoney > 0) { new Buy().execute(); } else { Notify.show("商品信息有误,暂不能购买"); } } else { Notify.show("此商品暂不能购买"); } } } /** * @Url: http://192.168.8.36:8089/api/order/cloudMallOrder/CloudMallAction/CreatSuNingOrder * @Parameters: [menberAccount=13032889558, name=雷小武, mobile=13032889558, address=解放路二段, spId=674, amount=30.0, provinceId=230, cityId=028, countyId=03, townId=02, sku=[{"num":1,"number":"120855028","name":"NEW17","price":30}]] * @Result: {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[],"totalCount":1,"dataMap":{"fuwuZuoji":"028-66133688","orderType":"新订单","orderNumber":"SN464351824310","zongjine":"30.0","freight":"5","productInfo":[{"num":1"Amount":30.0,"price":30.0,"spname":"NEW17"}],"fuwushang":"成都成华区罗飞加盟商","shijian":"2015-10-28 09:46:43","fuwuPhone":"13880353588"},"object":null} */ class Buy extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... voids) { List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("menberAccount", User.getUser().getUseraccount())); nameValuePairs.add(new BasicNameValuePair("name", addressFragment.getAddress().getPersonName())); nameValuePairs.add(new BasicNameValuePair("mobile", addressFragment.getAddress().getPhone())); nameValuePairs.add(new BasicNameValuePair("address", addressFragment.getAddress().getDetailedAddress())); nameValuePairs.add(new BasicNameValuePair("spId", Store.getStore().getStoreId())); nameValuePairs.add(new BasicNameValuePair("amount", goodsMoney + "")); nameValuePairs.add(new BasicNameValuePair("provinceId", SuningManager.getSuningAreas().getProvince().getCode())); nameValuePairs.add(new BasicNameValuePair("cityId", SuningManager.getSuningAreas().getCity().getCode())); nameValuePairs.add(new BasicNameValuePair("countyId", SuningManager.getSuningAreas().getDistrict().getCode())); nameValuePairs.add(new BasicNameValuePair("townId", SuningManager.getSuningAreas().getTown().getCode())); JSONArray skuArray = new JSONArray(); try { JSONObject skuObject = new JSONObject(); skuObject.put("number", productDetail.getSku()); skuObject.put("num", buyCount); skuObject.put("price", productPrice.getPrice()); skuObject.put("name", productDetail.getName()); skuObject.put("attr", productDetail.getModel()); skuArray.put(skuObject); } catch (JSONException e) { e.printStackTrace(); } nameValuePairs.add(new BasicNameValuePair("sku", skuArray.toString())); return netUtil.postWithoutCookie(API.API_SUNING_ORDER_ADD, nameValuePairs, false, false); } @Override protected void onPostExecute(String s) { hideLoading(); if (!TextUtils.isEmpty(s)) { try { JSONObject object = new JSONObject(s); if (object.optString("state").equals("SUCCESS")) { Notify.show("下单成功"); ModelSuningOrderResult orderResult = new ModelSuningOrderResult(object.optJSONObject("dataMap")); if (orderResult.getZongjine() > 0) { if (paymentFragment.getPaymentType() == OrderConfirmPartPaymentFragment.PAY_TYPE_CODE_ONLINE) { payMoney(orderResult.getOrderNumber(), orderResult.getZongjine() + orderResult.getFreight(), PayFragment.ORDER_TYPE_SN); getActivity().finish(); return; } } showOrder(PayFragment.ORDER_TYPE_SN); getActivity().finish(); return; } Notify.show(object.optString("message")); return; } catch (JSONException e) { e.printStackTrace(); } } Notify.show("下单失败"); } } class GetProductStock extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... params) { JSONObject data = new JSONObject(); try { data.put("accessToken", SuningManager.getSignature().getToken()); data.put("appKey", SuningManager.appKey); data.put("v", SuningManager.version); data.put("cityId", SuningManager.getSuningAreas().getCity().getCode()); data.put("countyId", SuningManager.getSuningAreas().getDistrict().getCode()); data.put("sku", productDetail.getSku()); data.put("num", buyCount); } catch (JSONException e) { e.printStackTrace(); } List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("data", data.toString())); return netUtil.postWithoutCookie(API.API_SUNING_PRODUCT_STOCK, nameValuePairs, false, false); } @Override protected void onPostExecute(String result) { hideLoading(); if (SuningManager.isSignatureOutOfDate(result)) { GetNewSignature getNewSignature = new GetNewSignature() { @Override protected void onPreExecute() { showLoading(); } @Override protected void onPostExecute(Boolean isSuccess) { hideLoading(); if (isSuccess) { new GetProductStock().execute(); } } }; getNewSignature.execute(); return; } /** * {"sku":null,"state":null,"isSuccess":false,"returnMsg":"无货"} */ if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optBoolean("isSuccess")) { state = object.optString("state"); if (state.equals("00")) { additionTextView.setText("有货"); } else if (state.equals("01")) { additionTextView.setText("暂不销售"); } else { additionTextView.setText("无货"); } } } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.money.ui; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.money.model.ModelBankCard; import yitgogo.consumer.tools.API; import yitgogo.consumer.view.NormalAskDialog; import yitgogo.consumer.view.Notify; public class BankCardDetailFragment extends BaseNotifyFragment { ImageView imageView; TextView cardNumberTextView, cardTypeTextView, deleteButton; ModelBankCard bankCard = new ModelBankCard(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_money_backcard_detail); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(BankCardDetailFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(BankCardDetailFragment.class.getName()); } private void init() { Bundle bundle = getArguments(); if (bundle != null) { if (bundle.containsKey("bankCard")) { try { bankCard = new ModelBankCard(new JSONObject( bundle.getString("bankCard"))); } catch (JSONException e) { e.printStackTrace(); } } } } @Override protected void findViews() { imageView = (ImageView) contentView .findViewById(R.id.bank_card_detail_image); cardNumberTextView = (TextView) contentView .findViewById(R.id.bank_card_detail_number); cardTypeTextView = (TextView) contentView .findViewById(R.id.bank_card_detail_type); deleteButton = (TextView) contentView .findViewById(R.id.bank_card_detail_delete); initViews(); registerViews(); } @Override protected void initViews() { ImageLoader.getInstance().displayImage(bankCard.getBank().getIcon(), imageView); cardNumberTextView .setText(getSecretCardNuber(bankCard.getBanknumber())); cardTypeTextView.setText(bankCard.getBank().getName() + " " + bankCard.getCardType()); } @Override protected void registerViews() { deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NormalAskDialog askDialog = new NormalAskDialog("确定要解绑这张银行卡吗?", "解绑", "取消") { @Override public void onDismiss(DialogInterface dialog) { if (makeSure) { PayPasswordDialog payPasswordDialog = new PayPasswordDialog( "请输入支付密码", false) { public void onDismiss(DialogInterface dialog) { if (!TextUtils.isEmpty(payPassword)) { new UnBindBankCard() .execute(payPassword); } super.onDismiss(dialog); } ; }; payPasswordDialog.show(getFragmentManager(), null); } super.onDismiss(dialog); } }; askDialog.show(getFragmentManager(), null); } }); } /** * 解绑银行卡 * * @author Tiger * @Url http://192.168.8.2:8030/member/bank/unbindbankcard * @Parameters [bankcardid=27, paypassword=<PASSWORD>] * @Put_Cookie JSESSIONID=5AC8B9CD76E3F6AF6D5E9728F048A1F6 * @Result {"state":"success","msg":"操作成功","databody":{"unbind":true}} */ class UnBindBankCard extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(String... params) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("bankcardid", bankCard .getId())); nameValuePairs .add(new BasicNameValuePair("paypassword", params[0])); return netUtil.postWithCookie(API.MONEY_BANK_UNBIND, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (!TextUtils.isEmpty(result)) { try { JSONObject object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("success")) { JSONObject databody = object.optJSONObject("databody"); if (databody.optBoolean("unbind")) { Notify.show("解绑成功"); getActivity().finish(); return; } } Notify.show(object.optString("msg")); } catch (JSONException e) { e.printStackTrace(); } } } } } <file_sep>package yitgogo.consumer.user.ui; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import yitgogo.consumer.BaseNotifyFragment; import yitgogo.consumer.tools.API; import yitgogo.consumer.view.Notify; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; public class UserFindPasswordFragment extends BaseNotifyFragment implements OnClickListener { EditText phoneEdit, smscodeEdit, passwordEdit, passwordConfirmEdit; TextView getSmscodeButton; ImageView showPassword; Button registerButton; boolean isShown = false; boolean isFinish = false; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj != null) { getSmscodeButton.setText(msg.obj + "s"); } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); } }; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_user_find_password); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(UserFindPasswordFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(UserFindPasswordFragment.class.getName()); } @Override public void onDestroy() { isFinish = true; super.onDestroy(); } @Override protected void findViews() { phoneEdit = (EditText) contentView .findViewById(R.id.user_find_password_phone); smscodeEdit = (EditText) contentView .findViewById(R.id.user_find_password_smscode); passwordEdit = (EditText) contentView .findViewById(R.id.user_find_password_password); passwordConfirmEdit = (EditText) contentView .findViewById(R.id.user_find_password_password_confirm); getSmscodeButton = (TextView) contentView .findViewById(R.id.user_find_password_smscode_get); registerButton = (Button) contentView .findViewById(R.id.user_find_password_enter); showPassword = (ImageView) contentView .findViewById(R.id.user_find_password_password_show); registerViews(); } @Override protected void registerViews() { getSmscodeButton.setOnClickListener(this); registerButton.setOnClickListener(this); showPassword.setOnClickListener(this); } private void findPassword() { if (!isPhoneNumber(phoneEdit.getText().toString())) { Notify.show("请输入正确的手机号"); } else if (smscodeEdit.length() != 6) { Notify.show("请输入您收到的验证码"); } else if (passwordEdit.length() == 0) { Notify.show("请输入新密码"); } else if (passwordConfirmEdit.length() == 0) { Notify.show("请确认新密码"); } else if (!passwordEdit.getText().toString() .equals(passwordConfirmEdit.getText().toString())) { Notify.show("两次输入的密码不相同 "); } else { new ResetPassword().execute(); } } private void getSmscode() { if (isPhoneNumber(phoneEdit.getText().toString())) { new GetSmscode().execute(); } else { Notify.show("请输入正确的手机号"); } } private void showPassword() { if (isShown) { passwordEdit.setTransformationMethod(PasswordTransformationMethod .getInstance()); passwordConfirmEdit .setTransformationMethod(PasswordTransformationMethod .getInstance()); } else { passwordEdit .setTransformationMethod(HideReturnsTransformationMethod .getInstance()); passwordConfirmEdit .setTransformationMethod(HideReturnsTransformationMethod .getInstance()); } isShown = !isShown; if (isShown) { showPassword.setImageResource(R.drawable.ic_hide); } else { showPassword.setImageResource(R.drawable.ic_show); } } class ResetPassword extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading(); } @Override protected String doInBackground(Void... arg0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("phone", phoneEdit .getText().toString())); nameValuePairs.add(new BasicNameValuePair("smsCode", smscodeEdit .getText().toString())); nameValuePairs .add(new BasicNameValuePair("password", getEncodedPassWord(passwordEdit.getText() .toString().trim()))); return netUtil.postWithCookie(API.API_USER_FIND_PASSWORD, nameValuePairs); } @Override protected void onPostExecute(String result) { hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { Notify.show("重设密码成功,请使用新密码登录"); getActivity().finish(); } else { Notify.show(object.optString("message")); } } catch (JSONException e) { Notify.show("重设密码失败"); e.printStackTrace(); } } else { Notify.show("重设密码失败"); } } } class GetSmscode extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { showLoading("正在获取验证码..."); getSmscodeButton.setEnabled(false); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorThird)); } @Override protected String doInBackground(Void... arg0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("phone", phoneEdit .getText().toString())); return netUtil.postAndSaveCookie( API.API_USER_FIND_PASSWORD_SMSCODE, nameValuePairs); } @Override protected void onPostExecute(String result) { // {"message":"ok","state":"SUCCESS","cacheKey":null,"dataList":[],"totalCount":1,"dataMap":{},"object":null} hideLoading(); if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { Notify.show("验证码已发送至您的手机"); new Thread(new Runnable() { @Override public void run() { int time = 60; while (time > -1) { if (isFinish) { break; } try { Message message = new Message(); if (time > 0) { message.obj = time; } handler.sendMessage(message); Thread.sleep(1000); time--; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); Notify.show(object.optString("message")); } } catch (JSONException e) { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); Notify.show("获取验证码失败"); e.printStackTrace(); } } else { getSmscodeButton.setEnabled(true); getSmscodeButton.setTextColor(getResources().getColor( R.color.textColorSecond)); getSmscodeButton.setText("获取验证码"); Notify.show("获取验证码失败"); } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.user_find_password_smscode_get: getSmscode(); break; case R.id.user_find_password_enter: findPassword(); break; case R.id.user_find_password_password_show: showPassword(); break; default: break; } } } <file_sep>package yitgogo.consumer.main.ui; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; import com.dtr.zxing.activity.CaptureActivity; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.nostra13.universalimageloader.core.ImageLoader; import com.smartown.yitian.gogo.R; import com.umeng.analytics.MobclickAgent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import yitgogo.consumer.BaseNetworkFragment; import yitgogo.consumer.home.model.ModelAds; import yitgogo.consumer.home.model.ModelListPrice; import yitgogo.consumer.home.model.ModelProduct; import yitgogo.consumer.product.ui.ClassesFragment; import yitgogo.consumer.product.ui.ProductSearchFragment; import yitgogo.consumer.product.ui.SaleTimeListFragment; import yitgogo.consumer.store.model.Store; import yitgogo.consumer.tools.API; import yitgogo.consumer.tools.ApplicationTool; import yitgogo.consumer.tools.Parameters; import yitgogo.consumer.tools.RequestParam; import yitgogo.consumer.view.InnerGridView; public class HomeYitgogoFragment extends BaseNetworkFragment { PullToRefreshScrollView refreshScrollView; InnerGridView productGridView; List<ModelProduct> products; HashMap<String, ModelListPrice> priceMap; ProductAdapter productAdapter; ImageView classButton, searchButton; String currentStoreId = ""; List<ModelAds> ads; AdsAdapter adsAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_home_yitgogo); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(HomeYitgogoFragment.class.getName()); if (!currentStoreId.equals(Store.getStore().getStoreId())) { currentStoreId = Store.getStore().getStoreId(); reload(); } } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(HomeYitgogoFragment.class.getName()); } @Override protected void init() { ads = new ArrayList<>(); adsAdapter = new AdsAdapter(); products = new ArrayList<>(); priceMap = new HashMap<>(); productAdapter = new ProductAdapter(); } @Override protected void findViews() { refreshScrollView = (PullToRefreshScrollView) contentView .findViewById(R.id.home_yitgogo_refresh); productGridView = (InnerGridView) contentView .findViewById(R.id.home_yitgogo_product_list); classButton = (ImageView) contentView .findViewById(R.id.home_yitgogo_class); searchButton = (ImageView) contentView .findViewById(R.id.home_yitgogo_search); initViews(); registerViews(); } @Override protected void initViews() { refreshScrollView.setMode(Mode.BOTH); productGridView.setAdapter(productAdapter); } @Override protected void registerViews() { refreshScrollView .setOnRefreshListener(new OnRefreshListener2<ScrollView>() { @Override public void onPullDownToRefresh( PullToRefreshBase<ScrollView> refreshView) { reload(); } @Override public void onPullUpToRefresh( PullToRefreshBase<ScrollView> refreshView) { pagenum++; getProduct(); } }); productGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { showProductDetail(products.get(arg2).getId(), products .get(arg2).getProductName(), CaptureActivity.SALE_TYPE_NONE); } }); classButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(ClassesFragment.class.getName(), "商品分类"); } }); searchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jump(ProductSearchFragment.class.getName(), "商品搜索"); } }); } @Override protected void reload() { super.reload(); getAds(); refreshScrollView.setMode(Mode.BOTH); pagenum = 0; products.clear(); productAdapter.notifyDataSetChanged(); pagenum++; getProduct(); } class ProductAdapter extends BaseAdapter { @Override public int getCount() { return products.size(); } @Override public Object getItem(int position) { return products.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.grid_product, null); holder.imageView = (ImageView) convertView .findViewById(R.id.grid_product_image); holder.nameTextView = (TextView) convertView .findViewById(R.id.grid_product_name); holder.priceTextView = (TextView) convertView .findViewById(R.id.grid_product_price); LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, ApplicationTool.getScreenWidth() / 25 * 16); convertView.setLayoutParams(params); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } ModelProduct product = products.get(position); holder.nameTextView.setText(product.getProductName()); if (priceMap.containsKey(product.getId())) { holder.priceTextView.setText(Parameters.CONSTANT_RMB + decimalFormat.format(priceMap.get(product.getId()) .getPrice())); } ImageLoader.getInstance().displayImage( getSmallImageUrl(product.getImg()), holder.imageView); return convertView; } class ViewHolder { ImageView imageView; TextView priceTextView, nameTextView; } } private void getAds() { ads.clear(); adsAdapter.notifyDataSetChanged(); List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("number", Store.getStore().getStoreNumber())); post(API.API_ADS, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (result.length() > 0) { JSONObject object; try { object = new JSONObject(result); if (object.optString("state").equalsIgnoreCase("SUCCESS")) { JSONArray array = object.optJSONArray("dataList"); if (array != null) { for (int i = 0; i < array.length(); i++) { ads.add(new ModelAds(array.getJSONObject(i))); } adsAdapter.notifyDataSetChanged(); } } } catch (JSONException e) { e.printStackTrace(); } } } }); } private void getProduct() { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("pageNo", pagenum + "")); requestParams.add(new RequestParam("jmdId", Store.getStore().getStoreId())); requestParams.add(new RequestParam("pageSize", pagesize + "")); post(API.API_PRODUCT_LIST, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { refreshScrollView.onRefreshComplete(); if (!TextUtils.isEmpty(result)) { JSONObject info; try { info = new JSONObject(result); if (info.getString("state").equalsIgnoreCase("SUCCESS")) { JSONArray productArray = info.optJSONArray("dataList"); if (productArray != null) { if (productArray.length() > 0) { if (productArray.length() < pagesize) { refreshScrollView .setMode(PullToRefreshBase.Mode.PULL_FROM_START); } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < productArray.length(); i++) { ModelProduct product = new ModelProduct( productArray.getJSONObject(i)); products.add(product); if (i > 0) { stringBuilder.append(","); } stringBuilder.append(product.getId()); } productAdapter.notifyDataSetChanged(); getProductPrice(stringBuilder.toString()); return; } } } } catch (JSONException e) { e.printStackTrace(); } } refreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START); } }); } private void getProductPrice(String productId) { List<RequestParam> requestParams = new ArrayList<>(); requestParams.add(new RequestParam("jmdId", Store.getStore().getStoreId())); requestParams.add(new RequestParam("productId", productId)); post(API.API_PRICE_LIST, requestParams, new OnNetworkListener() { @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)) { JSONObject object; try { object = new JSONObject(result); if (object.getString("state").equalsIgnoreCase("SUCCESS")) { JSONArray priceArray = object.getJSONArray("dataList"); if (priceArray.length() > 0) { for (int i = 0; i < priceArray.length(); i++) { ModelListPrice priceList = new ModelListPrice( priceArray.getJSONObject(i)); priceMap.put(priceList.getProductId(), priceList); } productAdapter.notifyDataSetChanged(); } } } catch (JSONException e) { e.printStackTrace(); } } } }); } class AdsAdapter extends PagerAdapter { @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return ads.size(); } @Override public Object instantiateItem(ViewGroup view, int position) { final int index = position; View imageLayout = layoutInflater.inflate( R.layout.adapter_viewpager, view, false); assert imageLayout != null; ImageView imageView = (ImageView) imageLayout .findViewById(R.id.view_pager_img); ProgressBar spinner = (ProgressBar) imageLayout .findViewById(R.id.view_pager_loading); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); spinner.setVisibility(View.GONE); if (ads.get(position).getAdverImg().length() > 0) { ImageLoader.getInstance().displayImage( ads.get(position).getAdverImg(), imageView); } else { ImageLoader.getInstance().displayImage( ads.get(position).getDefaultImg(), imageView); } imageLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 产品广告,跳转到产品详情界面 if (ads.get(index).getType().contains("产品")) { String productId = ""; if (ads.get(index).getAdverUrl().length() > 0) { productId = ads.get(index).getAdverUrl(); } else { productId = ads.get(index).getDefaultUrl(); } showProductDetail(productId, ads.get(index) .getAdvername(), CaptureActivity.SALE_TYPE_NONE); } else { // 主题广告,跳转到活动 String saleClassId = ""; if (ads.get(index).getAdverUrl().length() > 0) { saleClassId = ads.get(index).getAdverUrl(); } else { saleClassId = ads.get(index).getDefaultUrl(); } Bundle bundle = new Bundle(); bundle.putString("saleClassId", saleClassId); jump(SaleTimeListFragment.class.getName(), ads.get(index).getAdvername(), bundle); } } }); view.addView(imageLayout, 0); return imageLayout; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public Parcelable saveState() { return null; } } } <file_sep>package yitgogo.smart.sale.ui; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.widget.AbsListView.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.smartown.yitgogo.smart.R; import com.umeng.analytics.MobclickAgent; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.List; import yitgogo.smart.BaseNotifyFragment; import yitgogo.smart.home.model.HomeData; import yitgogo.smart.home.model.ModelSaleTheme; import yitgogo.smart.tools.QrCodeTool; public class SaleThemeFragment extends BaseNotifyFragment { FrameLayout imageLayout; HorizontalScrollView horizontalScrollView; GridView imageGridView; WebView webView; ProgressBar progressBar; List<ModelSaleTheme> saleThemes; SaleThemeAdapter saleThemeAdapter; ModelSaleTheme saleTheme = new ModelSaleTheme(); File htmlFile; int columWidth = 340; int columHeight = 140; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_fragment_sale_theme); init(); findViews(); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(SaleThemeFragment.class.getName()); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(SaleThemeFragment.class.getName()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); selectTheme(saleThemes.get(HomeData.getInstance() .getSaleThemeSelection())); } private void init() { htmlFile = new File(getActivity().getCacheDir().getPath(), "saleTheme.html"); saleThemes = HomeData.getInstance().getSaleThemes(); saleThemeAdapter = new SaleThemeAdapter(); } protected void findViews() { imageLayout = (FrameLayout) contentView.findViewById(R.id.image_layout); horizontalScrollView = (HorizontalScrollView) contentView .findViewById(R.id.image_scroll); imageGridView = (GridView) contentView.findViewById(R.id.image_grid); webView = (WebView) contentView.findViewById(R.id.sale_theme_web); progressBar = (ProgressBar) contentView .findViewById(R.id.sale_theme_web_progress); initViews(); registerViews(); } @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"}) protected void initViews() { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, columHeight); imageLayout.setLayoutParams(layoutParams); if (saleThemes.size() > 0) { int colums = saleThemes.size(); imageGridView.setLayoutParams(new LinearLayout.LayoutParams(colums * columWidth, LinearLayout.LayoutParams.MATCH_PARENT)); imageGridView.setColumnWidth(columWidth); imageGridView.setStretchMode(GridView.NO_STRETCH); imageGridView.setNumColumns(colums); } imageGridView.setAdapter(saleThemeAdapter); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar.setVisibility(View.GONE); } else { if (progressBar.getVisibility() == View.GONE) progressBar.setVisibility(View.VISIBLE); progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); webView.addJavascriptInterface(new JsInterface(), "yitgogo"); WebSettings settings = webView.getSettings(); settings.setDefaultTextEncodingName("utf-8"); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); settings.setUseWideViewPort(true); settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); settings.setLoadWithOverviewMode(true); settings.setCacheMode(WebSettings.LOAD_DEFAULT); settings.setDomStorageEnabled(true); settings.setDatabaseEnabled(true); settings.setAppCachePath(getActivity().getCacheDir().getPath()); settings.setAppCacheEnabled(true); } private void selectTheme(ModelSaleTheme modelSaleTheme) { if (!saleThemes.isEmpty()) { if (modelSaleTheme != null) { saleTheme = modelSaleTheme; } else { saleTheme = saleThemes.get(0); } saleThemeAdapter.notifyDataSetChanged(); new DownLoad().execute(); } } protected void registerViews() { imageGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { selectTheme(saleThemes.get(arg2)); } }); } class SaleThemeAdapter extends BaseAdapter { @Override public int getCount() { return saleThemes.size(); } @Override public Object getItem(int position) { return saleThemes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate( R.layout.list_image_scroll, null); viewHolder.imageView = (ImageView) convertView .findViewById(R.id.scroll_image); viewHolder.selectionImageView = (ImageView) convertView .findViewById(R.id.scroll_image_selection); LayoutParams layoutParams = new LayoutParams(columWidth, columHeight); convertView.setLayoutParams(layoutParams); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if (saleTheme.getId().equals(saleThemes.get(position).getId())) { viewHolder.selectionImageView.setVisibility(View.VISIBLE); } else { viewHolder.selectionImageView.setVisibility(View.GONE); } imageLoader.displayImage(getSmallImageUrl(saleThemes.get(position) .getMoblieImg()), viewHolder.imageView); return convertView; } class ViewHolder { ImageView imageView, selectionImageView; } } class DownLoad extends AsyncTask<Void, Float, Boolean> { @Override protected void onPreExecute() { showLoading(); } @Override protected Boolean doInBackground(Void... params) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(saleTheme.getMoblieUrl()); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; if (is != null) { fileOutputStream = new FileOutputStream(htmlFile); byte[] b = new byte[512]; int charb = -1; int count = 0; while ((charb = is.read(b)) != -1) { count += charb; publishProgress((float) count / (float) length); fileOutputStream.write(b, 0, charb); } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { hideLoading(); if (result) { webView.loadUrl("file://" + htmlFile.getPath()); } else { getActivity().finish(); } } } class JsInterface { @JavascriptInterface public boolean showProductInfo(String productId) { showProductDetail(productId, QrCodeTool.SALE_TYPE_NONE); return true; } } }
14288df45ef583a37c7d2d893f20034d9fb45e83
[ "Java", "Gradle" ]
55
Java
KungFuBrother/AndroidStudio
990a687ed0b4c29208f7df91ad94fc61ed9cc282
a1ce284f44f20bbdd1d90df356eed898137e7ebe
refs/heads/master
<file_sep>package copy import ( "fmt" "os" "syscall" "time" ) func preserveTime(info os.FileInfo, dest string) error { if info.Mode()&os.ModeSymlink != 0 { return nil } mtime := info.ModTime() statPtr := info.Sys() if statPtr == nil { return fmt.Errorf("Error in obtain stat structure") } stat := statPtr.(*syscall.Stat_t) atime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) return os.Chtimes(dest, atime, mtime) } <file_sep>module github.com/otiai10/copy go 1.12 require ( github.com/otiai10/mint v1.3.1 golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 ) <file_sep>package copy import ( "fmt" "os" "syscall" "golang.org/x/sys/unix" ) func preserveTime(info os.FileInfo, dest string) error { mtime := unix.NsecToTimeval(info.ModTime().UnixNano()) statPtr := info.Sys() if statPtr == nil { return fmt.Errorf("Error in obtain stat structure") } stat := statPtr.(*syscall.Stat_t) atime := unix.NsecToTimeval(int64(stat.Atim.Sec)*1e9 + int64(stat.Atim.Nsec)) return unix.Lutimes(dest, []unix.Timeval{atime, mtime}) }
461009c9eaac5c12518332eb3a6cd527aca1b9a8
[ "Go Module", "Go" ]
3
Go
siscia/copy
a10db568cf0eaa6214de0afd35930406178a00a0
fb796b380ca8593ab0c8884b68561d77de89d819
refs/heads/master
<repo_name>StarikovSergey/tetris<file_sep>/tetris2/Glass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class Glass { protected Figure walls; protected Figure bottom; public Glass() { walls = new Figure(GetWalls(0, 39,24)); bottom = new Figure(GetBottom(24)); } public List<Point> GetWalls(int xLeft, int xRight, int y) { List<Point> pList = new List<Point>(); for (int i = 4; i < y; i++) { Point p = new Point(xLeft, i); pList.Add(p); } for (int i = 4; i < y; i++) { Point p = new Point(xRight, i); pList.Add(p); } return pList; } public List<Point> GetBottom(int y) { List<Point> pList = new List<Point>(); for (int i = 0; i < 40; i++) { Point p = new Point(i, y); pList.Add(p); } return pList; } public Figure GetFigureBottom() { return bottom; } public Figure GetFigureWalls() { return walls; } public List<Point> GetList() { List<Point> pList = new List<Point>(); pList.AddRange(bottom.GetCurrent()); pList.AddRange(walls.GetCurrent()); return pList; } public void addtoBattom(Figure f) /*если в момент соприсокновения стакана с фигурой нажать <- , -> или вниз - фигура не добавляется в стакан, а исчезает. так же если зажать одну из клавишь управления происходит залипание , фигура становиться не управляемой и так же не добавляется в стакан, а исчезает.*/ { List<Point> pList = bottom.GetCurrent(); List<Point> fList = f.GetCurrent(); pList.AddRange(fList); bottom.SetList(pList); } } } <file_sep>/tetris2/Game.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class Game { Random random = new Random(); RenderingConsole Render = new RenderingConsole(); //отрисовщик public Figure[] CreateArrFigure() { FigureI figureI = new FigureI(); //фигуры FigureJ figureJ = new FigureJ(); FigureL figureL = new FigureL(); FigureO figureO = new FigureO(); FigureS figureS = new FigureS(); FigureT figureT = new FigureT(); FigureZ figureZ = new FigureZ(); Figure[] arrFigures = new Figure[] { figureI, figureJ, figureL, figureO, figureS, figureT, figureZ }; //массив фигур return arrFigures; } public Figure GetRandomFigure(Figure[] arrFigures) { Figure randomFigure = arrFigures[random.Next(arrFigures.Length)]; return randomFigure; } public void Draw(Glass glass, Figure randomFigure ) { Render.Clear(); //очистка экрана Render.Draw(glass.GetList(), '*'); //отрисовка стакана Render.Draw(randomFigure.GetCurrent(), '='); // отрисовка фигуры } } } <file_sep>/tetris2/ManagerCollide.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class ManagerCollide { public bool Collide(Figure f1, Figure f2) { List<Point> pList1 = f1.GetCurrent(); List<Point> pList2 = f2.GetCurrent(); foreach (Point pf1 in pList1) { foreach (Point pf2 in pList2) { if (pf1.x == pf2.x && pf1.y == pf2.y) { return true; } } } return false; } } } <file_sep>/tetris2/Render.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { interface Render { void Clear(); void Draw(List<Point> pList, char sym); } } <file_sep>/tetris2/Figure.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class Figure { protected Point currentPos; protected Point lastPos; protected List<Point> pList; //можно ли присвоить констанкте координаты точки????? //const Point startPosition = (20,4); const int startPositionX = 20; const int startPositionY = 4; public Figure() { currentPos = new Point(); lastPos = new Point(); pList = new List<Point>(); setPos(startPositionX, startPositionY); } public Figure(List<Point> pList) { currentPos = new Point(); this.pList = pList; } public void SetList(List<Point> pList) { this.pList = pList; } private void setPos(int x, int y) { lastPos.x = currentPos.x; lastPos.y = currentPos.y; currentPos.x = x; currentPos.y = y; } private void setPos(Point p) { currentPos.x = p.x; currentPos.y = p.y; } public List<Point> GetCurrent() { List<Point> currentFigure = new List<Point>(); foreach (Point p in pList) { Point tempP = new Point(); tempP.x = currentPos.x + p.x; tempP.y = currentPos.y + p.y; currentFigure.Add(tempP); } return currentFigure; } public void moveDownPerStep() { setPos(currentPos.x, currentPos.y + 1); } //public void moveDownFast() //{ // setPos(currentPos.x, currentPos.y + 1); //} public void moveLeftPerStep() { setPos(currentPos.x - 1, currentPos.y); } public void moveRightPerStep() { setPos(currentPos.x + 1, currentPos.y); } public void SetStartPosition() { setPos(1, 4); } public void moveRotate() { foreach (Point p in pList) { int temp = p.x; p.x = -(p.y); p.y = temp; } } public void RevertRotate() { foreach (Point p in pList) { int tepm = p.x; p.x = p.y; p.y = -(tepm); } } public void DiscardLastMove() { currentPos.x = lastPos.x; currentPos.y = lastPos.y; } } } <file_sep>/tetris2/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; //using System.Timers; namespace tetris2 { class Program { static void Main(string[] args) { Console.SetBufferSize(80, 25); //размер консоли Glass glass = new Glass(); //стакан Game game = new Game(); Figure[] arrF = game.CreateArrFigure(); Figure randomFigure = game.GetRandomFigure(arrF); ManagerCollide mc = new ManagerCollide(); TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, 300); while (true) { DateTime currentTimes = DateTime.Now; while (DateTime.Now < currentTimes + timeSpan) { if (Console.KeyAvailable) //проверка нажатия клавиш { ConsoleKeyInfo key = Console.ReadKey(); //randomFigure.HandleKey(key.Key); if (key.Key == ConsoleKey.Enter) { randomFigure.moveRotate(); if (mc.Collide(glass.GetFigureWalls(), randomFigure)) //отмена разворота фигуры при пересечении со стенками стакана { randomFigure.RevertRotate(); } else if (mc.Collide(glass.GetFigureBottom(), randomFigure)) //отмена разворота фигуры при пересечении со стаканом { randomFigure.RevertRotate(); } } else if (key.Key == ConsoleKey.LeftArrow || key.Key == ConsoleKey.RightArrow) { if (key.Key == ConsoleKey.LeftArrow) { randomFigure.moveLeftPerStep(); } else if (key.Key == ConsoleKey.RightArrow) { randomFigure.moveRightPerStep(); } if (mc.Collide(glass.GetFigureWalls(), randomFigure)) //отмена последнего действия при врезании в стену { randomFigure.DiscardLastMove(); } else if (mc.Collide(glass.GetFigureBottom(), randomFigure)) //проверка что бы фигура не прилипала к стакану если есть возможность падать дальше { randomFigure.DiscardLastMove(); } } } if (mc.Collide(glass.GetFigureBottom(), randomFigure)) //если просходит коллизия между дном стакана и фигурой //фигура откатывается в предыдущую позицию, добавляется в стакан и отрисовывается. //далее рандомной фируге присваевается новое значение и она устанавливается в стартовую позицию. { randomFigure.DiscardLastMove(); glass.addtoBattom(randomFigure); randomFigure = game.GetRandomFigure(arrF); } } game.Draw(glass, randomFigure); randomFigure.moveDownPerStep(); //движение фигуры вниз } Console.WriteLine("Game Over"); Console.ReadKey(); } } } <file_sep>/tetris2/RenderingConsole.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class RenderingConsole : Render { public void Clear() { Console.Clear(); } public void Draw(List<Point> pList, char sym) { foreach (Point p in pList) { Console.SetCursorPosition(p.x, p.y); Console.Write(sym); } } public void Draww() { Console.Write("ujk"); Console.ReadKey(); } } } <file_sep>/tetris2/FigureJ.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tetris2 { class FigureJ : Figure { public FigureJ() { pList = new List<Point>(); Point p1 = new Point(0, 0); Point p2 = new Point(0, 1); Point p3 = new Point(1, 1); Point p4 = new Point(2, 1); pList.Add(p1); pList.Add(p2); pList.Add(p3); pList.Add(p4); } } }
ea79767c2a222e3628f8eda388f38ea3860d0d34
[ "C#" ]
8
C#
StarikovSergey/tetris
2951407fde522f9d81a9c689bea676f6b9383089
9bd8acc06884593043dcc408530d5c82c3b2b0be
refs/heads/master
<repo_name>Progipedia/Progipedia<file_sep>/www-sites/benutzer_registrieren.php <?php session_start(); ?> <!DOCTYPE HTML> <html> <head> <title>Progipedia/Registrierung</title> <link rel="stylesheet" type="text/css" href="../css/standard.css" /> <link rel="stylesheet" type="text/safari" href="../css/standard_safari.css" /> <meta charset="UTF-8" /> <link rel="icon" href="../Bilder/favicon.ico" type="image/x-icon"/> </head> <body> <?php // Datenbankanbindung include ("datenbankanbindung.php"); if (isset($_POST['benutzername']) && isset($_POST['email']) && isset($_POST['passwort']) && isset($_POST['passwort2']) && isset($_POST['name']) && isset($_POST['vorname']) && !isset($_SESSION['berechtigter_benutzer'])) { //Variablenzuweisung $benutzername = $_POST['benutzername']; $email = $_POST['email']; $passwort = $_POST['<PASSWORD>']; $passwort2 = $_POST['<PASSWORD>']; $name = $_POST['name']; $vorname = $_POST['vorname']; //Überprüfung auf Korrektheit der Feldeintragung //Abfrage für die Untersuchung des bereits Vorhandenseins des selben Namens $abfrage = mysql_query ("SELECT id_benutzer FROM tbl_benutzer WHERE benutzername LIKE '$benutzername'" ); $menge = mysql_num_rows($abfrage); if($menge == 0) { $abfrage = mysql_query ("SELECT email FROM tbl_benutzer WHERE email LIKE '$email'" ); $menge = mysql_num_rows($abfrage); if ($menge == 0) { $exit=0; //Email-Überprüfung $email_pruefung = 0; $email_laenge = strlen($email)-1; $email_at = 0; $email_punkt = 0; for ($i = 0;$i <= $email_laenge;$i++) { if ($email[$i] == " ") { $email_pruefung = 1; } if ($email[$i] == "@" && $i != 0) { $email_at++; } } if ($email_at != 1) { $email_pruefung = 1; } if ($benutzername == "" || $email == "" || $passwort == "" || $passwort2 == "") { echo "Bitte füllen Sie alle Pflichtfelder aus! <br />"; $exit = 1; } if ($email_pruefung == 1 && $email != "") { echo "Bitte geben Sie eine gültige E-Mail-Adresse an! <br />"; $exit = 1; } if ($passwort != $passwort2 && $passwort != "" && $passwort2 != "") { echo "Bitte verwenden Sie für beide Passwort-Felder den selben Eintrag! <br />"; $exit = 1; } if ($benutzername >= 30) { echo "Bitte verwenden Sie für den Benutzernamen nicht mehr als 30 Zeichen! <br />"; $exit = 1; } //Verlassen des PHP-Programmes if ($exit == 1) { echo '<a href="benutzer_registrieren.php">Erneut versuchen</a>'; mysql_close($datenbank); exit; } //Passwort hashen $passwort = md5($passwort); //Eintragung des Benutzers $eintrag = "Insert Into tbl_benutzer (benutzername,passwort,email,name,vorname,benutzergruppe_id) VALUES ('$benutzername','$passwort','$email','$name','$vorname','3')"; $eintragen = mysql_query($eintrag); if($eintragen == 1) { echo 'Der Benutzer <span class="fett">'.$benutzername.'</span> wurde erstellt! <br /> <a href="benutzer_anmelden.php">Einloggen</a>'; //Versendung der Bestätigungsemail $progipedia_name = "Progipedia"; $progipedia_email = "<EMAIL>"; //Zurzeit $email_betreff = "Willkommen bei Progipedia"; $email_inhalt = "Hallo $benutzername, vielen Dank für die Anmeldung bei Progipedia!"; mail($email, $email_betreff, $email_inhalt, "From: $progipedia_name <$progipedia_email>"); } else { echo 'Fehler bei der Registrierung! <br /> <a href="benutzer_registrieren.php">Erneut versuchen</a>'; } } else { echo 'Die angegebene E-Mail-Adresse existiert bereits!<br /> <a href="benutzer_registrieren.php">Erneut versuchen</a>'; } } else { echo 'Der Benutzername <span class="fett">'.$benutzername.'</span> ist bereits vorhanden! <br /> <a href="benutzer_registrieren.php">Erneut versuchen</a>'; } exit; } else if (isset($_SESSION['berechtigter_benutzer'])) { echo 'Sie sind bereits als <span class="fett">'.$_SESSION['benutzername'].'</span> angemeldet.<br/>Sie können im angemeldetem Zustand keine Registrierung vornehmen!<br/>Bitte melden Sie sich zuvor ab:<br/>'; ?> <form action="benutzer_abmelden.php" method="POST"> <input type="submit" value="Abmelden" name="abmelden"> </form> <?php exit; } ?> <h1>Registrierung</h1> <form action="benutzer_registrieren.php" method="POST"> <input type="text" name="benutzername" maxlength="30" size="21" placeholder="Benutzername" />* <br /> <br /> <input type="text" name="email" maxlength="345" size="21" placeholder="E-Mail" />* <br /> <br /> <input type="text" name="name" maxlength="50" size="21" placeholder="Name" /> <br /> <br /> <input type="text" name="vorname" maxlength="50" size="21" placeholder="Vorname" /> <br /> <br /> <input type="password" name="passwort" maxlength="15" size="21" placeholder="Passwort" />* <br /> <br /> <input type="password" name="passwort2" maxlength="15" size="21" placeholder="Passwort <PASSWORD>" />* <br /> <br /> <input type="submit" value="Abschicken" /> </form> <br /> <a href="benutzer_anmelden.php">Einloggen</a> <br /> <br /> Die *-Felder sind Pflichtfelder und müssen ausgefüllt werden! <?php mysql_close($datenbank); ?> </body> </html><file_sep>/www-sites/benutzer_abmelden.php <?php session_start(); ?> <!DOCTYPE HTML> <html> <head> <title>Progipedia/Anmeldung</title> <link rel="stylesheet" type="text/css" href="../css/standard.css" /> <link rel="stylesheet" type="text/safari" href="../css/standard_safari.css" /> <meta charset="UTF-8" /> <link rel="icon" href="../Bilder/favicon.ico" type="image/x-icon"/> </head> <body> <?php //Dieser Fall trifft ein, wenn ein Benutzer auf den Abmeldebutton klickt oder die Seite daraufhinaktualisiert (der Wert "abmelden" wurde übertragen) if (isset($_POST['abmelden'])) { $abmelden = $_POST['abmelden']; if (isset($_SESSION['berechtigter_benutzer'])) { //Session wird gelöscht $_SESSION=array(); session_destroy(); if (!isset($_SESSION['berechtigter_benutzer'])) { echo "Sie haben sich erfolgreich abgemeldet!<br/>"; } // Paradoxer Fall: Die Session wird zuvor gelöscht, also dürfte dieser Fall niemals eintreten! else { echo "Bei Ihrer Abmeldung ist ein Fehler aufgetreten!<br/>Sie besitzen noch weiterhin eine gesetzte Session-Variable!<br/> Wenden Sie sich bitte an die Administratoren oder versuchen Sie es erneut"; ?> <a href="anmelden.php">Erneut anmelden</a> <form action="..." method="POST"> <input type="submit" value="Administrator melden" name="administrator_melden"> </form> <?php } } //Dieser Fall trifft ein, wenn ein bereits abgemeldeter Benutzer erneut den Abmeldebutton betätigt (z.B. wenn der Benutzer während seiner Anmeldephase weitere Tabs offen hat, in denen der Abmeldebutton noch zu sehen ist) oder die Seite aktualisiert else if (!isset($_SESSION['berechtigter_benutzer'])) { echo 'Sie haben diese Seite aktualisiert oder den Abmeldebutton erneut gedrückt. Dies hat keinen Effekt!<br/> Bitte melden Sie sich an: <a href="benutzer_anmelden.php">Benutzer anmelden</a>'; } } //Dieser Fall trifft ein, wenn ein Benutzer das PHP-Dokument in die URL-Leiste einträgt (der Wert "abmelden" wurde nicht übertragen) else if (!isset($_POST['abmelden'])) { //Dieser Fall trifft ein, wenn ein angemeldeter Benutzer das PHP-Dokument in die URL-Leiste einträgt if (isset($_SESSION['berechtigter_benutzer'])) { echo "Eine Löschung der aktuellen Sitzung (Session) bzw. eine Abmeldung durch das Einfügen des PHP-Dokumentes in die URL-Leiste zu erzwingen ist nicht möglich.<br/>Bitte melden Sie sich über den dafür vorgesehenen Abmelde-Button ab:<br/>"; ?> <form action="benutzer_abmelden.php" method="POST"> <input type="submit" value="Abmelden" name="abmelden"> </form> <?php } //Dieser Fall trifft ein, wenn ein nicht angemeldeter Benutzer das PHP-Dokument in die URL-Leiste einträgt (der Wert "abmelden" wurde nicht übertragen) else if (!isset($_SESSION['berechtigter_benutzer'])) { echo 'Eine Löschung der aktuellen Sitzung (Session) bzw. eine Abmeldung durch das Einfügen des PHP-Dokumentes in die URL-Leiste zu erzwingen ist nicht möglich.<br/>Darüber hinaus sind Sie nicht angemeldet.<br/> Bitte melden Sie sich an: <a href="benutzer_anmelden.php">Benutzer anmelden</a>'; } } ?> <a href="index.php">Zur Startseite</a> </body> </html><file_sep>/www-sites/benutzer_anmelden.php <?php session_start(); ?> <!DOCTYPE HTML> <html> <head> <title>Progipedia/Anmeldung</title> <link rel="stylesheet" type="text/css" href="../css/standard.css" /> <link rel="stylesheet" type="text/safari" href="../css/standard_safari.css" /> <meta charset="UTF-8" /> <link rel="icon" href="../Bilder/favicon.ico" type="image/x-icon"/> </head> <body> <?php // Datenbankanbindung include ("datenbankanbindung.php"); if (isset($_POST['benutzername']) && isset($_POST['passwort']) && !isset($_SESSION['berechtigter_benutzer'])) { //Variablenzuweisung $benutzername = $_POST['benutzername']; $passwort = md5($_POST['passwort']); $exit = 0; //Überprüfung auf Korrektheit der Feldeintragung if ($benutzername == "" || $passwort == "<PASSWORD>") { echo "Bitte füllen Sie beide Felder aus! <br />"; $exit = 1; } //Verlassen des PHP-Programmes if ($exit == 1) { echo '<a href="benutzer_anmelden.php">Erneut versuchen</a>'; mysql_close($datenbank); exit; } //Suchen des Benutzers $abfrage = "SELECT benutzername, passwort FROM tbl_benutzer WHERE benutzername LIKE '$benutzername' LIMIT 1"; $ergebnis = mysql_query($abfrage); $menge = mysql_num_rows($ergebnis); if ($menge == 0) { echo 'Der Benutzer <span class="fett">'.$benutzername.'</span> existiert nicht! <br /> <a href="benutzer_anmelden.php">Erneut versuchen</a>'; } else { $datensatz = mysql_fetch_object($ergebnis); if ($datensatz->passwort == $passwort) { //Feststellung der Benutzergruppe $abfrage = "SELECT bg.bezeichnung FROM tbl_benutzer b, tbl_benutzergruppe bg WHERE b.benutzername = '$benutzername' AND b.benutzergruppe_id = bg.id_benutzergruppe"; $ergebnis = mysql_query($abfrage); $benutzergruppe = mysql_result($ergebnis,0,0); //Sessionvariablen zuweisen if ($benutzergruppe == "Registrierter Benutzer") { $_SESSION['berechtigter_benutzer'] = 3; } if ($benutzergruppe == "Moderator") { $_SESSION['berechtigter_benutzer'] = 2; } if ($benutzergruppe == "Administrator") { $_SESSION['berechtigter_benutzer'] = 1; } $_SESSION['benutzername'] = $benutzername; echo 'Herzlich Willkommen <span class="fett">'.$benutzername.'</span><br/><a href="index.php">Zur Startseite</a>'; } else { echo 'Sie haben ein falsches Passwort verwendet! <br /> <a href="benutzer_anmelden.php">Erneut versuchen</a>'; } } exit; } else if (isset($_SESSION['berechtigter_benutzer'])) { echo 'Sie sind bereits als <span class="fett">'.$_SESSION['benutzername'].'</span> angemeldet.<br/>Sie können im angemeldetem Zustand keine erneute Anmeldung vornehmen!<br/>Bitte melden Sie sich zuvor ab:<br/>'; ?> <form action="benutzer_abmelden.php" method="POST"> <input type="submit" value="Abmelden" name="abmelden"> </form><br/> <a href="index.php">Zur Startseite</a> <?php exit; } ?> <h1>Anmeldung</h1> <form action="benutzer_anmelden.php" method="POST"> <input type="text" name="benutzername" maxlength="30" size="21" placeholder="Benutzername" /> <input type="password" name="passwort" maxlength="15" size="21" placeholder="Passwort" /> <input type="submit" value="Abschicken" /> </form> <br /> <a href="benutzer_registrieren.php">Regestrieren</a> <?php mysql_close($datenbank); ?> <br/><br/><a href="index.php">Zur Startseite</a> </body> </html><file_sep>/www-sites/datenbankanbindung.php <?php // Datenbankanbindung $datenbank = @mysql_connect("127.0.0.1","root","") OR die ("Die Verbindung zur Datenbank konnte nicht hergestellt werden!"); mysql_select_db("db_progipedia",$datenbank) OR die ('Die Datenbank "db_progipedia" nicht vorhanden!'); ?><file_sep>/Progipedia/FirstCommit.php <?php echo "Ich bin der erste Commit versuch NR 2 <br/>"; echo "Southpark kommt grade Biatch"; echo "Dilemma ACC";<file_sep>/www-sites/artikel_anlegen.php <?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Progipedia/Artikel anlegen</title> <link rel="stylesheet" type="text/css" href="../css/standard.css" /> <link rel="stylesheet" type="text/safari" href="../css/standard_safari.css" /> <meta charset="UTF-8" /> <link rel="icon" href="../Bilder/favicon.ico" type="image/x-icon"/> </head> <body> <!-- Kopfbereich --> <header> <a href="index.php"><img id="bild_banner" src="../Bilder/banner.jpg" alt="Home" title="Home"/></a> <img id="bild_progipedia" src="../Bilder/progipedia.jpg" alt="Progipedia" title="Progipedia"/> <?php if (!isset($_SESSION['berechtigter_benutzer'])) { ?> <a id="benutzerkonto_anlegen" href="benutzer_registrieren.php"> Benutzerkonto anlegen </a> <div id="login_feld"> <form action="benutzer_anmelden.php" method="POST"> <input type="text" name="benutzername" maxlength="30" size="21" placeholder="Benutzername" /> <input type="<PASSWORD>" name="passwort" maxlength="15" size="21" placeholder="Passwort" /> <input type="submit" value="Abschicken" /> </form> </div> <?php } else { ?> <div id="logout_feld"> <form action="benutzer_abmelden.php" method="POST"> <input type="submit" value="Abmelden" name="abmelden"> </form> </div> <?php } ?> </header> <!-- Inhaltsbereich --> <section> <!-- Navigationsbereich --> <nav> <!-- <form action="index.php" method="GET"> <input id="suchen_feld" type="search" name="suche" placeholder="Suche" /> </form> --> <ul> <li><a href="index.php">Startseite</a></li> <li><a href="hauptkategorie.php">Artikelverzeichnis</a> <ul> <li><a href="kategorie-C.php">C</a></li> <li><a href="kategorie-php.php">PHP</a></li> <li><a href="kategorie-JavaScript.php">JavaScript</a></li> <li><a href="kategorie-sql.php">SQL</a></li> </ul> </li> <li><a href="hilfe.php">Hilfe</a> <ul> <li><a href="hilfe-artikel_erstellen.php">Artikel erstellen</a></li> <li><a href="hilfe-media.php">Medien</a></li> </ul> </li> <li><span id="nav_aktiv">Artikel anlegen</span></li> <li><a href="...">Zufälliger Artikel</a></li> <li><a href="kategorie-jahrgang.php">Jahrgang</a> <ul> <li><a href="kategorie-jahrgang_1.php">Jahrgang 1</a></li> <li><a href="kategorie-jahrgang_2.php">Jahrgang 2</a></li> <li><a href="kategorie-jahrgang_3.php">Jahrgang 3</a></li> </ul> </li> <li><a href="kategorie-Programmierlehrer">Programmierlehrer</a> <ul> <li><a href="herr_bendadi.php"><NAME></a></li> <li><a href="herr_burlisnki.php"><NAME></a></li> <li><a href="herr_stein.php"><NAME></a></li> <li><a href="frau_zorlu.php"><NAME></a></li> </ul> </li> </ul> </nav> <!-- Artikelbereich --> <article> <?php if (isset($_SESSION['berechtigter_benutzer'])) { ?> <div id="artikel-anlegen_formular"> <form action="artikel_anlegen.php" method="POST"> <div id="artikel-anlegen_titel"> <input type="text" name="titel" maxlength="30" size="21" /> </div> <div id="artikel-anlegen_einleitung"> <textarea name="einleitung" cols="70" rows="10"></textarea> </div> <div id="artikel-anlegen_hauptteil"> <textarea name="hauptteil" cols="70" rows="30"></textarea> </div> <div id="artikel-anlegen_kategorie"> <input type="text" name="kategorie" size="94" /> </div> </form> </div> <?php } else { ?> Sie haben nicht das Recht einen Artikel zu erstellen. Bitte registrieren Sie sich oder melden Sie sich an. <?php } ?> </article> </section> <!-- Fußbereich --> <footer> <a href="ueber_progipedia.php">Über Progipedia</a> | <a href="impressum.php">Impressum</a> </footer> </body> </html>
2eb3a3d0764556e8df9ca9f6844651dd7e6b7bc0
[ "PHP" ]
6
PHP
Progipedia/Progipedia
d353689c9edda424986ef30b3aac335d04bc38fe
d2bad6141860b222b21ad00e8fd98fc11828c0b1
refs/heads/main
<file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Framework\App\RequestInterface; class GetSiteArea { /** * @var RequestInterface */ private $request; /** * @param RequestInterface $request */ public function __construct( RequestInterface $request ) { $this->request = $request; } /** * @return string */ public function execute(): string { $controllerName = $this->request->getControllerName(); return match ($controllerName) { 'account' => 'account', default => 'ecommerce', }; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Framework\View\Element\Block\ArgumentInterface; use Magento\Store\Model\StoreManagerInterface; class GetCurrencyCode implements ArgumentInterface { /** * @var StoreManagerInterface */ private $storeManager; /** * @param StoreManagerInterface $storeManager */ public function __construct ( StoreManagerInterface $storeManager ) { $this->storeManager = $storeManager; } /** * @return string */ public function execute(): string { try { return $this->storeManager->getStore()->getCurrentCurrencyCode(); } catch (\Exception $e) { unset($e); return ''; } } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model\Event; use Magento\Customer\Model\Session; class GetNewsletterSubscriptionEvent { /** @var string */ public const EVENT_NAME = 'newsletter_subscription'; /** * @var Session */ private $session; /** * @param Session $session */ public function __construct( Session $session ) { $this->session = $session; } /** * @return string */ public function execute(): string { $event = $this->session->getData(self::EVENT_NAME); if ($event) { $this->session->unsetData(self::EVENT_NAME); return $event; } return ''; } } <file_sep>define([ 'jquery', 'Magento_GoogleTagManager/js/google-tag-manager' ], function ($) { 'use strict'; /** * Dispatch product detail event to GA * * @param {Object} data - product data * * @private */ function notify(data) { window.dataLayer.push({ 'event': 'view_item', 'ecommerce': { 'currency': GA4.currencyCode, 'items': [data] } }); } return function (productData) { window.dataLayer ? notify(productData) : $(document).on('ga:inited', notify.bind(this, productData)); }; }); <file_sep>define([ 'jquery', 'mage/url' ], function ($, url) { 'use strict'; return function () { $.ajax({ url: url.build('ga4/showminicart'), dataType: 'json', cache: false, success: function (res) { if ( !res.hasOwnProperty('event') || res.event !== 'view_cart' ) { return; } window.dataLayer.push(res); }, error: console.log }); }; }); <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Observer\Cart; use GhostUnicorns\Ga4\Model\CategoryManager; use GhostUnicorns\Ga4\Model\Event\GetCartUpdateEvents; use GhostUnicorns\Ga4\Model\GetProductLayer; use GhostUnicorns\Ga4\Model\ProductManager; use Magento\Checkout\Model\Session as CheckoutSession; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Serialize\SerializerInterface; class Update implements ObserverInterface { /** * @var CheckoutSession */ protected $checkoutSession; /** * @var SerializerInterface */ private $serializer; /** * @var ProductManager */ private $productManager; /** * @var CategoryManager */ private $categoryManager; /** * @var GetProductLayer */ private $getProductLayer; /** * @param CheckoutSession $checkoutSession * @param SerializerInterface $serializer * @param ProductManager $productManager * @param CategoryManager $categoryManager * @param GetProductLayer $getProductLayer */ public function __construct ( CheckoutSession $checkoutSession, SerializerInterface $serializer, ProductManager $productManager, CategoryManager $categoryManager, GetProductLayer $getProductLayer ) { $this->checkoutSession = $checkoutSession; $this->serializer = $serializer; $this->productManager = $productManager; $this->categoryManager = $categoryManager; $this->getProductLayer = $getProductLayer; } /** * @param EventObserver $observer * @return void * @throws LocalizedException * @throws NoSuchEntityException */ public function execute(EventObserver $observer) { $cartItems = $observer->getRequest()->getParam('cart'); if (!$cartItems) { return; } $data = [ 'add' => [], 'remove' => [] ]; $finalData = []; foreach ($cartItems as $key => $cartItem) { if (!isset($cartItem['qty'])) { continue; } $quantity = (float) $cartItem['qty']; $item = $this->checkoutSession->getQuote()->getItemById($key); if (!$item || !$item->getId() || $quantity === (float)$item->getQty()) { continue; } $product = $item->getProduct(); $qty = $quantity > $item->getQty() ? ($quantity - $item->getQty()) : ($item->getQty() - $quantity); $productData = $this->getProductLayer->execute( $product->getSku(), $qty, (float)$item->getPriceInclTax(), (float)$item->getDiscountAmount() ); if ($quantity > $item->getQty()) { $data['add'][] = $productData; } else { $data['remove'][] = $productData; } } if (count($data['add'])) { $finalData[] = [ 'event' => 'add_to_cart', 'ecommerce' => [ 'items' => $data['add'] ] ]; } if (count($data['remove'])) { $finalData[] = [ 'event' => 'remove_to_cart', 'ecommerce' => [ 'items' => $data['remove'] ] ]; } if ($finalData) { $this->checkoutSession->setData(GetCartUpdateEvents::EVENT_NAME, $this->serializer->serialize($finalData)); } } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Plugin; use GhostUnicorns\Ga4\Model\GetProductLayer; use Magento\Checkout\CustomerData\Cart; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; class AddProductInfoToCustomerDataCart { /** * @var GetProductLayer */ private $getProductLayer; /** * @param GetProductLayer $getProductLayer */ public function __construct( GetProductLayer $getProductLayer ) { $this->getProductLayer = $getProductLayer; } /** * @param Cart $subject * @param array $result * @return array * @throws LocalizedException * @throws NoSuchEntityException */ public function afterGetSectionData(Cart $subject, array $result): array { if (is_array($result['items'])) { foreach ($result['items'] as $key => $itemAsArray) { $sku = $result['items'][$key]['product_sku']; $productLayer = $this->getProductLayer->execute($sku); $result['items'][$key] = array_merge($result['items'][$key], $productLayer); } } return $result; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Controller\ShowMiniCart; use GhostUnicorns\Ga4\Model\GetCartLayer; use Magento\Framework\App\ActionInterface; use Magento\Framework\Controller\Result\JsonFactory; class Index implements ActionInterface { /** * @var JsonFactory */ protected $resultJsonFactory; /** * @var GetCartLayer */ private $getCartLayer; /** * @param JsonFactory $resultJsonFactory * @param GetCartLayer $getCartLayer */ public function __construct ( JsonFactory $resultJsonFactory, GetCartLayer $getCartLayer ) { $this->resultJsonFactory = $resultJsonFactory; $this->getCartLayer = $getCartLayer; } /** * @see \Magento\Framework\App\ActionInterface::execute() */ public function execute() { return $this->resultJsonFactory->create()->setData( $this->getCartLayer->execute(true) ); } } <file_sep>define([ 'jquery', 'underscore' ], function ($, _) { 'use strict'; /** * Google analytics universal class * * @param {Object} config */ function GoogleAnalyticsUniversal(config) { this.blockNames = config.blockNames; this.dlCurrencyCode = config.dlCurrencyCode; this.dataLayer = config.dataLayer; this.staticImpressions = config.staticImpressions; this.staticPromotions = config.staticPromotions; this.updatedImpressions = config.updatedImpressions; this.updatedPromotions = config.updatedPromotions; } GoogleAnalyticsUniversal.prototype = { /** * Active on category action * * @param {String} id * @param {String} name * @param {String} category * @param {Object} list * @param {String} position */ activeOnCategory: function (id, name, category, list, position) { this.dataLayer.push({ 'event': 'select_item', 'ecommerce': { 'currency': GA4.currencyCode, 'items': [{ 'item_id': id, 'item_name': name, 'item_category': category, 'list': list, 'position': position }] } }); }, /** * Active on products action * * @param {String} id * @param {String} name * @param {Object} list * @param {String} position * @param {String} category */ activeOnProducts: function (id, name, list, position, category) { this.dataLayer.push({ 'event': 'select_item', 'ecommerce': { 'currency': GA4.currencyCode, 'items': [{ 'item_id': id, 'item_name': name, 'list': list, 'position': position, 'item_category': category }] } }); }, /** * Add to cart action * * @param {String} id * @param {String} name * @param {Number} price * @param {String} discount * @param {String} quantity * @param {String} manufacturer * @param {String} item_variant * @param {String} item_size * @param {String} item_category * @param {String} item_category2 * @param {String} item_category3 * @param {String} item_category4 * @param {String} item_category5 */ addToCart: function (id, name, price, discount, quantity, manufacturer, item_variant, item_size, item_category, item_category2, item_category3, item_category4, item_category5) { this.dataLayer.push({ 'event': 'add_to_cart', 'ecommerce': { 'currency': this.dlCurrencyCode, 'items': [{ 'item_id': id, 'item_name': name, 'price': parseFloat(price), 'discount': discount, 'quantity': quantity, 'item_brand': manufacturer, 'item_variant': item_variant, 'item_size': item_size, 'item_category': item_category, 'item_category2': item_category2, 'item_category3': item_category3, 'item_category4': item_category4, 'item_category5': item_category5 }] } }); }, /** * Remove from cart action * * @param {String} id * @param {String} name * @param {String} price * @param {String} quantity */ removeFromCart: function (id, name, price, quantity) { this.dataLayer.push({ 'event': 'remove_from_cart', 'ecommerce': { 'currencyCode': this.dlCurrencyCode, 'items': [{ 'item_id': id, 'item_name': name, 'price': parseFloat(price), 'quantity': quantity }] } }); }, /** * Click banner action * * @param {String} id * @param {String} name * @param {String} creative * @param {String} position */ clickBanner: function (id, name, creative, position) { this.dataLayer.push({ 'event': 'select_promotion', 'ecommerce': { 'currency': GA4.currencyCode, 'promoClick': { 'promotions': [{ 'promotion_id': id, 'promotion_name': name, 'creative_name': creative, 'creative_slot': position }] } } }); }, /** * Bind impression click * * @param {String} id * @param {String} type * @param {String} name * @param {String} category * @param {Object} list * @param {String} position * @param {String} blockType * @param {String} listPosition */ bindImpressionClick: function (id, type, name, category, list, position, blockType, listPosition) { var productLink = [], eventBlock; switch (blockType) { case 'catalog.product.related': eventBlock = '.products-related .products'; break; case 'product.info.upsell': eventBlock = '.products-upsell .products'; break; case 'checkout.cart.crosssell': eventBlock = '.products-crosssell .products'; break; case 'category.products.list': case 'search_result_list': eventBlock = '.products .products'; break; } productLink = $(eventBlock + ' .item:nth(' + listPosition + ') a'); if (type === 'configurable' || type === 'bundle' || type === 'grouped') { productLink = $( eventBlock + ' .item:nth(' + listPosition + ') .tocart,' + eventBlock + ' .item:nth(' + listPosition + ') a' ); } productLink.each(function (index, element) { $(element).on('click', function () { // Product category cannot be detected properly if customer is not on category page if (blockType !== 'category.products.list') { category = ''; } this.activeOnProducts( id, name, list, position, category); }.bind(this)); }.bind(this)); }, /** * Update impressions */ updateImpressions: function () { var pageImpressions = this.mergeImpressions(), dlImpressions = { 'event': 'view_item_list', 'ecommerce': { 'currency': GA4.currencyCode, 'items': [] } }, i = 0, impressionCounter = 0, impression, blockName; for (blockName in pageImpressions) { // jscs:disable disallowKeywords if (blockName === 'length' || !pageImpressions.hasOwnProperty(blockName)) { continue; } // jscs:enable disallowKeywords for (i; i < pageImpressions[blockName].length; i++) { impression = pageImpressions[blockName][i]; dlImpressions.ecommerce.items.push({ 'item_id': impression.id, 'item_name': impression.name, 'item_category': impression.category, 'list': impression.list, 'position': impression.position }); impressionCounter++; this.bindImpressionClick( impression.id, impression.type, impression.name, impression.category, impression.list, impression.position, blockName, impression.listPosition ); } } if (impressionCounter > 0) { this.dataLayer.push(dlImpressions); } }, /** * Merge impressions */ mergeImpressions: function () { var pageImpressions = []; this.blockNames.forEach(function (blockName) { // check if there is a new block generated by FPC placeholder update if (blockName in this.updatedImpressions) { pageImpressions[blockName] = this.updatedImpressions[blockName]; } else if (blockName in this.staticImpressions) { // use the static data otherwise pageImpressions[blockName] = this.staticImpressions[blockName]; } }, this); return pageImpressions; }, /** * Update promotions */ updatePromotions: function () { var dlPromotions = { 'event': 'view_promotion', 'ecommerce': { 'currency': GA4.currencyCode, 'promoView': { 'promotions': [] } } }, pagePromotions = [], promotionCounter = 0, bannerIds = [], i = 0, promotion, self = this; // check if there is a new block generated by FPC placeholder update if (this.updatedPromotions.length) { pagePromotions = this.updatedPromotions; } // use the static data otherwise if (!pagePromotions.length && this.staticPromotions.length) { pagePromotions = this.staticPromotions; } if ($('[data-banner-id]').length) { _.each($('[data-banner-id]'), function (banner) { var $banner = $(banner), ids = ($banner.data('ids') + '').split(','); bannerIds = $.merge(bannerIds, ids); }); } bannerIds = $.unique(bannerIds); for (i; i < pagePromotions.length; i++) { promotion = pagePromotions[i]; // jscs:disable disallowKeywords /* eslint-disable eqeqeq */ if ($.inArray(promotion.id, bannerIds) == -1 || promotion.activated == '0') { continue; } // jscs:enable disallowKeywords /* eslint-enable eqeqeq */ dlPromotions.ecommerce.promoView.promotions.push({ 'item_id': promotion.id, 'item_name': promotion.name, 'creative': promotion.creative, 'position': promotion.position }); promotionCounter++; } if (promotionCounter > 0) { this.dataLayer.push(dlPromotions); } $('[data-banner-id]').on('click', '[data-banner-id]', function () { var bannerId = $(this).attr('data-banner-id'), promotions = _.filter(pagePromotions, function (item) { return item.id === bannerId; }); _.each(promotions, function (promotionItem) { self.clickBanner( promotionItem.id, promotionItem.name, promotionItem.creative, promotionItem.position ); }); }); } }; return GoogleAnalyticsUniversal; }); <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model\Event; use Magento\Framework\Serialize\SerializerInterface; class GetAllEvents { /** * @var GetCustomerRegisterEvent */ private $getCustomerRegisterEvent; /** * @var GetNewsletterSubscriptionEvent */ private $getNewsletterSubscriptionEvent; /** * @var GetCartUpdateEvents */ private $getCartUpdateEvents; /** * @var SerializerInterface */ private $serializer; /** * @var GetCustomerLoginEvent */ private $getCustomerLoginEvent; /** * @param GetCustomerRegisterEvent $getCustomerRegisterEvent * @param GetNewsletterSubscriptionEvent $getNewsletterSubscriptionEvent * @param GetCartUpdateEvents $getCartUpdateEvents * @param SerializerInterface $serializer * @param GetCustomerLoginEvent $getCustomerLoginEvent */ public function __construct( GetCustomerRegisterEvent $getCustomerRegisterEvent, GetNewsletterSubscriptionEvent $getNewsletterSubscriptionEvent, GetCartUpdateEvents $getCartUpdateEvents, SerializerInterface $serializer, GetCustomerLoginEvent $getCustomerLoginEvent ) { $this->getCustomerRegisterEvent = $getCustomerRegisterEvent; $this->getNewsletterSubscriptionEvent = $getNewsletterSubscriptionEvent; $this->getCartUpdateEvents = $getCartUpdateEvents; $this->serializer = $serializer; $this->getCustomerLoginEvent = $getCustomerLoginEvent; } /** * @return array */ public function execute(): array { $events = []; $newsletterSubscriptionEvent = $this->getNewsletterSubscriptionEvent->execute(); if ($newsletterSubscriptionEvent) { $events[] = $newsletterSubscriptionEvent; } $cartUpdateEvents = $this->getCartUpdateEvents->execute(); if ($cartUpdateEvents) { $cartUpdateEventsArray = $this->serializer->unserialize($cartUpdateEvents); foreach ($cartUpdateEventsArray as $cartUpdateEvent) { $events[] = $this->serializer->serialize($cartUpdateEvent); } } $customerRegisterEvent = $this->getCustomerRegisterEvent->execute(); if ($customerRegisterEvent) { $events[] = $customerRegisterEvent; } $customerLoginEvent = $this->getCustomerLoginEvent->execute(); if ($customerLoginEvent) { $events[] = $customerLoginEvent; } // $contactEvent = $this->getContactEvent->execute(); // if ($contactEvent) { // $events[] = $contactEvent; // } return $events; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ResourceModel\Product; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable; class ProductManager { /** * @var Product */ protected $resourceProduct; /** * @var ProductFactory */ protected $productFactory; /** * @var Configurable */ protected $configurable; /** * @param Product $resourceProduct * @param ProductFactory $productFactory * @param Configurable $configurable */ public function __construct( Product $resourceProduct, ProductFactory $productFactory, Configurable $configurable ) { $this->resourceProduct = $resourceProduct; $this->productFactory = $productFactory; $this->configurable = $configurable; } /** * @param string $sku * @return float * @throws LocalizedException */ public function getProductDiscount(string $sku): float { if (!$sku) { throw new LocalizedException(__('Sku could not be empty')); } $productId = (int)$this->resourceProduct->getIdBySku($sku); $product = $this->getProductById($productId); if (!$product->getSpecialPrice()) { return 0.0; } return $product->getPrice() - $product->getSpecialPrice(); } /** * @param string $sku * @param string $attributeCode * @return string|array|bool * @throws NoSuchEntityException */ public function getProductAttributeValue(string $sku, string $attributeCode): string|array|bool { if (!$sku) { throw new NoSuchEntityException(__('Sku could not be empty')); } if (!$attributeCode) { throw new NoSuchEntityException(__('Attribute code could not be empty')); } $productId = (int)$this->resourceProduct->getIdBySku($sku); $product = $this->getProductById($productId); return $this->resourceProduct->getAttribute($attributeCode)->getFrontend()->getValue($product); } /** * @param int $productId * @return \Magento\Catalog\Model\Product * @throws LocalizedException */ public function getProductById(int $productId): \Magento\Catalog\Model\Product { $product = $this->productFactory->create(); $this->resourceProduct->load($product, $productId); if (!$product->getId()) { throw new LocalizedException(__('Product id not exist: %1', $productId)); } return $product; } /** * @param string $sku * @return string */ public function getProductParentSku(string $sku): string { $productId = (int)$this->resourceProduct->getIdBySku($sku); $parentIds = $this->configurable->getParentIdsByChild($productId); if (empty($parentIds)) { return $sku; } $parentId = reset($parentIds); $product = $this->productFactory->create(); $this->resourceProduct->load($product, $parentId); if (!$product->getId()) { return $sku; } return $product->getSku(); } /** * @param string $sku * @return string */ public function getProductName(string $sku): string { $productId = (int)$this->resourceProduct->getIdBySku($sku); $parentIds = $this->configurable->getParentIdsByChild($productId); if (!empty($parentIds)) { $productId = reset($parentIds); } $product = $this->productFactory->create(); $this->resourceProduct->load($product, $productId); return $product->getName(); } /** * @param string $sku * @return float */ public function getProductPrice(string $sku): float { $productId = (int)$this->resourceProduct->getIdBySku($sku); $product = $this->productFactory->create(); $this->resourceProduct->load($product, $productId); return (float)$product->getFinalPrice(); } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\ViewModel; use Exception; use GhostUnicorns\Ga4\Model\GetProductLayer; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\Block\ArgumentInterface; class ProductList implements ArgumentInterface { /** * @var GetProductLayer */ private $getProductLayer; /** * @var SerializerInterface */ private $serializer; /** * @param GetProductLayer $getProductLayer * @param SerializerInterface $serializer */ public function __construct( GetProductLayer $getProductLayer, SerializerInterface $serializer ) { $this->getProductLayer = $getProductLayer; $this->serializer = $serializer; } /** * @param string $sku * @param string $position * @param string $listName * @param string $listPosition * @return string */ public function getProductLayerInList(string $sku, string $position, string $listName, string $listPosition): string { try { $product = $this->getProductLayer->execute($sku); $product['position'] = $position; $product['list'] = $listName; $product['list_position'] = $listPosition; return $this->serializer->serialize($product); } catch (Exception $e) { unset($e); return ''; } } /** * @param string $sku * @return string */ public function getProductLayer(string $sku): string { try { return $this->serializer->serialize($this->getProductLayer->execute($sku)); } catch (Exception $e) { unset($e); return '""'; } } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model\Event; use Magento\Customer\Model\Session; class ReadCustomerLoginEvent { /** * @var Session */ private $session; /** * @param Session $session */ public function __construct( Session $session ) { $this->session = $session; } /** * @return string */ public function execute(): string { return $this->session->getData(GetCustomerLoginEvent::EVENT_NAME) ?: ''; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Framework\Locale\Resolver; class GetLanguage { /** * @var Resolver */ private $resolver; /** * @param Resolver $resolver */ public function __construct( Resolver $resolver ) { $this->resolver = $resolver; } /** * @return string */ public function execute(): string { return $this->resolver->getLocale(); } } <file_sep># Description This module adjust the GTM pushes to be compatible with the new GA4 ecommerce standards # Prerequisites Make sure you have Magento >= 2.4.5 or try install: `composer require magento/module-google-tag-manager` # Install `composer require ghost-unicorns/module-ga4` # How to configure Make sure that Google Analytics 4 through Google GTag is enabled `Stores -> Configuration -> Sales -> Google APIS -> Google GTag -> Google Analytics4 -> Enable -> Yes` Make sure that Google Analytics 4 is injected via GTM `Stores -> Configuration -> Sales -> Google APIS -> Google GTag -> Google Analytics4 -> Account type -> Google Tag Manager` Make sure that Google Analytics through Google Analytics standard is disabled `Stores -> Configuration -> Sales -> Google Analytics -> Enable -> No` # Customize You can create a plugin on the following file to change the products data: `GhostUnicorns\Ga4\Model\GetProductLayer` # Contribution Yes, of course you can contribute sending a pull request to propose improvements and fixes. <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Customer\Model\Context as ContextModel; use Magento\Customer\Model\Session; use Magento\Framework\App\Http\Context as Context; class IsCustomerLoggedIn { /** * @var Context */ private $context; /** * @var Session */ private $session; /** * @param Context $context * @param Session $session */ public function __construct( Context $context, Session $session ) { $this->context = $context; $this->session = $session; } /** * @return bool */ public function execute(): bool { if ($this->context->getValue(ContextModel::CONTEXT_AUTH)) { return true; } else if ($this->session->isLoggedIn()) { return true; } return false; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Checkout\Model\Session; use Magento\Framework\Exception\SessionException; class GetCartLayer { /** * @var GetCurrencyCode */ private $getCurrencyCode; /** * @var GetProductLayer */ private $getProductLayer; /** * @var Session */ protected $checkoutSession; /** * @param GetProductLayer $getProductLayer * @param GetCurrencyCode $getCurrencyCode * @param Session $checkoutSession */ public function __construct( GetProductLayer $getProductLayer, GetCurrencyCode $getCurrencyCode, Session $checkoutSession ) { $this->getProductLayer = $getProductLayer; $this->getCurrencyCode = $getCurrencyCode; $this->checkoutSession = $checkoutSession; } /** * @param bool $isMiniCart * @return array */ public function execute( bool $isMiniCart = false ): array { try { $quote = $this->getCheckoutSession()->getQuote(); } catch (\Exception $e) { unset($e); return []; } $cartProducts = $quote->getAllVisibleItems(); $cartTotal = $quote->getGrandTotal(); $products = []; foreach ($cartProducts as $cartProduct) { try { $products[] = $this->getProductLayer->execute( $cartProduct->getSku(), (float)$cartProduct->getQty(), (float)$cartProduct->getPriceInclTax(), (float)$cartProduct->getDiscountAmount() ); } catch (\Exception $e) { unset($e); } } return [ 'event' => 'view_cart', 'cart_type' => $isMiniCart ? 'mini_cart' : 'cart', 'ecommerce' => [ 'currency' => $this->getCurrencyCode->execute(), 'value' => (float)$cartTotal, 'items' => $products ] ]; } /** * @return Session * @throws SessionException */ private function getCheckoutSession(): Session { if (!$this->checkoutSession->isSessionExists()) { $this->checkoutSession->start(); } return $this->checkoutSession; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\ViewModel; use GhostUnicorns\Ga4\Model\Event\GetAllEvents; use GhostUnicorns\Ga4\Model\Event\ReadCustomerLoginEvent; use GhostUnicorns\Ga4\Model\Event\ReadCustomerLogoutEvent; use Magento\Framework\App\RequestInterface; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\Block\ArgumentInterface; class EventsLayer implements ArgumentInterface { /** * @var RequestInterface */ private $request; /** * @var SerializerInterface */ private $serializer; /** * @var GetAllEvents */ private $getAllEvents; /** * @var ReadCustomerLoginEvent */ private $readCustomerLoginEvent; /** * @param RequestInterface $request * @param SerializerInterface $serializer * @param GetAllEvents $getAllEvents * @param ReadCustomerLoginEvent $readCustomerLoginEvent */ public function __construct( RequestInterface $request, SerializerInterface $serializer, GetAllEvents $getAllEvents, ReadCustomerLoginEvent $readCustomerLoginEvent ) { $this->request = $request; $this->serializer = $serializer; $this->getAllEvents = $getAllEvents; $this->readCustomerLoginEvent = $readCustomerLoginEvent; } /** * @return array */ public function getLoginInfo(): array { if ($this->request->isXmlHttpRequest()) { return []; } $loginInfo = $this->readCustomerLoginEvent->execute(); if (!$loginInfo) { return []; } return $this->serializer->unserialize($loginInfo); } /** * @return array */ public function getEventsLayers(): array { if ($this->request->isXmlHttpRequest()) { return []; } return $this->getAllEvents->execute(); } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Exception; use Magento\Catalog\Model\Category; use Magento\Catalog\Model\CategoryFactory; use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ResourceModel\Category as ResourceCategory; use Magento\Catalog\Model\ResourceModel\Product as ResourceProduct; use Magento\Catalog\Model\Session; use Magento\Framework\App\RequestInterface; use Magento\Framework\Exception\LocalizedException; class CategoryManager { /** * @var Session */ private $catalogSession; /** * @var CategoryFactory */ private $categoryFactory; /** * @var ResourceCategory */ private $resourceCategory; /** * @var ProductFactory */ private $productFactory; /** * @var ResourceProduct */ private $resourceProduct; /** * @var RequestInterface */ private $request; /** * @var GetProductFromSession */ private $getProductFromSession; /** * @param Session $catalogSession * @param CategoryFactory $categoryFactory * @param ResourceCategory $resourceCategory * @param ProductFactory $productFactory * @param ResourceProduct $resourceProduct * @param RequestInterface $request * @param GetProductFromSession $getProductFromSession */ public function __construct( Session $catalogSession, CategoryFactory $categoryFactory, ResourceCategory $resourceCategory, ProductFactory $productFactory, ResourceProduct $resourceProduct, RequestInterface $request, GetProductFromSession $getProductFromSession ) { $this->catalogSession = $catalogSession; $this->categoryFactory = $categoryFactory; $this->resourceCategory = $resourceCategory; $this->productFactory = $productFactory; $this->resourceProduct = $resourceProduct; $this->request = $request; $this->getProductFromSession = $getProductFromSession; } /** * @param string $sku * @return Category * @throws Exception */ public function getCurrentCategory(string $sku = ''): Category { return $this->getCategoryByProductSku($sku); // if ($sku !== '') { // return $this->getCategoryByProductSku($sku); // } // switch ($this->request->getControllerName()) { // case GetPageType::CONTROLLER_CATEGORY: // $currentCategoryId = $this->catalogSession->getData('last_viewed_category_id'); // $category = $this->categoryFactory->create(); // $this->resourceCategory->load($category, $currentCategoryId); // return $category; // case GetPageType::CONTROLLER_PRODUCT: // $product = $this->getProductFromSession->execute(); // return $this->getCategoryByProductSku($product->getSku()); // default: // throw new Exception('No category found'); // } } /** * @throws LocalizedException */ private function getCategoryByProductSku(string $sku): Category { $product = $this->productFactory->create(); $productId = $this->resourceProduct->getIdBySku($sku); $this->resourceProduct->load($product, $productId); $categories = $product->getCategoryCollection(); $categoriesFirst = $categories->getFirstItem(); $categoryId = (int)$categoriesFirst->getId(); try { return $this->getCategoryByCategoryId($categoryId); } catch (LocalizedException $e) { unset($e); throw new LocalizedException(__('Product with sku %1 has no category', $sku)); } } /** * @throws LocalizedException */ private function getCategoryByCategoryId(int $categoryId): Category { $category = $this->categoryFactory->create(); $this->resourceCategory->load($category, $categoryId); if (!$category->getId()) { throw new LocalizedException(__('Category with id %1 not found', $categoryId)); } return $category; } /** * @return string */ public function getCurrentArea(): string { return match ($this->request->getControllerName()) { GetPageType::CONTROLLER_HOME => 'home', GetPageType::CONTROLLER_RESULT => 'search', default => '', }; } /** * @param string $sku * @param int $level * @return string */ public function getCategoryLevel(int $level, string $sku = ''): string { try { $currentCategory = $this->getCurrentCategory($sku); } catch (Exception $e) { unset($e); return $this->getCurrentArea(); } $categoryTree = $currentCategory->getParentCategories(); if (!is_array($categoryTree)) { return ''; } return $this->getCategoryFromTreeByLevel($categoryTree, $level); } /** * @param string $sku * @return string */ public function getCategoryLevel1(string $sku = ''): string { return $this->getCategoryLevel(0, $sku); } /** * @param string $sku * @return string */ public function getCategoryLevel2(string $sku = ''): string { return $this->getCategoryLevel(1, $sku); } /** * @param string $sku * @return string */ public function getCategoryLevel3(string $sku = ''): string { return $this->getCategoryLevel(2, $sku); } /** * @param string $sku * @return string */ public function getCategoryLevel4(string $sku = ''): string { return $this->getCategoryLevel(3, $sku); } /** * @param string $sku * @return string */ public function getCategoryLevel5(string $sku = ''): string { return $this->getCategoryLevel(4, $sku); } /** * @param $categoryTree * @param int $categoryLevel * @return string */ public function getCategoryFromTreeByLevel($categoryTree, int $categoryLevel): string { $categoryCount = count($categoryTree); if ($categoryCount >= $categoryLevel) { $i = 0; $noName = false; foreach ($categoryTree as $categoryItem) { $category = $categoryItem; if ($categoryLevel == $i) { break; } $i++; if (count($categoryTree) === $i) { $noName = true; } } if ($noName) { return ''; } return $category->getName(); } return ''; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\ViewModel; use GhostUnicorns\Ga4\Model\GetCartLayer; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\Block\ArgumentInterface; class CartLayer implements ArgumentInterface { /** * @var SerializerInterface */ private $serializer; /** * @var GetCartLayer */ private $getCartLayer; /** * @param SerializerInterface $serializer * @param GetCartLayer $getCartLayer */ public function __construct( SerializerInterface $serializer, GetCartLayer $getCartLayer ) { $this->serializer = $serializer; $this->getCartLayer = $getCartLayer; } /** * @return string */ public function getCartLayers(): string { return $this->serializer->serialize($this->getCartLayer->execute()); } } <file_sep>define(['jquery'], function ($) { 'use strict'; return function (widget) { $.widget('mage.SwatchRenderer', widget, { _UpdatePrice: function () { this._super(); (function (callback) {})((function (context) { if (context && 'undefined' !== typeof context.getProduct()) { var simple = {}, key = context.getProduct().toString(); if (GA4.configurableProducts.hasOwnProperty(key)) { simple = GA4.configurableProducts[key]; } return function () { if(!Object.keys(simple).length){ return; } dataLayer.push({ 'event': 'view_item', 'ecommerce': { 'currency': GA4.currencyCode, 'items': [simple] } }); } } else { return function () { dataLayer.push({'event': 'resets_swatch_selection'}); } } })(this)); } }); return $.mage.SwatchRenderer; } }); <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Framework\App\RequestInterface; class GetPageType { const CONTROLLER_HOME = 'index'; const CONTROLLER_CART = 'cart'; const CONTROLLER_CATEGORY = 'category'; const CONTROLLER_PRODUCT = 'product'; const CONTROLLER_RESULT = 'result'; /** * @var RequestInterface */ private $request; /** * @param RequestInterface $request */ public function __construct( RequestInterface $request ) { $this->request = $request; } /** * @return string */ public function execute(): string { $controllerName = $this->request->getControllerName(); return match ($controllerName) { self::CONTROLLER_HOME => 'home', self::CONTROLLER_CART => 'cart', self::CONTROLLER_CATEGORY => 'category', self::CONTROLLER_PRODUCT => 'product', self::CONTROLLER_RESULT => 'searchresults', default => 'other', }; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Observer\Customer; use GhostUnicorns\Ga4\Model\Event\GetCustomerRegisterEvent; use Magento\Customer\Model\Session; use Magento\Customer\Model\SessionFactory; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Serialize\SerializerInterface; class Register implements ObserverInterface { /** * @var Session */ protected $session; /** * @var SerializerInterface */ private $serializer; /** * @param SessionFactory $sessionFactory * @param SerializerInterface $serializer */ public function __construct ( SessionFactory $sessionFactory, SerializerInterface $serializer ) { $this->session = $sessionFactory->create(); $this->serializer = $serializer; } /** * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { if ($customer = $observer->getCustomer()) { $this->session->setData( GetCustomerRegisterEvent::EVENT_NAME, $this->serializer->serialize([ 'event' => 'new_registration', 'new_registration_result' => 'OK', 'user_email_md5' => hash('md5', $customer->getEmail()), 'user_email_sha256' => hash('sha256', $customer->getEmail()) ]) ); } } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Plugin; use Exception; use GhostUnicorns\Ga4\Model\GetProductLayer; use Magento\Checkout\Model\Session; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Exception\SessionException; use Magento\Framework\Serialize\SerializerInterface; use Magento\GoogleTagManager\Block\ListJson; use Magento\Quote\Model\Quote\Item; class GetCartContentPlugin { /** * @var Session */ private $checkoutSession; /** * @var SerializerInterface */ private $serializer; /** * @var GetProductLayer */ private $getProductLayer; /** * @param Session $checkoutSession * @param SerializerInterface $serializer * @param GetProductLayer $getProductLayer */ public function __construct( Session $checkoutSession, SerializerInterface $serializer, GetProductLayer $getProductLayer ) { $this->checkoutSession = $checkoutSession; $this->serializer = $serializer; $this->getProductLayer = $getProductLayer; } /** * @param ListJson $subject * @param string $result * @return string * @throws LocalizedException * @throws NoSuchEntityException * @throws SessionException */ public function afterGetCartContent(ListJson $subject, string $result): string { unset($result); $cart = []; $quote = $this->getCheckoutSession()->getQuote(); foreach ($quote->getAllVisibleItems() as $item) { $cart[]= $this->formatProduct($item); } return $this->serializer->serialize($cart); } /** * @param ListJson $subject * @param string $result * @return string * @throws LocalizedException * @throws NoSuchEntityException * @throws SessionException */ public function afterGetCartContentForUpdate(ListJson $subject, string $result): string { unset($result); $cart = []; $quote = $this->getCheckoutSession()->getQuote(); foreach ($quote->getAllVisibleItems() as $item) { $cart[$item->getSku()]= $this->formatProduct($item); } return $this->serializer->serialize($cart); } /** * @return Session * @throws SessionException */ private function getCheckoutSession() { if (!$this->checkoutSession->isSessionExists()) { $this->checkoutSession->start(); } return $this->checkoutSession; } /** * @param Item $item * @return array */ private function formatProduct($item): array { $sku = $item->getSku(); try { $product = $this->getProductLayer->execute( $sku, (float)$item->getQty(), (float)$item->getPrice(), (float)$item->getDiscountAmount() ); } catch (Exception $e) { unset($e); $product = []; } return $product; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\ViewModel; use GhostUnicorns\Ga4\Model\CategoryManager; use GhostUnicorns\Ga4\Model\GetCurrencyCode; use GhostUnicorns\Ga4\Model\GetProductFromSession; use GhostUnicorns\Ga4\Model\GetProductLayer; use GhostUnicorns\Ga4\Model\ProductManager; use Magento\Bundle\Model\Product\Type as Simple; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\Block\ArgumentInterface; use Magento\Store\Model\StoreManagerInterface; class Header implements ArgumentInterface { /** * @var StoreManagerInterface */ private $storeManager; /** * @var SerializerInterface */ private $serializer; /** * @var GetProductFromSession */ private $getProductFromSession; /** * @var Collection */ private $optionCollection; /** * @var ProductManager */ private $productManager; /** * @var CategoryManager */ private $categoryManager; /** * @var GetCurrencyCode */ private $getCurrencyCode; /** * @var GetProductLayer */ private $getProductLayer; /** * @param StoreManagerInterface $storeManager * @param SerializerInterface $serializer * @param GetProductFromSession $getProductFromSession * @param Collection $optionCollection * @param ProductManager $productManager * @param CategoryManager $categoryManager * @param GetCurrencyCode $getCurrencyCode * @param GetProductLayer $getProductLayer */ public function __construct ( StoreManagerInterface $storeManager, SerializerInterface $serializer, GetProductFromSession $getProductFromSession, Collection $optionCollection, ProductManager $productManager, CategoryManager $categoryManager, GetCurrencyCode $getCurrencyCode, GetProductLayer $getProductLayer ) { $this->storeManager = $storeManager; $this->serializer = $serializer; $this->getProductFromSession = $getProductFromSession; $this->optionCollection = $optionCollection; $this->productManager = $productManager; $this->categoryManager = $categoryManager; $this->getCurrencyCode = $getCurrencyCode; $this->getProductLayer = $getProductLayer; } /** * @return string */ public function getStoreName(): string { try { return $this->serializer->serialize($this->storeManager->getStore()->getName()); } catch (\Exception $e) { unset($e); return ''; } } /** * @return string */ public function getCurrentCurrencyCode(): string { return $this->getCurrencyCode->execute(); } /** * @return string */ public function getSuper(): string { $super = []; try { $product = $this->getProductFromSession->execute(); if (Configurable::TYPE_CODE == $product->getTypeId()) { $attributes = $product->getTypeInstance()->getConfigurableAttributes($product); foreach($attributes as $attribute) { $object = $attribute->getProductAttribute(); $super[] = [ 'id' => $object->getAttributeId(), 'label' => $attribute->getFrontendLabel(), 'code' => $object->getAttributeCode(), 'options' => $this->getAttributeOptions($attribute) ]; } } } catch (\Exception $e) { unset($e); return '{}'; } return $this->serializer->serialize($super); } /** * @param string $sku * @param string $attributeCode * @return string */ public function getProductAttribute(string $sku, string $attributeCode): string { try { $brand = $this->productManager->getProductAttributeValue($sku, $attributeCode); return $brand ? (string)$brand : ''; } catch (\Exception $e) { unset($e); return ''; } } /** * @param string $sku * @param int $level * @return string */ public function getItemCategory(string $sku, int $level): string { return $this->categoryManager->getCategoryLevel($level, $sku); } /** * @return string */ public function getConfigurableSimples(): string { $simples = []; try { $product = $this->getProductFromSession->execute(); if (Configurable::TYPE_CODE == $product->getTypeId()) { foreach ($product->getTypeInstance()->getUsedProducts($product) as $simple) { $simples[$simple->getId()] = $this->getProductLayer->execute($simple->getSku()); } } } catch (\Exception $e) { unset($e); return '{}'; } return $this->serializer->serialize($simples); } /** * @return string */ public function getBundle(): string { $bundles = []; $options = []; try { $product = $this->getProductFromSession->execute(); if (Simple::TYPE_CODE === $product->getTypeId()) { foreach ($product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product),$product) as $bundle) { $bundles[$bundle->getOptionId()][$bundle->getId()] = $this->getProductLayer->execute($bundle->getSku()); } foreach ($product->getTypeInstance()->getOptionsCollection($product) as $option) { $options[$option->getOptionId()] = [ 'option_title' => $option->getDefaultTitle(), 'option_type' => $option->getType() ]; } } } catch (\Exception $e) { unset($e); return '{}'; } return $this->serializer->serialize([ 'bundles' => $bundles, 'options' => $options ]); } /** * @param mixed $attribute * @return array */ private function getAttributeOptions(mixed $attribute): array { $options = []; foreach ($attribute->getOptions() as $option) { $options[] = $option; } try { foreach ($options as &$option) { $this->optionCollection->clear(); $this->optionCollection->getSelect()->reset(\Zend_Db_Select::WHERE); $this->optionCollection->getSelect()->where('main_table.option_id IN (?)',[$option['value_index']]); $this->optionCollection->getSelect()->group('main_table.option_id'); $option['admin_label'] = $this->optionCollection->getFirstitem()->getValue(); } unset($option); } catch (\Exception $e) { unset($e); return []; } return $options; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Controller\Events; use GhostUnicorns\Ga4\Model\Event\GetAllEvents; use Magento\Framework\App\ActionInterface; use Magento\Framework\Controller\Result\JsonFactory; class Index implements ActionInterface { /** * @var JsonFactory */ protected $resultJsonFactory; /** * @var GetAllEvents */ private $getAllEvents; /** * @param JsonFactory $resultJsonFactory * @param GetAllEvents $getAllEvents */ public function __construct ( JsonFactory $resultJsonFactory, GetAllEvents $getAllEvents ) { $this->resultJsonFactory = $resultJsonFactory; $this->getAllEvents = $getAllEvents; } /** * @see \Magento\Framework\App\ActionInterface::execute() */ public function execute() { $events = $this->getAllEvents->execute(); return $this->resultJsonFactory->create()->setData([ 'events' => $events ]); } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Customer\Model\Session; class GetCustomerEmailMd5 { /** * @var Session */ private $session; /** * @param Session $session */ public function __construct( Session $session, ) { $this->session = $session; } /** * @return string */ public function execute(): string { if (!$this->session->isLoggedIn()) { return ''; } $customer = $this->session->getCustomer(); $email = $customer->getEmail(); return hash('md5', $email); } } <file_sep>define([ 'jquery', 'Magento_Checkout/js/view/payment', 'Magento_Checkout/js/model/totals', 'Magento_Checkout/js/model/quote' ], function ($, payment, totals, quote) { 'use strict'; function notify(cart, stepIndex, stepDescription) { var i = 0, product, subtotal = parseFloat(totals.totals()['subtotal']), dlUpdate = { 'event': stepDescription, 'ecommerce': { 'currency': window.dlCurrencyCode, 'value': subtotal, 'items': [ ] } }; if (stepIndex === '2') { var shippingTier = quote.shippingMethod().method_code; if (!shippingTier) { return false; } dlUpdate.ecommerce.shipping_tier = shippingTier; } if (stepIndex === '3') { var paymentMethod = quote.paymentMethod().method; if (!paymentMethod) { return false; } dlUpdate.ecommerce.payment_type = paymentMethod; } for (i; i < cart.length; i++) { product = cart[i]; dlUpdate.ecommerce.items.push({ 'item_id': product.item_id, 'item_name': product.name, 'price': product.price, 'quantity': product.qty, 'item_brand': product.manufacturer, 'item_variant': product.item_variant, 'item_size': product.item_size, 'item_category': product.item_category, 'item_category2': product.item_category2, 'item_category3': product.item_category3, 'item_category4': product.item_category4, 'item_category5': product.item_category5 }); } window.dataLayer.push(dlUpdate); return true; } return function (data) { var events = { begin: { description: 'begin_checkout', index: '1' }, shipping: { description: 'add_shipping_info', index: '2' }, payment: { description: 'add_payment_info', index: '3' } }, subscriptionShipping = payment.prototype.isVisible.subscribe(function (value) { if (value && window.dataLayer) { if (notify(data.cart, events.shipping.index, events.shipping.description)) { subscriptionShipping.dispose(); } } }), subscriptionPayment = quote.paymentMethod.subscribe(function (value) { if (value && window.dataLayer) { if (notify(data.cart, events.payment.index, events.payment.description)) { subscriptionPayment.dispose(); } } }, null, 'change'); window.dataLayer ? notify(data.cart, events.begin.index, events.begin.description) : $(document).on( 'ga:inited', notify.bind(this, data.cart, events.begin.index, events.begin.description) ); }; }); <file_sep><?php namespace GhostUnicorns\Ga4\Plugin; use GhostUnicorns\Ga4\Model\GetCurrencyCode; use GhostUnicorns\Ga4\Model\GetProductLayer; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\GoogleTagManager\Block\GtagGa; use Magento\Sales\Model\OrderRepository; class CheckoutSuccessPlugin { /** * @var GetProductLayer */ private $getProductLayer; /** * @var GetCurrencyCode */ private $getCurrencyCode; /** * @var OrderRepository */ private $orderRepository; /** * @var SearchCriteriaBuilder */ private $searchCriteriaBuilder; /** * @param GetProductLayer $getProductLayer * @param GetCurrencyCode $getCurrencyCode * @param OrderRepository $orderRepository * @param SearchCriteriaBuilder $searchCriteriaBuilder */ public function __construct ( GetProductLayer $getProductLayer, GetCurrencyCode $getCurrencyCode, OrderRepository $orderRepository, SearchCriteriaBuilder $searchCriteriaBuilder ) { $this->getProductLayer = $getProductLayer; $this->getCurrencyCode = $getCurrencyCode; $this->orderRepository = $orderRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; } /** * @param GtagGa $subject * @param array $result * @return array * @throws LocalizedException * @throws NoSuchEntityException */ public function afterGetOrdersDataArray(GtagGa $subject, array $result): array { unset($result); $result = []; $orderIds = $subject->getOrderIds(); if (empty($orderIds) || !is_array($orderIds)) { return $result; } $this->searchCriteriaBuilder->addFilter( 'entity_id', $orderIds, 'in' ); $collection = $this->orderRepository->getList($this->searchCriteriaBuilder->create()); /** @var \Magento\Sales\Model\Order $order */ foreach ($collection->getItems() as $order) { $products = []; /** @var \Magento\Sales\Model\Order\Item $item*/ foreach ($order->getAllVisibleItems() as $item) { $products[] = $this->getProductLayer->execute($item->getSku(), $item->getQtyOrdered(), $item->getPriceInclTax(), $item->getDiscountAmount()); } $result[] = [ 'event' => 'purchase', 'ecommerce' => [ 'currency' => $this->getCurrencyCode->execute(), 'value' => (float)$order->getGrandTotal(), 'tax' => (float)$order->getTaxAmount(), 'shipping' => (float)$order->getShippingInclTax(), 'transaction_id' => $order->getIncrementId(), 'coupon' => (string)$order->getCouponCode(), 'payment_type' => $order->getPayment()->getMethod(), 'shipping_tier' => $order->getShippingMethod(), 'items' => $products ] ]; } return $result; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductFactory; use Magento\Catalog\Model\ResourceModel\Product as ResourceProduct; use Magento\Catalog\Model\Session as CatalogSession; use Magento\Framework\Exception\LocalizedException; class GetProductFromSession { /** * @var CatalogSession */ private $catalogSession; /** * @var ProductFactory */ private $productFactory; /** * @var ResourceProduct */ private $resourceProduct; /** * @param CatalogSession $catalogSession * @param ProductFactory $productFactory * @param ResourceProduct $resourceProduct */ public function __construct( CatalogSession $catalogSession, ProductFactory $productFactory, ResourceProduct $resourceProduct ) { $this->catalogSession = $catalogSession; $this->productFactory = $productFactory; $this->resourceProduct = $resourceProduct; } /** * @return Product * @throws LocalizedException */ public function execute(): Product { $productId = $this->catalogSession->getData('last_viewed_product_id'); $product = $this->productFactory->create(); $this->resourceProduct->load($product, $productId); if (!$product->getId()) { throw new LocalizedException(__('No product found ')); } return $product; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Model; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; class GetProductLayer { const DEFAULT_VALUE = -99999.99; /** * @var ProductManager */ private $productManager; /** * @var CategoryManager */ private $categoryManager; /** * @var GetCurrencyCode */ private $getCurrencyCode; /** * @param ProductManager $productManager * @param CategoryManager $categoryManager * @param GetCurrencyCode $getCurrencyCode */ public function __construct( ProductManager $productManager, CategoryManager $categoryManager, GetCurrencyCode $getCurrencyCode ) { $this->productManager = $productManager; $this->categoryManager = $categoryManager; $this->getCurrencyCode = $getCurrencyCode; } /** * @param string $sku * @param float $quantity * @param float $price * @param float $discount * @return array * @throws LocalizedException * @throws NoSuchEntityException */ public function execute( string $sku, float $quantity = self::DEFAULT_VALUE, float $price = self::DEFAULT_VALUE, float $discount = self::DEFAULT_VALUE ): array { $data = []; $parentSku = $this->productManager->getProductParentSku($sku); $category1 = $this->categoryManager->getCategoryLevel1($parentSku); $category2 = $this->categoryManager->getCategoryLevel2($parentSku); $category3 = $this->categoryManager->getCategoryLevel3($parentSku); $category4 = $this->categoryManager->getCategoryLevel4($parentSku); $category5 = $this->categoryManager->getCategoryLevel5($parentSku); $brand = $this->productManager->getProductAttributeValue($sku, 'manufacturer'); $variant = $this->productManager->getProductAttributeValue($sku, 'swatch_color'); $size = $this->productManager->getProductAttributeValue($sku, 'size'); $data['item_id'] = (string)$parentSku; $data['item_name'] = (string)$this->productManager->getProductName($parentSku); $data['currency'] = (string)$this->getCurrencyCode->execute(); $data['price'] = $price !== self::DEFAULT_VALUE ? (float)$price : (float)$this->productManager->getProductPrice($sku); $data['item_brand'] = (string)$brand; $data['item_category'] = (string)$category1; $data['item_category2'] = (string)$category2; $data['item_category3'] = (string)$category3; $data['item_category4'] = (string)$category4; $data['item_category5'] = (string)$category5; $data['item_variant'] = (string)$variant; $data['item_size'] = (string)$size; if ($quantity > 0) { $data['quantity'] = (float)$quantity; } if ($discount === self::DEFAULT_VALUE) { $discount = $this->productManager->getProductDiscount($sku); } if ($discount !== self::DEFAULT_VALUE && $discount !== 0.0) { $data['discount'] = (float)$discount; } return $data; } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\Observer; use GhostUnicorns\Ga4\Model\Event\GetNewsletterSubscriptionEvent; use Magento\Customer\Model\Session; use Magento\Customer\Model\SessionFactory; use Magento\Framework\App\RequestInterface; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Serialize\SerializerInterface; class Newsletter implements ObserverInterface { /** * @var Session */ protected $session; /** * @var RequestInterface */ protected $request; /** * @var SerializerInterface */ private $serializer; /** * @param SessionFactory $sessionFactory * @param RequestInterface $request * @param SerializerInterface $serializer */ public function __construct ( SessionFactory $sessionFactory, RequestInterface $request, SerializerInterface $serializer ) { $this->session = $sessionFactory->create(); $this->request = $request; $this->serializer = $serializer; } /** * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { $isSubscribed = $this->request->getParam('is_subscribed'); if (is_null($isSubscribed)) { $isSubscribed = true; } else { $isSubscribed = 1 === (int) $isSubscribed; } $email = $this->request->getParam('email'); if (is_null($email)) { return; } $this->session->setData( GetNewsletterSubscriptionEvent::EVENT_NAME, $this->serializer->serialize([ 'event' => 'newsletter_subscription', 'newsletter_subscription_result' => $isSubscribed ? 'OK' : 'KO', 'user_email_md5' => hash('md5', $email), 'user_email_sha256'=> hash('sha256', $email) ]) ); } } <file_sep><?php declare(strict_types=1); namespace GhostUnicorns\Ga4\ViewModel; use GhostUnicorns\Ga4\Model\CategoryManager; use GhostUnicorns\Ga4\Model\GetCustomerEmailMd5; use GhostUnicorns\Ga4\Model\GetCustomerEmailSha256; use GhostUnicorns\Ga4\Model\GetLanguage; use GhostUnicorns\Ga4\Model\GetPageType; use GhostUnicorns\Ga4\Model\GetSiteArea; use GhostUnicorns\Ga4\Model\IsCustomerLoggedIn; use Magento\Framework\View\Element\Block\ArgumentInterface; class GenericLayer implements ArgumentInterface { const STATUS_LOGGED = 'logged'; const STATUS_NOT_LOGGED = 'not_logged'; /** * @var CategoryManager */ private $categoryManager; /** * @var IsCustomerLoggedIn */ private $isCustomerLoggedIn; /** * @var GetPageType */ private $getPageType; /** * @var GetSiteArea */ private $getSiteArea; /** * @var GetLanguage */ private $getCurrentLanguage; /** * @var GetCustomerEmailMd5 */ private $customerEmailMd5; /** * @var GetCustomerEmailSha256 */ private $customerEmailSha256; /** * @param CategoryManager $categoryManager * @param IsCustomerLoggedIn $isCustomerLoggedIn * @param GetPageType $getPageType * @param GetSiteArea $getSiteArea * @param GetLanguage $getCurrentLanguage * @param GetCustomerEmailMd5 $customerEmailMd5 * @param GetCustomerEmailSha256 $customerEmailSha256 */ public function __construct( CategoryManager $categoryManager, IsCustomerLoggedIn $isCustomerLoggedIn, GetPageType $getPageType, GetSiteArea $getSiteArea, GetLanguage $getCurrentLanguage, GetCustomerEmailMd5 $customerEmailMd5, GetCustomerEmailSha256 $customerEmailSha256 ) { $this->categoryManager = $categoryManager; $this->isCustomerLoggedIn = $isCustomerLoggedIn; $this->getPageType = $getPageType; $this->getSiteArea = $getSiteArea; $this->getCurrentLanguage = $getCurrentLanguage; $this->customerEmailMd5 = $customerEmailMd5; $this->customerEmailSha256 = $customerEmailSha256; } /** * @param string $value * @return string */ private function format(string $value): string { $value = strtolower($value); $value = str_replace(' ', '_', $value); return preg_replace('/[^\w-]/', '', $value); } /** * @return string */ public function getLoginStatus(): string { return $this->isCustomerLoggedIn->execute() ? self::STATUS_LOGGED : self::STATUS_NOT_LOGGED; } /** * @return string */ public function getPageType(): string { return $this->format($this->getPageType->execute()); } /** * @return string */ public function getSiteArea(): string { return $this->format($this->getSiteArea->execute()); } /** * @return string */ public function getEcommerceArea(): string { return $this->format($this->categoryManager->getCategoryLevel1()); } /** * @return string */ public function getLanguage(): string { return $this->format($this->getCurrentLanguage->execute()); } /** * @return string */ public function getUserEmailMd5(): string { return $this->format($this->customerEmailMd5->execute()); } /** * @return string */ public function getUserEmailSha256(): string { return $this->format($this->customerEmailSha256->execute()); } }
f3b697567fe52fcdcb2f9ce0285913a9d5075047
[ "JavaScript", "Markdown", "PHP" ]
33
PHP
ghostunicorns/module-ga4
7efd7da0cd9ad1fc4bab80069ac45cbc13bdb4d8
095b941dc8be9dbaa5f09d52fb4cd98c1fcf7d4f
refs/heads/master
<repo_name>los123/MeBay<file_sep>/app/models/ad.rb class Ad < ActiveRecord::Base #VALIDATIONS: validates :price, :numericality => true validates :description, presence: true end <file_sep>/app/controllers/ads_controller.rb class AdsController < ApplicationController before_filter :check_logged_in, :only => [:edit, :destroy] def show @ad = Ad.find(params[:id]) end def stats @seller = Seller.find(params[:id]) end def index @ads = Ad.find(:all) end def new @ad = Ad.new end def create @ad=Ad.new(params[:ad]) if @ad.save redirect_to "/ads/#{@ad.id}" else render :template => "ads/new" end end def edit @ad=Ad.find(params[:id]) #logger.debug "The object is #{@ad}" #RAILS_DEFAULT_LOGGER.debug @ad #puts @ad.inspect end def update @ad=Ad.find(params[:id]) if @ad.update_attributes(params[:ad]) redirect_to ad_path(@ad) else render :template=>"/ads/edit" end #redirect_to "/ads/#{@ad.id}" end def delete @ad=Ad.find(params[:id]) @ad.destroy redirect_to '/ads' end end private def check_logged_in authenticate_or_request_with_http_basic("Ads") do |username, password| username == "admin" && password == "<PASSWORD>" end end # notes for above: # 1. def show - this is a controller 'method' with a name that matches the name of # the action 'show' (it also matches entry for show in in routes.rb # 2. @ad - query from the database (as requested in URL) is stored in the memory # and assigned to a variable called @ad. Actually here is the important part - how # exactly Rails read the record from the database? tha data from the database is # concerted into an object. That object is stored in the memory and controller # assigns it the name @ad # 3. Ad.find - method used to get information from the database.
98bd2168465d6ca736fcd83627c6a1c2b27a7021
[ "Ruby" ]
2
Ruby
los123/MeBay
a25009bfee1595de6f6c81b3b58a45278603e285
706d067e32b20085aa24e7b06a854f94b2c6eb73
refs/heads/master
<file_sep>package mx.com.beo.api; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import mx.com.beo.exceptions.HeaderNotFoundException; import mx.com.beo.util.Constantes; import mx.com.beo.util.HeadersParser; import mx.com.beo.util.Operaciones; import mx.com.beo.util.Urls; import mx.com.beo.util.UtilidadesRest; @RestController @RequestMapping(value = "/") public class AppControlador { private UtilidadesRest utilidadesRest = new UtilidadesRest(); private static final Logger LOGGER = LoggerFactory.getLogger(AppControlador.class); @SuppressWarnings("unchecked") @RequestMapping(value = "/cambioContrasena", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> cambioContrasena(RequestEntity<Object> request) { LOGGER.info(Constantes.LOG_ENDPOINT_CAMBIO_CONTRASENA); Set<Entry<String, Object>> entries = null; HeadersParser headersParser = new HeadersParser(); Map<String, Object> mapaHeader = null; Map<String, Object> sendRequestBody = null; try { sendRequestBody = (Map<String, Object>) request.getBody(); // ValidaHeaders mapaHeader = headersParser.validaHeaders(request); entries = mapaHeader.entrySet(); } catch (HeaderNotFoundException headerNotFoundException) { LOGGER.error(headerNotFoundException.getMessage()); Map<String, Object> responseError = new HashMap<>(); responseError.put(Constantes.RESPONSE_STATUS, 400); responseError.put(Constantes.RESPONSE_ERROR, headerNotFoundException.getMessage()); return new ResponseEntity<>(responseError, HttpStatus.OK); } catch (Exception e) { LOGGER.error(Constantes.EXCEPTION_HEADERS, e.toString()); Map<String, Object> responseError = new HashMap<>(); responseError.put(Constantes.RESPONSE_STATUS, 400); responseError.put(Constantes.RESPONSE_ERROR, e.getMessage()); return new ResponseEntity<>(responseError, HttpStatus.OK); } for (Entry<String, Object> e : entries) { sendRequestBody.put(e.getKey(), e.getValue()); } String url = Urls.CONTRASENA.getPath(); LOGGER.info(Constantes.LOG_ENDPOINT_CONTRASENA, url); Set<MediaType> mediaTypeValidos = new HashSet<>(); mediaTypeValidos.add(MediaType.APPLICATION_JSON); mediaTypeValidos.add(MediaType.APPLICATION_JSON_UTF8); LOGGER.debug(Constantes.LOG_OK); sendRequestBody.remove("cliente"); LOGGER.info("CambioContraseña--------- {}" , sendRequestBody); return utilidadesRest.enviarPeticion(url, HttpMethod.POST, mediaTypeValidos, null, sendRequestBody, Urls.URL_BITACORA.getPath(), request.getHeaders()); } @RequestMapping(value = "/accesoCliente", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> accesoCliente(RequestEntity<Object> request) { LOGGER.info(Constantes.LOG_ENDPOINT_ACCESO_CLIENTES); LOGGER.debug(Constantes.HEADERS_AUTENTICACION , request.getHeaders()); Map<String, Object> mapaHeader = null; Set<Entry<String, Object>> entries = null; HeadersParser headersParser = new HeadersParser(); Map<String, Object> sendRequestBody = new HashMap<>(); Map<String, Object> mapaHeadersAValidar = new HashMap<>(); Map<String, Object> ticket = new HashMap<>(); Map<String, Object> headers = new HashMap<>(); Map<String, Object> consultaDatosBasicos = new HashMap<>(); Map<String, Object> consultaServicioContratado = new HashMap<>(); Map<String, Object> perfil = new HashMap<>(); Map<String, Object> perfilInterno= new HashMap<>(); Map<String, Object> mapGeneral = new HashMap<>(); Map<String, Object> mapParameters = new HashMap<>(); Map<String, String> mapHeaders = request.getHeaders().toSingleValueMap(); ticket.put("iv-user", "id_user"); ticket.put("cookie", "id_creds"); mapaHeadersAValidar.put("ticket", ticket); mapaHeadersAValidar.put("tipocanal", Constantes.CANAL); mapaHeadersAValidar.put("iv-user", "idPersona"); mapaHeadersAValidar.put("numero-cliente", "cliente"); mapaHeadersAValidar.put("contrato-aceptado", "contrato"); mapaHeadersAValidar.put("nombre-completo", "nombreUsuario"); mapaHeadersAValidar.put("fechaultimoacceso", "fechaUltimoAcceso"); mapaHeadersAValidar.put("mail", "mailCliente"); try { // ValidaHeaders mapaHeader = headersParser.validaHeaders(mapaHeadersAValidar, request); mapaHeader.remove("contrato"); entries = mapaHeader.entrySet(); } catch (HeaderNotFoundException headerNotFoundException) { LOGGER.error(headerNotFoundException.getMessage()); Map<String, Object> responseError = new HashMap<>(); responseError.put(Constantes.RESPONSE_STATUS, 400); responseError.put(Constantes.RESPONSE_ERROR, headerNotFoundException.getMessage()); return new ResponseEntity<>(responseError, HttpStatus.OK); } catch (Exception e) { LOGGER.error(Constantes.EXCEPTION_HEADERS , e.toString()); Map<String, Object> responseError = new HashMap<>(); responseError.put(Constantes.RESPONSE_STATUS, 400); responseError.put(Constantes.RESPONSE_ERROR, e.getMessage()); return new ResponseEntity<>(responseError, HttpStatus.OK); } for (Entry<String, Object> e : entries) { sendRequestBody.put(e.getKey(), e.getValue()); } Map<String, Object> envioNotificacionBody = new HashMap<>(); Map<String, Object> consultaServiciosContratadosBody = new HashMap<>(); envioNotificacionBody.put(Constantes.IDPERSONA, sendRequestBody.get(Constantes.IDPERSONA)); envioNotificacionBody.put(Constantes.TICKET, sendRequestBody.get(Constantes.TICKET)); envioNotificacionBody.put("tipoMensaje", "texto"); envioNotificacionBody.put("tipoNotificacion", "notificacion"); envioNotificacionBody.put("to", "<EMAIL>"); mapParameters.put("key", "1234"); envioNotificacionBody.put("mapParameters", mapParameters); envioNotificacionBody.put("canal", sendRequestBody.get("canal")); Map<String, Object> envioNotificacion = new HashMap<>(); envioNotificacion.put(Constantes.ENDPOINT, Urls.URL_ENVIO_NOTIFICACIONES.getPath()); envioNotificacion.put(Constantes.METHOD, "POST"); envioNotificacion.put(Constantes.CONNECT_TIMEOUT, 5000); envioNotificacion.put(Constantes.READ_TIMEOUT, 5000); envioNotificacion.put(Constantes.CONNECT_REQUEST_TIMEOUT, 5000); envioNotificacion.put(Constantes.HEADER, headers); envioNotificacion.put(Constantes.BODY, envioNotificacionBody); consultaServiciosContratadosBody.put(Constantes.TICKET, sendRequestBody.get(Constantes.TICKET)); consultaServiciosContratadosBody.put(Constantes.CANAL, sendRequestBody.get(Constantes.CANAL)); consultaServiciosContratadosBody.put(Constantes.IDPERSONA ,sendRequestBody.get(Constantes.IDPERSONA)); consultaDatosBasicos.put(Constantes.ENDPOINT, Urls.SER_CONSULTA_DATOS_BASICOS.getPath()); consultaDatosBasicos.put(Constantes.METHOD, "POST"); consultaDatosBasicos.put(Constantes.CONNECT_TIMEOUT, 5000); consultaDatosBasicos.put(Constantes.READ_TIMEOUT, 5000); consultaDatosBasicos.put(Constantes.CONNECT_REQUEST_TIMEOUT, 5000); consultaDatosBasicos.put(Constantes.HEADER, headers); consultaDatosBasicos.put(Constantes.BODY, consultaServiciosContratadosBody); consultaServicioContratado.put(Constantes.ENDPOINT, Urls.URL_SERVICIOS_CONTRATADOS.getPath()); consultaServicioContratado.put(Constantes.METHOD, "POST"); consultaServicioContratado.put(Constantes.CONNECT_TIMEOUT, 5000); consultaServicioContratado.put(Constantes.READ_TIMEOUT, 5000); consultaServicioContratado.put(Constantes.CONNECT_REQUEST_TIMEOUT, 5000); consultaServicioContratado.put(Constantes.HEADER, headers); consultaServicioContratado.put(Constantes.BODY, consultaServiciosContratadosBody); perfilInterno.put(Constantes.TICKET,sendRequestBody.get(Constantes.TICKET)); perfilInterno.put(Constantes.CANAL,sendRequestBody.get(Constantes.CANAL)); perfilInterno.put(Constantes.IDPERSONA,sendRequestBody.get(Constantes.IDPERSONA)); perfilInterno.put(Constantes.NOMBRESISTEMA, "MultivaNet"); perfil.put(Constantes.ENDPOINT, Urls.URL_PERFIL.getPath()); perfil.put(Constantes.METHOD, "POST"); perfil.put(Constantes.CONNECT_TIMEOUT, 5000); perfil.put(Constantes.READ_TIMEOUT, 5000); perfil.put(Constantes.CONNECT_REQUEST_TIMEOUT, 5000); perfil.put(Constantes.HEADER, headers); perfil.put(Constantes.BODY, perfilInterno); LOGGER.info("consultaServicioContratado----------------- {}" , consultaServicioContratado); LOGGER.info("envioNotificacion----------------- {}", envioNotificacion); LOGGER.info("consultaDatosBasicos----------------- {}" , consultaDatosBasicos); LOGGER.info("perfil----------------- {}", perfil); mapGeneral.put(Constantes.ENVIO_NOTIFICACION, envioNotificacion); mapGeneral.put(Constantes.DATOS_BASICOS, consultaDatosBasicos); mapGeneral.put(Constantes.SERVICIOS_CONTRATADOS, consultaServicioContratado); mapGeneral.put(Constantes.PERFIL_GENERAL, perfil); Operaciones operaciones = new Operaciones(); switch (mapHeaders.get("contrato-aceptado")) { case "1": LOGGER.debug(Constantes.LOG_CONTRATO_ACEPTADO); Map<String, Object> respuesta = utilidadesRest.restMultiples(mapGeneral,"login",Urls.URL_BITACORA.getPath(),request.getHeaders()); return operaciones.obtenerRespuestaLogin(respuesta,mapaHeader); case "0": LOGGER.debug(Constantes.LOG_CONTRATO_NO_ACEPTADO); return operaciones.banderaAcceso(envioNotificacion, mapGeneral, (Map<String, Object>) request.getBody(), mapaHeader, request.getHeaders()); default: return utilidadesRest.getErrorResponse(400, "Valor invalido en contrato aceptado", "Valor invalido en contrato aceptado"); } } } <file_sep>package mx.com.beo.util; public class Constantes { private Constantes() { } public static final String FORMATO_FECHA = "yyyyMMddHHmmss'.0Z'"; public static final String FORMATO_FECHA_SERVICIO = "yyyy-MM-dd'T'HH:mm:ss"; public static final String ERROR_FORMATO_FECHA_SERVICIO = "Error en Formato fecha Ultimo Acceso"; public static final String ERROR_FORMATO_FECHA = "Error en Formato fecha"; public static final String EXCEPTION_HEADERS = "Valida Headers exception"; public static final String MAP_GENERAL = "mapGeneral"; public static final String URLS = "urls"; public static final String HTTPHEADERS = "httpHeaders"; public static final String HEADERS_AUTENTICACION = "Headers autenticacion: {}"; public static final String PROTOCOLO = "PROTOCOLO"; public static final String HOSTNAME_BEO = "HOSTNAME_BEO"; public static final String PUERTO = "PUERTO"; public static final String BASEPATH = "BASEPATH"; public static final String BITACORA_URL = "BITACORA_URL"; public static final String URL_MODIFICA_CONTRATO = "URL_MODIFICA_CONTRATO"; public static final String BASEPATH_AUTENTICACION = "BASEPATH_AUTENTICACION"; public static final String BASEPATH_PERSONA = "BASEPATH_PERSONA"; public static final String BASEPATH_FACULTAMIENTO = "BASEPATH_FACULTAMIENTO"; public static final String ENDPOINT = "endpoint"; public static final String METHOD = "method"; public static final String CONNECT_TIMEOUT = "connectTimeout"; public static final String READ_TIMEOUT = "readTimeout"; public static final String CONNECT_REQUEST_TIMEOUT = "connectionRequestTimeout"; public static final String HEADER = "headers"; public static final String BODY = "body"; public static final String BANDERA_ACCESO = "banderaAcceso"; public static final String CLIENTE ="cliente"; public static final String RESPONSE_STATUS = "responseStatus"; public static final String RESPONSE_ERROR = "responseError"; public static final String LOG_ENDPOINT_CAMBIO_CONTRASENA = "EndPoint /autenticacion/cambioContrasena"; public static final String LOG_ENDPOINT_CONTRASENA = "EndPoint Contrasena {}"; public static final String LOG_CONTRASENAS_MODIFICAR = "Las contraseñas a modificar son diferentes"; public static final String LOG_CONTRATO_ACEPTADO = "el contrato ya esta aceptado"; public static final String LOG_CONTRATO_NO_ACEPTADO = "el contrato no esta aceptado"; public static final String LOG_OK_BANDERA_ACCESO = "Ok, banderaAcceso trae 1"; public static final String LOG_OK_CONTRATO_MODIFICADO = "Ok, Se ha modificado el contrato"; public static final String LOG_OK_MOSTRAR_CONTRATO = "OK, Se envia mostrar contrato"; public static final String LOG_ENDPOINT_ACCESO_CLIENTES = "EndPoint accesoCliente"; public static final String LOG_ERROR_CONTRATO = "Error, el cliente no ha aceptado el contrato"; public static final String DATOS_BASICOS = "consultaDatosBasicos"; public static final String SERVICIOS_CONTRATADOS = "consultaServiciosContratados"; public static final String PERFIL_GENERAL = "perfilGeneral"; public static final String ENVIO_NOTIFICACION = "envioNotificacion"; public static final String LOG_OK = "OK"; //Tipo de respuesta del servicio public static final String VACIO = ""; public static final String TICKET = "ticket"; public static final String CANAL = "canal"; public static final String IDPERSONA = "idPersona"; public static final String NOMBRESISTEMA = "nombreSistema"; } <file_sep>package mx.com.beo.local; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import mx.com.beo.App; @RunWith(SpringRunner.class) @SpringBootTest(classes = App.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class AutenticacionTest { private static final Logger LOGGER = LoggerFactory.getLogger(AutenticacionTest.class); @Autowired private TestRestTemplate restTemplate; @LocalServerPort private int port; @SuppressWarnings("unchecked") @Test public void cambioContrasena() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "123456"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("otp", "1"); body.put("oldPassword", "999"); body.put("newPassword","123"); body.put("confirmNewPassword","123"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {} " , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/cambioContrasena"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void cambioContrasenaSinHeader() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "123456"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("otp", "1"); body.put("oldPassword", "999"); body.put("newPassword","123"); body.put("confirmNewPassword","123"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/cambioContrasena"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void cambioContrasenaErrorActualNoExiste() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "123456"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("otp", "1"); body.put("oldPassword", "<PASSWORD>"); body.put("newPassword","123"); body.put("confirmNewPassword","123"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/cambioContrasena"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 404); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteCodigo0() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "19990"); headers.set("nombre-completo", "111"); headers.set("tipo-authenticacion", "22333333"); headers.set("contrato-aceptado", "0"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "5555"); headers.set("mail", "66666"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", ""); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "999"); headers.set("nombre-completo", "111"); headers.set("tipo-authenticacion", "22333333"); headers.set("contrato-aceptado", "0"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "5555"); headers.set("mail", "66666"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "0"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteSinHeaders() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "444"); headers.set("nombre-completo", "333"); headers.set("tipo-authenticacion", "2222"); headers.set("contrato-aceptado", "1"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("mail", "111"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", ""); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido{} " , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteContratoNoAceptado() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "0"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "0"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteContratobanderaAcceso0() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "0"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocapackagenal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "0"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteContratobanderaAcceso1() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "1"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "1"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteContratobanderaAcce1() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "1"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "1"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteContratobanderaAcceso1SinCodigo() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "0"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", ""); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteNull() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "4"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", ""); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 400); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteFechaExitosa() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGb<KEY>; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "1"); headers.set("fechaUltimoAcceso", "20170226111322.0Z"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "1"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } @SuppressWarnings("unchecked") @Test public void accesoClienteFechaError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("iv-user", "1"); headers.set("cookie", "JSESSIONID=1yO8dxBx6mq6aiboiFwcvBlc_W59rvlcrHGUKyvE.mmxmtzbelectronica; PD-S-SESSION-ID=1_Nh7mjwEuiVa8VtpIkM650frHGbzu3mWIQRreACSikfZFqpYoG44=_AAAAAAA=_ckMIbwznVUzytnBfaF96sprhEcQ=; LFR_SESSION_STATE_20120=1506553957696"); headers.set("iv-groups", "1"); headers.set("numero-cliente", "123456"); headers.set("nombre-completo", "123456"); headers.set("tipo-authenticacion", "123456"); headers.set("contrato-aceptado", "1"); headers.set("fechaUltimoAcceso", "20170226111322"); headers.set("tipocanal", "123456"); headers.set("mail", "123456"); Map<String, Object> body = new HashMap<String, Object>(); body.put("banderaAcceso", "1"); HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); LOGGER.info("Cuerpo que se arma {}" , entity.getBody()); ResponseEntity<Object> response = restTemplate.exchange(createURLWithPort("/accesoCliente"), HttpMethod.POST, entity, Object.class); Map<String, Object> respuesta = new HashMap<String, Object>(); respuesta.put("responseStatus", 200); Map<String, Object> mapBody = new HashMap<String, Object>(); LOGGER.info("Cabecera del servicio consumido {}" , response.getHeaders()); LOGGER.info("Cuerpo del servicio consumido {}" , response.getBody()); mapBody = (Map<String, Object>) response.getBody(); assertEquals(respuesta.get("responseStatus"), mapBody.get("responseStatus")); } private String createURLWithPort(String uri) { return "http://localhost:" + port + uri; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mx.com.beo</groupId> <artifactId>autenticacion</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>autenticacion</name> <description>microservicio para envio de app</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <jacoco.version>0.7.9</jacoco.version> <full-artifact-name>target/${project.artifactId}.jar</full-artifact-name> </properties> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.version}</version> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> <execution> <id>post-unit-test</id> <phase>test</phase> <goals> <goal>report</goal> </goals> <configuration> <!-- Sets the path to the file which contains the execution data. --> <dataFile>target/jacoco.exec</dataFile> <!-- Exclude Spring Boot main class from tests --> <excludes> <exclude>mx/com/beo/App.class</exclude> <exclude>mx/com/beo/util/Urls.class</exclude> <exclude>mx/com/beo/util/Constantes.class</exclude> <exclude>mx/com/beo/util/Utilerias.class</exclude> <exclude>mx/com/beo/util/Operaciones.class</exclude> </excludes> <!-- Sets the output directory for the code coverage report. --> <outputDirectory>target/jacoco-ut</outputDirectory> </configuration> </execution> <execution> <id>jacoco-check</id> <goals> <goal>check</goal> </goals> <configuration> <rules> <rule> <element>PACKAGE</element> <limits> <limit> <counter>LINE</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> </rule> <rule> <element>PACKAGE</element> <limits> <limit> <counter>METHOD</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> </rule> <rule> <element>PACKAGE</element> <limits> <limit> <counter>CLASS</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> </rule> <rule> <element>PACKAGE</element> <limits> <limit> <counter>INSTRUCTION</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> </rule> <rule> <element>PACKAGE</element> <limits> <limit> <counter>COMPLEXITY</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> </rule> </rules> <excludes> <exclude>mx/com/beo/App.class</exclude> <exclude>mx/com/beo/util/Urls.class</exclude> <exclude>mx/com/beo/util/Constantes.class</exclude> <exclude>mx/com/beo/util/Utilerias.class</exclude> <exclude>mx/com/beo/util/Operaciones.class</exclude> </excludes> </configuration> </execution> </executions> <configuration> <systemPropertyVariables> <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile> </systemPropertyVariables> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mx.com.beo</groupId> <artifactId>commons</artifactId> <version>1.0</version> </dependency> <!-- ==================================== TEST ======================================= --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- ==================================== Log Framework ============================== --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.19</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jcl</artifactId> <version>2.5</version> </dependency> </dependencies> </project> <file_sep>server.port=8082 spring.application.name=microservicio-beo-app<file_sep>package mx.com.beo.util; public enum Urls { /** * Enum que nos arma la url del servicio notificaciones * * VARIABLES DE AMBIENTE. * - PROTOCOLO * - HOSTNAME * - PUERTO * - BASEPATH * */ CONTRASENA(System.getenv(Constantes.PROTOCOLO) +"://"+System.getenv(Constantes.HOSTNAME_BEO)+((System.getenv(Constantes.PUERTO)!=null && !System.getenv(Constantes.PUERTO).equals(""))?":"+System.getenv(Constantes.PUERTO):"")+(System.getenv(Constantes.BASEPATH_AUTENTICACION)!=null?System.getenv(Constantes.BASEPATH_AUTENTICACION):"")+ "/cambioContrasena"), URL_ENVIO_NOTIFICACIONES(System.getenv(Constantes.PROTOCOLO) +"://"+System.getenv(Constantes.HOSTNAME_BEO)+((System.getenv(Constantes.PUERTO)!=null && !System.getenv(Constantes.PUERTO).equals(""))?":"+System.getenv(Constantes.PUERTO):"")+(System.getenv(Constantes.BASEPATH_PERSONA)!=null?System.getenv(Constantes.BASEPATH_PERSONA):"")+ "/envioNotificaciones"), SER_CONSULTA_DATOS_BASICOS(System.getenv(Constantes.PROTOCOLO) +"://"+System.getenv(Constantes.HOSTNAME_BEO)+((System.getenv(Constantes.PUERTO)!=null && !System.getenv(Constantes.PUERTO).equals(""))?":"+System.getenv(Constantes.PUERTO):"")+(System.getenv(Constantes.BASEPATH_PERSONA)!=null?System.getenv(Constantes.BASEPATH_PERSONA):"")+"/consultaDatosBasicos"), URL_SERVICIOS_CONTRATADOS(System.getenv(Constantes.PROTOCOLO) +"://"+System.getenv(Constantes.HOSTNAME_BEO)+((System.getenv(Constantes.PUERTO)!=null && !System.getenv(Constantes.PUERTO).equals(""))?":"+System.getenv(Constantes.PUERTO):"")+(System.getenv(Constantes.BASEPATH_PERSONA)!=null?System.getenv(Constantes.BASEPATH_PERSONA):"")+ "/consultaServiciosContratados"), URL_PERFIL(System.getenv(Constantes.PROTOCOLO) +"://"+System.getenv(Constantes.HOSTNAME_BEO)+((System.getenv(Constantes.PUERTO)!=null && !System.getenv(Constantes.PUERTO).equals(""))?":"+System.getenv(Constantes.PUERTO):"")+(System.getenv(Constantes.BASEPATH_FACULTAMIENTO)!=null?System.getenv(Constantes.BASEPATH_FACULTAMIENTO):"")+ "/consultaPerfiles"), URL_MODIFICA_CONTRATO(System.getenv(Constantes.URL_MODIFICA_CONTRATO)), URL_BITACORA((System.getenv(Constantes.BITACORA_URL)!=null?System.getenv(Constantes.BITACORA_URL):"") +"/bitacoraOperaciones"); private String path; private Urls(String path){ this.path=path; } public String getPath() { return path; } } <file_sep># Nombre de microservicio Microservicio que propociona la funcion de ...(Pruebas) ## Uso Instalar las dependencias mediante En caso de que se quieran saltar las pruebas unitarias aplicar este comando con mvn ##### Ambiente con Internet ``` mvn --settings settings_local.xml clean package -Dmaven.test.skip=true ``` ##### Ambiente de desarrollo ``` mvn --settings settings_dev.xml clean package -Dmaven.test.skip=true ``` En caso de que no requiera saltar pruebas unitarias realizar este comando ##### Ambiente con Internet ``` mvn --settings settings_local.xml clean package ``` ##### Ambiente de desarrollo ``` mvn --settings settings_dev.xml clean package ``` ## Variables de ambiente Previo a la ejecucion del programa es necesario configurar variables de ambiente ``` PROTOCOLO=http PUERTO=9094 HOSTNAME_BEO=172.16.31.10 BASEPATH= URL_MODIFICA_CONTRATO=http://localhost:9094/modificaContrato #URL Servicio de nologin BITACORA_URL=http://historial ``` ##### ENMASCARAMIENTO En caso de ser necesario enmascarar alguna variable correspondiente al Request o Response en el archivo de bitacora Multiva sera necesario utilizar la siguiente variable de ambiente para indicar la configuración necesaria. NOTA: en caso de no requerir enmascarar ninguna información no sera necesario configurar esta variable de ambiente ``` LOG_ESB_ENMASCARAMIENTO Ejemplo: LOG_ESB_ENMASCARAMIENTO={"config":[{"servicio":"cambioContrasena","request":["oldPassword","newPassword","confirmNewPassword"],"response":[]}]} * Explicacion: { "config":[ { "servicio": "request":[], "response":[] } ] } config: arreglo de objetos, cada objeto representa la configuracion de un servicio. servicio: nombre del endpoind del servicio que se esta configurando. request: es un arreglo con el nombre de todos los campos que deben ser enmascarados que se encuentran en el Request que invoca al servicio. response: es un arreglo con el nombre de todos los campos que deben ser enmascarados que se encuentran en el Response que respondio el servicio. ``` ### Puerto donde se encuentra este microservicio ``` server.port=8080 ``` ## Ejecucion ``` java -jar microservicio-0.0.1-SNAPSHOT.jar ``` <file_sep>package mx.com.beo.util; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; public class Operaciones { private static final Logger LOGGER = LoggerFactory.getLogger(Operaciones.class); UtilidadesRest utilidadesRest = new UtilidadesRest(); public ResponseEntity<Object> banderaAcceso(Map<String, Object> envioNotificacion, Map<String, Object> mapGeneral, Map<String, Object> requestBody, Map<String, Object> mapHeaders, HttpHeaders httpHeaders) { if (existsAndHasValue(requestBody, Constantes.BANDERA_ACCESO, "1")) { String urlModificaContrato = Urls.URL_MODIFICA_CONTRATO.getPath(); LOGGER.info("URL DEL CONTRATO----------- {}" , urlModificaContrato); Set<MediaType> mediaTypeValidos = new HashSet<>(); mediaTypeValidos.add(MediaType.APPLICATION_JSON); mediaTypeValidos.add(MediaType.APPLICATION_JSON_UTF8); Map<String, Object> modificaContrato = new HashMap<>(); modificaContrato.put("contratoAceptado", requestBody.get(Constantes.BANDERA_ACCESO)); modificaContrato.put("usuario", mapHeaders.get(Constantes.CLIENTE)); ResponseEntity<Object> entity = utilidadesRest.enviarPeticion(urlModificaContrato, HttpMethod.POST, mediaTypeValidos, null, modificaContrato, Urls.URL_BITACORA.getPath(), httpHeaders); @SuppressWarnings("unchecked") Map<String, Object> mapaRespuesta = (Map<String, Object>) entity.getBody(); mapGeneral.put(Constantes.ENVIO_NOTIFICACION, envioNotificacion); LOGGER.info(Constantes.MAP_GENERAL , mapGeneral); LOGGER.info(Constantes.URLS , Urls.URL_BITACORA.getPath()); LOGGER.info(Constantes.HTTPHEADERS , httpHeaders); if (existsAndHasValue(mapaRespuesta, "codigo", "0")) { LOGGER.debug(Constantes.LOG_OK_CONTRATO_MODIFICADO); // Se lanza peticiones para realizar login Map<String, Object> respuesta = utilidadesRest.restMultiples(mapGeneral,"login",Urls.URL_BITACORA.getPath(),httpHeaders); return obtenerRespuestaLogin(respuesta, mapHeaders); } else { return error400("Error, Al intentar modificar el contrato"); } } else if (existsAndHasValue(requestBody, Constantes.BANDERA_ACCESO, "")) { LOGGER.debug(Constantes.LOG_OK_MOSTRAR_CONTRATO); Map<String, Object> respuesta = new HashMap<>(); respuesta.put("mostrarContrato", true); respuesta.put(Constantes.RESPONSE_STATUS, 200); respuesta.put(Constantes.RESPONSE_ERROR, Constantes.VACIO); return new ResponseEntity<>(respuesta, HttpStatus.OK); } else if(existsAndHasValue(requestBody, Constantes.BANDERA_ACCESO, "0")){ LOGGER.debug(Constantes.LOG_ERROR_CONTRATO , httpHeaders.get("iv-user")); return utilidadesRest.getErrorResponse(400, "Contrato no aceptado", "Dato invalido en banderaAcceso"); } return null; } public Boolean existsAndHasValue(Map<String, Object> map, String key, Object value) { return map.containsKey(key) && map.get(key).equals(value); } public ResponseEntity<Object> obtenerRespuestaLogin(Map<String, Object> respuestaMultiple, Map<String, Object> headers) { Map<String, Object> respuestaLogin = obtieneBody(respuestaMultiple, headers); return new ResponseEntity<>(respuestaLogin, HttpStatus.OK); } @SuppressWarnings("unchecked") public Map<String, Object> obtieneBody(Map<String, Object> respuesta, Map<String, Object> headers) { Map<String, Object> mapaRespuesta; Map<String, Object> mapaRespuesta2; Map<String, Object> mapaRespuesta3; Map<String, Object> mapaRespuesta4; Map<String, Object> respuestaGeneral = new HashMap<>(); respuestaGeneral.put("responseStatus", 200); respuestaGeneral.put("responseError", ""); mapaRespuesta = obtenerBodyRespuesta(respuesta,respuestaGeneral,Constantes.DATOS_BASICOS); if (mapaRespuesta != null) { respuestaGeneral.put("nombreRazonSocial", mapaRespuesta.get("nombre")); respuestaGeneral.put("listaTelefonos", mapaRespuesta.get("listaTelefonos")); } mapaRespuesta2 = obtenerBodyRespuesta(respuesta,respuestaGeneral,Constantes.SERVICIOS_CONTRATADOS); if (mapaRespuesta2 != null) { respuestaGeneral.put(Constantes.SERVICIOS_CONTRATADOS, mapaRespuesta2); } mapaRespuesta3 = obtenerBodyRespuesta(respuesta,respuestaGeneral,Constantes.ENVIO_NOTIFICACION); if (mapaRespuesta3 != null) { respuestaGeneral.putAll(mapaRespuesta3); } mapaRespuesta4 = obtenerBodyRespuesta(respuesta,respuestaGeneral,Constantes.PERFIL_GENERAL); if (mapaRespuesta4 != null) { respuestaGeneral.put("facultadesSimples", mapaRespuesta4.get("facultadesSimples")); } respuestaGeneral.put("fechaUltimoAcceso",Utilerias.fechaFormatoServicio((String) headers.get("fechaUltimoAcceso"), Constantes.FORMATO_FECHA)); respuestaGeneral.put("nombreUsuario", headers.get("nombreUsuario")); respuestaGeneral.put("medioAcceso", headers.get("canal")); respuestaGeneral.put("mail", headers.get("mailCliente")); respuestaGeneral.put("cliente", headers.get("cliente")); return respuestaGeneral; } @SuppressWarnings("unchecked") public Map<String, Object> obtenerBodyRespuesta(Map<String, Object> respuesta,Map<String, Object> respuestaGeneral,String llave) { if(respuesta.containsKey(llave)) { Map<String, Object> mapaRespuesta = (Map<String, Object>) respuesta.get(llave); return (Map<String, Object>) mapaRespuesta.get(Constantes.BODY); }else { respuestaGeneral.put("responseStatus", 400); respuestaGeneral.put("responseError", "Error al consultar la respuesta del servicio: "+ llave); return null; } } /** * * @return Regresa un JSON que nos trae el error 403 Description Metodo * donde manejamos el error 403. Este error se ejecuta en caso de * que se produsca un error al consumir uno de los servicios. */ public ResponseEntity<Object> error400(String mensaje) { return utilidadesRest.getErrorResponse(400, mensaje, mensaje); } }
15225070ed6dd44d528f00d9e790f6adf833b316
[ "Markdown", "Java", "Maven POM", "INI" ]
8
Java
fabiang81/autenticacion
d15365c3269a531dc3a2b4c9c80d25dc7df04539
95f9d0ec5531f9c88e545e2b9f7a698682b09c8b
refs/heads/master
<file_sep>import java.util.Scanner; public class TablaMultiplicar { public static void main (String[] args) { int valor, limite; Scanner teclado = new Scanner(System.in); System.out.print("Nro de la tabla de multiplicar? "); valor = teclado.nextInt(); System.out.print("Nro. maximo para multiplicar? "); limite = teclado.nextInt(); for (int nro = 0; nro <= limite; nro = nro + 1) { System.out.println("" + valor + "*" + nro + "=" + (valor * nro)); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package veterinariaherencia; import java.util.ArrayList; /** * * @author meschoyez */ public class VeterinariaHerencia { private ArrayList<Perro> perros; private ArrayList<Gato> gatos; private ArrayList<Cucha> cuchas; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here VeterinariaHerencia vet = new VeterinariaHerencia(); vet.ListarPerros(); vet.ListarGatos(); vet.ListarCuchas(); } public VeterinariaHerencia () { perros = new ArrayList<>(); gatos = new ArrayList<>(); cuchas = new ArrayList<>(); InicializarVeterinaria(); } public void InicializarVeterinaria () { perros.add(new Perro("terrbald", "marron", "Toby")); perros.add(new Perro("cordubensis", "negro")); perros.add(new Perro("setter", "gris", "Picante")); gatos.add(new Gato("siames", "crema", "Daisy")); gatos.add(new Gato("comun", "marron")); cuchas.add(new Cucha(Material.MADERA, Tamano.MEDIANO, "blanco", false, "Toby")); cuchas.add(new Cucha(Material.TELA, Tamano.CHICO, "rosa", true, "Daisy")); } public void ListarCuchas () { System.out.println("Cuchas registrados:"); for (Cucha c : cuchas) { System.out.println(c); } } public void ListarGatos () { System.out.println("Gatos registrados:"); for (Gato g : gatos) { System.out.println(g); } } public void ListarPerros () { System.out.println("Perros registrados:"); for (Perro p : perros) { System.out.println(p); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cineventaentradas; import java.util.ArrayList; /** * * @author meschoyez */ public class CineVentaEntradas { public static void main(String[] args) { int desocupadas = 0; boolean resultado; ArrayList<Boolean> butacas; butacas = new ArrayList<>(); /* Hacer el metodo principal (main) para que el programa * realice lo siguiente: * - El cine cuenta con 15 butacas */ for (int p = 0; p < 15; p++) { butacas.add(false); } /* - El primer cliente compra 3 entradas * (sugerencia: agregar metodo ComprarNEntradas) */ boolean venta; venta = ComprarNEntradas(butacas, 3); ImprimirResultadoVenta(venta, 3); /* - El segundo cliente compra 2 entradas */ venta = ComprarNEntradas(butacas, 2); ImprimirResultadoVenta(venta, 2); /* - El tercer cliente compra 5 entradas */ venta = ComprarNEntradas(butacas, 5); ImprimirResultadoVenta(venta, 5); /* - El segundo cliente cancela sus 2 entradas * (sugerencia: agregar los metodos LiberarButaca * CancelarReservaNButacas) */ CancelarReservaNButacas(butacas, 2, 3); System.out.println("Se cancela reserva 2 entradas"); /* - El cuarto cliente compra 4 entradas */ venta = ComprarNEntradas(butacas, 4); ImprimirResultadoVenta(venta, 4); /* - El quinto cliente compra 1 entrada */ venta = ComprarNEntradas(butacas, 1); ImprimirResultadoVenta(venta, 1); /* Finalmente, mostrar por pantalla la cantidad de butacas * ocupadas y el porcentaje de ocupacion el cine */ System.out.println("Butacas ocupadas: " + ContarButacasOcupadas(butacas)); System.out.println("Porcentaje ocupacion: " + PorcentajeOcupacion(butacas)); } private static void CancelarReservaNButacas (ArrayList<Boolean> butacas, int cant, int pos) { for (int b = 0; b < cant; b++) { LiberarButaca(butacas, pos + b); } } private static boolean ComprarNEntradas (ArrayList<Boolean> butacas, int n) { int pos = -2; boolean vendido = true; pos = BuscarNButacasLibresContiguas(butacas, n); if (pos >= 0) { for (int b = pos; b < pos + n; b++) { OcuparButaca(butacas, b); } // for (int b = 0; b < n; b++) { // OcuparButaca(butacas, pos + b); // } } else { vendido = false; } return vendido; } private static void ImprimirResultadoVenta (boolean v, int n) { if (v) { System.out.println("Vendidas " + n + " entradas"); } else { System.out.println("No se pudieron vender las entradas"); } } private static void LiberarButaca( ArrayList<Boolean> butacas, int nro) { butacas.set(nro, false); } private static int ContarButacasLibres(ArrayList<Boolean> butacas) { int desocupadas = 0; for (boolean ocupada : butacas) { if (!ocupada) { desocupadas++; } } return desocupadas; } private static int ContarButacasLibresForComun(ArrayList<Boolean> butacas) { int desocupadas = 0; for (int b = 0; b < butacas.size(); b++) { if (ButacaLibre(butacas, b)) { desocupadas++; } } return desocupadas; } private static boolean OcuparButaca( ArrayList<Boolean> butacas, int nro) { boolean libre = ButacaLibre(butacas, nro); if (libre) { butacas.set(nro, true); } return libre; } private static boolean ButacaLibre(ArrayList<Boolean> butacas, int nro) { return ! butacas.get(nro); } /* Completar metodos faltantes */ private static boolean ButacaOcupada (ArrayList<Boolean> butacas, int nro) { return butacas.get(nro); } private static boolean CineVacioFor(ArrayList<Boolean> butacas) { boolean vacio = true; for (int pos = 0; pos < butacas.size(); pos++) { if (butacas.get(pos)) { vacio = false; } } return vacio; } private static boolean CineVacioForeach(ArrayList<Boolean> butacas) { boolean vacio = true; for (Boolean b : butacas) { if (b) { vacio = false; } } return vacio; } private static boolean CineVacio(ArrayList<Boolean> butacas) { return ! butacas.contains(true); } private static boolean CineLleno(ArrayList<Boolean> butacas) { return ! butacas.contains(false); } private static int ContarButacasOcupadasFor(ArrayList<Boolean> butacas) { int ocupadas = 0; for (int b = 0; b < butacas.size(); b++) { if (ButacaOcupada(butacas, b)) { ocupadas++; } } return ocupadas; } private static int ContarButacasOcupadas(ArrayList<Boolean> butacas) { int ocupadas = 0; for (boolean b : butacas) { if (b) { ocupadas++; } } return ocupadas; } private static int BuscarButacaLibre1(ArrayList<Boolean> butacas) { int posicion = 0, libre = -1; for (Boolean b : butacas) { if (b == false) { libre = posicion; } posicion++; } return libre; } private static int BuscarButacaLibre2(ArrayList<Boolean> butacas) { int posicion = 0, libre = -1; for (Boolean b : butacas) { if ((b == false) && (libre < 0)) { libre = posicion; } posicion++; } return libre; } private static int BuscarButacaLibre(ArrayList<Boolean> butacas) { return butacas.indexOf(false); } private static float PorcentajeOcupacion (ArrayList<Boolean> butacas) { float ocupacion = 100 * (float)ContarButacasOcupadas(butacas) / (float)butacas.size(); return ocupacion; } private static int Buscar2ButacasLibresContiguas (ArrayList<Boolean> butacas) { return BuscarNButacasLibresContiguas(butacas, 2); } private static int BuscarNButacasLibresContiguas (ArrayList<Boolean> butacas, int n) { int posicion = 0, contiguos = 0, primeraLibre = -1; while ((contiguos < n) && (posicion < butacas.size())) { if (ButacaLibre(butacas, posicion)) { contiguos++; } else { contiguos = 0; } posicion++; } if (contiguos == n) { primeraLibre = posicion - n; } return primeraLibre; } private static int BuscarNButacasLibresContiguasForeach (ArrayList<Boolean> butacas, int n) { int posicion = 0, contiguos = 0, primeraLibre = -1; for (boolean b : butacas) { if ((contiguos < n) && (primeraLibre == -1) && (ButacaLibre(butacas, posicion))) { contiguos++; if (contiguos == n) { primeraLibre = posicion - n + 1; } } else { contiguos = 0; } posicion++; } return primeraLibre; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package veterinariaherencia; /** * * @author meschoyez */ public class Hogar { private final Material material; private boolean ocupado; private String dueno; private final Tamano tamano; private final String color; private String origen; public Hogar (Material material, Tamano tamano, String color, boolean ocupado, String dueno) { this.dueno = dueno; this.material = material; this.ocupado = ocupado; this.tamano = tamano; this.color = color; } /** * @return the material */ public Material getMaterial() { return material; } /** * @return the ocupado */ public boolean isOcupado() { return ocupado; } /** * @param ocupado the ocupado to set */ public void setOcupado(boolean ocupado) { this.ocupado = ocupado; } /** * @return the dueno */ public String getDueno() { return dueno; } /** * @param dueno the dueno to set */ public void setDueno(String dueno) { this.dueno = dueno; } /** * @return the tamano */ public Tamano getTamano() { return tamano; } /** * @return the color */ public String getColor() { return color; } /** * @return the origen */ public String getOrigen() { return origen; } @Override public String toString () { String inicio = "Material: " + material + " - Tamaño: " + tamano + " - Color: " + color; String fin; if (ocupado) { fin = " - " + dueno + " está dentro"; } else { fin = " - Está vacía"; } return inicio + fin; } } <file_sep># 111mil Material producido durante el dictado del programa 111mil <file_sep>import java.util.Scanner; public class FuncionesSimples { // Cabecera de la Funcion/Metodo public static void main (String[] args) // | Tipo Acceso | Valor retorno| Nombre | Argumentos // Fin de la Cabecera { int valor, limite; Scanner teclado = new Scanner(System.in); System.out.print("Nro de la tabla de multiplicar? "); valor = teclado.nextInt(); System.out.print("Nro. maximo para multiplicar? "); limite = teclado.nextInt(); Multiplicaciones(valor, limite); } public static int Multiplica (int a, int b) { // | Tipo Acceso | Valor retorno| Nombre | Argumentos return a * b; } public static void Multiplicaciones (int valor, int limite) { for (int nro = 0; nro <= limite; nro = nro + 1) { System.out.println("" + valor + "*" + nro + "=" + Multiplica(valor, nro)); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package veterinariaherencia; /** * * @author meschoyez */ public class Cucha extends Hogar { public Cucha () { super(Material.MADERA, Tamano.MEDIANO, "madera", false, null); } public Cucha (Material material, Tamano tamano, String color, boolean ocupado, String dueno) { super(material, tamano, color, ocupado, dueno); } @Override public String toString () { return "-CUCHA- " + super.toString(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package colasconlistas; import java.util.LinkedList; import java.util.Scanner; /** * * @author meschoyez */ public class ColasConListas { /** * @param args the command line arguments */ public static void main(String[] args) { String nombre; Scanner teclado = new Scanner(System.in); LinkedList<String> fila; fila = new LinkedList<>(); for (int n = 0; n < 5; n++) { System.out.print("Ingrese un nombre: "); nombre = teclado.nextLine(); fila.add(nombre); } while (fila.size() > 0) { String quitado; quitado = fila.remove(); System.out.println(quitado); } } } <file_sep>import java.util.Scanner; public class Sumar { public static void main (String[] args) { int nro1, nro2; Scanner teclado = new Scanner(System.in); System.out.print("Ingrese un numero entero: "); nro1 = teclado.nextInt(); System.out.print("Ingrese otro numero entero: "); nro2 = teclado.nextInt(); int resultado; resultado = nro1 + nro2; System.out.println("El resultado es " + resultado); } } <file_sep>package prueba111mil; import java.util.Scanner; public class Prueba111mil { public static void main(String[] args) { int valor, a, b, resultado; Scanner teclado = new Scanner(System.in); System.out.print("Valor para factorial? "); valor = teclado.nextInt(); resultado = Factorial(valor); System.out.println("Factorial = " + resultado); resultado = FactorialIt(valor); System.out.println("Factorial (it) = " + resultado); System.out.println("Valor a mult? "); a = teclado.nextInt(); System.out.println("Valor b mult? "); b = teclado.nextInt(); resultado = Multiplicar(a, b); System.out.println("Multiplicacion = " + resultado); resultado = MultiplicarIt(a, b); System.out.println("Multiplicacion (it) = " + resultado); resultado = MultiplicarIt2(a, b); System.out.println("Multiplicacion (it2) = " + resultado); } private static int Factorial(int nro) { int resultado; if ((nro == 0) || (nro == 1)) { resultado = 1; } else { resultado = nro * Factorial(nro - 1); } return resultado; } private static int FactorialIt (int nro) { int resultado = 1; for ( ; nro > 1; nro--) { resultado *= nro; } return resultado; } private static int Multiplicar (int x, int y) { int resultado; if (y == 0) { resultado = 0; } else { resultado = x + Multiplicar(x, y-1); } return resultado; } private static int MultiplicarIt (int x, int y) { int resultado = 0; for (int i = 1; i <= y; i++) { // resultado = resultado + x; resultado += x; } return resultado; } private static int MultiplicarIt2 (int x, int y) { int resultado = 0; for ( ; y > 0; y--) { resultado += x; } return resultado; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pruebapilas; import java.util.Scanner; import java.util.Stack; /** * * @author meschoyez */ public class PruebaPilas { /** * @param args the command line arguments */ public static void main(String[] args) { String nombre; Scanner teclado = new Scanner(System.in); Stack<String> miPila; miPila = new Stack<>(); for (int n = 0; n < 5; n++) { System.out.print("Ingrese un nombre: "); nombre = teclado.nextLine(); miPila.push(nombre); } while (!miPila.empty()) { String quitado; quitado = miPila.pop(); System.out.println(quitado); } } }
5a3bfed6ab2c453a2751651d96eaabcdd374e56a
[ "Markdown", "Java" ]
11
Java
meschoyez/111mil
b8de132c072351133edca4e5fcb7009430deeca1
4ab856d2d07bf7d32146ff9bf1b594895ccd74cf
refs/heads/master
<repo_name>kishanmundha/kishanmundha.github.io<file_sep>/_posts/mvc/2016-08-20-form-authentication.md --- author: todo layout: master title: MVC Form authentication categories: mvc --- Integration of MVC form authentication ### Login action controller code ``` csharp [HttpPost] public ActionResult Login(User model, string returnUrl) { if (ModelState.IsValid) { bool userValid = _repository.IsValidUserSignIn(model.username, model.password); if (userValid) { FormsAuthentication.SetAuthCookie(username, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } return View(model); } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } ``` ### Change in `Global.asax.cs` ``` csharp protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; roles = _repository.getUserRoles(username); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); } } } ``` <file_sep>/_posts/mvc/2015-10-23-ActionFilter.md --- layout: master title: Action filter categories: mvc --- Action filter is used to filter request before or after execution action <file_sep>/_posts/mvc/2015-10-23-Validations.md --- author: todo layout: master title: MVC Validations using data anotation categories: mvc --- Data anotation is powerfull tool to validate model in client side and server side. ### Remote <file_sep>/google-map-react-demo/precache-manifest.3673950f5f29727349bba0673cc94920.js self.__precacheManifest = [ { "revision": "1145a64d6a49a9c52a10", "url": "/google-map-react-demo/static/js/runtime~main.1145a64d.js" }, { "revision": "5742a2fe78e1e0c43d81", "url": "/google-map-react-demo/static/js/main.5742a2fe.chunk.js" }, { "revision": "843a7e6b2ef30d7432fe", "url": "/google-map-react-demo/static/js/1.843a7e6b.chunk.js" }, { "revision": "5742a2fe78e1e0c43d81", "url": "/google-map-react-demo/static/css/main.504d46ed.chunk.css" }, { "revision": "742df1d3f3fb5b170729bd40ce5ebbd0", "url": "/google-map-react-demo/index.html" } ];<file_sep>/_posts/2015-09-27-angular.md --- layout: master title: AngularJS --- <file_sep>/_posts/sql/2015-10-23-queries.md --- layout: master title: SQL Queries categories: sql excerpt: Most complex, logical queries --- ### Find maximum match string in two string ``` sql -- dummy data DECLARE @tbl TABLE (code VARCHAR(20), rate FLOAT) INSERT INTO @tbl VALUES ('91', 0.02), ('917', 0.03), ('9179', 0.01), ('916', 0.03), ('9188', 0.02) -- parameter DECLARE @code VARCHAR(10) = '9179' /* FIND LOGIC */ -- method 1 select top 1 * from @tbl where CHARINDEX(code, @code)>0 order by LEN(code) desc -- method 2 DECLARE @len INT = LEN(@code) WHILE @len > 0 BEGIN IF EXISTS (SELECT * FROM @tbl WHERE code=LEFT(@code, @len)) BEGIN SELECT TOP 1 code, rate FROM @tbl WHERE code=LEFT(@code, @len) BREAK END SET @len = @len - 1 END GO ``` ### Search data in any table of any database ``` sql CREATE PROCEDURE [dbo].[SearchData] -- Parameters @searchText varchar(MAX) = NULL, @tables varchar(1024) = '*', @database varchar(50) = NULL AS /************************************ * Search Any Content * @Version 1.0.0.1 * * Example: * exec SearchData 'text' * exec SearchData 'text', 'tables' * exec SearchData 'text', 'tables', 'databases' * exec SearchData 'text', 'tables', 'databases', 'varchar' * * Parameter can accept in this format: * 'text1,text2' * 'text1|text2' * 't*' * 't*|m*' ***********************************/ SET NOCOUNT ON IF @searchText IS NULL BEGIN PRINT ' Search Any Content' PRINT ' @Version 1.0.0.1' PRINT '' PRINT ' Example:' PRINT ' exec SearchData ''text''' PRINT ' exec SearchData ''text'', ''tables''' PRINT ' exec SearchData ''text'', ''tables'', ''databases''' PRINT '' PRINT ' Parameter can accept in this format:' PRINT ' ''text1,text2''' PRINT ' ''text1|text2''' PRINT ' ''t*''' PRINT ' ''t*|m*''' RETURN END -- variables declare @i int = 0 declare @s varchar (50) = '' declare @s2 varchar (50) = '' declare @d varchar (50) = '' declare @count int = 0 declare @search_content table (s varchar(50)) declare @database_table table (database_name char(50)) declare @table_list table (id int IDENTITY(1,1), database_name char(50), table_name varchar(1000)) declare @column_list table(database_name varchar(50), table_name varchar(1000), column_name varchar(100), ordinal_position int, data_type varchar(50)) declare @result_column table (database_name char(50), table_name varchar(1000), column_name varchar(100), count_item int) -- replace paramter string set @database = REPLACE(@database, '*', '%') set @database = REPLACE(@database, ',', '|') set @tables = REPLACE(@tables, '*', '%') set @tables = REPLACE(@tables, ',', '|') set @searchText = REPLACE(@searchText, '*', '%') set @searchText = REPLACE(@searchText, ',', '|') -- prepare database list if @database is null insert into @database_table select QUOTENAME(DB_NAME()) else begin while LEN(@database)>0 begin if PATINDEX('%|%',@database) > 0 begin set @s = SUBSTRING(@database, 0, PATINDEX('%|%',@database)) set @database = SUBSTRING(@database, len(@s) + 2, LEN(@database)) end else begin set @s = @database set @database = NULL end insert into @database_table select QUOTENAME(name) from sys.databases where name like @s --and QUOTENAME(name) not in (select database_name from @database_table) end end --select * from @database_table -- prepare table list if @tables is null begin set @d = (select top 1 database_name from @database_table) insert into @table_list select @d, QUOTENAME(TABLE_NAME) from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE' insert into @column_list select @d, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS end else begin set @d = '' while @d is not null begin set @d = rtrim(ltrim((select MIN(database_name) from @database_table where database_name>@d))) set @s2 = @tables while LEN(@s2)>0 and @d is not null begin if PATINDEX('%|%',@s2) > 0 begin set @s = SUBSTRING(@s2, 0, PATINDEX('%|%',@s2)) set @s2 = SUBSTRING(@s2, len(@s) + 2, LEN(@s2)) end else begin set @s = @s2 set @s2 = NULL end insert into @table_list exec ( 'select ''' + @d + ''', QUOTENAME(TABLE_NAME) from ' + @d + ' .INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' and TABLE_NAME like ''' + @s + '''') insert into @column_list exec ( 'SELECT ''' + @d + ''', TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE FROM ' + @d + '.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME like ''' + @s + '''' ) end end end --select * from @column_list set @s2 = @searchText while LEN(@s2)>0 begin if PATINDEX('%|%',@s2) > 0 begin set @s = SUBSTRING(@s2, 0, PATINDEX('%|%',@s2)) set @s2 = SUBSTRING(@database, len(@s) + 2, LEN(@database)) end else begin set @s = @s2 set @s2 = NULL end insert into @search_content values (@s) end declare @ColumnName varchar(50) = '' declare @t varchar(50) = '' set @i = 0 set @count = (select COUNT(*) from @table_list) while @i is not null begin set @i = (select MIN(id) from @table_list where id > @i) set @t = (select table_name from @table_list where id = @i) set @d = rtrim(ltrim((select database_name from @table_list where id = @i))) IF SUBSTRING(@t, 2, 1) = '#' CONTINUE set @ColumnName = '' while @ColumnName is not null and @i is not null begin --set @ColumnName = (select MIN(COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS where DATA_TYPE IN --('char', 'varchar', 'nchar', 'nvarchar') and TABLE_NAME=@t and COLUMN_NAME>@ColumnName) set @ColumnName = (select MIN(column_name) from @column_list where data_type IN ('char', 'varchar', 'nchar', 'nvarchar') and QUOTENAME(TABLE_NAME)=@t and COLUMN_NAME>@ColumnName and database_name=@d) --select @ColumnName, @t if @ColumnName is not null begin set @s = (select MIN(s) from @search_content) while @s is not null begin if @s is not null declare @tt varchar(100) = REPLACE(@t, '''', '''''') insert into @result_column exec ('select ''' + @d + ''', ''' + @tt + ''', ''' + @ColumnName + ''', COUNT(*) from ' + @d + '..' + @t + ' with (nolock) where [' + @ColumnName + '] like ''' + @s + '''') set @s = (select MIN(s) from @search_content where s>@s) end end end print convert(varchar(10), @i) + '/' + convert(varchar(10), @count) end select * from @result_column where count_item>0 GO ``` ### Find total sunday for a month ``` sql CREATE FUNCTION [dbo].[TotalDayInMonth] ( @Month int, @Year int ) RETURNS int AS BEGIN declare @d date = convert(date, ltrim(str(@Year)) + '-' + ltrim(str(@Month)) + '-01') declare @daysinmonth int = DATEDIFF(D, @d, DATEADD(M, 1, @d)) return @daysinmonth END GO CREATE FUNCTION [dbo].[TotalWeekDayInMonth] ( @Month int, @Year int, @WeekDay int ) RETURNS int AS BEGIN declare @d date = convert(date, ltrim(str(@Year)) + '-' + ltrim(str(@Month)) + '-01') declare @daysinmonth int = dbo.TotalDayInMonth(@Month, @Year) declare @firstOn int = (7 - (DATEPART(DW, @d) - @WeekDay)) % 7 declare @total int = floor((@daysinmonth-@firstOn+6) / 7) return @total END GO CREATE FUNCTION [dbo].[TotalSundayInMonth] ( @Month int, @Year int ) RETURNS int AS BEGIN declare @totalSunday int = dbo.TotalWeekDayInMonth(@Month, @Year, 1) return @totalSunday END GO ``` ### Get period list ``` sql CREATE FUNCTION [dbo].[fn_GetPeriodList] ( @DateTo datetime, @Count int, @PeriodType int -- 1=daily, 2=weekly, 3=monthly, 4=quatrly, 5=halfyearly, 6 = yearly ) RETURNS @t TABLE (id int, dStart datetime, dEnd datetime, DisplayString VARCHAR(100)) AS BEGIN IF @PeriodType = 1 -- daily BEGIN ;WITH date_list (id, dStart, dEnd, DisplayString) AS ( SELECT @Count, @DateTo, DATEADD(SECOND, -1, DATEADD(D, 1, @DateTo)), convert(varchar, @DateTo, 105) AS DisplayString UNION ALL SELECT id - 1, DATEADD(D, -1, dStart), DATEADD(D, -1, dEnd), convert(varchar, DATEADD(D, -1, dEnd), 105) FROM date_list WHERE id > 1 ) INSERT INTO @t SELECT id, dStart, dEnd, DisplayString FROM date_list OPTION (MAXRECURSION 0) END IF @PeriodType = 2 -- weekly BEGIN --SET @DateFrom = dateadd(ww, datediff(ww, 0, @DateFrom), 0) SET @DateTo = dateadd(ww, datediff(ww, 0, dateadd(D, -1, @DateTo)), 6) --dateadd(ww, datediff(ww, 0, @DateTo), 6) ;WITH date_list (id, dStart, dEnd, DisplayString) AS ( SELECT @Count, DATEADD(DAY, -6, @DateTo), DATEADD(SECOND, -1, DATEADD(D, 1, @DateTo)), convert(varchar, DATEADD(SECOND, -1, DATEADD(D, 1, @DateTo)), 105) UNION ALL SELECT id - 1, DATEADD(DAY, -7, dStart), DATEADD(DAY, -7, dEnd), convert(varchar, DATEADD(DAY, -7, dEnd), 105) FROM date_list WHERE id > 1 --SELECT id + 1, DATEADD(DAY, -7, dStart), DATEADD(DAY, -7, dEnd), convert(varchar, DATEADD(SECOND, -1, DATEADD(ww, 1, DATEADD(ww, 1, dStart))), 105) FROM date_list WHERE id < @Count ) INSERT INTO @t SELECT id, dStart, dEnd, DisplayString FROM date_list OPTION (MAXRECURSION 0) END IF @PeriodType = 3 -- monthly BEGIN -- SET datefrom to first date of month and dateto to last date of month --SET @DateFrom = DATEADD(mm, DATEDIFF(m,0,@DateFrom),0) SET @DateTo = DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,@DateTo)+1,0)) ;WITH date_list (id, dStart, dEnd, DisplayString) AS ( SELECT @Count, DATEADD(mm, DATEDIFF(m,0,@DateTo),0), DATEADD(SECOND, -1, DATEADD(D, 1, @DateTo)), convert(varchar, DATENAME(M, @DateTo)) + ' ' + convert(varchar, DATEPART(YYYY, @DateTo)) AS DisplayString UNION ALL SELECT id - 1, DATEADD(M, -1, dStart), DATEADD(S, -1, dStart), convert(varchar, DATENAME(M, DATEADD(M, -1, dStart))) + ' ' + convert(varchar, DATEPART(YYYY, DATEADD(M, -1, dStart))) FROM date_list WHERE id > 1 ) INSERT INTO @t SELECT id, dStart, dEnd, DisplayString FROM date_list OPTION (MAXRECURSION 0) END IF @PeriodType = 4 -- quaterly BEGIN --SET @DateFrom = DATEADD(qq, DATEDIFF(qq, 0, @DateFrom), 0) SET @DateTo = DATEADD (dd, -1, DATEADD(qq, DATEDIFF(qq, 0, @DateTo) +1, 0)) ;WITH date_list (id, dStart, dEnd, DisplayString) AS ( SELECT @Count, DATEADD(qq, DATEDIFF(qq, 0, @DateTo), 0), DATEADD (SECOND, -1, DATEADD(qq, DATEDIFF(qq, 0, @DateTo) +1, 0)), 'FY' + CONVERT(varchar, DATEPART(YYYY, DATEADD(M, -3, @DateTo))) + ' - Q' + CONVERT(varchar, (((((DATEPART(MM, @DateTo)-1)+9)%12)/3) + 1)) AS DisplayString UNION ALL SELECT id - 1, DATEADD(qq, -1, dStart), DATEADD (qq, -1, dEnd), 'FY' + CONVERT(varchar, DATEPART(YYYY, DATEADD (qq, -1, DATEADD(M, -3, dEnd)))) + ' - Q' + CONVERT(varchar, (((((DATEPART(MM, DATEADD (qq, -1, dEnd))-1)+9)%12)/3) + 1)) FROM date_list WHERE id > 1 ) INSERT INTO @t SELECT id, dStart, dEnd, DisplayString FROM date_list OPTION (MAXRECURSION 0) END --IF @PeriodType = 5 -- half yearly --BEGIN -- raiserror ('not impleted yt', 15, 1) --END IF @PeriodType = 6 -- yearly BEGIN --SET @DateFrom = DATEADD(M, 3, DATEADD(yy, DATEDIFF(yy,0, dateadd(M, -3, @DateFrom)), 0)) SET @DateTo = DATEADD(D, -1, DATEADD(YY, 1, DATEADD(M, 3, DATEADD(yy, DATEDIFF(yy,0, dateadd(M, -3, @DateTo)), 0)))) ;WITH date_list (id, dStart, dEnd, DisplayString) AS ( SELECT @Count, DATEADD(M, 3, DATEADD(yy, DATEDIFF(yy,0, dateadd(M, -3, @DateTo)), 0)), DATEADD(SECOND, -1, DATEADD(D, 1, @DateTo)), RIGHT(datepart(yy, DATEADD(YY, -1, @DateTo)),2) + '-' + RIGHT(datepart(yy, @DateTo),2) AS DisplayString UNION ALL SELECT id - 1, DATEADD(YY, -1, dStart), DATEADD(YY, -1, dEnd), RIGHT(datepart(yy, DATEADD(YY, -1, dStart)),2) + '-' + RIGHT(datepart(yy, DATEADD(YY, -1, dEnd)),2) FROM date_list WHERE id > 1 ) INSERT INTO @t SELECT id, dStart, dEnd, DisplayString FROM date_list OPTION (MAXRECURSION 0) END RETURN END GO ``` ``` sql DELIMITER $$ CREATE DEFINER=`root`@`localhost` FUNCTION `FindWeekday`( findDay int, startDate date, endDate date ) RETURNS int(11) BEGIN DECLARE wDay int; declare addDay int; declare firstDay date; declare countDay int; declare totalWeekDay int; -- Start 2015-10-01 -- End 2015-10-12 -- 0 = monday, 1 = Tuesday, 2 = ....... -- Find Tuesday set wDay = (select weekday(startDate)); -- weekday of startDate = 3 -- first tuesday is on 2015-10-06 -- wee need add 5 to get first tuesday -- farmula two get add days to get first required weekday -- ((7 - cw) + rw) % 7 set addDay = (select ((7-wDay) + findDay) % 7 as v); set firstDay = (select date_add(startDate, interval addDay day) as first); set countDay = (select datediff(endDate, firstDay) as diff); set totalWeekDay = (select floor(countDay / 7) + 1 as total); RETURN totalWeekDay; END$$ DELIMITER ; ``` <file_sep>/_posts/2015-10-23-bower-version-operators.md --- layout: master title: Bower operators categories: bower --- Bower commands ### Bower version operator We can `~` to narrow the range of versions. for example if we use `~1.2.4` then this accept all `1.2.x` but not accept `1.3` <file_sep>/_posts/mvc/2015-10-22-CrossDomain.md --- layout: master title: Cross domain setup in MVC Web API categories: mvc --- Setup for cross domain ajax request ### web.config ``` xml <system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*"/> <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/> <!--<add name="Access-Control-All-Headers" value="Origin, X-Requested-With, Content-Type, Accept"/>--> <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept"/> </customHeaders> </httpProtocol> </system.webServer> ``` ``` csharp [AcceptVerbs("OPTIONS")] [HttpOptions] [HttpPost] public IHttpActionResult Login(LoginModel model) { if (Request.Method == System.Net.Http.HttpMethod.Options) return Ok(); if (model == null) { return BadRequest(); } var u = db.Usermasters.Where(x => (x.ExtUserId == model.UserName || x.EmailId == model.UserName) && x.Active).FirstOrDefault(); if (u == null) { return Unauthorized(); } if (u.Password != model.Password) { return BadRequest("Invalid username of password"); } FormsAuthentication.SetAuthCookie(model.UserName, true); //System.Web.HttpContext.Current.Session["userId"] = u.UserId; //System.Web.HttpContext.Current.Session["roleId"] = u.RoleId; return Ok(new { firstName = u.FirstName, username = u.ExtUserId, email = u.EmailId, role = u.RoleId }); } ```<file_sep>/_posts/dotnet/2016-10-06-load-dll-dynamically.md --- author: todo layout: master title: Load dll file on dynamically from diffrent path categories: dotnet --- Load dll file on dynamically from diffrent path ### Register event ``` csharp AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve); static Assembly currentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { //This handler is called only when the common language runtime tries to bind to the assembly and fails. //Retrieve the list of referenced assemblies in an array of AssemblyName. Assembly MyAssembly, objExecutingAssemblies; string strTempAssmbPath = ""; objExecutingAssemblies = Assembly.GetExecutingAssembly(); AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies(); //Loop through the array of referenced assembly names. foreach (AssemblyName strAssmbName in arrReferencedAssmbNames) { //Check for the assembly names that have raised the "AssemblyResolve" event. if (strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(","))) { //Build the path of the assembly from where it has to be loaded. //The following line is probably the only line of code in this method you may need to modify: strTempAssmbPath += System.IO.Directory.GetCurrentDirectory() + @"\test.dll"; break; } } var bytes = System.IO.File.ReadAllBytes(strTempAssmbPath); //Load the assembly from the specified path. //MyAssembly = Assembly.LoadFrom(strTempAssmbPath); MyAssembly = Assembly.Load(bytes); //Return the loaded assembly. return MyAssembly; } ```<file_sep>/_posts/general/2016-09-27-git.md --- layout: master title: GIT categories: general --- Git is a version control system that is used for software development and other version control tasks. As a distributed revision control system it is aimed at speed, data integrity, and support for distributed, non-linear workflows. ### Revert changes to modified files. ``` $ git reset --hard ``` ### Remove all untracked files and directories. ``` $ git clean -fd ``` > (`-f` is `force`, `-d` is `remove directories`) ### Revert any commited code ``` bash $ git checkout master $ git reset --hard e3f1e37 $ git push --force origin master # Then to prove it (it won't print any diff) $ git diff master..origin/master ``` > View [stackoverflow link](http://stackoverflow.com/questions/17667023/git-how-to-reset-origin-master-to-a-commit) ### Update git, remove unreferenced ``` bash $ git prune ```<file_sep>/README.md # kishanmundha.github.io <file_sep>/_posts/2016-10-06-dotnet.md --- layout: master title: .NET documents --- ## .NET documents <style> .class2 { list-style-type:none; background-color:white; margin:10px 0px; border-radius: 2px; padding: 10px; } body { background-color:#eee; } </style> <ul style="padding-left:0px;"> {% for post in site.posts %} {% if post.categories contains 'dotnet' %} <li class="class2"><a href="{{ BASE_PATH }}{{ post.url }}">{{ post.title }}</a> <div> {{ post.excerpt | remove: '<p>' | remove: '</p>' }} </div> </li> {% endif %} {% endfor %} </ul> <file_sep>/_posts/general/2016-09-09-javascript-in-bat-file.md --- author: todo layout: master title: Execute a javascript code in batch file categories: general --- Execute a javascript code in batch file ### Example for execute a api from javascript in bat file ``` bat @if (@This==@IsBatch) @then @echo off rem **** batch zone ********************************************************* setlocal enableextensions disabledelayedexpansion rem Batch file will delegate all the work to the script engine rem if not "%~1"=="" ( wscript //E:JScript "%~dpnx0" rem %1 rem ) rem End of batch area. Ensure batch ends execution before reaching rem javascript zone exit /b @end // **** Javascript zone ***************************************************** // Instantiate the needed component to make url queries var http = WScript.CreateObject("MSXML2.ServerXMLHTTP"); // Retrieve the url parameter //var url = WScript.Arguments.Item(0) // Make the request http.open("GET", 'http://www.google.com', false); http.send(); // All done. Exit WScript.Quit(0); ``` <file_sep>/_posts/mvc/2016-08-20-enable-gzip-web-api.md --- author: todo layout: master title: Enable GZip for Web API categories: mvc --- GZip enable to compress response and maximize speed of response ### Add NuGet Refrence Install `Microsoft.AspNet.WebApi.MessageHandlers.Compression` package by NuGet https://www.nuget.org/packages/Microsoft.AspNet.WebApi.MessageHandlers.Compression/ ### Change in `WebApiConfig.cs` Add this line in `Register` Method ``` csharp config.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor())); ``` ----- View more on [https://damienbod.com/2014/07/16/web-api-using-gzip-compression/](https://damienbod.com/2014/07/16/web-api-using-gzip-compression/)
20e3f7233b6a00b31a12861ba8ae7bf763813018
[ "Markdown", "JavaScript" ]
14
Markdown
kishanmundha/kishanmundha.github.io
c9f5fec7ade352111d9da387cf943740b01aade0
ac569fe4c42249a52399cfcdd1f63f545724b6c5
refs/heads/master
<repo_name>jpbel65/ProjetRabbit<file_sep>/main.py from tkinter import * from pafy import * from vlc import * from PIL import Image as PILImage, ImageTk import asyncio import websockets import threading import multiprocessing import requests import queue import io class App: def __init__(self, window, title, kq): self.videoOnly = False self.previewList = False self.kq = kq self.window = window window.bind('<Escape>', self.switch_view) window.bind('<Return>', self.create_request) self.window.title(title) self.window.attributes("-topmost", True) self.panel = None self.media = None self.player = None self.webSocket = None self.videoQueue = queue.Queue() self.videoFrame = LabelFrame(window) self.videoFrame.pack(fill="both", expand="yes", sid="left") self.optionFrame = LabelFrame(window, text="Option") self.optionFrame.pack(fill="both", expand="no", sid="right") self.toolsFrame = LabelFrame(self.optionFrame) self.toolsFrame.pack(fill="x", expand="no", sid="top") self.slider = Scale(self.toolsFrame, from_=0, to=100, orient=HORIZONTAL, command=lambda value: self.set_volume(value)) self.currentTimer = Label(self.toolsFrame, text="00:00") self.totalTimer = Label(self.toolsFrame, text="/ 00:00") self.buttonFullScreen = Button(self.toolsFrame, command=lambda: self.switch_view('fullScreen'), text="FullScreen") self.buttonHide = Button(self.toolsFrame, command=lambda: self.switch_view('hide'), text="Hide") self.currentTimer.pack(sid="left") self.totalTimer.pack(sid="left") self.buttonFullScreen.pack(sid="left") self.buttonHide.pack(sid="left") self.slider.pack(sid="right") self.input = Entry(self.optionFrame) self.input.pack(fill="x", expand="no", sid="top") self.previewFrame = LabelFrame(self.optionFrame, text="Preview") self.previewFrame.pack(fill="x", expand="no", sid="top") self.window.protocol("WM_DELETE_WINDOW", self.on_closing) t1 = threading.Thread(target=self.async_run_video) t2 = threading.Thread(target=self.async_run_comm_web) t3 = threading.Thread(target=self.get_video_time) t1.start() t2.start() t3.start() async def request_async(self): await self.webSocket.send(self.input.get()) self.input.delete(0, 'end') def create_request(self, event): asyncio.new_event_loop().run_until_complete(self.request_async()) def add_request(self, request): frame = LabelFrame(self.previewFrame) info_frame = Label(frame) info_frame.pack(sid="right") thumb_frame = Label(frame) thumb_frame.pack(sid="left") pafy_request = pafy.new(request) respond = requests.get(pafy_request.thumb).content data = PILImage.open(io.BytesIO(respond)) image = ImageTk.PhotoImage(data) thumb = Label(thumb_frame, image=image) thumb.pack() titles = pafy_request.title.split() segment = [] for i in range(4): element = '' while len(element) < 20 and titles: element += (titles.pop(0) + ' ') segment.append(element) for element in segment: Label(info_frame, text=element).pack() timer = Label(info_frame, text='Time : {}'.format(pafy_request.duration)) timer.pack() frame.pack() self.videoQueue.put((request, frame, image)) def switch_view(self, event): if self.videoOnly is True: self.window.attributes("-fullscreen", False) self.optionFrame.pack(fill="both", expand="no", sid="right") self.videoOnly = False elif event == 'fullScreen': self.window.attributes("-fullscreen", True) self.videoOnly = True self.optionFrame.pack_forget() elif event == 'hide': self.videoOnly = True self.optionFrame.pack_forget() def set_volume(self, value): if self.player is not None: self.player.audio_set_volume(int(value)) def get_video_time(self): while True: if self.player is not None: time = int(int(libvlc_media_player_get_time(self.player)) / 1000) second = time % 60 minute = int((time - second) / 60) self.currentTimer.configure(text='{0:0=2d}:{1:0=2d}'.format(minute, second)) def get_video_length(self): time = int(int(libvlc_media_player_get_length(self.player)) / 1000) second = time % 60 minute = int((time - second) / 60) return ' / {0:0=2d}:{1:0=2d}'.format(minute, second) async def video_run(self): while True: url, frame, image = self.videoQueue.get() if self.player is not None: self.panel.destroy() self.panel = Label(self.videoFrame) self.panel.pack(fill=BOTH, expand=1, sid="bottom") link_pafy = pafy.new(url) best_link_video = link_pafy.getbest() vlc_instance = Instance() self.player = vlc_instance.media_player_new() self.player.set_hwnd(self.panel.winfo_id()) # tkinter label or frame self.media = vlc_instance.media_new(best_link_video.url) self.media.get_mrl() self.player.set_media(self.media) self.player.audio_set_volume(20) self.slider.set(20) self.player.play() while self.player.get_state().value != 3: pass self.player.pause() self.totalTimer.configure(text=self.get_video_length()) await self.webSocket.send("ready") while self.player.get_state().value != 6: pass frame.destroy() def on_closing(self): if self.player is not None: self.player.stop() self.kq.put(True) self.window.quit() self.window.destroy() def async_run_comm_web(self): asyncio.new_event_loop().run_until_complete(self.web_socket_canal()) def async_run_video(self): asyncio.new_event_loop().run_until_complete(self.video_run()) async def web_socket_canal(self): response = requests.get('https://afternoon-woodland-81509.herokuapp.com/') port = response.json() uri = "ws://afternoon-woodland-81509.herokuapp.com/"+port async with websockets.connect(uri, ping_interval=1, ping_timeout=None) as self.webSocket: while self.webSocket.closed is False: respond = await self.webSocket.recv() print(f"< {respond}") if respond == 'play': if self.player is not None: self.player.play() elif respond == 'stop': if self.player is not None: self.player.pause() else: self.add_request(respond) def start(kq): app = App(Tk(), "ProjetRabbit", kq) app.window.mainloop() if __name__ == '__main__': multiprocessing.freeze_support() killQueue = multiprocessing.Queue() p = multiprocessing.Process(target=start, args=(killQueue,)) p.start() while True: if killQueue.get() is True: p.kill() break
27b482f104161e78da7414c984f3b0d7c897b591
[ "Python" ]
1
Python
jpbel65/ProjetRabbit
6811f68bdf773da000477f349bb97179f344431d
7d6c3896e39f4005cfb2ddbfba18bf49b9fe9122
refs/heads/master
<file_sep>const users = [ { name: "Carlos", technologies: ["HTML", "CSS"] }, { name: "Jasmine", technologies: ["JavaScript", "CSS"] }, { name: "Tuane", technologies: ["HTML", "Node.js"] } ]; for (let list of users) { console.log(`${list.name} works with ${list.technologies.join(', ')}`); } function checkIfUseCSS(user) { for ( let technology of user.technologies ) { if ( technology === 'CSS' ) { return true; } } return false; } console.log('=========================='); for (let i = 0; i < users.length; i++) { const userWorksWithCSS = checkIfUseCSS(users[i]); if (userWorksWithCSS) { console.log(`${users[i].name} works with CSS`); } }<file_sep>const express = require('express'); const nunjucks = require('nunjucks'); const server = express(); const data = require('./data'); // configurar a pasta public server.use(express.static('public')); // configurar a template engine (njk, html...) server.set("view engine", "njk"); // configurar a pasta views nunjucks.configure("views", { express: server, }) server.get('/', (request, response) => { response.redirect('/courses'); }); server.get('/courses', (request, response) => { response.render('courses', { courses: data }); }); server.get('/courses/:id', (request, resopnse) => { const id = request.params.id; course = data.find((course) => { return course.id == id; }); if (!course) { return resopnse.render('not-found'); } return resopnse.render('course', { course }); }); server.get('/about', (request, response) => { response.render('about'); }); server.use((request, response)=>{ response.status(404).render('not-found'); }) server.listen(5000, () => { console.log('Server is running'); });<file_sep>const users = [ { name: "Salvio", recipes: [115.3, 48.7, 98.3, 14.5], expenses: [85.3, 13.5, 19.9] }, { name: "Marcio", recipes: [24.6, 214.3, 45.3], expenses: [185.3, 12.1, 120.0] }, { name: "Lucia", recipes: [9.8, 120.3, 340.2, 45.3], expenses: [450.2, 29.9] } ]; function calculatesBalanceTests(recipes, expenses) { const sumRecipes = sumNumbers(recipes); const sumExpenses = sumNumbers(expenses); return sumRecipes - sumExpenses; } function sumNumbers(numbers) { let sum = 0; for ( let number of numbers ) { sum += number; } return sum; } for ( let user of users ) { const balance = calculatesBalanceTests(user.recipes, user.expenses); if ( balance >= 0 ) { console.log(`${user.name} has a POSITIVE balance of ${balance.toFixed(2)}`); } else { console.log(`${user.name} has a NEGATIVE balance of ${balance.toFixed(2)}`); } }<file_sep>module.exports = [ { id: "nextjs-novidades-na-versao-10-e-atualizacao-do-blog-para-melhorar-a-performance", image_url: "https://blog.rocketseat.com.br/content/images/2020/11/capa_visao-geral-sobre-next-js-na-versao-10-e-atualizacao-do-blog-para-melhorar-a-performance.jpg", title: "Next.JS - Novidades na versão 10 e atualização do blog para melhorar a performance", author: "<NAME>", duration: "4 MIN", }, { id: "mapas-com-react-usando-leaflet", image_url: "https://blog.rocketseat.com.br/content/images/2020/11/blog-thumb-utilizando-mapas-no-react-com-leaflet-1.jpg", title: "Mapas com React usando Leaflet", author: "<NAME>", duration: "11 MIN", }, { id: "como-renomear-varios-arquivos-de-uma-vez-usando-o-terminal", image_url: "https://blog.rocketseat.com.br/content/images/2020/11/thumb-como-renomear-varios-arquivos-de-uma-vez-usando-o-terminal.jpg", title: "Como renomear vários arquivos de uma vez usando o terminal", author: "<NAME>", duration: "2 MIN", } ]; <file_sep>const programmer = { name: "Hilton", age: 18, technologies: [ { name: 'C++', specialty: 'Desktop' }, { name: 'Python', specialty: 'Data Science' }, { name: 'JavaScript', specialty: 'Web/Mobile' } ] }; console.log(`${programmer.name} is ${programmer.age} years old and uses ${programmer.technologies[0].name} with specialty in ${programmer.technologies[0].specialty}`);<file_sep>const name = 'Hilton'; const weight = 76; const height = 1.87; const sex = 'M'; const imc = weight / (height * height); if ( imc >= 30 ) { console.log(`${name}, are you overweight.`); } else { console.log(`${name}, you are not overweight.`); }<file_sep>const user = { name: "Hilton", transactions: [], balance: 0 } // Adicionar Transações function createTransaction (transaction) { user.transactions.push(transaction) if (transaction.type == 'credit') { user.balance += transaction.value } else { user.balance -= transaction.value } } // =========== Relatórios =========== // // Retorna a maior transação do tipo escolhido (debit/credit) function getHigherTransactionByType (transactionType) { let higherTransaction = 0 let highestValue = 0 for (let transaction of user.transactions) { if (transaction.type === transactionType && transaction.value > highestValue ) { higherTransaction = transaction highestValue = transaction.value } } return higherTransaction } // Retorna o valor médio de todas as transações function getAverageTransactionValue() { let sumTransactions = 0 for (let transaction of user.transactions) { sumTransactions += transaction.value } return sumTransactions / user.transactions.length } // Retorna o número de transações de cada tipo (debit/credit) function getTransactionsCount() { const numberOfTransactionsOfEachType = {credit: 0, debit: 0} for (let transaction in user.transactions) { if (user.transactions[transaction].type == "credit") { numberOfTransactionsOfEachType.credit += 1 } else { numberOfTransactionsOfEachType.debit += 1 } } return numberOfTransactionsOfEachType } createTransaction({ type: "credit", value: 50 }); createTransaction({ type: "credit", value: 120 }); createTransaction({ type: "debit", value: 80 }); createTransaction({ type: "debit", value: 30 }); console.log(user.balance); // 60 console.log(getHigherTransactionByType("credit")); // { type: 'credit', value: 120 } console.log(getHigherTransactionByType("debit")); // { type: 'debit', value: 80 } console.log(getAverageTransactionValue()); // 70 console.log(getTransactionsCount()); // { credit: 2, debit: 2 }
b624f0ef435e237fbaedc3b79a6486e26c307911
[ "JavaScript" ]
7
JavaScript
Hilton1/desafios-bootcamp-launchbase
2e504e64d8b4d8cc15ff177d461d3f77b6c76e3c
ede69311e383cdeb1c721bd35fc0c6969b16b7db
refs/heads/master
<file_sep>$(".navbuttons").hover( function() { $(this).addClass("highlightedButton"); }, function(){ $(this).removeClass("highlightedButton"); } ); $(".navbuttons").click( function(){ $(this).toggleClass("active"); $(this).removeClass("highlightedButton"); var panelId = $(this).attr("id") + "Panel"; $("#" + panelId).toggleClass("hidden"); var numberOfActivePanels = 4 - $('.hidden').length; $(".panel").width(($(window).width() / numberOfActivePanels) -5); } ); $(".panel").height($(window).height() - $("#navbar").height()-15); $(".panel").width(($(window).width() / 2) -7); outputUpdate(); $('textarea').on('change keyup paste', function() { outputUpdate(); }); function outputUpdate(){ $("iframe").contents().find("html").html("<html><head><style type='text/css'>" + $("#cssPanel").val() + "</style></head><body>" + $("#htmlPanel").val().replace(/\n/g, '<br />') + "</body></html>"); document.getElementById('outputPanel').contentWindow.eval($("#javascriptPanel").val()); }
9fed8fc1ffd7530ad4bcf2fc2271be9c50549770
[ "JavaScript" ]
1
JavaScript
VaheMinasian/codePlayer
624ab41940b4370fe6e0ff88152a9adf7a281a52
34fda95a814043cc6e0458159390b63d8e7f64cc
refs/heads/master
<file_sep>#ifndef IOLISP_ERRORS_HPP #define IOLISP_ERRORS_HPP #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "./show.hpp" #include "./value.hpp" namespace iolisp { class error : public std::runtime_error { public: explicit error(std::string const &msg) : std::runtime_error(msg) {} }; class wrong_number_of_arguments : public error { public: template <class FoundArgs> wrong_number_of_arguments(int expected, FoundArgs const &found) : error(build_message(expected, found)) {} private: template <class FoundArgs> static std::string build_message(int expected, FoundArgs const &found) { std::ostringstream oss; oss << "Expected " << expected << " args; found values"; for (auto const &v : found) oss << ' ' << v; return oss.str(); } }; class type_mismatch : public error { public: type_mismatch(std::string expected, value const &found) : error("Invalid type: expected " + std::move(expected) + ", found " + show(found)) {} }; class parse_error : public error { public: explicit parse_error(std::string msg) : error("Parse error at " + std::move(msg)) {} }; class bad_special_form : public error { public: bad_special_form(std::string msg, value const &form) : error(std::move(msg) + ": " + show(form)) {} }; class not_function : public error { public: not_function(std::string msg, std::string func) : error(std::move(msg) + ": " + std::move(func)) {} }; class unbound_variable : public error { public: unbound_variable(std::string msg, std::string name) : error(msg + ": " + name) {} }; } #endif <file_sep>#define BOOST_RESULT_OF_USE_DECLTYPE #define BOOST_SPIRIT_USE_PHOENIX_V3 #include <iostream> #include <map> #include <memory> #include <string> #include <boost/range/adaptors.hpp> #include <boost/range/functions.hpp> #include <boost/range/iterator_range.hpp> #include "./eval.hpp" #include "./io_primitives.hpp" #include "./primitives.hpp" #include "./read.hpp" #include "./show.hpp" using namespace iolisp; environment primitive_bindings() { auto const env = std::make_shared<std::map<std::string, std::shared_ptr<value>>>(); for (auto const &prim : primitives()) env->insert({ prim.first, std::make_shared<value>(value::make<primitive_function>(prim.second))}); for (auto const &io_prim : io_primitives()) env->insert({ io_prim.first, std::make_shared<value>(value::make<io_function>(io_prim.second))}); return env; } void eval_and_print(environment const &env, std::string const &input) try { std::cout << eval(env, read(input)) << std::endl; } catch (error const &e) { std::cerr << e.what() << std::endl; } void run_repl() { auto const env = primitive_bindings(); while (true) { std::cout << "iolisp>>> "; std::string input; std::getline(std::cin, input); if (input == "quit") break; else eval_and_print(env, input); } } void run_one(boost::iterator_range<char **> rng) { auto const env = primitive_bindings(); auto const args = rng | boost::adaptors::sliced(1, boost::size(rng)) | boost::adaptors::transformed(&value::make<string>); define_variable(env, "args", value::make<list>({boost::begin(args), boost::end(args)})); auto const val = value::make<list>({ value::make<atom>("load"), value::make<string>(*rng.begin())}); std::cout << eval(env, val) << std::endl; } int main(int argc, char *argv[]) { if (argc == 1) run_repl(); else run_one(boost::make_iterator_range(argv + 1, argv + argc)); } <file_sep>#ifndef IOLISP_EVAL_HPP #define IOLISP_EVAL_HPP #include <array> #include <functional> #include <map> #include <memory> #include <string> #include <vector> #include <boost/range/adaptors.hpp> #include <boost/range/functions.hpp> #include <boost/optional.hpp> #include "./errors.hpp" #include "./value.hpp" namespace iolisp { namespace eval_detail { inline bool is_bound(environment const &env, std::string const &var) { return env->find(var) != env->end(); } inline value get_variable(environment const &env, std::string const &var) { auto const it = env->find(var); if (it != env->end()) return *(it->second); throw unbound_variable("Getting an unbound variable: ", var); } inline value set_variable(environment const &env, std::string const &var, value const &val) { auto const it = env->find(var); if (it != env->end()) { *(it->second) = val; return val; } throw unbound_variable("Setting an unbound variable: ", var); } inline value define_variable(environment const &env, std::string const &var, value const &val) { auto const it = env->find(var); if (it != env->end()) { *(it->second) = val; return val; } else { env->insert(it, {var, std::make_shared<value>(val)}); return val; } } template <class Parameters, class Body> inline value make_function( Parameters const &params, boost::optional<value> const &varargs, Body const &body, environment const &env) { auto const param_strs = params | boost::adaptors::transformed(&show); return value::make<function>({ {boost::begin(param_strs), boost::end(param_strs)}, varargs ? boost::make_optional(show(*varargs)) : boost::none, {boost::begin(body), boost::end(body)}, env}); } } value eval(environment const &envm, value const &val); template <class Args> inline value apply(value const &func, Args const &args) { if (func.is<primitive_function>()) return func.get<primitive_function>()(args); else if (func.is<io_function>()) return func.get<io_function>()(args); else if (func.is<function>()) { auto const &rep = func.get<function>(); if (rep.parameters.size() != boost::size(args) && !rep.variadic_argument) throw wrong_number_of_arguments(rep.parameters.size(), args); else { auto const closure = std::make_shared<std::map<std::string, std::shared_ptr<value>>>(*rep.closure); auto it2 = boost::begin(args); for ( auto it1 = rep.parameters.begin(); it1 != rep.parameters.end() && it2 != boost::end(args); ++it1, ++it2) (*closure)[*it1] = std::make_shared<value>(*it2); if (rep.variadic_argument) (*closure)[*rep.variadic_argument] = std::make_shared<value>(value::make<list>({it2, boost::end(args)})); value ret; for (auto const &val : rep.body) ret = eval(closure, val); return ret; } } throw not_function("Unrecognized primitive function args", show(func)); } std::vector<value> load(std::string const &filename); inline value eval(environment const &env, value const &val) { // eval env val@(Number _) = val if (val.is<number>()) return val; // eval env val@(String _) = val else if (val.is<string>()) return val; // eval env val@(Bool _) = val else if (val.is<bool_>()) return val; // eval env val@(Atom var) = getVar env var if (val.is<atom>()) return eval_detail::get_variable(env, val.get<atom>()); else if (val.is<list>()) { auto const &vec = val.get<list>(); // eval env (List [Atom "quote", val]) = val if (vec.size() == 2 && vec[0].is<atom>() && vec[0].get<atom>() == "quote") return vec[1]; // eval env (List [Atom "if", pred, conseq, alt]) = case eval env pred of // Bool False -> eval alt // _ -> eval conseq else if (vec.size() == 4 && vec[0].is<atom>() && vec[0].get<atom>() == "if") { auto const res = eval(env, vec[1]); return res.is<bool_>() && !res.get<bool_>() ? eval(env, vec[3]) : eval(env, vec[2]); } // eval env (List [Atom "set!", Atom var, form]) = setVar env var (eval env form) else if ( vec.size() == 3 && vec[0].is<atom>() && vec[0].get<atom>() == "set!" && vec[1].is<atom>()) return eval_detail::set_variable(env, vec[1].get<atom>(), eval(env, vec[2])); // eval env (List [Atom "define", Atom var, form]) = defineVar env var (eval env form) else if ( vec.size() == 3 && vec[0].is<atom>() && vec[0].get<atom>() == "define" && vec[1].is<atom>()) return eval_detail::define_variable(env, vec[1].get<atom>(), eval(env, vec[2])); // eval env (List (Atom "define" : List (Atom var : params) : body)) = ... else if ( vec.size() >= 2 && vec[0].is<atom>() && vec[0].get<atom>() == "define" && vec[1].is<list>()) { auto const &var_params = vec[1].get<list>(); if (!var_params.empty() && var_params[0].is<atom>()) return eval_detail::define_variable( env, var_params[0].get<atom>(), eval_detail::make_function( var_params | boost::adaptors::sliced(1, var_params.size()), boost::none, vec | boost::adaptors::sliced(2, vec.size()), env)); } // eval env (DottedList (Atom "define" : List (Atom var : params)) varargs : body)) = ... else if ( vec.size() >= 2 && vec[0].is<atom>() && vec[0].get<atom>() == "define" && vec[1].is<dotted_list>()) { auto const &var_params = vec[1].get<dotted_list>().first; if (!var_params.empty() && var_params[0].is<atom>()) return eval_detail::define_variable( env, var_params[0].get<atom>(), eval_detail::make_function( var_params | boost::adaptors::sliced(1, var_params.size()), vec[1].get<dotted_list>().second, vec | boost::adaptors::sliced(2, vec.size()), env)); } // eval env (List [Atom "lambda" : List params : body]) = ... else if ( vec.size() >= 2 && vec[0].is<atom>() && vec[0].get<atom>() == "lambda" && vec[1].is<list>()) return eval_detail::make_function( vec[1].get<list>(), boost::none, vec | boost::adaptors::sliced(2, vec.size()), env); // eval env (List [Atom "lambda" : DottedList params varargs : body]) = ... else if ( vec.size() >= 2 && vec[0].is<atom>() && vec[0].get<atom>() == "lambda" && vec[1].is<dotted_list>()) return eval_detail::make_function( vec[1].get<dotted_list>().first, vec[2].get<dotted_list>().second, vec | boost::adaptors::sliced(2, vec.size()), env); // eval env (List [Atom "lambda" : varargs@(Atom _) : body]) = ... else if ( vec.size() >= 2 && vec[0].is<atom>() && vec[0].get<atom>() == "lambda" && vec[1].is<atom>()) return eval_detail::make_function( std::array<value, 0>(), boost::none, vec | boost::adaptors::sliced(2, vec.size()), env); // eval env (List [Atom "load", String filename]) = ... else if ( vec.size() == 2 && vec[0].is<atom>() && vec[0].get<atom>() == "load" && vec[1].is<string>()) { auto const exprs = load(vec[1].get<string>()); value ret; for (auto const &expr : exprs) ret = eval(env, expr); return ret; } // eval env (List (function : args)) = ... else if (!vec.empty()) { struct eval_env { environment env; value operator()(value const &val) const { return eval(env, val); } }; return apply( eval(env, vec[0]), vec | boost::adaptors::sliced(1, vec.size()) | boost::adaptors::transformed(eval_env{env})); } } throw bad_special_form("Unrecognized special form", val); } using eval_detail::define_variable; } #include "./io_primitives.hpp" #endif <file_sep>#ifndef IOLISP_VALUE_HPP #define IOLISP_VALUE_HPP #include <cstddef> #include <fstream> #include <functional> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include <boost/assert.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/iterator.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/pair.hpp> #include <boost/optional.hpp> #include <boost/range/any_range.hpp> #include <boost/variant.hpp> namespace iolisp { struct atom {}; struct list {}; struct dotted_list {}; struct number {}; struct string {}; struct bool_ {}; struct port {}; struct primitive_function {}; struct io_function {}; struct function {}; class value; using arguments = boost::any_range< value, boost::random_access_traversal_tag, value, std::ptrdiff_t>; using environment = std::shared_ptr<std::map< std::string, std::shared_ptr<value>>>; class value { public: struct function_rep { std::vector<std::string> parameters; boost::optional<std::string> variadic_argument; std::vector<value> body; environment closure; }; using reps = boost::mpl::map< boost::mpl::pair<atom, std::string>, boost::mpl::pair<list, std::vector<value>>, boost::mpl::pair<dotted_list, std::pair<std::vector<value>, value>>, boost::mpl::pair<number, int>, boost::mpl::pair<string, std::string>, boost::mpl::pair<bool_, bool>, boost::mpl::pair<port, std::shared_ptr<std::fstream>>, boost::mpl::pair<primitive_function, std::function<value (arguments)>>, boost::mpl::pair<io_function, std::function<value (arguments)>>, boost::mpl::pair<function, function_rep>>; template <class Type> using rep = typename boost::mpl::at<reps, Type>::type; value() : value(make<list>({})) {} template <class Type> static value make(rep<Type> const &r) { return value(boost::fusion::make_pair<Type>(r)); } template <class Type> bool is() const { return impl_.type() == typeid(boost::fusion::pair<Type, rep<Type>>); } template <class Type> rep<Type> &get() { BOOST_ASSERT(is<Type>()); return boost::get<boost::fusion::pair<Type, rep<Type>>>(impl_).second; } template <class Type> rep<Type> const &get() const { BOOST_ASSERT(is<Type>()); return boost::get<boost::fusion::pair<Type, rep<Type>>>(impl_).second; } private: using impl = boost::variant< boost::fusion::pair<atom, rep<atom>>, boost::recursive_wrapper<boost::fusion::pair<list, rep<list>>>, boost::recursive_wrapper<boost::fusion::pair<dotted_list, rep<dotted_list>>>, boost::fusion::pair<number, rep<number>>, boost::fusion::pair<string, rep<string>>, boost::fusion::pair<bool_, rep<bool_>>, boost::fusion::pair<port, rep<port>>, boost::fusion::pair<primitive_function, rep<primitive_function>>, boost::fusion::pair<io_function, rep<io_function>>, boost::fusion::pair<function, rep<function>>>; template <class Type> value(boost::fusion::pair<Type, rep<Type>> const &p) : impl_(p) {} impl impl_; }; } #endif <file_sep>#ifndef IOLISP_PRIMITIVES_HPP #define IOLISP_PRIMITIVES_HPP #include <array> #include <memory> #include <utility> #include <vector> #include <boost/lexical_cast.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm_ext/insert.hpp> #include <boost/range/functions.hpp> #include <boost/range/numeric.hpp> #include "./value.hpp" namespace iolisp { namespace primitives_detail { template <class T> value::rep<T> unpack(value const &v); template <> inline value::rep<number> unpack<number>(value const &v) { if (v.is<number>()) return v.get<number>(); else if (v.is<string>()) try { return boost::lexical_cast<int>(v.get<string>()); } catch (boost::bad_lexical_cast const &) { throw type_mismatch("number", v); } else if (v.is<list>()) { auto const &vec = v.get<list>(); if (vec.size() == 1) return unpack<number>(vec[0]); } throw type_mismatch("number", v); } template <> inline value::rep<string> unpack<string>(value const &v) { if (v.is<string>()) return v.get<string>(); else if (v.is<number>()) return boost::lexical_cast<std::string>(v.get<number>()); else if (v.is<bool_>()) return v.get<bool_>() ? "True" : "False"; throw type_mismatch("string", v); } template <> inline value::rep<bool_> unpack<bool_>(value const &v) { if (v.is<bool_>()) return v.get<bool_>(); throw type_mismatch("boolean", v); } inline value numeric_binary_op(std::function<int (int, int)> fn, arguments args) { if (boost::size(args) == 1) throw wrong_number_of_arguments(2, args); auto const ns = args | boost::adaptors::transformed(&unpack<number>); return value::make<number>(boost::accumulate( ns | boost::adaptors::sliced(1, boost::size(ns)), *boost::begin(ns), fn)); } template <class Type> inline value bool_binary_op( std::function<bool (value::rep<Type> const &, value::rep<Type> const &)> func, arguments args) { if (boost::size(args) != 2) throw wrong_number_of_arguments(2, args); return value::make<bool_>(func( unpack<Type>(*boost::begin(args)), unpack<Type>(*(boost::begin(args) + 1)))); } inline value car(arguments args) { if (boost::size(args) == 1) { auto const &val = *boost::begin(args); if (val.is<list>()) { auto const &vec = val.get<list>(); if (!vec.empty()) return vec[0]; } else if (val.is<dotted_list>()) { auto const &init = val.get<dotted_list>().first; if (init.size() == 2) return init[0]; } throw type_mismatch("pair", val); } throw wrong_number_of_arguments(1, args); } inline value cdr(arguments args) { if (boost::size(args) == 1) { auto const &val = *boost::begin(args); if (val.is<list>()) { auto const &vec = val.get<list>(); if (!vec.empty()) return value::make<list>({vec.begin() + 1, vec.end()}); } else if (val.is<dotted_list>()) { auto const &init = val.get<dotted_list>().first; auto const &last = val.get<dotted_list>().second; if (init.size() == 1) return last; else if (init.size() >= 2) return value::make<dotted_list>({{init.begin() + 1, init.end()}, last}); } throw type_mismatch("pair", val); } throw wrong_number_of_arguments(1, args); } inline value cons(arguments args) { if (boost::size(args) == 2) { auto const &head = *boost::begin(args); auto const &tail = *(boost::begin(args) + 1); if (tail.is<list>()) { std::vector<value> vec{head}; boost::insert(vec, vec.end(), tail.get<list>()); return value::make<list>(vec); } else if (tail.is<dotted_list>()) { std::vector<value> vec{head}; boost::insert(vec, vec.end(), tail.get<dotted_list>().first); return value::make<dotted_list>({vec, tail.get<dotted_list>().second}); } else return value::make<dotted_list>({{head}, tail}); } throw wrong_number_of_arguments(2, args); } inline value eqv(arguments args) { if (boost::size(args) == 2) { auto const &lhs = *boost::begin(args); auto const &rhs = *(boost::begin(args) + 1); if (lhs.is<bool_>() && rhs.is<bool_>()) return value::make<bool_>(lhs.get<bool_>() == rhs.get<bool_>()); else if (lhs.is<number>() && rhs.is<number>()) return value::make<bool_>(lhs.get<number>() == rhs.get<number>()); else if (lhs.is<string>() && rhs.is<string>()) return value::make<bool_>(lhs.get<string>() == rhs.get<string>()); else if (lhs.is<atom>() && rhs.is<atom>()) return value::make<bool_>(lhs.get<atom>() == rhs.get<atom>()); else if (lhs.is<dotted_list>() && rhs.is<dotted_list>()) { auto const to_list = [](value const &val) -> value { auto vec = val.get<dotted_list>().first; vec.push_back(val.get<dotted_list>().second); return value::make<list>(vec); }; return eqv(std::array<value, 2>{{to_list(lhs), to_list(rhs)}}); } else if (lhs.is<list>() && rhs.is<list>()) return value::make<bool_>(boost::equal( lhs.get<list>(), rhs.get<list>(), [](value const &val1, value const &val2) -> bool { auto const res = eqv(std::array<value, 2>{{val1, val2}}); BOOST_ASSERT(res.is<bool_>()); return res.get<bool_>(); })); return value::make<bool_>(false); } throw wrong_number_of_arguments(2, args); } template <class Type> inline bool unpack_equals(value const &lhs, value const &rhs) try { return unpack<Type>(lhs) == unpack<Type>(rhs); } catch (type_mismatch const &) { return false; } inline value equal(arguments args) { if (boost::size(args) == 2) { auto const &lhs = *boost::begin(args); auto const &rhs = *(boost::begin(args) + 1); if (unpack_equals<number>(lhs, rhs) || unpack_equals<string>(lhs, rhs) || unpack_equals<bool_>(lhs, rhs)) return value::make<bool_>(true); return eqv(std::array<value, 2>{{lhs, rhs}}); } throw wrong_number_of_arguments(2, args); } } inline std::map<std::string, std::function<value (arguments)>> primitives() { using namespace primitives_detail; using namespace std::placeholders; return { {"+", std::bind(&numeric_binary_op, std::plus<int>(), _1)}, {"-", std::bind(&numeric_binary_op, std::minus<int>(), _1)}, {"*", std::bind(&numeric_binary_op, std::multiplies<int>(), _1)}, {"/", std::bind(&numeric_binary_op, std::divides<int>(), _1)}, {"mod", std::bind(&numeric_binary_op, std::modulus<int>(), _1)}, {"quotient", std::bind(&numeric_binary_op, std::divides<int>(), _1)}, {"remainder", std::bind(&numeric_binary_op, std::modulus<int>(), _1)}, {"=", std::bind(&bool_binary_op<number>, std::equal_to<int>(), _1)}, {"<", std::bind(&bool_binary_op<number>, std::less<int>(), _1)}, {">", std::bind(&bool_binary_op<number>, std::greater<int>(), _1)}, {"/=", std::bind(&bool_binary_op<number>, std::not_equal_to<int>(), _1)}, {">=", std::bind(&bool_binary_op<number>, std::greater_equal<int>(), _1)}, {"<=", std::bind(&bool_binary_op<number>, std::less_equal<int>(), _1)}, {"&&", std::bind(&bool_binary_op<bool_>, std::logical_and<bool>(), _1)}, {"||", std::bind(&bool_binary_op<bool_>, std::logical_or<bool>(), _1)}, {"string=?", std::bind(&bool_binary_op<string>, std::equal_to<std::string>(), _1)}, {"string<?", std::bind(&bool_binary_op<string>, std::less<std::string>(), _1)}, {"string>?", std::bind(&bool_binary_op<string>, std::greater<std::string>(), _1)}, {"string<=?", std::bind(&bool_binary_op<string>, std::less_equal<std::string>(), _1)}, {"string>=?", std::bind(&bool_binary_op<string>, std::greater_equal<std::string>(), _1)}, {"car", &car}, {"cdr", &cdr}, {"cons", &cons}, {"eq?", &eqv}, {"eqv?", &eqv}, {"equal?", &equal}}; } } #endif <file_sep>#ifndef IOLISP_IO_PRIMITIVES_HPP #define IOLISP_IO_PRIMITIVES_HPP #include <array> #include <cstddef> #include <fstream> #include <functional> #include <ios> #include <map> #include <memory> #include <string> #include <boost/assert.hpp> #include <boost/range/adaptor/sliced.hpp> #include <boost/range/functions.hpp> #include <boost/scope_exit.hpp> #include "./eval.hpp" #include "./read.hpp" #include "./show.hpp" #include "./value.hpp" namespace iolisp { namespace io_primitives_detail { inline value apply_proc(arguments args) { if (boost::size(args) == 2 && (boost::begin(args) + 1)->is<list>()) return apply(*boost::begin(args), (boost::begin(args) + 1)->get<list>()); else if (boost::size(args) >= 1) return apply(*boost::begin(args), args | boost::adaptors::sliced(1, boost::size(args))); throw wrong_number_of_arguments(1, args); } inline value make_port(std::ios::openmode mode, arguments args) { if (boost::size(args) == 1 && boost::begin(args)->is<string>()) { return value::make<port>( std::make_shared<std::fstream>(boost::begin(args)->get<string>(), mode)); } throw wrong_number_of_arguments(1, args); } inline value close_port(arguments args) { if (boost::size(args) == 1 && boost::begin(args)->is<port>()) { boost::begin(args)->get<port>()->close(); return value::make<bool_>(true); } return value::make<bool_>(false); } inline value read_proc(arguments args) { if (boost::empty(args)) { std::string ret; std::getline(std::cin, ret); return value::make<string>(ret); } else if (boost::size(args) == 1 && boost::begin(args)->is<port>()) { std::string ret; std::getline(*boost::begin(args)->get<port>(), ret); return value::make<string>(ret); } throw wrong_number_of_arguments(0, args); } inline value write_proc(arguments args) { if (boost::size(args) == 1) { std::cout << *boost::begin(args) << std::endl; return value::make<bool_>(true); } else if (boost::size(args) == 2 && (boost::begin(args) + 1)->is<port>()) { *(boost::begin(args) + 1)->get<port>() << *boost::begin(args) << std::endl; return value::make<bool_>(true); } throw wrong_number_of_arguments(0, args); } inline std::string read_file(std::string const &filename) { std::ifstream ifs(filename); ifs.seekg(0, std::ifstream::end); auto const len = ifs.tellg(); ifs.seekg(0, std::ifstream::beg); std::string buf(len, '\0'); if (len != 0) ifs.read(&buf.front(), len); return buf; } inline value read_contents(arguments args) { if (boost::size(args) == 1 && boost::begin(args)->is<string>()) return value::make<string>(read_file(boost::begin(args)->get<string>())); throw wrong_number_of_arguments(1, args); } inline value read_all(arguments args) { if (boost::size(args) == 1 && boost::begin(args)->is<string>()) return value::make<list>(load(boost::begin(args)->get<string>())); throw wrong_number_of_arguments(1, args); } } inline std::vector<value> load(std::string const &filename) { return read_expr_list(io_primitives_detail::read_file(filename)); } inline std::map<std::string, std::function<value (arguments)>> io_primitives() { using namespace io_primitives_detail; using namespace std::placeholders; return { {"apply", &apply_proc}, {"open-input-file", std::bind(&make_port, std::fstream::in, _1)}, {"open-output-file", std::bind(&make_port, std::fstream::out, _1)}, {"close-input-port", &close_port}, {"close-output-port", &close_port}, {"read", &read_proc}, {"write", &write_proc}, {"read-contents", &read_contents}, {"read-all", &read_all}}; } } #endif <file_sep>#ifndef IOLISP_SHOW_HPP #define IOLISP_SHOW_HPP #include <ostream> #include <string> #include <boost/lexical_cast.hpp> #include <boost/range/adaptor/sliced.hpp> #include "./value.hpp" namespace iolisp { template <class C, class CT> inline std::basic_ostream<C, CT> &operator<<(std::basic_ostream<C, CT> &os, value const &val) { if (val.is<atom>()) os << val.get<atom>(); else if (val.is<list>()) { os << '('; auto const &vec = val.get<list>(); if (!vec.empty()) { os << vec.front(); for (auto const &elem : vec | boost::adaptors::sliced(1, vec.size())) os << ' ' << elem; } os << ')'; } else if (val.is<dotted_list>()) { os << '('; for (auto const &elem : val.get<dotted_list>().first) os << elem << ' '; os << ". " << val.get<dotted_list>().second << ')'; } else if (val.is<number>()) os << val.get<number>(); else if (val.is<string>()) os << '"' << val.get<string>() << '"'; else if (val.is<bool_>()) os << (val.get<bool_>() ? "#t" : "#f"); else if (val.is<port>()) os << "<IO port>"; else if (val.is<primitive_function>()) os << "<primitive>"; else if (val.is<io_function>()) os << "<IO primitive>"; else if (val.is<function>()) { auto const &rep = val.get<function>(); os << "(lambda ("; if (!rep.parameters.empty()) { os << '"' << rep.parameters.front() << '"'; for ( auto const &elem : rep.parameters | boost::adaptors::sliced(1, rep.parameters.size())) os << " \"" << elem << '"'; } if (rep.variadic_argument) os << " . " << *rep.variadic_argument; os << ") ...)"; } return os; } inline std::string show(value const &val) { return boost::lexical_cast<std::string>(val); } } #endif <file_sep>#ifndef IOLISP_READ_HPP #define IOLISP_READ_HPP #include <ios> #include <istream> #include <string> #include <vector> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include "./errors.hpp" #include "./value.hpp" namespace iolisp { namespace read_detail { namespace ascii = boost::spirit::ascii; namespace phx = boost::phoenix; namespace qi = boost::spirit::qi; template <class Iterator> class value_grammar : public qi::grammar<Iterator, value (), ascii::space_type> { public: value_grammar() : value_grammar::base_type(expr_) { symbol_ = ascii::char_("!#$%&|*+/:<=>?@^_~") | ascii::char_('-'); atom_ = qi::lexeme[qi::as_string[(ascii::alpha | symbol_) >> *(ascii::alnum | symbol_)][ phx::bind( [](value &val, std::string const &attr) { if (attr == "#t") val = value::make<bool_>(true); else if (attr == "#f") val = value::make<bool_>(false); else val = value::make<atom>(attr); }, qi::_val, qi::_1)]]; list_ = ('(' >> *expr_ >> ')')[ phx::bind( [](value &val, std::vector<value> const &attr) { val = value::make<list>(attr); }, qi::_val, qi::_1)]; dotted_list_ = ('(' >> *expr_ > '.' > expr_ > ')')[ phx::bind( [](value &val, std::vector<value> const &init, value const &last) { val = value::make<dotted_list>({init, last}); }, qi::_val, qi::_1, qi::_2)]; string_ = qi::lexeme[qi::as_string['"' >> *(ascii::char_ - '"') >> '"'][ phx::bind( [](value &val, std::string const &attr) { val = value::make<string>(attr); }, qi::_val, qi::_1)]]; number_ = qi::uint_[ phx::bind( [](value &val, unsigned int attr) { val = value::make<number>(attr); }, qi::_val, qi::_1)]; quoted_ = (qi::lexeme['\'' >> !ascii::space] > expr_)[ phx::bind( [](value &val, value const &attr) { val = value::make<list>({value::make<atom>("quote"), attr}); }, qi::_val, qi::_1)]; expr_ = atom_ | list_ | dotted_list_ | string_ | number_ | quoted_; expr_.name("expr"); qi::on_error( expr_, phx::bind( [this](Iterator first, Iterator, Iterator error_pos, qi::info const &info) { std::ostringstream s; s << "column " << (error_pos - first + 1) << ": expecting " << info; error_ = s.str(); }, qi::_1, qi::_2, qi::_3, qi::_4)); } std::string get_error() const { return error_; } private: qi::rule<Iterator, value (), ascii::space_type> expr_, atom_, list_, dotted_list_, string_, number_, quoted_; qi::rule<Iterator, char ()> symbol_; std::string error_; }; } template <class C, class CT> inline std::basic_istream<C, CT> &operator>>(std::basic_istream<C, CT> &is, value &val) { using iterator = boost::spirit::basic_istream_iterator<C, CT>; read_detail::value_grammar<iterator> expr; auto it = iterator(is); auto const res = boost::spirit::qi::phrase_parse( it, iterator(), expr, boost::spirit::ascii::space, val); if (!res) is.setstate(std::ios::failbit); return is; } inline value read(std::string const &input) { read_detail::value_grammar<std::string::const_iterator> expr; auto it = input.begin(); value val; auto const res = boost::spirit::qi::phrase_parse( it, input.end(), expr, boost::spirit::ascii::space, val); if (!res) throw parse_error(expr.get_error()); return val; } inline std::vector<value> read_expr_list(std::string const &input) { read_detail::value_grammar<std::string::const_iterator> expr; auto it = input.begin(); std::vector<value> vals; auto const res = boost::spirit::qi::phrase_parse( it, input.end(), *expr, boost::spirit::ascii::space, vals); if (!res) throw parse_error(expr.get_error()); return vals; } } #endif
d14f783a034f56e371b73934b08562a7e55e33d9
[ "C++" ]
8
C++
iorate/iolisp
72b5822302a2093b5be969e9b1d44c61139e71d3
23768f792e69e92c0fc0330028f32245629cc3af
refs/heads/main
<repo_name>mariusamza/C-Programming<file_sep>/main.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <windows.h> // Aici incepe aplicatia de SPANZURATOAREA void afisareJoc(char* arrayJoc, int nrCaractere); void convUpper(char* litera); int aiCastigat(char* tablaJoc, int lungimeCuvant); void checkLitera(char* literaJucator, char* cuvantAles, char* tablaJoc, int lungimeCuvant); int vieti = 6; int checkWin = 0; int winCondition = 0; int main(){ srand(time(0)); // seed random char literaJucator; char cuvantAles[15]; char tablaJoc[15]; char listaCuvinte[4][15] = { "FERICIRE", "ARDUINO", "PROGRAMARE", "PORTOCALE" }; strcpy(cuvantAles, listaCuvinte[rand()%4] ); int lungimeCuvant = strlen(cuvantAles); for(int i=0; i<=lungimeCuvant; i++) { if(i == 0) { //prima litera tablaJoc[i] = cuvantAles[i]; } else if(i == lungimeCuvant-1) { // penultima litera tablaJoc[i] = cuvantAles[i]; } else if(i == lungimeCuvant) { // incheierea corecta de string tablaJoc[i] = '\0'; } else { tablaJoc[i] = '_'; } } do { // partea de afisare o implementam in functie afisareJoc(tablaJoc, lungimeCuvant); printf("\n"); printf("Ghiceste o litera: "); scanf("%c", &literaJucator); fflush(stdin); //functie de convertire litera mare la litera mica convUpper(&literaJucator); checkLitera(&literaJucator, cuvantAles, tablaJoc, lungimeCuvant); system("CLS"); // sterge ce e pe ecran } while( (vieti>0) && aiCastigat(tablaJoc, lungimeCuvant) ); afisareJoc(tablaJoc, lungimeCuvant); return 0; } void checkLitera(char* literaJucator, char* cuvantAles, char* tablaJoc, int lungimeCuvant) { int flag = 0; for(int i=0; i<=lungimeCuvant; i++) { if( *literaJucator == *(cuvantAles+i) ){ //cuvantAles[i] *(tablaJoc+i) = *(cuvantAles+i); flag = 1; // daca am ghicit o litera il setam ca 1 } } if(flag == 0) { vieti--; } } // HAHAHA 2 int aiCastigat(char* tablaJoc, int lungimeCuvant) { checkWin = 0; for(int i=0; i<=lungimeCuvant; i++) { if(*(tablaJoc + i) == '_'){ // AICI AM SCHIMBAT checkWin=1; } } if(checkWin == 0) { return 0; } return 1; } // HAHAHAHAHA void afisareJoc(char* arrayJoc, int nrCaractere) { printf("Ai %d vieti! \n\n", vieti); printf(" |-----| \n"); switch(vieti) { case 6: printf(" | \n"); printf(" | \n"); printf(" | \n"); break; case 5: printf(" | O \n"); printf(" | \n"); printf(" | \n"); break; case 4: printf(" | O \n"); printf(" | | \n"); printf(" | \n"); break; case 3: printf(" | O \n"); printf(" | /| \n"); printf(" | \n"); break; case 2: printf(" | O \n"); printf(" | /|\\ \n"); printf(" | \n"); break; case 1: printf(" | O \n"); printf(" | /|\\ \n"); printf(" | / \n"); break; case 0: printf(" | O \n"); printf(" | /|\\ \n"); printf(" | / \\ \n"); break; default: printf(" | \n"); printf(" | \n"); printf(" | \n"); break; } printf("=O=======O=|\n"); // Afisam tabla de joc for(int i=0; i<=nrCaractere; i++) { printf("%c ", *(arrayJoc+i) ); } printf("\n"); if( !aiCastigat(arrayJoc, nrCaractere) ) { printf("AI CASTIGAT ! FELICITARI!"); } if(vieti == 0) { printf("AI PIERDUT ! NU MAI AI VIETI!"); } } // afisareJoc()
ed96171a69718e2d8a0ff31fa133590f084cacde
[ "C" ]
1
C
mariusamza/C-Programming
799bfb0a460739e0e2223d6990cb54dbddee42f6
4039dd5c1ecd7892fbb8753fb4b2d5a25a368782
refs/heads/master
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href='http://fonts.googleapis.com/css?family=Eagle+Lake' rel='stylesheet' type='text/css'> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ink and Edges Contact Form</title> <link href="main.css" rel="stylesheet" type="text/css" /> <style type="text/css"> p{ color:white; text-align:center; } table{ margin-left:auto; margin-right:auto; color:white; } </style> </head> <body> <div id="container"> <header><img src="images/inkbanner.jpg" width="770" height="270" alt="ink and edges banner"/> <nav> <ul> <li><a href = "index.htm">Home</a></li> <li><a href = "contact.htm">Contact</a></li> <li><a href = "pens.htm">Pens</a></li> <li><a href = "sharpening.htm">Sharpening</a></li> <li><a href = "pricing.htm">Pricing</a></li> </ul> </nav> <h2>Thank you</h2> <p>Thank you for your interest in Ink and Edges. Please allow 24 to 48 hours for a reply.</p><p>I look forward to speaking with you soon.</p> <br /> <h6>Below is the form that was submitted. A copy will be sent to the email address you provided.</h6> <br /> <?php echo "<table border='1'>"; echo "<tr><th>Field Name</th><th>Value of field</th></tr>"; foreach($_POST as $key => $value) { echo '<tr>'; echo '<td>',$key,'</td>'; echo '<td>',$value,'</td>'; echo "</tr>"; } echo "</table>"; echo "<p>&nbsp;</p>"; date_default_timezone_set('America/Chicago'); echo date('l jS \of F Y h:i:s A'); $body = "Your form was submitted on: " . date('l jS \of F Y h:i:s A') . "\n\n" . "Please allow 24 to 48 hours for a reply. I look forward to speaking with you soon. \n\n" ; foreach($_POST as $key => $value) { $body.= $key."=".$value."\n"; } $email = $_POST['email']; $from = '<EMAIL>'; $to = '<EMAIL>' . ', '; $to .= $email; $subject = "Ink and Edges form request"; if (mail($to, $subject, $body, 'From: ' . $from)) { echo("<p>Message successfully sent!</p>"); } else { echo("<p>Message delivery failed...</p>"); } ?> </section> <!-- end container --> </body> </html> <file_sep># IntroPHPclass My work from my PHP class at DMACC <file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <titleDanielle's PHP Project 1</title> </head> <body> <p>1. Create a PHP page called project1. This will be a PHP page. Do all of the following work on that page. </p> <p>2. Use an echo command to display your name below this line. It should be within an &lt;h1&gt; element.</p> <h1><?php echo "Danielle" ?></h1> <p>3. Use a print command to display your name below this line. It should be within an &lt;h1&gt; element. </p> <?php print "<h1>Danielle</h1>" ?> <p>4. Use an echo command to put your name inside the following line where the word <strong>yourName</strong> appears. </p> <?php $yourName="Danielle!"; ?> <h2>Hi <?php echo $yourName ?> Welcome to WDV341 Intro to PHP</h2> <p>5. Use one or more echo commands to write out an unordered list that contains the following: red, green, blue.</p> <?php echo "<ul> <li>red</li> <li>green</li> <li>blue</li> </ul>"; ?> </body> </html><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WDV341 Intro PHP - Project-6 Form Handlers Homework</title> </head> <body> <h1>WDV341 Intro HTML</h1> <h3>Project-2b Form Handlers - Homework</h3> <p>Complete the following exercises. When finished upload to your server. Update your links on your WDV341 Homework page to include this assignment. Zip your work and attach it to your Blackboard assignment and submit it to Blackboard.</p> <p>1. Given the form below create a PHP form handler that will create a confirmation page. The page should display all of the data from this form in the confirmation message. </p> <p>2. Given the form below create a PHP form handler that will create a confirmation page that emails the form data to the customer.</p> <?php echo "You have Successfully Registered! Thank you! <br />"; echo "<fieldset>"; echo "<legend>Customer Loyalty Registration</legend>"; echo "<table width='60%' border='0'>"; foreach($_POST as $key => $value) { echo '<tr>'; echo '<td width="17%">',$key,'</td>'; echo '<td width="83%">',$value,'</td>'; echo "</tr>"; } echo "</table>"; echo "</fieldset>"; $email = $_POST['cusEmail']; $from = '<EMAIL>'; $to = $email; $subject = 'Project 2b Customer Registration Confirmation'; $body = "Form Data\n\n "; //stores the content of the email foreach($_POST as $key => $value) { $body.= $key."=".$value."\n"; } if (mail($to, $subject, $body, 'From: ' . $from)) //puts pieces together and emails { echo("<p>Message successfully sent!</p>"); } else { echo("<p>Message delivery failed...</p>"); } ?> </body> </html><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WDV341 Into PHP - insertEvent</title> <style type="text/css"> body{ background-image: url(background.jpg); font-size:36px; color:white; text-align:center; } </style> <?php $dbc = mysqli_connect('localhost', 'dlkunze_wdv341', 'wdv341', 'dlkunze_wdv341'); //connects to the database $event_name = $_POST['event_name']; $event_description = $_POST['event_description']; $event_presenter = $_POST['event_presenter']; $event_date = $_POST['event_date']; $event_time = $_POST['event_time']; $query = "INSERT INTO wdv341_events (event_name, event_description, event_presenter, event_date, event_time) " . "VALUES ('$event_name', '$event_description', '$event_presenter', '$event_date', '$event_time')"; $result = mysqli_query($dbc, $query) or die('Error querying database' . mysqli_error($dbc)); mysqli_close($dbc); echo 'Thanks for submitting your form. <br />'; echo 'Your event is ' . $event_name; echo ' presented by ' . $event_presenter . '<br />'; echo 'Your event is on ' . $event_date . ' at ' . $event_time . '<br />'; echo 'We will be in contact soon and look forward to your event. Have a great day!'; ?> </head> </html> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WDV341 Into PHP - Presenters CMS Example</title> <?php include '../dbConnect.php'; //connects to the database //Get the name value pairs from the $_POST variable into PHP variables //For this example I am using PHP variables with the same name as the name atribute from the HTML form $event_name = $_POST['event_name']; $event_description = $_POST['event_description']; $event_presenter = $_POST['event_presenter']; $event_date = $_POST['event_date']; $event_time = $_POST['event_time']; $event_id = $_POST['event_id']; //from the hidden field of the update form ?> </head> <body> <h1>WDV341 Intro PHP</h1> <h2>Presenters CMS Example</h2> <h3>UPDATE Record Process</h3> <p>This page is called from the eventsUpdateForm.php using the form's action attribute. This page will pull the form data from the $_POST array into PHP variables. </p> <p>It will then build the SQL UPDATE query using the PHP variables. The query will overwrite the existing fields in the database with the new values provided by the form. </p> <p>If the query processes correctly this page will display a confirmation message to the user/customer. If not, this page will display an error message to the user/customer. </p> <p>Note: In a production environment this error message should be user/customer friendly. Additional information should be sent to the developer so that they can see what happened when they attempt to fix it. </p> <?php //Create the SQL UPDATE query or command $sql = "UPDATE wdv341_events SET " ; $sql .= "event_name='$event_name', "; $sql .= "event_description='$event_description', "; $sql .= "event_presenter='$event_presenter', "; $sql .= "event_date='$event_date', "; $sql .= "event_time='$event_time' "; //NOTE last one does NOT have a comma after it $sql .= " WHERE (event_id='$event_id')"; //VERY IMPORTANT Only update the requested record id echo "<h3>$sql</h3>"; //testing if (mysqli_query($link,$sql) ) { echo "<h1>Your record has been successfully UPDATED the database.</h1>"; echo "<p>Please <a href='viewPresenters.php'>view</a> your records.</p>"; } else { echo "<h1>You have encountered a problem.</h1>"; echo "<h2 style='color:red'>" . mysqli_error($link) . "</h2>"; } mysqli_close($link); //closes the connection to the database once this page is complete. ?> </body> </html><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WDV341 Into PHP Select from Where</title> <?php include '../dbConnect.php'; //connects to the database $sql = "SELECT * FROM wdv341_events WHERE event_name = 'SupernaturalCon'"; //build the SQL query //Note the WHERE clause allows us to select ONLY the desired record $result = mysqli_query($link,$sql); //run the Query and store the result in $result if(!$result ) //Make sure the Query ran correctly and created result { echo "<h1 style='color:red'>Houston, We have a problem!</h1>"; //Problems were encountered. echo mysqli_error($result); //Display error message information } ?> </head> <body> <h1>WDV341 Intro PHP</h1> <h2>Select & Display WHERE</h2> <?php echo "<h3>" . mysqli_num_rows($result). " records were found.</h3>"; //display number of rows found by query ?> <div> <table border="1"> <tr> <th>Event Name</th> <th>Event Description</th> <th>Event Presenter</th> <th>Event Date</th> <th>Event Time</th> </tr> <?php while($row = mysqli_fetch_array($result)) //Turn each row of the result into an associative array { //For each row you found int the table create an HTML table in the response object echo "<tr>"; echo "<td>" . $row['event_name'] . "</td>"; echo "<td>" . $row['event_description'] . "</td>"; echo "<td>" . $row['event_presenter'] . "</td>"; echo "<td>" . $row['event_date'] . "</td>"; echo "<td>" . $row['event_time'] . "</td>"; echo "</tr>"; } mysqli_close($link); //Close the database connection to free up server resources. ?> </table> </div> </body> </html><file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <title>Danielle's PHP Date Handling Homework</title> </head> <body> <h1>PHP Date Handling</h1> <h2>Homework</h2> <p>1. Create a date object with the value of 7/1/2014.</p> <br /> <p>Hint: Use the date_create function and follow it to the DateTime process</p> <p>Create the date object using the Object Oriented process.</p> <?php $date = new DateTime('7/1/2014'); echo $date->format('l F d, Y'); ?> <p>Create the date object using the Procedural process.</p> <?php $date=date_create('7/1/2014'); echo date_format($date, 'l F d, Y'); ?> <br /> <p>2. Display the date object you created in part 1. above in the following formats.</p> <p>mm/dd/yyyy</p><?php $date = new DateTime('7/1/2014'); echo $date->format('m/d/Y'); ?> <p>dd/mm/yyyy</p><?php $date = new DateTime('7/1/2014'); echo $date->format('d/m/Y'); ?> <p>Monday September 1, YYYY</p> <?php $date = new DateTime('7/1/2014'); echo $date->format('l F d, Y'); ?> <br /> <p>3. Find and display the difference between the current date and the date you created in part 1.</p> <?php $date1 = new DateTime('now'); $date2 = new DateTime('7/1/2014'); $interval = date_diff($date1, $date2); echo $interval->format('%d days'); ?> <br /> <p>4. Create a date object with a value of 9/1/2014.</p> <p>Hint: Use the date_create function and follow it to the DateTime process</p> <p>Create the date object using the Object Oriented process.</p> <?php $date = new DateTime('9/1/2014'); echo $date->format('l F d, Y'); ?> <p>Create the date object using the Procedural process.</p> <?php $date=date_create('9/1/2014'); echo date_format($date, 'l F d, Y'); ?> <p>5. Find and display how many hours have passed between the current date/time and the 9/1/2014 date.</p> <?php $date1 = new DateTime('9/1/2014'); $date2 = new DateTime('now'); $interval = $date1->diff($date2); echo $interval->format('%h hours'); ?> <br /> <br /> <br /> </body> </html><file_sep><?php $deleteRecId = $_GET['recId']; //Pull the presenter_id from the GET parameter include '../dbConnect.php'; //connects to the database ?> <body> <h1>WDV341 Intro PHP </h1> <h2>Presenters CMS Example</h2> <h3>DELETE Record Page</h3> <p>This page is called from the viewPresenters.php page when the user/customer clicks on the Delete link. This page will use the presenter_id that has been passed as a GET parameter on the URL to this page. </p> <p>The SQL DELETE query will be created. Once the query is processed this page will confirm that it processed correctly. It will display a confirmation to the user/customer if it worked correctly or it will display an error message if there were problems.</p> <p>Note: In a production environment this error message should be user/customer friendly. Additional information should be sent to the developer so that they can see what happened when they attempt to fix it. </p> <?php echo "<h2>Please delete record number: " . $_GET['recId'] . "</h2>"; //Display a message verifying the record to be deleted. This could be turned into a second confirmation $sql = "DELETE FROM wdv341_events WHERE event_id = $deleteRecId"; //echo "<p>The SQL Command: $sql </p>"; //testing if (mysqli_query($link,$sql) ) //process the query { echo "<h1>Your record has been successfully deleted.</h1>"; echo "<p>Please <a href='../Project 7 PHP Select and Display/selectEvents.php'>view</a> your records.</p>"; } else { echo "<h1>You have encountered a problem with your delete.</h1>"; echo "<h2 style='color:red'>" . mysqli_error($link) . "</h2>"; } mysqli_close($link); //close the database connection and free up server resources ?> </body> </html> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WDV341 Intro PHP - Presenters CMS Example</title> <!-- This is an UPDATE form. It will pull information for a specific presenter from the database. It will place the information from the database into the appropriate fields using PHP. The user/customer will see the form already filled out with the original information from the database. Any changes they make in the fields will be sent to the presenterUpdate.php page. That page will replace the existing record with the values from this form. Effectively erasing the original values and putting the new values into the table. The following steps are used for most updates: 1. Connect to the database. 2. Get the record id that was attached to the URL from the GET parameter. 3. Create an SQL SELECT command to find the specific record that we want to modify. 4. Run the query and check for any errors with the SELECT. Most common is record not found. 5. Pull the column values for each field and use PHP to place them in the HTML default values depending upon the HTML element. 6. The rendered page will be sent to the user/customer as HTML. 7. Once the user/customer has made their changes the submit will send the form and its name-value pairs to the updatePresenters.php page which will update the database with the form information. --> <?php $updateRecId = $_GET['recId']; //This comes from the viewPresenters link. Much like the delete works include '../dbConnect.php'; //connects to the database //$updateRecId = 2; //Hard code a key for testing purposes $sql = "SELECT * FROM wdv341_events WHERE event_id = $updateRecId"; //Finds a specific record in the table //echo "<p>The SQL Command: $sql </p>"; //For testing purposes as needed. //Run the SQL command against the database $result = mysqli_query($link,$sql); //Check the result to make sure it ran correctly if (!$result) { echo "<h1>You have encountered a problem with your update.</h1>"; die( "<h2>" . mysqli_error($link) . "</h2>") ; //This will display the error and then stop the page } $row = mysqli_fetch_array($result); //Turn the result into an associative array so we can get the column values ?> </head> <body> <h1>WDV341 Intro PHP</h1> <h1>Presenters CMS Example</h1> <h3>UPDATE Form for Changing information on a Presenter</h3> <p>This page is called from the selectEvents.php page when you click on the Update link of a presenter. That page attaches the event_id to the URL of this page making it a GET parameter.</p> <p>This page uses that information to SELECT the requested record from the database. Then PHP is used to pull the various column values for the record and place them in the form fields as their default values. </p> <p>The user/customer can make changes as needed or leave the information as is. When the form is submitted and validated it will send the form data to the the updateEvent.php page. The PHP page will update the record in the database.</p> <p>Notice that this form uses a hidden field. The value of this hidden field contains the event_id. It is passed as one of the form name value pairs. The updateEvent.php page will use that value to update the selected record on the database.</p> <form id="eventsForm" name="eventsForm" method="post" action="updateEvent.php"> <p>Update the following Event Information. Place the new information in the appropriate field(s)</p> <p>Event Name: <input type="text" name="event_name" id="event_name" value="<?php echo $row['event_name']; ?>"/> <!-- PHP will put the name into the value of field--> </p> <p>Event Description: <input type="text" name="event_description" id="event_description" value="<?php echo $row['event_description']; ?>" /> </p> <p>Event Presenter: <input type="text" name="event_presenter" id="event_presenter" value="<?php echo $row['event_presenter']; ?>" /> </p> <p>Event Date: <input type="text" name="event_date" id="event_date" value="<?php echo $row['event_date']; ?>" /> </p> <p>Event Time: <input type="text" name="event_time" id="event_time" value="<?php echo $row['event_time']; ?>" /> </p> <!--The hidden form contains the record if for this record. You can use this hidden field to pass the value of record id to the update page. It will go as one of the name value pairs from the form. --> <input type="hidden" name="event_id" id="event_id" value="<?php echo $updateRecId; ?>" /> <p> <input type="submit" name="button" id="button" value="Update" /> <input type="reset" name="button2" id="button2" value="Clear Form" /> </p> </form> </body> </html> <file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <title>Danielle's PHP Project 1b</title> <?php $courseName="WDV 341 Intro to PHP"; $firstName="Danielle"; $lastName="Kunze"; $hwPage="<a href=http://daniellekunze.com/Intro%20to%20PHP/wdv341.php>Danielle's WDV 341 Homework Page</a>" ?> </head> <body> <p>1. Use this page as the source and conver it so that it will process your PHP code on the server.</p> <p>2. Use PHP to fill in the following information. </p> <p>Course Name: <?php echo $courseName ; ?> </p> <h2>First Name: <?php echo $firstName ; ?></h2> <h2>Last Name: <?php echo $lastName ; ?></h2> <p>My homework is located at: <?php echo $hwPage ; ?> </p> <h3>&nbsp;</h3> <p>3. Create an ordered list using PHP. Place it in the area below. It should describe the sequence of steps that the server and PHP processor performs when you request this page until you see the results. The more detailed the better!</p> <?php print "<ol> <li>The Client gathers information and sends the Request Object to the server.</li> <li>The server uses information from the client and locates the requested file.</li> <li>PHP code is then sent to the PHP processor to be processed, while HTML, CSS & Javascript are sent to the Response Object.</li> <li>The PHP processor outputs results in HTML, CSS & Javascript and sends that to the Response Object as well.</li> <li>The Response Object is sent to the client, which is then read by the Browser and is displayed on the client.</li> <ol>" ?> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>Grading:</p> <p> Each exercise is graded seperately and totaled for the Project grade. Each exercise will be graded using the following scale. Exercises 2 and 3 are worth 10 points each.</p> <table width="530" border="1"> <tr> <td width="138">Grade</td> <td width="376">Expectation</td> </tr> <tr> <td>5</td> <td>Works as expected. Correctly uses concepts presented in class. Documented as needed and well formatted.</td> </tr> <tr> <td>4</td> <td>Works as expected. Uses some of the concepts presented in class. Lacks documentation if needed or poorly formatted/structured.</td> </tr> <tr> <td>2</td> <td>Produces results but not as expected OR Exercise is attempted but produces an error.</td> </tr> <tr> <td>0</td> <td>Does not produce any results. Fails to use any concepts presented in class or not attempted.</td> </tr> </table> </body> </html><file_sep> <head> <style> body { text-align:center; } </style> <title>WDV341 Into PHP Select & Display</title> <?php include '../dbConnect.php'; //connects to the database $sql = "SELECT * FROM wdv341_events"; //build the SQL command $result = mysqli_query($link,$sql); //run the Query and store the result in $result if(!$result ) //Make sure the Query ran correctly and created result { echo "<h1 style='color:red'>I'm sorry, there appears to have been an error. My apologies</h1>"; //Problems were encountered. echo mysqli_error($link); //Display error message information } ?> </head> <body> <h1>WDV341 Intro PHP</h1> <h2>Select & Display events</h2> <?php echo "<h3>" . mysqli_num_rows($result). " records were found.</h3>"; //display number of rows found by query ?> <div> <table border="1"> <tr> <th>Event Name</th> <th>Event Description</th> <th>Event Presenter</th> <th>Event Date</th> <th>Event Time</th> </tr> <?php while($row = mysqli_fetch_array($result)) //Turn each row of the result into an associative array { //For each row you found int the table create an HTML table in the response object echo "<tr>"; echo "<td>" . $row['event_name'] . "</td>"; echo "<td>" . $row['event_description'] . "</td>"; echo "<td>" . $row['event_presenter'] . "</td>"; echo "<td>" . $row['event_date'] . "</td>"; echo "<td>" . $row['event_time'] . "</td>"; echo "<td><a href='../Project 9 PHP Update Event/eventsUpdateForm.php?recId=" . $row['event_id'] . "'>Update</a></td>"; echo "<td><a href='../Project 8 PHP Delete Event/deleteEvent.php?recId=" . $row['event_id'] ."'>Delete</a></td>"; echo "</tr>"; } mysqli_close($link); //Close the database connection to free up server resources. ?> </table> </div> </body> </html>
45147dc5570212d05f5f0826c2944d4f25f8c9e1
[ "Markdown", "PHP" ]
12
PHP
dlkunze/IntroPHPclass
4532af60d6201d1a4daf6f065be62f712e05645d
025d21d9f536de1bfa780e5dfea95d31b4412fdc
refs/heads/main
<repo_name>steph-tseng/goose-backend<file_sep>/models/Project.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const Topic = require("./Topic"); const User = require("./User"); const projectSchema = Schema( { title: { type: String, required: true }, content: { type: String, required: true }, researchQuestion: { type: String }, tags: [String], images: [String], author: { type: Schema.Types.ObjectId, required: true, ref: "User" }, topicId: { type: Schema.Types.ObjectId, ref: "Topic" }, reactions: { love: { type: Number, default: 0 }, thumbup: { type: Number, default: 0 }, thumbdown: { type: Number, default: 0 }, laugh: { type: Number, default: 0 }, emphasize: { type: Number, default: 0 }, question: { type: Number, default: 0 }, }, reviewCount: { type: Number, default: 0 }, isDeleted: { type: Boolean, default: false, select: false }, }, { timestamps: true } ); projectSchema.statics.calculateProjectCount = async function (userId) { const projectCount = await this.find({ author: userId, }).countDocuments(); await User.findByIdAndUpdate(userId, { projectCount: projectCount }); }; projectSchema.statics.calculateProjectInTopicCount = async function (topicId) { const projectCount = await this.find({ topic: topicId, }).countDocuments(); await Topic.findByIdAndUpdate(topicId, { projectCount: projectCount }); }; projectSchema.post("save", async function () { this.constructor.calculateProjectCount(this.author); this.constructor.calculateProjectInTopicCount(this.topic); }); projectSchema.pre(/^findOneAnd/, async function (next) { this.doc = await this.findOne(); next(); }); projectSchema.post(/^findOneAnd/, async function (next) { // if (this.doc) await this.doc.constructor.calculateProjectCount(this.doc.author); // if (this.doc) await this.doc.constructor.calculateProjectInTopicCount(this.doc.topic); }); projectSchema.plugin(require("./plugins/isDeletedFalse")); const Project = mongoose.model("Project", projectSchema); module.exports = Project; <file_sep>/models/Follower.js const mongoose = require("mongoose"); const User = require("./User"); const Schema = mongoose.Schema; const followerSchema = Schema( { follower: { type: Schema.ObjectId, required: true, ref: "User" }, following: { type: Schema.ObjectId, required: true, ref: "User" }, status: { type: String, enum: ["following", "mutual", "notFollowing"] }, }, { timestamps: true } ); const Follower = mongoose.model("Follower", followerSchema); module.exports = Follower; <file_sep>/controllers/topic.controller.js const { AppError, catchAsync, sendResponse, } = require("../helpers/utils.helper"); const Topic = require("../models/Topic"); const topicController = {}; // TODO topicController.getTopics = catchAsync(async (req, res, next) => { let { page, limit, sortBy, ...filter } = { ...req.query }; page = parseInt(page) || 1; limit = parseInt(limit) || 9; const totalTopics = await Topic.countDocuments({ ...filter, isDeleted: false, }); const totalPages = Math.ceil(totalTopics / limit); const offset = limit * (page - 1); // console.log({ filter, sortBy }); const topics = await Topic.find({ ...filter }) .sort({ ...sortBy, title: 1 }) .skip(offset) .limit(limit) .populate("author") .populate("projects"); return sendResponse(res, 200, true, { topics, totalPages }, null, ""); }); topicController.getAllTopics = catchAsync(async (req, res, next) => { let { sortBy, ...filter } = { ...req.query }; const totalTopics = await Topic.countDocuments({ ...filter, isDeleted: false, }); const topics = await Topic.find(filter).sort({ ...sortBy, title: 1 }); return sendResponse(res, 200, true, { topics, totalTopics }, null, ""); }); topicController.getSelectedTopic = catchAsync(async (req, res, next) => { let topic = await await Topic.findById(req.params.id) .populate("author") .populate("projects"); if (!topic) return next( new AppError(404, "Topic not found", "Get specific topic error") ); topic = topic.toJSON(); return sendResponse(res, 200, true, topic, null, null); }); topicController.createNewTopic = catchAsync(async (req, res, next) => { // const author = req.userId; const { title, description, image } = req.body; const topic = await Topic.create({ title, description, image }); return sendResponse( res, 200, true, topic, null, "Successfully created a new topic" ); }); topicController.updateProject = catchAsync(async (req, res, next) => { const { title, description, image } = req.body; const topicId = req.params.id; const topic = await Topic.findOneAndUpdate( { _id: topicId }, { title, description, image }, { new: true } ); if (!topic) return next( new AppError( 400, "Topic not found or User not authorized", "Update topic error" ) ); return sendResponse(res, 200, true, topic, null, "Update topic successful"); }); topicController.deleteTopic = catchAsync(async (req, res, next) => { const topicId = req.params.id; const topic = await Topic.findOneAndUpdate( { _id: topicId }, { isDeleted: true }, { new: true } ); if (!topic) return next( new AppError( 400, "Topic not found or User not authorized", "Delete Topic Error" ) ); return sendResponse(res, 200, true, null, null, "Topic deleted successfully"); }); module.exports = topicController; <file_sep>/routes/project.api.js const express = require("express"); const projectController = require("../controllers/project.controller"); const router = express.Router(); const authMiddleware = require("../middlewares/authentication"); const validators = require("../middlewares/validators"); /** * @route GET api/projects * @description Get list of all projects * @access Public */ router.get("/", projectController.getProjects); /** * @route GET api/projects/topics/:id?page=1&limit=10 * @description Get projects of a topic with pagination * @access Public */ router.get("/topics/:id", projectController.getProjectByTopic); /** * @route GET api/projects/following * @description Get list of all projects of followed users * @access Login required */ router.get( "/following", authMiddleware.loginRequired, projectController.getProjectsOfFollowing ); /** * @route GET api/projects/:projectId * @description Get details of a single project * @access Public */ router.get("/:id", projectController.getSelectedProject); /** * @route POST api/projects * @description Create a new project in a topic * @access Login required */ router.post( "/", authMiddleware.loginRequired, projectController.createNewProject ); /** * @route PUT api/projects/:projectId * @description Update a project * @access Login required */ router.put( "/:id", authMiddleware.loginRequired, projectController.updateProject ); /** * @route DELETE api/projects/:projectId * @description Delete a project * @access Login required */ router.delete( "/:id", authMiddleware.loginRequired, projectController.deleteProject ); module.exports = router; <file_sep>/models/Topic.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; // const User = require("./User"); const topicSchema = Schema( { title: { type: String, required: true }, description: { type: String, required: true }, tags: [String], projectCount: { type: Number, default: 0 }, projects: [String], image: [String], isDeleted: { type: Boolean, default: false, select: false }, }, { timestamps: true } ); // topicSchema.statics.calculateTopicCount = async function (userId) { // const topicCount = await this.find({ // $or: [{ from: userId }, { to: userId }], // status: "accepted", // }).countDocuments(); // await User.findByIdAndUpdate(userId, { topicCount: topicCount }); // }; // topicSchema.post("save", function () { // this.constructor.calculateTopicCount(this.from); // this.constructor.calculateTopicCount(this.to); // }); // topicSchema.pre(/^findOneAnd/, async function (next) { // this.doc = await this.findOne(); // next(); // }); // topicSchema.post(/^findOneAnd/, async function (next) { // await this.doc.constructor.calculateTopicCount(this.doc.from); // await this.doc.constructor.calculateTopicCount(this.doc.to); // }); topicSchema.plugin(require("./plugins/isDeletedFalse")); const Topic = mongoose.model("Topic", topicSchema); module.exports = Topic;
3f903354ac3e58ed6ea28e97dd2425a20dad7e40
[ "JavaScript" ]
5
JavaScript
steph-tseng/goose-backend
d22e8d4e9a56110d8a1220497f4add37c028c72c
aa894406b7935e35b46487869294424e147ce6ae
refs/heads/master
<file_sep>package labs_examples.generics.labs; import java.util.*; /** * Generics Exercise 3: * * 1) Write a generic method that accepts two generic arguments. This generic method should only accept * arguments which are sublasses of Number. The generic method must return the sum (as a double) of whatever two * numbers were passed in regardless of their type. * * 2) Write a generic method to count the number of elements in a collection of Strings that are palindromes * * 3) Write a generic method to exchange the positions of two different elements in an array. * * 4) Write a generic method to find the largest element within the range (begin, end) of a list. * * 5) */ public class Exercise_03 { public static void main(String[] args) { //1 System.out.println(add(4.5,5.6)); System.out.println(""); //2 ArrayList<String> list1 = new ArrayList<>(); list1.add("madam"); list1.add("aabbaa"); list1.add("aaabbbaaa"); list1.add("blue"); System.out.println("Array size: " + list1.size()); System.out.println("Number of Palindrome:" + countPalindrome(list1)); //3 System.out.println(""); ArrayList<String> list = new ArrayList<>(); list.add("The"); list.add("dog"); list.add("is"); list.add("happy"); Collections.swap(list, 1, 2); System.out.println(list); //4 System.out.println(""); List<Integer> c = Arrays.asList(1, 2, 55, 4, 9, 6, 12, 8, 11, 20); System.out.println(maximalElement(c, 1, 10)); } // 1) Write a generic method that accepts two generic arguments. This generic method should only accept // arguments which are sublasses of Number. The generic method must return the sum (as a double) of whatever two // numbers were passed in regardless of their type. public static<T extends Number> T add(T x, T y){ Double sum; sum = x.doubleValue() + y.doubleValue(); return (T) sum; } //2) Write a generic method to count the number of elements in a collection of Strings that are palindromes public static < E extends Collection<String>> int countPalindrome(E inputCollection ) { int count = 0; boolean palindrome; for(String element : inputCollection) { //boolean flag - palidnrome true, if otherwise, .... palindrome = true; for(int i = 0; i < element.length()/2; i++){ char c = element.charAt(i); char k = element.charAt(element.length() - 1 - i); if(c == k){ continue; } else{ palindrome = false; break; } } if(palindrome){ count++; } } return count; } // 3) Write a generic method to exchange the positions of two different elements in an array. public static <T> void swap(T[] a, int i, int j) { T temp = a[i]; a[i] = a[j]; a[j] = temp; } // 4) Write a generic method to find the largest element within the range (begin, end) of a list. public static <T extends Comparable> T maximalElement (List<T> list, int begin, int end) { T max = list.get(begin); for (int i = begin + 1; i < end; i++) { T elem1 = list.get(i); if (elem1.compareTo(max) > 0) { max = elem1; } } return max; } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.C_blackjack; /** * Card.java (POJO - this will hold card data) * * char[] suit = new char[]{'♠', '♦', '♥', '♣'}; * * int cardValue; */ public class Card{ private char suit; private String value; private int scoreValue; public Card(char suit, String value){ this.suit = suit; this.value = value; } public String customToString() { return suit + value + suit; } public int getScoreValue() { try{ return Integer.valueOf(value); }catch (Exception e){ if (value.equalsIgnoreCase("ACE")){ return 11; }else { return 10; } } } @Override public String toString() { return "Card{" + "suit=" + suit + ", value='" + value + '\'' + ", scoreValue=" + scoreValue + '}'; } }<file_sep>package labs_examples.Bali_InPerson_MarApr2020.AbstractDataStructure; //public class ListEmptyException extends Exception { // // public ListEmptyException //} <file_sep>package labs_examples.generics.labs; import java.util.ArrayList; /** * Generics Exercise 2: * * Create a class with a generic method that takes in an ArrayList of any Numeric type and returns the sum of all * Numbers in the ArrayList */ class ReturnSum{ public static void main(String[] args) { ArrayList<Double> doubleList = new ArrayList<>(); Double[] doubles = { 5.5, 4.4, 6.6, 7.7, 8.8, 9.9 }; for (Double element : doubles) doubleList.add(element); System.out.printf("doubleList contains: %s\n", doubleList); System.out.printf("Total of the elements in doubleList: %.1f\n\n", sumCollection(doubleList)); } // ? - wild card public static double sumCollection(ArrayList<? extends Number> nums){//arraylist of any type double sum = 0; for(int i = 0; i <nums.size(); i++){ sum += nums.get(i).doubleValue(); } return sum; } } <file_sep>package labs_examples.multi_threading.labs; /** * Multithreading Exercise 5: * * Demonstrate the use of a wait() and notify() */ //alarm goes off class Alarm { private int hour; private String state; //true (wakeUp) if t = (specified hour) should wait //false (sleep) if t != (specified hour) should wait private Boolean ring = true; synchronized void wakeUp(int hour) { state = "wake up"; this.hour = hour; while (ring) { for (int t = 1; t < 24; t++) { //24 hr time try { t = hour; if (t <= 5) { System.out.println("Alarm goes off when: hour = " + t + ". Time to " + state); wait(1); return; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } ring = true; notify(); } synchronized void sleep(int hour) { this.hour = hour; state = "sleeping"; while (!ring) { for (int t = 1; t < 24; t++) { try { t = hour; if (t <= 24) { System.out.println("Continue" + state + " when t = " + t); wait(1); return; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } ring = false; notify(); } //Thread static class SyncThreadAlarmClock implements Runnable { Thread thread; Alarm alarmWakeUp = new Alarm(); int hr; public SyncThreadAlarmClock(int hour, String name) { thread = new Thread(this, name); hr = hour; thread.start(); } @Override public void run() { System.out.println("Starting " + Thread.currentThread().getName()); alarmWakeUp.wakeUp(hr); alarmWakeUp.sleep(hr); } } //controller static class Exercise_5 { public static void main(String[] args) { System.out.println("Main thread starting"); SyncThreadAlarmClock syncThreadAlarmClock = new SyncThreadAlarmClock(5, "synThread1"); SyncThreadAlarmClock syncThreadAlarmClock2 = new SyncThreadAlarmClock(9, "synThread2"); try { System.out.println("starting join thread"); syncThreadAlarmClock.thread.join(); syncThreadAlarmClock2.thread.join(); System.out.println("join complete"); } catch (InterruptedException exc) { System.out.println("Main thread interrupted."); } } } } <file_sep>package labs_examples.exception_handling.labs; /** * Exception Handling Exercise 2: * * Demonstrate a try/catch with multiple catch statements. * */ class Exercise_2{ public static void main(String[] args) { int [] a = anArray(0,6,22,54,12); try { int x = a[4] / a[0]; //ArrayIndexOutOfBoundsException //int x = a[4] / a[5]; ArithmeticException } catch (ArrayIndexOutOfBoundsException aeExc){ System.out.println("An array index out of bound"); } catch (ArithmeticException arExc){ System.out.println("Not divisible by an index out of bound"); } catch (Exception exc){ System.out.println("error detected"); } System.out.println("end of program"); } public static int[] anArray(int...anArray){ return anArray; } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.D_my_oop; //subclass public class NailTechnician extends BookingSystem { private String skill; public NailTechnician(String skill) { this.skill = skill; } public NailTechnician(int time, int date) { super(time, date); } public NailTechnician(int time, int date, double businessHour) { super(time, date, businessHour); } public NailTechnician(String firstName, String lastName, int phoneNum, String email) { super(firstName, lastName, phoneNum, email); } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.C_blackjack; public class Game { private String name; private String basicRules; private static int numGamesPlayed = 0; private static int gameWonByComputer = 0; private static int gameWonByUser = 0; public static int getNumGamesPlayed() { return numGamesPlayed; } public static void setNumGamesPlayed(int numGamesPlayed) { Game.numGamesPlayed = numGamesPlayed; } public static int getGameWonByComputer() { return gameWonByComputer; } public static void setGameWonByComputer(int gameWonByComputer) { Game.gameWonByComputer = gameWonByComputer; } public static int getGameWonByUser() { return gameWonByUser; } public static void setGameWonByUser(int gameWonByUser) { Game.gameWonByUser = gameWonByUser; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBasicRules() { return basicRules; } public void setBasicRules(String basicRules) { this.basicRules = basicRules; } } <file_sep>package labs_examples.static_nonstatic.labs; /* **** Exercise 2 DONE - please refer to the BlackJackGame.java and Game.java files. **** */ <file_sep>package labs_examples.Bali_InPerson_MarApr2020.Lambda.Practice; import java.util.Collection; @FunctionalInterface interface SomeInterface { public double noParameter(); } interface SomeInterface2 { double TwoParameter(Double b, Double c); } interface SomeInterface3 { Boolean trueOrFalse(Integer val1); } interface GenericInterface <S, T, O> { S convert(T val1, O val2); } interface GenArrlistInterface <C extends Collection, T extends Number> { C list(T[] element); } <file_sep>package labs_examples.lambdas.labs; import java.sql.SQLOutput; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.Function; import java.util.function.UnaryOperator; /** * Lambdas Exercise 1: * * 1) Demonstrate creating a functional interface with an abstract method that takes no parameters and returns void * 2) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating * an anonymous inner class from this interface. * * 3) Demonstrate creating a functional interface with an abstract method that takes 1 parameter and returns a * value of the same type as the parameter * 4) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating * an anonymous inner class from this interface. * * 5) Demonstrate creating a functional interface with an abstract method that takes 2 parameters and returns a * value * 6) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating * an anonymous inner class from this interface. * * 7) Demonstrate the use of at least two built-in functional interfaces from the java.util.function package. * * * * */ class Exercise_1 { public static void main(String[] args) { // 2) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating // * an anonymous inner class from this interface. //lambda expression AnInterface lambdaInterface = () -> { int a = 12; int b = 11; int c = a * b; System.out.println("empty parameter - Lambda expression - " + c); }; lambdaInterface.noParameter(); //anonymous inner class AnInterface anonymousInterface = new AnInterface() { @Override public void noParameter() { int a = 12; int b = 12; int c = a * b; System.out.println("empty parameter - Anonymous inner - " + c); } }; anonymousInterface.noParameter(); // * 4) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating // * an anonymous inner class from this interface. OneParameterInterface lamndaNum = (d) -> d; System.out.println("One parameter Interface - Lambda expression - "+ lamndaNum.number(3.14)); OneParameterInterface AnonymousNum = new OneParameterInterface() { @Override public double number(double d) { return d; } }; System.out.println("One parameter Interface - Anonymous Inner - " + AnonymousNum.number(3.14)); // * 6) Implement the previous functional interface with a lambda expression and use it. Also demonstrate creating // * an anonymous inner class from this interface. //lambda expression MathInterface lambdaDivide = (a, b) -> (a / b); System.out.println("Two parameter Interface - lambda expression - " + lambdaDivide.divide(12, 6)); double c = lambdaDivide.divide(12,6); System.out.println("lambdaDivide - 12/ 6 = " + c); //anonymous inner class MathInterface AnonymousDivide = new MathInterface() { @Override public int divide(int a, int b) { int m = a / b; return m; } }; System.out.println("Two parameter Interface - Anonymous Inner - " + AnonymousDivide.divide(12, 6)); // * 7) Demonstrate the use of at least two built-in functional interfaces from the java.util.function package. //Binary BinaryOperator<Integer> intB = Integer::sum; System.out.println("Binary Operator - sum of two numbers - " + intB.apply(7,8)); //Double Binary DoubleBinaryOperator db = (x, y) -> x*y; System.out.println("Double Binary Operator - multiplication of two numbers - " + db.applyAsDouble(3.34,4.44)); //Function Function<Integer, String> intToString = (i) -> Integer.toString(i); System.out.println("Function - conversion - " + intToString.apply(456754).length()); //Unary Operator UnaryOperator<String> i = (x) -> x.replace('d','b'); System.out.println(i.apply("Unary Operator - replacing old char with new char - " + "doggie")); } } // 1) Demonstrate creating a functional interface with an abstract method that takes no parameters and returns void @FunctionalInterface interface AnInterface{ void noParameter(); } // * 3) Demonstrate creating a functional interface with an abstract method that takes 1 parameter and returns a // * value of the same type as the parameter @FunctionalInterface interface OneParameterInterface{ double number(double d); } // * 5) Demonstrate creating a functional interface with an abstract method that takes 2 parameters and returns a // * value @FunctionalInterface interface MathInterface { int divide(int a, int b); } //done <file_sep>package labs_examples.arrays.labs; import java.util.Arrays; /** * Reversing an array in place * * * This is a very common interview challenge. * * Using a for loop, please demonstrate how to reverse an array in place using only one extra variable. Please note, * you cannot use a second array and you can only instantiate one variable outside of the for loop. * */ public class Exercise_06 { public static void main(String[] args) { int [] array = new int [5]; array [0] = 1; array [1] = 2; array [2] = 3; array [3] = 4; array [4] = 5; //5 4 3 2 1 //temp = 2 //populate array int temp; for (int i=0; i < array.length/2; i++){ temp = array[i]; array[i] = array[array.length - 1 - i]; array[array.length - 1 - i] = temp; } System.out.print(Arrays.toString(array) + " "); } } <file_sep>package labs_examples.Bali_InPerson_MarApr2020.Lambda.Practice; public class InterfaceController { public static void main(String[] args) { //--------------------SomeInterface1-------------------------- //invoking lambda from another method double printSum = sumMethod(); System.out.println("lambda takes no parameter and calling from another method: " + printSum); //invoking lambda right in the main method double a = 24.54; double b = 32.54; SomeInterface takesNoParameter = () -> (int) ((double) a + b); System.out.println("Takes no parameter defined within main method: " + takesNoParameter.noParameter()); //----------------------SomeInterface2------------------------- // lambda, method body on one line SomeInterface2 someInterface2 = (d, c) -> (int) (d * c); int multiply = (int) someInterface2.TwoParameter(55.45,62.33); System.out.println("lambda takes in two parameter and multiplies: " + multiply); //lambda, method body in curly brackets SomeInterface2 someInterface21 = (d, c) -> { return d * c; }; int multiply1 = (int) someInterface21.TwoParameter(55.45, 62.33); System.out.println(); //-----------------------SomeInterface3----------------------- // lambda, method body on one line SomeInterface3 someInterface3 = (val1) -> (val1 >= 1); Boolean aBoolean = someInterface3.trueOrFalse(4); System.out.println(aBoolean); //lambda, method body in curly brackets int x = 20; SomeInterface3 someInterface31 = val1 -> { if (val1 == x && val1 >= 3){ }else{ return false; } return true; }; boolean aBoolean1 = someInterface31.trueOrFalse(1); System.out.println("if logic is true print true, else, false: " + aBoolean1); //--------------------------------------GenericInterface---------------------------------- // lambda, method body on one line GenericInterface<Integer, Double, String> genericInterface = (Double d, String s) -> (int)(Double.parseDouble(s) * d); int cast = genericInterface.convert(23.44, "2"); System.out.println("\nlambda on one line - converting a string to double and casting it to an integer: " + cast); //lambda, method body in curly brackets GenericInterface<Integer, Double, String> genericInterface1 = (Double d, String s) ->{ int e = 12; int c; if (d >= 2){ c = (int) (Double.parseDouble(s)*d) + e; return c; }else { return null; } }; int casting = genericInterface1.convert(2.33,"12"); System.out.println("lambda inside curly brackets - converting a string to double and casting it to an integer: " + casting); //--------------------------------------GenArraylistInterface---------------------------- // GenArrlistInterface<ArrayList<Integer>, Integer> genericInterface2 = (Integer[] vals) -> { // //taking in an array and returning an arraylist // // for(Integer i :vals) { // Array.setInt(vals, 0,33); // Array.setInt(vals, 1,44); // Array.setInt(vals, 2,55); // Array.setInt(vals, 3,66); // Array.setInt(vals, 4,77); // Array.setInt(vals, 5,88); // Array.setInt(vals, 6,99); // } // System.out.println(i); // // return null; // }; // // ArrayList<Integer> list = genericInterface2.list() } public static double sumMethod(){ SomeInterface takesNoParameter = () -> { int a = 24; int b = 32; double c = a + b; return c; }; double sum = takesNoParameter.noParameter(); return sum; } } <file_sep>package labs_examples.datatypes_operators.labs; import sun.management.snmp.jvmmib.JVM_MANAGEMENT_MIBOidTable; /** * Data Types and Operators Exercise 1: Variable declaration and Initialization * * Write the necessary code to complete the following: * * 1. Declare an int, a double, a float and a char * 2. Assign appropriate values to each * 3. Print out each variable to the console * * */ public class Exercise_01 { public static void main(String[] args) { int iNum = 53237954; System.out.println(" the value of int is " + iNum); double dNum = 34534634699998567785565645646456765.4456; System.out.println(" the value of double is " + dNum); float fNum = 456566332446.4456f; System.out.println(" the value of float is " + fNum); char c = 'j'; System.out.println(" the value of char is " + c); } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.B_polymorphism; import javax.xml.crypto.KeySelector; /** * 1) Demonstrate the three forms of Polymorphism: * - Overloading * - Overriding * - Interfaces * * 2) Demonstrate the three forms of polymorphism again - but in a new set of classes. We want to lock this in. * Challenge yourself. Build something you're proud of. * * 3) Demonstrate using an interface as an instance variable - have a constructor that takes in the interface as a * parameter. Also have a setter that allows you to update the interface object. Through code, demonstrate that you * understand how we can use Interfaces as dependencies (instance variables) and how useful and flexible they make our * application. */ public class Exercise_1 { public static void main(String[] args) { //objects Bag bag = new Bag(); BackPack backPack = new BackPack(); //invoking methods bag.Purpose("anything", "shape"); backPack.Purpose("travel", "cuboid");//overriding parent method } } // 1) Demonstrate the three forms of Polymorphism: // * - Overloading // * - Overriding // * - Interfaces interface Features{ public boolean Portable(); public void Travel(); public void Functional(); } class Bag{ private int size; private boolean pocket; private String use; private String shape; public Bag(){ } //example of constructor overloading public Bag(int size, boolean pocket, String use, String shape) { this.size = size; this.pocket = pocket; this.use = use; shape = shape; } //example of constructor overloading public Bag(String use, String shape) { this.use = use; shape = shape; } public void Purpose(String use, String shape){ this.use = use; this.shape = shape; System.out.println("Invoking from parent class: " + "A bag can be used for " + use + " and has all sorts of " + shape + "s"); } } class BackPack extends Bag { private int numPocket; private String compartment; private String strap; private String padding; public BackPack() { } public BackPack(int numPocket, String compartment, String strap, String padding) { this.numPocket = numPocket; this.compartment = compartment; this.strap = strap; this.padding = padding; } public BackPack(int size, boolean pocket, String use, String shape, int numPocket, String compartment, String strap, String padding) { super(size, pocket, use, shape); this.numPocket = numPocket; this.compartment = compartment; this.strap = strap; this.padding = padding; } public BackPack(String use, String shape, int numPocket, String compartment, String strap, String padding) { super(use, shape); this.numPocket = numPocket; this.compartment = compartment; this.strap = strap; this.padding = padding; } @Override public void Purpose(String use, String shape) { //overriding parent method (Purpose) with a different System.out.println() System.out.println("This bag is used for " + use + "ing" + " and is shaped like a " + shape); } } //Backpack implementing Features class Backpack implements Features{ String strap; String Handle; boolean portability; public Backpack(String strap, String handle, boolean portability) { this.strap = strap; this.Handle = handle; this.portability = portability; } @Override public boolean Portable() { return false; } @Override public void Travel() { } @Override public void Functional() { } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.D_my_oop; //subclass public class Client extends BookingSystem { private String interest; private String style; private String request; public Client(int time, int date) { super(time, date); } public Client(String interest, String style, String request) { this.interest = interest; this.style = style; this.request = request; } public Client(String firstName, String lastName, int phoneNum, String email) { super(firstName, lastName, phoneNum, email); } } <file_sep>package labs_examples.exception_handling.labs; /** * Exception Handling Exercise 6: * * Demonstrate throwing an exception in one method and catching it in another method. * */ class Exercise_6 { public static void main(String[] args) { try { int x = anArray(12); System.out.println(x); } catch (IndexOutOfBoundsException aeExc) { System.out.println("Error: index out of bound"); } System.out.println("end of program"); } public static int anArray(int i) throws IndexOutOfBoundsException { int[] a = {2, 3, 4, 5, 67, 8}; return a[i]; } }<file_sep>package labs_examples.multi_threading.labs; /** * Multithreading Exercise 4: * * Demonstrate the use of a synchronized block and a synchronized method - ensure that the synchronization is * working as expected */ //POJO1 class MultiplySyncBlock { private int y; int MultiplySyncBlock(int y) { this.y = y; //multiply int total = 0; //as x increments by 1, gets multiplied by y (in other words, every incremented value of x is multiplied by y) for (int x=0; x<20; x++){ try { total = x * y; System.out.println("In " + Thread.currentThread().getName() + " total = " + total); } catch (Exception e){ System.out.println("error detected"); } }return total; } } //POJO2 class MultiplySyncMethod { private int z; private int a; synchronized int MultiplySyncMethod(int z, int a) { this.z = z; this.a = a; //multiply int total = 0; //as x increments by 1, gets multiplied by y (in other words, every incremented value of x is multiplied by y) for (int x=0; x<10; x++){ try { total = x * z * a; System.out.println("In " + Thread.currentThread().getName() + " total = " + total); } catch (Exception e){ System.out.println("error detected"); } }return total; } } //Thread class SyncThread implements Runnable{ //creating thread object that will manage the thread Thread thread; static MultiplySyncBlock mB = new MultiplySyncBlock(); static MultiplySyncMethod mM = new MultiplySyncMethod(); int mY; int mZ; int mA; int answer; //reference to sync block public SyncThread(int y, String name) { //create thread object - pass "this" object and the name given thread = new Thread(this, name); mY = y; //start the thread automatically when the MultiplySyncBlock object is created thread.start(); } //reference to sync method public SyncThread(int z, int a, String name) { //create thread object - pass "this" object and the name given thread = new Thread(this, name); mZ = z; mA = a; //start the thread automatically when the MultiplySyncMethod object is created thread.start(); } @Override public void run() { System.out.println("Starting " + Thread.currentThread().getName()); //synchronized block synchronized(mB) { answer = mB.MultiplySyncBlock(mY); } //synchronized method answer = mM.MultiplySyncMethod(mZ,mA); } } //controller class Exercise_4{ public static void main(String[] args) { System.out.println("Let's multiple"); SyncThread syncThread1 = new SyncThread(1, "ThreadMultiplySync1"); SyncThread syncThread2 = new SyncThread(2, "ThreadMultiplySync2"); SyncThread syncThread3 = new SyncThread(3,3, "ThreadMultiplySync3"); SyncThread syncThread4 = new SyncThread(4, 4, "ThreadMultiplySync4"); try { syncThread1.thread.join(); syncThread2.thread.join(); syncThread3.thread.join(); syncThread4.thread.join(); } catch(InterruptedException exc) { System.out.println("Main thread interrupted."); } } }<file_sep>package labs_examples.objects_classes_methods.labs.objects; /** * Following the example in CarExample.java, please use Object Composition to model an Airplane class. * The Airplane class must be composed of at least 4 other classes (as well as any primitive types you'd like). * The Airplane class itself should have a fuel capacity (double) variable, as well as a currentFuelLevel variable. * We'll use these a bit later. */ class Exercise_1{ public static void main(String[] args) { Model model = new Model("Boeing", 747, "Delta"); Make make = new Make ( 2012); FuelCap fuelCap = new FuelCap(26000.00); AEngine engine = new AEngine(400); Airplane myAirplane = new Airplane (model, make, fuelCap, 10000.00, engine); System.out.println("My frequent flyer is " + myAirplane.model.name + " " + myAirplane.model.series + " , made in the year of - " + myAirplane.make + ", with a tank size of " + myAirplane.fuelCap.tankSizeInLiters + " liters and a " +myAirplane.aEngine.horsePower + " engine."); System.out.println("\n"); System.out.println(myAirplane.toString()); } } class Airplane { Model model; Make make; FuelCap fuelCap; Double currentFuelLevel; AEngine aEngine; public Airplane(Model model, Make make, FuelCap fuelCap, Double currentFuelLevel, AEngine aEngine) { this.make = make; this.fuelCap = fuelCap; this.currentFuelLevel = currentFuelLevel; this.model = model; this.aEngine = aEngine; } @Override public String toString() { return "Airplane {" + ",\n model = " + model.toString() + ",\n make = " + make + ",\n fuelCap = " + fuelCap.toString() + ",\n currentFuelLevel = " + currentFuelLevel.toString() + ",\n aEngine = " + aEngine.toString() + '}'; } } class Make { int year; public Make(int year){ this.year = year; } @Override public String toString() { return "Make {" + "year = " + year + '}'; } } class Model { String name; int series; String brand; public Model(String name, int series, String brand){ this.name = name; this.series = series; this.brand = brand; } @Override public String toString() { return "Model {" + " name = " + name + " series = " + series + " brand = " + brand + '}'; } } class FuelCap { double tankSizeInLiters; public FuelCap(double tankSizeInLiters){ this.tankSizeInLiters = tankSizeInLiters; } @Override public String toString() { return "FuelCap {" + "tankSize = " + tankSizeInLiters + '}'; } } class CurrentFuelLevel { double currentLevel; public CurrentFuelLevel(double currentLevel){ this.currentLevel = currentLevel; } @Override public String toString() { return "currentFuelLevel {" + "currentLevel = " + currentLevel + '}'; } } class AEngine { double horsePower; public AEngine(double horsePower){ this.horsePower = horsePower; } @Override public String toString() { return "AEngine {" + "horsePower = " + horsePower + '}'; } } <file_sep>package labs_examples.Bali_InPerson_MarApr2020.Lambda.Examples; public class MyGenericInterface { public static void main(String[] args) { //Integer.parseInt() casts a String to an Integer if the String is a number, if not (a word for example) then it would not be able to cast/execute SomeInterface<Double, Integer, String> someName = (Integer i, String s) -> (double) Integer.parseInt(s) + i; double pen = someName.calc(7, "7"); System.out.println(pen); } } @FunctionalInterface interface SomeInterface <N,S,J>{ public N calc (S val1, J val2); } <file_sep>package labs_examples.static_nonstatic.labs; /** * 1) A static method calling another static method in the same class * 2) A static method calling a non-static method in the same class * 3) A static method calling a static method in another class * 4) A static method calling a non-static method in another class * 5) A non-static method calling a non-static method in the same class * 6) A non-static method calling a non-static method in another class * 7) A non-static method calling a static method in the same class * 8) A non-static method calling a static method in another class */ public class StaticNonStatic_Exercise_1 { public static void main(String[] args) { //same class - static calling static staticMethod(); int divide = divide(12,6); System.out.println(divide); //same class - static calling non-static StaticNonStatic_Exercise_1 object = new StaticNonStatic_Exercise_1(); object.nonStaticMethod(); StaticNonStatic_Exercise_1 multiply = new StaticNonStatic_Exercise_1(); multiply.multiply(22.22,33.33); //static calling non-static - another class System.out.println("printing static method calling a non-static method - another class "); Backpack type = new Backpack(); type.backPackType("Book bag"); // static calling static - another class System.out.println("printing static method calling a static method - another class "); Backpack.isPortable(); //static main method calling nonStatic1 to print nonStatic2 calling from nonStatic1 - same class System.out.println("printing (static main method calling nonStatic1) to print (non-static multiply calling from nonStatic1)"); StaticNonStatic_Exercise_1 nonStaticNonStatic = new StaticNonStatic_Exercise_1(); nonStaticNonStatic.nonStatic1(); //A non-static method calling a non-static method in another class StaticNonStatic_Exercise_1 nonStaticNonStaticAnotherClass = new StaticNonStatic_Exercise_1(); nonStaticNonStaticAnotherClass.nonStatic2(); //A non-static method calling a static method in the same class StaticNonStatic_Exercise_1 nonStaticStaticSameClass = new StaticNonStatic_Exercise_1(); nonStaticNonStaticAnotherClass.nonStatic3(); //A non-static method calling a static method in another class StaticNonStatic_Exercise_1 nonStaticStaticAnotherClass = new StaticNonStatic_Exercise_1(); nonStaticStaticAnotherClass.nonStatic4(); } public static void staticMethod(){ System.out.println("printing static method calling static method - same class"); } public static int divide(int a, int b){ return a*b; } public void nonStaticMethod(){ System.out.println("printing static method calling non-static method - same class"); } public void multiply(double a, double b){ double x = a*b; System.out.println(x); } public static int simpleMath(int a, int b, int c){ return ((a+b)/c); } public void nonStatic1(){ multiply(6,3); } public void nonStatic2(){ System.out.println("printing static main method calling nonStatic2 - nonStatic2 calling non-static backPackTyp1 from another class - non-static backPackType1 calling non-static backPackType and non-static isNotPortable"); Backpack type2 = new Backpack(); type2.backPackType1(); } public void nonStatic3(){ int x = simpleMath(3,3,2); System.out.println("printing static main method calling nonStatic3 - nonStatic3 calling static simpleMath from the same class"); System.out.println(x); } public void nonStatic4(){ System.out.println("printing static main method calling nonStatic4 - nonStatic4 calling static backPackType2 from another class"); Backpack.backPackType2(); } } class Backpack { protected String type; protected static int strap; protected static String portable; protected static String notPortable; public Backpack(){ } public void backPackType(String type) { System.out.println(type); } public void backPackType1(){ backPackType("not a backpack"); isNotPortable(); } public static void backPackType2(){ Backpack type2 = new Backpack(); type2.backPackType("Day pack");//non static isPortable();//static } public void isNotPortable(){ notPortable = "is not portable"; System.out.println(notPortable); } public static void isPortable(){ portable = "is portable"; System.out.println(portable); } } <file_sep>package labs_examples.input_output.labs; import java.io.*; /** * Input/Output Exercise 2: File encryption * * -Using the BufferedReader, read a file character by character and write an encrypted version to a new file. * -For example, change every 'a' to '-' and every 'e' to '~' . * -Make sure you close the connections to both files. * * Then, ead back the encrypted file using the BufferedReader and * print out the unencrypted version. Does it match the original file? * */ class Exercise_2{ public static void main(String[] args) { //passing in file String fileReadPath = "src/labs_examples/input_output/files/char_data_copy.txt"; String fileWritePath = "src/labs_examples/input_output/files/char_data_rewrite.txt"; //temp st variable String st ; //declaring and initializing files try (BufferedReader br = new BufferedReader(new FileReader(new File (fileReadPath))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File (fileWritePath)))) { //while end of file is not reached while ((st = br.readLine()) != null) { //write to new file and replace "a" with "-" and "e" with "~" bw.write((st.replaceAll("a", "-").replaceAll("e","~"))); //line by line bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } //reading back encrypted file try (BufferedReader brNew = new BufferedReader(new FileReader(new File(fileWritePath)))){ //while end of file is not reached while ((st = brNew.readLine()) != null) { //print encrypted file to console System.out.println(st); } } catch (IOException ex){ ex.printStackTrace(); } } }<file_sep>package labs_examples.objects_classes_methods.labs.oop.C_blackjack; import java.util.ArrayList; /** * Deck.java (POJO - this will hold deck data) * * Card[] cards; * * ArrayList<Integer> usedCards; */ public class Deck { private Card[] deck = new Card[52]; private ArrayList<Integer> usedCards = new ArrayList<>(); char[] suit = new char[]{'♠', '♦', '♥', '♣'}; private static int freshDecksLoaded; public Deck() { loadFreshDeck(); freshDecksLoaded++; } public Card[] getDeck() { return deck; } public void setDeck(Card[] deck) { this.deck = deck; } public ArrayList<Integer> getUsedCards() { return usedCards; } public void setUsedCards(ArrayList<Integer> usedCards) { this.usedCards = usedCards; } public char[] getSuit() { return suit; } public void setSuit(char[] suit) { this.suit = suit; } public static int getFreshDecksLoaded() { return freshDecksLoaded; } public static void setFreshDecksLoaded(int freshDecksLoaded) { Deck.freshDecksLoaded = freshDecksLoaded; } private void loadFreshDeck() { int count = 0; for (int x = 0; x < 4; x++) { for (int i = 1; i < 14; i++) { if (i == 1) { deck[count] = new Card(suit[x], "ACE"); } else if (i == 11) { deck[count] = new Card(suit[x], "JACK"); } else if (i == 12) { deck[count] = new Card(suit[x], "QUEEN"); } else if (i == 13) { deck[count] = new Card(suit[x], "KING"); } else { deck[count] = new Card(suit[x], Integer.toString(i).toUpperCase()); } count++; } } } public boolean isCardUsed(int value) { if (usedCards.contains(value)){ return true; } else { return false; } } public Card getCardAt(int randomNum) { return deck[randomNum]; } } <file_sep>package labs_examples.objects_classes_methods.labs.oop.D_my_oop; public class Service { //TODO: ask Ryan, would it be better to create a class and detail all the different types of services or create just one instance variable called service? /*services include: Manicure pedicure manicure + pedicure polish change acrylic fill hard gel maintenance deluxe Manicure deluxe Pedicure art/design dip powder */ } <file_sep>package labs_examples.objects_classes_methods.labs.oop.A_inheritance; /** * Why does the output print in the order it does? * * You answer: Due to the order of execution, the static blocks are executed first, * followed by constructors and then the instance methods (a non-static method of a class). * * But in an inheritance relationship, the order of execution of constructors is * parent class to child class. * * In this case, although, the main method (which has a static keyword) should print first * but it is invoking the constructor in subclass C_1 * therefore, the order of execution of constructors in inheritance relationship kicks in. * So, the parent class A_1 prints first, then following subclass B_1, lastly subclass C_1. * */ class A_1 { public A_1() { System.out.println("Class A Constructor"); } } class B_1 extends A_1 { public B_1() { System.out.println("Class B Constructor"); } } class C_1 extends B_1 { public C_1() { System.out.println("Class C Constructor"); } } public class Exercise_03 { public static void main(String[] args) { C_1 c = new C_1(); } } <file_sep>package labs_examples.objects_classes_methods.labs.methods; /** * Create a recursive method named factorial that will return the factorial of any number passed to it. * * For instance, after creatin the factorial method, uncomment the two lines in the main() method. When you run * it, it should print 120. It should also work for any ther number you pass it. * */ public class Exercise_04 { public static void main(String[] args) { int x = factorial(5);//5 will get passed in first, then 4, 3, 2, 1 until it knows what x equals, //in this case, x = 1, 1! = 1, so then it continues to loop back around, 2*1! -> 3*2! -> 4*3! -> 5*4! -> 5! = 120 System.out.println(x); } // 1 * 2 * 3 * 4 * 5 = 120 static int factorial(int x){ int total; //base case - this will be used to end the recursive calls if(x == 1) return 1; //other wise, factorial is called and passed x -1, //reducing x each time until it reaches 1. total = x * factorial(x - 1); return total; } } /* 2*1! -> 2 * 1 = 2 3*2! -> 3 * 2 = 6 4*3! -> 4 * 6 = 24 5*4! -> 5 * 24 = 120 5! =120 (oldest, first to be in the stack) */ <file_sep>package labs_examples.multi_threading.labs; /** * Multithreading Exercise 3: * * In one of the previous exercises, demonstrate changing the priority of a thread */ //using Exercise 2 to demo changing priority class Exercise_3{ public static void main(String[] args) throws Exception { System.out.println("Let's multiple simultaneously"); MultiplySetPriority multiplyingSimultaneously = new MultiplySetPriority(2, "ThreadMultiply2"); MultiplySetPriority multiplyingSimultaneously1 = new MultiplySetPriority(3, "ThreadMultiply3"); //setting thread priority multiplyingSimultaneously.thread.setPriority(Thread.NORM_PRIORITY+1); multiplyingSimultaneously1.thread.setPriority(Thread.NORM_PRIORITY-1); //starting ThreadMultiply2 multiplyingSimultaneously.thread.start(); //executing ThreadMultiply2 first try { multiplyingSimultaneously.thread.join(); } catch(InterruptedException exc) { System.out.println("Main thread interrupted."); } //THEN //starting ThreadMultiply3 //executing ThreadMultiply3 second multiplyingSimultaneously1.thread.start(); try { multiplyingSimultaneously1.thread.join(); } catch(InterruptedException exc) { System.out.println("Main thread interrupted."); } //priority count System.out.println("\n" + multiplyingSimultaneously.thread.getName() + " : High priority thread counted to " + multiplyingSimultaneously.count); System.out.println(multiplyingSimultaneously1.thread.getName() + " : Low priority thread counted to " + multiplyingSimultaneously1.count); } } class MultiplySetPriority implements Runnable{ int count; //multiplying by y private int y; //creating thread object that will manage the thread Thread thread; static boolean stop = false; static String currentName; int id = 0; public MultiplySetPriority(int y, String name) { //passing in value for y in the main thread this.y = y; //create thread object - pass "this" object and the name given thread = new Thread(this, name); count = 0; currentName = name; //start the thread automatically when the MultiplyingSimultaneously object is created } @Override public void run() { System.out.println("\nStarting" + Thread.currentThread().getName()); do { count++; if(currentName.compareTo(thread.getName()) != 0) { currentName = thread.getName(); //multiply int total; //as x increments by 1, gets multiplied by y (in other words, every incremented value of x is multiplied by y) for (int x = 0; x < 20; x++){ try { total = x * y; System.out.println("In " + Thread.currentThread().getName() + " total = " + total); } catch (Exception e){ System.out.println("error detected"); } } } //HIGH priority is 10 //LOW priority is 1 } while(stop == false && count < 10); stop = true; } } <file_sep>package labs_examples.multi_threading.labs; /** * Multithreading Exercise 2: * * Create an application that creates a Thread using the Thread class */ class Exercise_2{ public static void main(String[] args) { System.out.println("Let's multiple in parallel"); SyncThread multiplyingSimultaneously = new SyncThread(2, "ThreadMultiply2"); SyncThread multiplyingSimultaneously1 = new SyncThread(3, "ThreadMultiply3"); Multiply multiply1 = new Multiply(2, "Thread1"); Multiply multiply2 = new Multiply(4, "Thread2"); } } //POJO implementing thread class Multiply implements Runnable{ //multiplying by y private int y; //creating thread object that will manage the thread Thread thread; public Multiply(int y, String name) { //passing in value for y in the main thread this.y = y; //create thread object - pass "this" object and the name given thread = new Thread(this, name); //start the thread automatically when the MultiplyingSimultaneously object is created thread.start(); } @Override public void run() { System.out.println("Starting " + Thread.currentThread().getName()); //multiply int total; //as x increments by 1, gets multiplied by y (in other words, every incremented value of x is multiplied by y) for (int x=0; x<20; x++){ try { total = x*y; System.out.println("In " + Thread.currentThread().getName() + " total = " + total); } catch (Exception e){ System.out.println("error detected"); } } } }<file_sep>package labs_examples.arrays.labs; import java.util.ArrayList; import java.util.Arrays; import java.util.function.DoubleToIntFunction; /** * ArrayLists * * Please demonstrate how to create an ArrayList, populate an array list, access elements within an ArrayList. * Also take a moment to explore the many methods that are available to you when you use an ArrayList. By simply * typing the dot operator (".") after the ArrayList object that you create. You should see a menu pop up that * shows a list of methods. * */ public class Exercise_07 { public static void main(String[] args) { //creating/declaring and array list by name of list ArrayList<String> list = new ArrayList<String>(); // add values to ArrayList list.add("Green"); list.add("Yellow"); list.add("Blue"); list.add("Purple"); list.add("Red"); list.add("orange"); //printing array list by using the for loop for (String element : list){ System.out.println(element); } //space break System.out.println(" "); //accessing and printing all elements by iteration using the for loop System.out.println("Accessing and printing all elements by iteration using the for loop: "); if (!list.isEmpty()) { for (int i = 0; i < 6; i++) { System.out.println("First element at index " + i + " is " + list.get(i)); } } //space break System.out.println(" "); //accessing and printing: // an element using .get (int index) // an index by using .indexOf("element_name") System.out.println("Using .indexOf to return index at element_name and .get() to return element name at int index: "); System.out.println("First element at index " + list.indexOf("Yellow") + " is "+ list.get(1)); //System.out.println("First element at index " + list.indexOf("Blue") + " is "+ list.get(2)); //System.out.println("First element at index " + list.indexOf("Purple") + " is "+ list.get(3)); //System.out.println("First element at index " + list.indexOf("Red") + " is "+ list.get(4)); //System.out.println("First element at index " + list.indexOf("orange") + " is "+ list.get(5)); //demonstrating other methods System.out.println("\n"); System.out.println("Number of elements in the list:" + list.size()); System.out.println("\n"); System.out.println("A copy of the array list:" + list.clone());//Returns a copy of the array list System.out.println("\n"); System.out.println("Remove element: " + list.remove("Purple") + " at index: " + list.indexOf(3)); //after executing list.remove, it should returns true and -1 when the list has no element } }
4f2cdf911fd99aaaf8efd0a2b78554aa72dd230f
[ "Java" ]
29
Java
nngocjade/java_fundamentals
ac7345fc33ec196d065e6f07aa35fe88578efe3e
61ded072144f7e0acf1498e9c05ccc7c1a418e45
refs/heads/master
<repo_name>myronos/testqamy<file_sep>/step-definitions/actions.js const {Given, When} = require('cucumber'); Given('User prints comment {string}', (comment) => { return console.log(comment); }); When('User navigates to the {string} with url {string}', (_, url) => { return browser.driver.get(url); }); When('User clicks {string} {string}', (_,locator) => { const elem = element(by.css(locator)); return elem.click(); }); /*When('User enters {int} in field {string}', (number, locator) => { return element(by.model(locator)).sendKeys(number); });*/
a25397458949f5e244cf15233e5032c12b99c4b6
[ "JavaScript" ]
1
JavaScript
myronos/testqamy
cb7e097bd947c03930e42cfeea86b2d41f1694a8
3cbe691681d8cbe415a6048b17ad3f560d82f9fe
refs/heads/master
<file_sep><?php namespace apibotApi\controllers; use Monolog\Logger; use Stomp\SimpleStomp; use Stomp\Transport\Message; use Symfony\Component\HttpFoundation\JsonResponse; use Telegram\Bot\Api; class HookTelegramController { /** @var Api */ private $api; /** @var Logger */ private $logger; /** @var SimpleStomp */ private $stomp; /** @var string */ private $certificatePath; /** @var string */ private $url; public function __construct( Api $api, Logger $logger, SimpleStomp $stomp, $url = '', $certificatePath = '' ) { $this->api = $api; $this->logger = $logger; $this->stomp = $stomp; $this->url = $url; $this->certificatePath = $certificatePath; } public function actionHook() { $this->logger->addInfo('controllers.hook.telegram:actionHook start'); $update = $this->api->getWebhookUpdates(); $this->logger->addInfo('controllers.hook.telegram:actionHook message: ' . json_encode($update['message'])); try { $isSuccess = $this->stomp->send( '/queue/incoming.telegram', new Message(json_encode($update['message'])) ); } catch (\Exception $e) { $this->logger->addInfo( sprintf( 'controllers.hook.telegram:actionHook exception: %s: %s', get_class($e), $e->getMessage() ) ); $isSuccess = false; } $this->logger->addInfo('controllers.hook.telegram:actionHook send: ' . $isSuccess); return new JsonResponse(); } public function actionStart() { $hook = [ 'url' => $this->url, 'certificate' => $this->certificatePath ]; $this->logger->addInfo('controllers.hook.telegram:actionStart', $hook); $response = $this->api->setWebhook($hook); return new JsonResponse($response); } public function actionStop() { $response = $this->api->removeWebhook(); $this->logger->addInfo('controllers.hook.telegram:actionStop'); return new JsonResponse($response); } } <file_sep><?php namespace apibotApi\controllers; use GuzzleHttp\Client; use Monolog\Logger; use Stomp\SimpleStomp; use Stomp\Transport\Message; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class HookKikController { /** @var SimpleStomp */ private $stomp; /** @var Client */ private $guzzle; /** @var Logger */ private $logger; /** @var string */ private $urlHook; /** @var string */ private $urlConfig; /** @var string */ private $username; /** @var string */ private $apiKey; public function __construct( SimpleStomp $stomp, Client $guzzle, Logger $logger, $urlHook, $urlConfig, $username, $apiKey ) { $this->stomp = $stomp; $this->guzzle = $guzzle; $this->logger = $logger; $this->urlHook= $urlHook; $this->urlConfig= $urlConfig; $this->username = $username; $this->apiKey = $apiKey; } public function actionHook(Request $request) { $this->logger->addInfo('controllers.hook.kik:actionHook start'); try { $isSuccess = $this->stomp->send( '/queue/incoming.kik', new Message($request->getContent()) ); } catch (\Exception $e) { $this->logger->addInfo( sprintf( 'controllers.hook.kik:actionHook exception: %s: %s', get_class($e), $e->getMessage() ) ); $isSuccess = false; } $this->logger->addInfo('controllers.hook.kik:actionHook send: ' . $isSuccess); return new JsonResponse(); } public function actionStart() { $request = [ 'auth' => [$this->username, $this->apiKey], 'headers' => [ 'Content-Type' => 'application/json' ], 'body' => json_encode( [ 'webhook' => $this->urlHook, 'features' => [ 'manuallySendReadReceipts' => false, 'receiveReadReceipts' => false, 'receiveDeliveryReceipts' => false, 'receiveIsTyping' => false ] ] ) ]; $this->guzzle->request( 'post', $this->urlConfig, $request ); return new JsonResponse(['ok']); } } <file_sep><?php namespace tests\models\db; use apibotApi\models\db\Replies; class RepliesTest extends \PHPUnit_Framework_TestCase { /** @test */ public function shouldReturnRepliesByState() { /** @var \Mockery\Mock $queryMock */ $queryMock = \Mockery::mock(); $queryMock->shouldReceive('bindParam')->withArgs([':message_id', 690, \PDO::PARAM_INT])->once(); $queryMock->shouldReceive('execute'); $queryMock ->shouldReceive('fetchAll') ->andReturn( [ [ 'id' => 56, 'message_id' => 690, 'message_to' => 691, 'value' => 'Yes', 'visible' => '1', 'conditions' => null, 'modifications' => null, 'keyboard_row' => 1 ], [ 'id' => 57, 'message_id' => 690, 'message_to' => 692, 'value' => 'No', 'visible' => '1', 'conditions' => null, 'modifications' => null, 'keyboard_row' => 1 ] ] ); /** @var \PDO|\Mockery\Mock $pdoMock */ $pdoMock = \Mockery::mock('\PDO'); $pdoMock->shouldReceive('prepare')->andReturn($queryMock); $replies = new Replies($pdoMock, 50); $result = $replies->getRepliesByMessage(690); self::assertEquals( [ [ 'id' => 56, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'message_to' => 691, 'modifications' => null, 'value' => 'Yes', 'keyboard_row' => 1, 'visible' => true ], 'links' => [ 'self' => '/v1/replies/56/', 'message' => '/v1/messages/690/' ] ], [ 'id' => 57, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'message_to' => 692, 'modifications' => null, 'value' => 'No', 'keyboard_row' => 1, 'visible' => true ], 'links' => [ 'self' => '/v1/replies/57/', 'message' => '/v1/messages/690/' ] ] ], $result ); } }<file_sep><?php namespace apibotApi\controllers; use apibotApi\models\db\Replies; use apibotApi\models\Pager; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class RepliesController { /** @var Replies */ private $replies; public function __construct(Replies $replies) { $this->replies = $replies; } public function actionList(Request $request) { $count = $this->replies->count(); $pager = new Pager($request, $count, '/v1/replies/'); return new JsonResponse( [ 'links' => [ 'self' => $pager->getSelf(), 'prev' => $pager->getPrevLink(), 'next' => $pager->getNextLink(), 'first' => $pager->getFirstLink(), 'last' => $pager->getLastLink() ], 'meta' => [ 'total-pages' => $pager->getTotal() ], 'data' => $this->replies->getList( $pager->getLimit(), $pager->getOffset() ) ] ); } public function actionOne($id) { $items = $this->replies->getOne($id); $links = array_merge( ['parent' => '/v1/replies/'], $items['links'] ); unset($items['links']); return new JsonResponse( [ 'links' => $links, 'data' => $items ] ); } } <file_sep><?php namespace apibotApi\models\db; abstract class RedisListResource { public function getList() { return []; } } <file_sep><?php namespace tests\models\response; use apibotApi\models\response\Message; use apibotApi\models\response\Resolver; class ResolverTest extends \PHPUnit_Framework_TestCase { /** @test */ public function shouldGetResponseMessage() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(690)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 691])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(690) ->andReturn( [ [ 'id' => 56, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 691, 'visible' => true, 'value' => 'Yes' ] ], [ 'id' => 57, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 692, 'visible' => true, 'value' => 'No' ] ] ] ) ->once(); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(691) ->andReturn( [ [ 'id' => 58, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 693, 'visible' => true, 'value' => 'Yep', 'keyboard_row' => null ] ], [ 'id' => 59, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 694, 'visible' => true, 'value' => 'Nuh', 'keyboard_row' => null ] ] ] ) ->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(691) ->andReturn( [ 'id' => 691, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => 'Sure?' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, null); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals( [ new Message( 'Sure?', [ ['Yep', 'Nuh'] ] ) ], $result ); } /** @test */ public function shouldGetResponseForSetOfMessages() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(690)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 693])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(690) ->andReturn( [ [ 'id' => 56, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 691, 'visible' => true, 'value' => 'Yes' ] ], [ 'id' => 57, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 692, 'visible' => true, 'value' => 'No' ] ] ] ) ->once(); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(693) ->andReturn( [ [ 'id' => 58, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 694, 'visible' => true, 'value' => 'Yep', 'keyboard_row' => null ] ], [ 'id' => 59, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 695, 'visible' => true, 'value' => 'Nuh', 'keyboard_row' => null ] ] ] ) ->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(691) ->andReturn( [ 'id' => 691, 'type' => 'messages', 'attributes' => [ 'message_next' => 692, 'value' => 'ARE' ] ] ); $messagesMock ->shouldReceive('getOne') ->with(692) ->andReturn( [ 'id' => 692, 'type' => 'messages', 'attributes' => [ 'message_next' => 693, 'value' => 'YOU' ] ] ); $messagesMock ->shouldReceive('getOne') ->with(693) ->andReturn( [ 'id' => 693, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => 'SURE???' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, null); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals( [ new Message('ARE', []), new Message('YOU', []), new Message( 'SURE???', [ ['Yep', 'Nuh'] ] ) ], $result ); } /** @test */ public function shouldHonorKeyboardRow() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(690)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 691])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(690) ->andReturn( [ [ 'id' => 56, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 691, 'visible' => true, 'value' => 'Yes', 'keyboard_row' => null ] ] ] ) ->once(); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(691) ->andReturn( [ [ 'id' => 58, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 693, 'visible' => true, 'value' => 'Yep', 'keyboard_row' => 1 ] ], [ 'id' => 61, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 694, 'visible' => true, 'value' => 'Yes', 'keyboard_row' => 2 ] ], [ 'id' => 59, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 694, 'visible' => true, 'value' => 'Nuh', 'keyboard_row' => 1 ] ], [ 'id' => 60, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 693, 'visible' => true, 'value' => 'No', 'keyboard_row' => 2 ] ], [ 'id' => 62, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => null, 'message_to' => 694, 'visible' => true, 'value' => 'Well...', 'keyboard_row' => null ] ] ] ) ->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(691) ->andReturn( [ 'id' => 691, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => 'Sure?' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, null); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals( [ new Message( 'Sure?', [ ['Yep', 'Nuh'], ['Yes', 'No'], ['Well...'] ] ) ], $result ); } /** @test */ public function shouldModifyUserPropsOnAnswer() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(690)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 691])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock ->shouldReceive('getRepliesByMessage') ->with(690) ->andReturn( [ [ 'id' => 56, 'type' => 'replies', 'attributes' => [ 'conditions' => null, 'modifications' => [ '$inc' => [ 'yesssss' => 2, 'nooo0' => -1 ], '$set' => [ 'good_man' => true ], '$unset' => [ 'good_man' => true ] ], 'message_to' => 691, 'visible' => true, 'value' => 'Yes', 'keyboard_row' => null ] ] ] ) ->once(); $repliesMock->shouldReceive('getRepliesByMessage')->with(691)->andReturn([])->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(691) ->andReturn( [ 'id' => 691, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => 'Sure?' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $redisMock->shouldReceive('incrBy')->with('users:1:props:yesssss', 2); $redisMock->shouldReceive('incrBy')->with('users:1:props:nooo0', -1); $redisMock->shouldReceive('set')->with('users:1:props:good_man', true); $redisMock->shouldReceive('del')->with('users:1:props:good_man'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, null); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals([new Message('Sure?', [])], $result); } /** @test */ public function shouldPrepareMessageText() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(null)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 690])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock->shouldReceive('getRepliesByMessage')->with(690)->andReturn([])->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(690) ->andReturn( [ 'id' => 690, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => '{props:hour} ❤{props:health}' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $redisMock->shouldReceive('get')->with('users:1:props:hour')->andReturn('21'); $redisMock->shouldReceive('get')->with('users:1:props:health')->andReturn('45'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, 690); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals([new Message('21 ❤45', [])], $result); } /** @test */ public function shouldPrepareMessageTextAndFormatIt() { /** @var \apibotApi\models\redis\UserState|\Mockery\Mock $userStateMock */ $userStateMock = \Mockery::mock('\apibotApi\models\redis\UserState'); $userStateMock->shouldReceive('getUserState')->with(1)->andReturn(null)->once(); $userStateMock->shouldReceive('setUserState')->withArgs([1, 690])->once(); /** @var \apibotApi\models\db\Replies|\Mockery\Mock $repliesMock */ $repliesMock = \Mockery::mock('\apibotApi\models\db\Replies'); $repliesMock->shouldReceive('getRepliesByMessage')->with(690)->andReturn([])->once(); /** @var \apibotApi\models\db\Messages|\Mockery\Mock $messagesMock */ $messagesMock = \Mockery::mock('\apibotApi\models\db\Messages'); $messagesMock ->shouldReceive('getOne') ->with(690) ->andReturn( [ 'id' => 690, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => '{props:hour|mod:12|icon_clock} {props:hour|mod:24} ❤{props:health}' ] ] ); /** @var \Redis|\Mockery\Mock $redisMock */ $redisMock = \Mockery::mock('\Redis'); $redisMock->shouldReceive('get')->with('users:1:props:hour')->andReturn('25'); $redisMock->shouldReceive('get')->with('users:1:props:health')->andReturn('45'); $resolver = new Resolver($userStateMock, $repliesMock, $messagesMock, $redisMock, 690); $result = $resolver->getResponseMessages(1, 'Yes'); self::assertEquals([new Message('🕐 1 ❤45', [])], $result); } }<file_sep><?php require __DIR__ . '/../vendor/autoload.php'; error_reporting(E_ALL); ini_set('display_errors', 1); use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $app = new Silex\Application(); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $buildMetaDataFilePath = __DIR__ . '/../metadata.json'; $buildMetaData = []; if (file_exists($buildMetaDataFilePath)) { $buildMetaDataContents = file_get_contents($buildMetaDataFilePath); $buildMetaData = json_decode($buildMetaDataContents, true); } $app->after(function (Request $request, Response $response) use ($buildMetaData) { $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE, HEAD'); $response->headers->set('Access-Control-Allow-Credentials', 'true'); $response->headers->set('Access-Control-Allow-Headers', 'Origin,Content-Type,Accept,Authorization'); if (array_key_exists('build_id', $buildMetaData)) { $response->headers->set('X-Build-Id', $buildMetaData['build_id']); } }); $configFilePath = __DIR__ . '/../config/config.json'; if (!file_exists($configFilePath)) { $configFilePath = '/etc/apibot/config.json'; } $app['config'] = json_decode(file_get_contents($configFilePath), true); if ($app['config']['app']['debug'] === true) { $app['debug'] = true; ExceptionHandler::register(true); // handle fatal errors } else { ExceptionHandler::register(false); } $app['monolog.app'] = function ($app) { $monolog = new \Monolog\Logger('app'); $formatter = new \Monolog\Formatter\LineFormatter(null, 'c'); $handler = new \Monolog\Handler\StreamHandler( $app['config']['monolog']['app']['path'], $app['config']['monolog']['app']['level'] ); $handler->setFormatter($formatter); $monolog->pushHandler($handler); return $monolog; }; $app['monolog.telegram'] = function ($app) { $monolog = new \Monolog\Logger('telegram'); $formatter = new \Monolog\Formatter\LineFormatter(null, 'c'); $handler = new \Monolog\Handler\StreamHandler( $app['config']['monolog']['telegram']['path'], $app['config']['monolog']['telegram']['level'] ); $handler->setFormatter($formatter); $monolog->pushHandler($handler); return $monolog; }; $app['monolog.kik'] = function ($app) { $monolog = new \Monolog\Logger('kik'); $formatter = new \Monolog\Formatter\LineFormatter(null, 'c'); $handler = new \Monolog\Handler\StreamHandler( $app['config']['monolog']['kik']['path'], $app['config']['monolog']['kik']['level'] ); $handler->setFormatter($formatter); $monolog->pushHandler($handler); return $monolog; }; $app['redis'] = function ($app) { $redis = new Redis(); $redis->connect( $app['config']['redis']['host'], $app['config']['redis']['port'] ); return $redis; }; $app['redis.messages'] = function ($app) { return new \apibotApi\models\redis\Messages($app['redis']); }; $app['stomp'] = function ($app) { $client = new Stomp\Client($app['config']['stomp']['uri']); $client->setLogin($app['config']['stomp']['user'], $app['config']['stomp']['password']); $client->connect(); $stomp = new \Stomp\SimpleStomp($client); return $stomp; }; $app['pdo'] = function ($app) { return new PDO( $app['config']['db']['dsn'], $app['config']['db']['username'], $app['config']['db']['password'] ); }; $app['db.conversations'] = function ($app) { return new \apibotApi\models\db\Conversations($app['pdo'], 50); }; $app['db.messages'] = function ($app) { return new \apibotApi\models\db\Messages($app['pdo'], 50); }; $app['db.replies'] = function ($app) { return new \apibotApi\models\db\Replies($app['pdo'], 50); }; $app['db.users'] = function ($app) { return new \apibotApi\models\db\Users($app['pdo'], 50); }; $app['clients.telegram'] = function ($app) { return new \Telegram\Bot\Api($app['config']['telegram']['token']); }; $app['guzzle'] = function () { return new \GuzzleHttp\Client(); }; $app['controllers.conversations'] = $app->share(function () use ($app) { return new \apibotApi\controllers\ConversationsController($app['db.conversations'], $app['db.messages']); }); $app['controllers.messages'] = $app->share(function () use ($app) { return new \apibotApi\controllers\MessagesController($app['db.messages'], $app['db.replies']); }); $app['controllers.replies'] = $app->share(function () use ($app) { return new \apibotApi\controllers\RepliesController($app['db.replies']); }); $app['controllers.users'] = $app->share(function () use ($app) { return new \apibotApi\controllers\UsersController($app['db.users'], $app['redis.messages']); }); $app['controllers.hook.telegram'] = $app->share(function () use ($app) { return new \apibotApi\controllers\HookTelegramController( $app['clients.telegram'], $app['monolog.telegram'], $app['stomp'], $app['config']['telegram']['url'], $app['config']['telegram']['certificate_path'] ); }); $app['controllers.hook.kik'] = $app->share(function () use ($app) { return new \apibotApi\controllers\HookKikController( $app['stomp'], $app['guzzle'], $app['monolog.kik'], $app['config']['kik']['url_hook'], $app['config']['kik']['url_config'], $app['config']['kik']['username'], $app['config']['kik']['api_key'] ); }); $app['controllers.systems.redis'] = $app->share(function () use ($app) { return new \apibotApi\controllers\SystemsRedisController($app['redis']); }); $app->get('/v1/conversations/', 'controllers.conversations:actionList'); $app->get('/v1/conversations/{id}/', 'controllers.conversations:actionOne'); $app->get('/v1/conversations/{id}/messages/', 'controllers.conversations:actionMessages'); $app->get('/v1/messages/', 'controllers.messages:actionList'); $app->get('/v1/messages/{id}/', 'controllers.messages:actionOne'); $app->get('/v1/messages/{id}/replies/', 'controllers.messages:actionReplies'); $app->get('/v1/replies/', 'controllers.replies:actionList'); $app->get('/v1/replies/{id}', 'controllers.replies:actionOne'); $app->get('/v1/users/', 'controllers.users:actionList'); $app->get('/v1/users/{id}/', 'controllers.users:actionOne'); $app->get('/v1/users/{id}/messages/', 'controllers.users:actionMessages'); $app->post('/v1/hook/telegram/hook/', 'controllers.hook.telegram:actionHook'); $app->get('/v1/hook/telegram/start/', 'controllers.hook.telegram:actionStart'); $app->get('/v1/hook/telegram/stop/', 'controllers.hook.telegram:actionStop'); $app->post('/v1/hook/kik/hook/', 'controllers.hook.kik:actionHook'); $app->get('/v1/hook/kik/start/', 'controllers.hook.kik:actionStart'); $app->get('/v1/systems/redis/', 'controllers.systems.redis:actionStatus'); $app->error(function (\Exception $e, $code) use ($app) { $errors = [ [ 'status' => $code, 'detail' => $e->getMessage() ] ]; if ($app['debug'] === true) { $errors['file'] = $e->getFile(); $errors['line'] = $e->getLine(); } return new JsonResponse(['errors' => $errors]); }); $app->run(); <file_sep><?php namespace apibotApi\controllers; use apibotApi\models\db\Replies; use apibotApi\models\db\Messages; use apibotApi\models\Pager; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class MessagesController { /** @var Messages */ private $messages; /** @var Replies */ private $replies; public function __construct(Messages $messages, Replies $replies) { $this->messages = $messages; $this->replies = $replies; } public function actionList(Request $request) { $count = $this->messages->count(); $pager = new Pager($request, $count, '/v1/messages/'); return new JsonResponse( [ 'links' => [ 'self' => $pager->getSelf(), 'prev' => $pager->getPrevLink(), 'next' => $pager->getNextLink(), 'first' => $pager->getFirstLink(), 'last' => $pager->getLastLink() ], 'meta' => [ 'total-pages' => $pager->getTotal() ], 'data' => $this->messages->getList( $pager->getLimit(), $pager->getOffset() ) ] ); } public function actionOne($id) { $items = $this->messages->getOne($id); $links = array_merge( ['parent' => '/v1/messages/'], $items['links'] ); unset($items['links']); return new JsonResponse( [ 'links' => $links, 'data' => $items ] ); } public function actionReplies($id) { return new JsonResponse( [ 'links' => [ 'self' => sprintf('/v1/messages/%d/replies/', $id) ], 'data' => $this->replies->getList( null, 0, 'message_id = :message_id', [':message_id' => $id] ) ] ); } } <file_sep><?php namespace apibotApi\models\db; class Conversations extends PdoResource { protected function getFields() { return [ 'id', 'name', 'message_from' ]; } protected function getTableName() { return 'conversations'; } protected function getItemType() { return 'conversations'; } protected function getItemAttributes($item) { unset($item['id']); return $item; } protected function getItemLinks($item) { return [ 'self' => sprintf('/v1/conversations/%s/', $item['id']), 'messages' => sprintf('/v1/conversations/%s/messages/', $item['id']), 'message_from' => sprintf('/v1/messages/%s/', $item['message_from']) ]; } } <file_sep><?php namespace apibotApi\models\response; class Message { private $text; private $keyboard; public function __construct($text, $keyboard) { $this->text = $text; $this->keyboard = $keyboard; } public function getText() { return $this->text; } public function getKeyboard() { return $this->keyboard; } }<file_sep><?php namespace apibotApi\models; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; class Pager { private $count; private $basicUrl; private $defaultPage = [ 'number' => 1, 'size' => 50 ]; public function __construct(Request $request, $count, $basicUrl) { $this->count = $count; $this->basicUrl = $basicUrl; $this->page = $this->defaultPage; $pageRequest = $request->get('page'); if (!is_array($pageRequest)) { return; } if (array_key_exists('number', $pageRequest) && is_numeric($pageRequest['number'])) { $this->page['number'] = (int) $pageRequest['number']; } if (array_key_exists('size', $pageRequest) && is_numeric($pageRequest['size'])) { $this->page['size'] = (int) $pageRequest['size']; } } public function getTotal() { return (int) ceil($this->count / $this->page['size']); } public function getSelf() { return sprintf( '%s?%s', $this->basicUrl, urldecode( http_build_query( [ 'page' => $this->page ] ) ) ); } public function getPrevLink() { if ($this->page['number'] < 1) { throw new BadRequestHttpException('Pager number cannot be smaller than 1.'); } if ($this->page['number'] === 1) { return null; } return sprintf( '%s?%s', $this->basicUrl, urldecode( http_build_query( [ 'page' => [ 'number' => ($this->page['number'] - 1), 'size' => $this->page['size'] ] ] ) ) ); } public function getNextLink() { if ($this->page['number'] > $this->getTotal()) { throw new BadRequestHttpException( sprintf( 'Pager number cannot be greater than total pages amount: %d.', $this->getTotal() ) ); } if ($this->page['number'] === $this->getTotal()) { return null; } return sprintf( '%s?%s', $this->basicUrl, urldecode( http_build_query( [ 'page' => [ 'number' => ($this->page['number'] + 1), 'size' => $this->page['size'] ] ] ) ) ); } public function getFirstLink() { return sprintf( '%s?%s', $this->basicUrl, urldecode( http_build_query( [ 'page' => [ 'number' => 1, 'size' => $this->page['size'] ] ] ) ) ); } public function getLastLink() { return sprintf( '%s?%s', $this->basicUrl, urldecode( http_build_query( [ 'page' => [ 'number' => $this->getTotal(), 'size' => $this->page['size'] ] ] ) ) ); } public function getLimit() { return $this->page['size']; } public function getOffset() { return $this->page['size'] * ($this->page['number'] - 1); } } <file_sep><?php namespace apibotApi\models\db; class Replies extends PdoResource { public function getRepliesByMessage($messageId) { $queryStatement = sprintf( 'SELECT %s FROM %s WHERE message_id = :message_id', implode(',', $this->getFields()), $this->getTableName() ); $query = $this->pdo->prepare($queryStatement); $bindParameters = [':message_id' => (int) $messageId]; foreach ($bindParameters as $param => &$value) { $query->bindParam($param, $value, \PDO::PARAM_INT); } $query->execute(); $queryResult = $query->fetchAll(\PDO::FETCH_ASSOC); array_walk( $queryResult, function (&$item) { $item = $this->transformItem($item); } ); return $queryResult; } protected function getFields() { return [ 'id', 'message_id', 'message_to', 'value', 'conditions', 'modifications', 'visible', 'keyboard_row' ]; } protected function getTableName() { return 'replies'; } protected function getItemType() { return 'replies'; } protected function getItemAttributes($item) { unset( $item['id'], $item['message_id'] ); $item['modifications'] = $this->formatJson($item['modifications']); $item['conditions'] = $this->formatJson($item['conditions']); $item['visible'] = ($item['visible'] == '1'); $item['keyboard_row'] = (int) $item['keyboard_row']; $item['message_to'] = ($item['message_to'] === null) ? null : $item['message_to']; return $item; } protected function getItemLinks($item) { return [ 'self' => sprintf('/v1/replies/%d/', $item['id']), 'message' => sprintf('/v1/messages/%d/', $item['message_id']) ]; } /** * @param null|string $value * @return null|array */ protected function formatJson($value) { if ($value === null) { return null; } return json_decode($value, true); } } <file_sep><?php namespace apibotApi\models\redis; class Messages { const DEFAULT_MAX_MESSAGES_PER_USER = 30; const FROM_USER = 0; const FROM_BOT = 1; /** @var \Redis */ private $redis; /** @var int */ private $maxMessagesPerUser; public function __construct(\Redis $redis, $maxMessagesPerUser = null) { $this->maxMessagesPerUser = $maxMessagesPerUser ?: static::DEFAULT_MAX_MESSAGES_PER_USER; $this->redis = $redis; } public function addMessage($userID, $data) { $key = $this->getKey($userID); $this->redis->rPush($key, json_encode($data)); $length = $this->redis->lLen($key); if ($length <= $this->maxMessagesPerUser) { return; } $neededToDelete = $length - $this->maxMessagesPerUser; for ($i = 0; $i < $neededToDelete; $i++) { $this->redis->lPop($key); } } public function getMessagesList($userID) { $key = $this->getKey($userID); $list = $this->redis->lRange($key, 0, -1); $typeMap = [ static::FROM_BOT => 'bot', static::FROM_USER => 'user', ]; return array_map( function ($item) use ($typeMap) { $item = json_decode($item, true); $item['type'] = $typeMap[$item['type']]; return $item; }, $list ); } private function getKey($userID) { return sprintf('users:%d:messages', $userID); } }<file_sep><?php namespace apibotApi\models\redis; class UserState { /** @var \Redis */ private $redis; public function __construct(\Redis $redis) { $this->redis = $redis; } public function getUserState($userID, $default = null) { $key = $this->getKey($userID); $state = $this->redis->get($key); if ($state === false) { return $default; } return (int) $state; } public function setUserState($userID, $stateID) { $key = $this->getKey($userID); return $this->redis->set($key, $stateID); } private function getKey($userID) { return sprintf('users:%d:state', $userID); } }<file_sep><?php use apibotApi\models\redis\Messages; use Stomp\Exception\StompException; use Stomp\SimpleStomp; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Telegram\Bot\Api; class OutgoingTelegramWorkerCommand extends Command { /** @var \Stomp\StatefulStomp */ private $stomp; /** @var Messages */ private $messages; /** @var Api */ private $telegram; /** @var \Monolog\Logger */ private $logger; public function __construct( SimpleStomp $stomp, Messages $messages, Api $telegram, Monolog\Logger $logger ) { parent::__construct(); $this->stomp = $stomp; $this->telegram = $telegram; $this->messages = $messages; $this->logger = $logger; } protected function configure() { $this->setName('outgoing:telegram'); } public function execute(InputInterface $input, OutputInterface $output) { try { $this->stomp->subscribe('/queue/outgoing.telegram', uniqid(), 'client'); while (true) { if ($frame = $this->stomp->read()) { $this->processFrame($frame); $this->stomp->ack($frame); } } } catch(StompException $e) { die('Connection failed: ' . $e->getMessage()); } } private function processFrame($frame) { $data = json_decode($frame->body, true); if ($data['text'] === '' || $data['text'] === null) { return; } $params = [ 'chat_id' => $data['chat_id'], 'text' => $data['text'], 'parse_mode' => 'Markdown', 'disable_web_page_preview' => true ]; $this->messages->addMessage( $data['user_id'], [ 'text' => $data['text'], 'type' => Messages::FROM_BOT, 'ts' => time() ] ); if (is_array($data['options']) && count($data['options']) > 0) { $params['reply_markup'] = $this->telegram->replyKeyboardMarkup( [ 'keyboard' => $data['options'], 'resize_keyboard' => true, 'one_time_keyboard' => false ] ); } try { $this->telegram->sendMessage($params); } catch (Telegram\Bot\Exceptions\TelegramSDKException $e) { $this->logger->error(get_class($e) . ': ' . $e->getMessage()); } } } <file_sep><?php namespace tests\models\db; use apibotApi\models\db\Messages; class MessagesTest extends \PHPUnit_Framework_TestCase { /** @test */ public function shouldReturnOneState() { /** @var \Mockery\Mock $queryMock */ $queryMock = \Mockery::mock(); $queryMock->shouldReceive('bindParam')->withArgs([':id', 691, \PDO::PARAM_INT])->once(); $queryMock->shouldReceive('execute'); $queryMock ->shouldReceive('fetch') ->andReturn( [ 'id' => 56, 'conversation_id' => 2, 'message_next' => null, 'value' => 'Hello' ] ); /** @var \PDO|\Mockery\Mock $pdoMock */ $pdoMock = \Mockery::mock('\PDO'); $pdoMock->shouldReceive('prepare')->andReturn($queryMock); $messages = new Messages($pdoMock, 50); $result = $messages->getOne(691); self::assertEquals( [ 'id' => 56, 'type' => 'messages', 'attributes' => [ 'message_next' => null, 'value' => 'Hello' ], 'links' => [ 'self' => '/v1/messages/56/', 'replies' => '/v1/messages/56/replies/', 'conversation' => '/v1/conversations/2/' ] ], $result ); } }<file_sep><?php namespace apibotApi\models\db; class Users extends PdoResource { public function getUser($id) { $queryStatement = sprintf( 'SELECT %s FROM %s WHERE id_telegram = :id', implode(',', $this->getFields()), $this->getTableName() ); $query = $this->pdo->prepare($queryStatement); $bindParameters = [':id' => (int) $id]; foreach ($bindParameters as $param => &$value) { $query->bindParam($param, $value, \PDO::PARAM_INT); } $query->execute(); $queryResult = $query->fetchAll(\PDO::FETCH_ASSOC); array_walk( $queryResult, function (&$item) { $item = $this->transformItem($item); } ); return $queryResult[0]; } /** * @param array $from * * Example from: * [ * "id": 4885399, * "first_name": "Konstantin", * "last_name": "Chukhlomin", * "username": "chuhlomin" * ] * * @return array */ public function getUserIdOrCreateNewFromTelegram(array $from) { $userId = $this->getUserIdByTelegramId($from['id']); if ($userId === null || $userId === 0) { $userId = $this->create( $from['first_name'], $from['last_name'], $from['username'], $from['id'] ); } return $userId; } /** * @param string $kikUsername * @return array */ public function getUserIdOrCreateNewFromKikUsername($kikUsername) { $userId = $this->getUserIdByKikUsername($kikUsername); if ($userId === null || $userId === 0) { $userId = $this->create( '', '', $kikUsername, null, $kikUsername ); } return $userId; } private function create($firstName, $lastName, $username, $idTelegram = null, $kikUsername = '') { $queryStatement = sprintf( 'INSERT INTO %s (first_name, last_name, username, id_telegram, kik_username) VALUES (?, ?, ?, ?, ?)', $this->getTableName() ); $query = $this->pdo->prepare($queryStatement); $query->bindParam(1, $firstName); $query->bindParam(2, $lastName); $query->bindParam(3, $username); $query->bindParam(4, $idTelegram); $query->bindParam(5, $kikUsername); $query->execute(); return $this->pdo->lastInsertId(); } protected function getFields() { return [ 'id', 'first_name', 'last_name', 'username', 'id_telegram', 'kik_username' ]; } protected function getTableName() { return 'users'; } protected function getItemType() { return 'users'; } protected function getItemAttributes($item) { unset($item['id']); $item['id_telegram'] = $item['id_telegram'] ? (int)$item['id_telegram'] : null; return $item; } protected function getItemLinks($item) { return [ 'self' => sprintf('/v1/users/%d/', $item['id']), 'props' => sprintf('/v1/users/%d/props/', $item['id']), 'messages' => sprintf('/v1/users/%d/messages/', $item['id']) ]; } private function getUserIdByTelegramId($idTelegram) { $queryStatement = sprintf( 'SELECT id FROM %s WHERE id_telegram = :id_telegram LIMIT 1', $this->getTableName() ); $query = $this->pdo->prepare($queryStatement); $query->bindParam(':id_telegram', $idTelegram, \PDO::PARAM_INT); $query->execute(); $queryResult = $query->fetch(\PDO::FETCH_ASSOC); if ($queryResult === false) { return null; } return $queryResult['id']; } public function getUserIdByKikUsername($kikUsername) { $queryStatement = sprintf( 'SELECT id FROM %s WHERE kik_username = :kik_username LIMIT 1', $this->getTableName() ); $query = $this->pdo->prepare($queryStatement); $query->bindParam(':kik_username', $kikUsername); $query->execute(); $queryResult = $query->fetch(\PDO::FETCH_ASSOC); if ($queryResult === false) { return null; } return $queryResult['id']; } } <file_sep><?php namespace apibotApi\models\response; use apibotApi\models\db\Replies; use apibotApi\models\db\Messages; use apibotApi\models\redis\UserState; class Resolver { /** @var UserState */ private $userState; /** @var Replies */ private $replies; /** @var Messages */ private $messages; /** @var int */ private $initialState; /** @var \Redis */ private $redis; public function __construct( UserState $userState, Replies $replies, Messages $messages, \Redis $redis, $initialState ) { $this->userState = $userState; $this->replies = $replies; $this->messages = $messages; $this->redis = $redis; $this->initialState = $initialState; } public function getResponseMessages($userID, $userMessage) { $messageId = $this->userState->getUserState($userID); if ($messageId === null) { // it was first user message without state return $this->userMessageUpdated($userID, $this->initialState); } // there was some state and user answering to some question $replies = $this->replies->getRepliesByMessage($messageId); $selectedReply = $this->findSelectedReply($userMessage, $replies); if ($selectedReply === null) { // user selected wrong/old reply return $this->resendReplies($replies); } if ($selectedReply['attributes']['modifications'] !== null) { $this->applyModifications($userID, $selectedReply['attributes']['modifications']); } // user selected some option return $this->userMessageUpdated($userID, $selectedReply['attributes']['message_to']); } private function findSelectedReply($userMessage, $replies) { foreach ($replies as $reply) { if (trim($userMessage) === trim($reply['attributes']['value'])) { return $reply; } } return null; } private function prepareKeyboard($replies) { $replies = array_filter( $replies, function ($item) { if ($item['attributes']['visible'] === false) { return false; } if ($item['attributes']['message_to'] === null) { return false; } return true; } ); $rows = [0 => []]; foreach ($replies as $reply) { $row = (int) $reply['attributes']['keyboard_row']; if (!array_key_exists($row, $rows)) { $rows[$row] = []; } $rows[$row][] = $reply['attributes']['value']; } $rowNull = $rows[0]; unset($rows[0]); ksort($rows); if (count($rowNull) > 0) { $rows[] = $rowNull; } return array_values($rows); } private function userMessageUpdated($userID, $newMessageID) { $messages = []; $currentMessageID = $newMessageID; $nextMessageID = $currentMessageID; while ($nextMessageID !== null) { $message = $this->messages->getOne($nextMessageID); $currentMessageID = $nextMessageID; $nextMessageID = $message['attributes']['message_next']; $replies = []; if ($nextMessageID === null) { $replies = $this->replies->getRepliesByMessage($message['id']); } $messages[] = new Message( $this->prepareText($userID, $message['attributes']['value']), $this->prepareKeyboard($replies) ); } $this->userState->setUserState($userID, $currentMessageID); return $messages; } private function resendReplies($replies) { return [ new Message( 'Sorry, did not catch what just you said. Could you pick from provided options?', $this->prepareKeyboard($replies) ) ]; } private function applyModifications($userID, array $modifications) { foreach ($modifications as $operator => $array) { switch ($operator) { case '$inc': foreach ($array as $field => $value) { if (!is_int($value)) { continue; } $this->redis->incrBy($this->getUserPropertyKey($userID, $field), (int) $value); } break; case '$set': foreach ($array as $field => $value) { $this->redis->set($this->getUserPropertyKey($userID, $field), $value); } break; case '$unset': foreach ($array as $field => $value) { $this->redis->del($this->getUserPropertyKey($userID, $field)); } break; } } } private function getUserPropertyKey($userID, $field) { return sprintf( 'users:%d:props:%s', $userID, $field ); } private function prepareText($userID, $message) { preg_match_all('/{props:(.*?)}/', $message, $matches); foreach ($matches[1] as $id => $match) { $match = explode('|', $match); $propertyName = array_shift($match); $propertyValue = $this->redis->get($this->getUserPropertyKey($userID, $propertyName)); foreach ($match as $mod) { $propertyValue = $this->applyPropertyMod($propertyValue, $mod); } $message = str_replace($matches[0][$id], $propertyValue, $message); } return $message; } private function applyPropertyMod($value, $mod) { $mod = explode(':', $mod); $name = array_shift($mod); $option = array_shift($mod); switch ($name) { case 'int': return (int) $value; case 'mod': if ($option === null) { return $value; } return (int) $value % $option; case 'icon_clock': $clockMap = [ 0 => '🕛', 1 => '🕐', 2 => '🕑', 3 => '🕒', 4 => '🕓', 5 => '🕔', 6 => '🕕', 7 => '🕖', 8 => '🕗', 9 => '🕘', 10 => '🕙', 11 => '🕚' ]; if (!array_key_exists($value, $clockMap)) { return ''; } return $clockMap[$value]; } return $value; } } <file_sep><?php namespace apibotApi\controllers; use Symfony\Component\HttpFoundation\JsonResponse; class SystemsRedisController { /** @var \Redis */ private $redis; public function __construct(\Redis $redis) { $this->redis = $redis; } public function actionStatus() { return new JsonResponse($this->redis->info()); } } <file_sep><?php namespace apibotApi\models\db; class Messages extends PdoResource { protected function getFields() { return [ 'id', 'conversation_id', 'message_next', 'value' ]; } protected function getTableName() { return 'messages'; } protected function getItemType() { return 'messages'; } protected function getItemAttributes($item) { unset( $item['id'], $item['conversation_id'] ); $item['message_next'] = ($item['message_next'] === null) ? null : (int) $item['message_next']; return $item; } protected function getItemLinks($item) { return [ 'self' => sprintf('/v1/messages/%d/', $item['id']), 'replies' => sprintf('/v1/messages/%d/replies/', $item['id']), 'conversation' => sprintf('/v1/conversations/%d/', $item['conversation_id']) ]; } } <file_sep><?php use apibotApi\models\redis\Messages; use Stomp\Exception\StompException; use Stomp\SimpleStomp; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class OutgoingKikWorkerCommand extends Command { /** @var \Stomp\StatefulStomp */ private $stomp; /** @var Messages */ private $messages; /** @var \GuzzleHttp\Client */ private $guzzle; /** @var \Monolog\Logger */ private $logger; /** @var string */ private $username; /** @var string */ private $apiKey; /** @var string */ private $urlMessage; public function __construct( SimpleStomp $stomp, Messages $messages, \GuzzleHttp\Client $guzzle, Monolog\Logger $logger, $username, $apiKey, $urlMessage ) { parent::__construct(); $this->stomp = $stomp; $this->guzzle = $guzzle; $this->messages = $messages; $this->logger = $logger; $this->username = $username; $this->apiKey = $apiKey; $this->urlMessage = $urlMessage; } protected function configure() { $this->setName('outgoing:kik'); } public function execute(InputInterface $input, OutputInterface $output) { try { $this->stomp->subscribe('/queue/outgoing.kik', uniqid(), 'client'); while (true) { if ($frame = $this->stomp->read()) { $this->processFrame($frame); $this->stomp->ack($frame); } } } catch(StompException $e) { die('Connection failed: ' . $e->getMessage()); } } /** * @param \Stomp\Transport\Frame $frame * has: user_id, username, chat_id, text, options */ private function processFrame($frame) { $data = json_decode($frame->body, true); if ($data['text'] === '' || $data['text'] === null) { return; } $this->messages->addMessage( $data['user_id'], [ 'text' => $data['text'], 'type' => Messages::FROM_BOT, 'ts' => time() ] ); $message = [ 'body' => $this->stripMarkdown($data['text']), 'to' => $data['username'], 'type' => 'text', 'chatId' => $data['chat_id'] ]; if (is_array($data['options']) && count($data['options']) > 0) { // downgrading options from telegram layout to list of responses for Kik $responses = []; foreach ($data['options'] as $optionRow) { foreach ($optionRow as $optionCell) { $responses[] = $optionCell; } } $message['keyboards'] = [ [ 'type' => 'suggested', 'responses' => array_map( function ($item) { return [ 'type' => 'text', 'body' => $item ]; }, $responses ) ] ]; } $request = [ 'auth' => [$this->username, $this->apiKey], 'headers' => [ 'Content-Type' => 'application/json' ], 'body' => json_encode( [ 'messages' => [ $message ] ] ) ]; $this->guzzle->request( 'post', $this->urlMessage, $request ); } /** * @param string * @return string, sorry, links */ private function stripMarkdown($text) { return preg_replace( '/\[(.*?)\]\((.*?)\)/', '$1', $text ); } } <file_sep><?php use apibotApi\models\db\Users; use apibotApi\models\redis\Messages; use apibotApi\models\response\Resolver; use Stomp\Exception\StompException; use Stomp\SimpleStomp; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class IncomingTelegramWorkerCommand extends Command { /** @var \Stomp\StatefulStomp */ private $stomp; /** @var Users */ private $users; /** @var Messages */ private $messages; /** @var \Monolog\Logger */ private $logger; /** @var Resolver */ private $resolver; public function __construct( SimpleStomp $stomp, Users $users, Messages $messages, Monolog\Logger $logger, Resolver $resolver ) { parent::__construct(); $this->stomp = $stomp; $this->messages = $messages; $this->users = $users; $this->logger = $logger; $this->resolver = $resolver; } protected function configure() { $this->setName('incoming:telegram'); } public function execute(InputInterface $input, OutputInterface $output) { try { $this->stomp->subscribe('/queue/incoming.telegram', uniqid(), 'client'); while (true) { if ($frame = $this->stomp->read()) { $this->processFrame($frame); $this->stomp->ack($frame); } } } catch(StompException $e) { die('Connection failed: ' . $e->getMessage()); } } private function processFrame($frame) { $data = json_decode($frame->body, true); if (!array_key_exists('text', $data)) { return; } $userID = $this->users->getUserIdOrCreateNewFromTelegram($data['from']); $chatID = $data['chat']['id']; $userMessage = $data['text']; $this->messages->addMessage( $userID, [ 'text' => $userMessage, 'type' => Messages::FROM_USER, 'ts' => $data['date'] ] ); /** @var \apibotApi\models\response\Message[] $messages */ $messages = $this->resolver->getResponseMessages($userID, $userMessage); foreach ($messages as $i => $message) { $data = [ 'user_id' => $userID, 'chat_id' => $chatID, 'text' => $message->getText(), 'options' => $message->getKeyboard() ]; if ($i > 0) { sleep(1.5); } else { sleep(0.5); } $this->stomp->send( '/queue/outgoing.telegram', new \Stomp\Transport\Message(json_encode($data)) ); } } } <file_sep><?php require __DIR__.'/vendor/autoload.php'; function getConfig() { $configFilePath = __DIR__ . '/config/config.json'; if (!file_exists($configFilePath)) { $configFilePath = '/etc/apibot/config.json'; } return json_decode(file_get_contents($configFilePath), true); } $config = getConfig(); // --------------------------- $monolog = new \Monolog\Logger('app'); $formatter = new \Monolog\Formatter\LineFormatter(null, 'c'); $handler = new \Monolog\Handler\StreamHandler( $config['monolog']['worker']['path'], $config['monolog']['worker']['level'] ); $handler->setFormatter($formatter); $monolog->pushHandler($handler); // --------------------------- $application = new \Symfony\Component\Console\Application(); $redis = new Redis(); $redis->connect($config['redis']['host'], $config['redis']['port']); $messagesLog = new \apibotApi\models\redis\Messages($redis); $userState = new \apibotApi\models\redis\UserState($redis); // --------------------------- $guzzle = new \GuzzleHttp\Client(); // --------------------------- $pdo = new PDO( $config['db']['dsn'], $config['db']['username'], $config['db']['password'] ); $users = new \apibotApi\models\db\Users($pdo, 50); $replies = new \apibotApi\models\db\Replies($pdo, 50); $messages = new \apibotApi\models\db\Messages($pdo, 50); // --------------------------- $resolver = new \apibotApi\models\response\Resolver( $userState, $replies, $messages, $redis, $config['app']['state_init'] ); // --------------------------- $client = new \Stomp\Client($config['stomp']['uri']); $client->setLogin($config['stomp']['user'], $config['stomp']['password']); $client->connect(); $stomp = new \Stomp\SimpleStomp($client); $telegram = new \Telegram\Bot\Api($config['telegram']['token']); $application->addCommands( [ new IncomingTelegramWorkerCommand($stomp, $users, $messagesLog, $monolog, $resolver), new OutgoingTelegramWorkerCommand($stomp, $messagesLog, $telegram, $monolog), new IncomingKikWorkerCommand($stomp, $users, $messagesLog, $monolog, $resolver), new OutgoingKikWorkerCommand( $stomp, $messagesLog, $guzzle, $monolog, $config['kik']['username'], $config['kik']['api_key'], $config['kik']['url_message'] ) ] ); $application->run(); <file_sep><?php namespace apibotApi\controllers; use apibotApi\models\db\Users; use apibotApi\models\Pager; use apibotApi\models\redis\Messages; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class UsersController { /** @var Users */ private $users; /** @var Messages */ private $messages; public function __construct(Users $users, Messages $messages) { $this->users = $users; $this->messages = $messages; } public function actionList(Request $request) { $count = $this->users->count(); $pager = new Pager($request, $count, '/v1/users/'); return new JsonResponse( [ 'links' => [ 'self' => $pager->getSelf(), 'prev' => $pager->getPrevLink(), 'next' => $pager->getNextLink(), 'first' => $pager->getFirstLink(), 'last' => $pager->getLastLink() ], 'meta' => [ 'total-pages' => $pager->getTotal() ], 'data' => $this->users->getList( $pager->getLimit(), $pager->getOffset() ) ] ); } public function actionOne($id) { $items = $this->users->getOne($id); $links = array_merge( ['parent' => '/v1/users/'], $items['links'] ); unset($items['links']); return new JsonResponse( [ 'links' => $links, 'data' => $items ] ); } public function actionMessages($id) { $messages = $this->messages->getMessagesList($id); return new JsonResponse( [ 'links' => [ 'parent' => sprintf('/v1/users/%d/', $id) ], 'data' => $messages ] ); } } <file_sep><?php namespace apibotApi\models\db; use Symfony\Component\HttpKernel\Exception\HttpException; abstract class PdoResource { /** @var \PDO */ protected $pdo; /** @var int */ protected $limit; public function __construct(\PDO $pdo, $limit) { $this->pdo = $pdo; $this->limit = $limit; } public function count() { $query = $this->pdo->prepare( sprintf( 'SELECT COUNT(*) FROM %s', $this->getTableName() ) ); $query->execute(); return $query->fetchColumn(); } public function getList($limit = null, $offset = 0, $filter = '', array $filterParameters = null) { $limit = ($limit === null) ? $this->limit : $limit; $bindParameters = array_merge( $filterParameters ?: [], [ ':limit' => $limit, ':offset' => $offset ] ); $queryStatement = ($filter === '') ? sprintf( 'SELECT %s FROM %s LIMIT :limit OFFSET :offset', implode(',', $this->getFields()), $this->getTableName() ) : sprintf( 'SELECT %s FROM %s WHERE %s LIMIT :limit OFFSET :offset', implode(',', $this->getFields()), $this->getTableName(), $filter ); $query = $this->pdo->prepare($queryStatement); foreach ($bindParameters as $param => &$value) { $query->bindParam($param, $value, \PDO::PARAM_INT); } $query->execute(); $queryResult = $query->fetchAll(\PDO::FETCH_ASSOC); array_walk( $queryResult, function (&$item) { $item = $this->transformItem($item); } ); return $queryResult; } public function getOne($id) { $query = $this->pdo->prepare( sprintf( 'SELECT %s FROM %s WHERE id = :id', implode(',', $this->getFields()), $this->getTableName() ) ); $query->bindParam(':id', $id, \PDO::PARAM_INT); $query->execute(); $orig = $query->fetch(\PDO::FETCH_ASSOC); if ($orig === false) { throw new HttpException(404, sprintf('Conversation not found: %d', $id)); } return $this->transformItem($orig); } protected function transformItem($item) { return [ 'id' => (int) $item['id'], 'type' => $this->getItemType(), 'attributes' => $this->getItemAttributes($item), 'links' => $this->getItemLinks($item) ]; } abstract protected function getFields(); abstract protected function getTableName(); abstract protected function getItemType(); abstract protected function getItemAttributes($item); abstract protected function getItemLinks($item); } <file_sep><?php use apibotApi\models\db\Users; use apibotApi\models\redis\Messages; use apibotApi\models\response\Resolver; use Stomp\Exception\StompException; use Stomp\SimpleStomp; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class IncomingKikWorkerCommand extends Command { /** @var \Stomp\StatefulStomp */ private $stomp; /** @var Users */ private $users; /** @var Messages */ private $messages; /** @var \Monolog\Logger */ private $logger; /** @var Resolver */ private $resolver; public function __construct( SimpleStomp $stomp, Users $users, Messages $messages, Monolog\Logger $logger, Resolver $resolver ) { parent::__construct(); $this->stomp = $stomp; $this->messages = $messages; $this->users = $users; $this->logger = $logger; $this->resolver = $resolver; } protected function configure() { $this->setName('incoming:kik'); } public function execute(InputInterface $input, OutputInterface $output) { try { $this->stomp->subscribe('/queue/incoming.kik', uniqid(), 'client'); while (true) { if ($frame = $this->stomp->read()) { $this->processFrame($frame); $this->stomp->ack($frame); } } } catch(StompException $e) { die('Connection failed: ' . $e->getMessage()); } } private function processFrame($frame) { $data = json_decode($frame->body, true); if (!array_key_exists('messages', $data)) { return; } $messages = $data['messages']; $message = $messages[0]; // just assume there will be always one message if (!array_key_exists('type', $message) || $message['type'] != 'text') { return; } $kikUsername = $message['from']; $chatID = $message['chatId']; $userMessage = $message['body']; // todo: use API https://dev.kik.com/#/docs/messaging#user-profiles $userID = $this->users->getUserIdOrCreateNewFromKikUsername($kikUsername); $this->messages->addMessage( $userID, [ 'text' => $userMessage, 'type' => Messages::FROM_USER, 'ts' => $message['timestamp'] ] ); /** @var \apibotApi\models\response\Message[] $messages */ $messages = $this->resolver->getResponseMessages($userID, $userMessage); foreach ($messages as $message) { $data = [ 'user_id' => $userID, 'username' => $kikUsername, 'chat_id' => $chatID, 'text' => $message->getText(), 'options' => $message->getKeyboard() ]; $this->stomp->send( '/queue/outgoing.kik', new \Stomp\Transport\Message(json_encode($data)) ); } } }
6ec88221f21fc381b682160c395c79d28cbfcd97
[ "PHP" ]
26
PHP
apibotxyz/api
872d3c8875a8ff7b2a01b99f7375b405adf46836
328ec5ca8b3fda3674231b08ef46ddb2c02d9c8a
refs/heads/master
<repo_name>schuchert/wholesaler<file_sep>/src/main/java/com/tradefederation/wholesaler/endpoint/ReservationRequest.java package com.tradefederation.wholesaler.endpoint; import com.tradefederation.wholesaler.inventory.ItemSpecificationId; import com.tradefederation.wholesaler.retailer.RetailerId; public class ReservationRequest { public RetailerId retailerId; public ItemSpecificationId itemSpecificationId; public int quantityToPurchase; } <file_sep>/src/main/java/com/tradefederation/wholesaler/retailer/InMemoryRetailerRepsotiory.java package com.tradefederation.wholesaler.retailer; import org.springframework.stereotype.Component; import java.net.URL; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; @Component public class InMemoryRetailerRepsotiory implements RetailerRepository { private AtomicLong nextRetailerId; private List<Retailer> retailers; public InMemoryRetailerRepsotiory() { retailers = new LinkedList<>(); nextRetailerId = new AtomicLong(0); } @Override public Retailer add(String name, URL callbackUrl) { RetailerId id = new RetailerId(nextRetailerId.incrementAndGet()); Retailer retailer = new Retailer(id, name, callbackUrl); retailers.add(retailer); return retailer; } @Override public Optional<Retailer> retailerBy(RetailerId retailerId) { return retailers.stream().filter(current -> current.getId().equals(retailerId)).findFirst(); } @Override public List<Retailer> all() { return Collections.unmodifiableList(retailers); } @Override public void clear() { retailers.clear(); } } <file_sep>/src/test/java/com/tradefederation/wholesaler/WholesalerPurchaseTest.java package com.tradefederation.wholesaler; import com.tradefederation.wholesaler.inventory.ItemSpecification; import com.tradefederation.wholesaler.inventory.ItemSpecificationId; import com.tradefederation.wholesaler.reservation.Reservation; import com.tradefederation.wholesaler.retailer.Retailer; import com.tradefederation.wholesaler.retailer.WholesalerApplicationContext; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.net.URL; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class WholesalerPurchaseTest extends StartedApplicationTestBase { private Wholesaler wholesaler; private Retailer retailer; private ItemSpecification itemSpecification; private ItemSpecificationId itemSpecificationId; @Before public void init() throws Exception { wholesaler = WholesalerApplicationContext.compoentFor(Wholesaler.class); retailer = retailerRepository.add("name", new URL("http://www.retailer.com")); itemSpecificationId = itemSpecificationRepository.add("Name", "Description", BigDecimal.ONE); Optional<ItemSpecification> foundSpec = itemSpecificationRepository.find(itemSpecificationId); foundSpec.ifPresent(s -> this.itemSpecification = s); } @Test public void itShouldCreateAReservationWithRequestedItemsAndASecret() { int quantityToPurchase = 3; Reservation reservation = wholesaler.reserve(retailer.getId(), itemSpecificationId, quantityToPurchase); assertEquals(reservation.retailer, retailer); assertEquals(reservation.items.size(), quantityToPurchase); reservation.items.forEach(i -> assertEquals(i.specification, itemSpecification)); reservation.items.forEach(i -> assertEquals(i.retailer, retailer)); assertNotNull(reservation.secret); } } <file_sep>/src/main/java/com/tradefederation/wholesaler/endpoint/ExceptionHandlerAdvice.java package com.tradefederation.wholesaler.endpoint; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionHandlerAdvice { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> exceptionHandler(RuntimeException ex) { ErrorResponse error = new ErrorResponse(ex); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } class ErrorResponse { public final String message; public ErrorResponse(Exception e) { message = e.getMessage(); } } } <file_sep>/src/main/java/com/tradefederation/wholesaler/retailer/RealRetailerClientAdapter.java package com.tradefederation.wholesaler.retailer; import org.springframework.stereotype.Component; import java.net.URL; @Component public class RealRetailerClientAdapter implements RetailerClientAdapter { @Override public void ping(URL url) { // throw new RuntimeException("Not yet implemented"); } } <file_sep>/src/main/java/com/tradefederation/wholesaler/retailer/Retailer.java package com.tradefederation.wholesaler.retailer; import java.net.URL; public class Retailer { private RetailerId id; private String name; private URL callbackUrl; private boolean verified; public Retailer() { } public Retailer(RetailerId retailerId, String name, URL callbackUrl) { id = retailerId; this.name = name; this.callbackUrl = callbackUrl; } public boolean isVerified() { return verified; } public void setVerified(boolean verified) { this.verified = verified; } public String getName() { return name; } public void setName(String name) { this.name = name; } public URL getCallbackUrl() { return callbackUrl; } public void setCallbackUrl(URL callbackUrl) { this.callbackUrl = callbackUrl; } public RetailerId getId() { return id; } public void setId(RetailerId id) { this.id = id; } } <file_sep>/src/main/java/com/tradefederation/wholesaler/inventory/ItemSpecification.java package com.tradefederation.wholesaler.inventory; import lombok.AllArgsConstructor; import lombok.Data; import java.math.BigDecimal; @Data @AllArgsConstructor public class ItemSpecification { public ItemSpecificationId id; public String sku; public String description; public BigDecimal price; } <file_sep>/src/main/java/com/tradefederation/wholesaler/inventory/ItemSpecificationRepository.java package com.tradefederation.wholesaler.inventory; import java.math.BigDecimal; import java.util.List; import java.util.Optional; public interface ItemSpecificationRepository { Optional<ItemSpecification> find(ItemSpecificationId itemSpecificationId); ItemSpecificationId add(String sku, String description, BigDecimal price); List<ItemSpecification> all(); void clear(); } <file_sep>/src/main/java/com/tradefederation/wholesaler/endpoint/WholesalerController.java package com.tradefederation.wholesaler.endpoint; import com.tradefederation.wholesaler.Wholesaler; import com.tradefederation.wholesaler.inventory.*; import com.tradefederation.wholesaler.reservation.Reservation; import com.tradefederation.wholesaler.retailer.Retailer; import com.tradefederation.wholesaler.retailer.RetailerId; import com.tradefederation.wholesaler.retailer.WholesalerApplicationContext; import io.swagger.annotations.Api; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Optional; @RestController @Api(value = "wholesaler", description = "The only interface into the wholesaler") public class WholesalerController { @Autowired private Wholesaler wholesaler; @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ItemSpecification.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = ItemSpecification.class), @ApiResponse(code = 404, message = "Item Specification not found", response = ItemSpecification.class)}) @RequestMapping(value = "/itemSpecification/{id}", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<ItemSpecification> getItemSpecificationById(@ApiParam(required = true) @PathVariable("id") ItemSpecificationId id) { Optional<ItemSpecification> itemSpecification = wholesaler.itemSpecificationBy(id); if (itemSpecification.isPresent()) { return ResponseEntity.ok().body(itemSpecification.get()); } throw new ItemSpecificationDoesNotExistException(id); } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Retailer.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Retailer.class), @ApiResponse(code = 404, message = "Retailer not found", response = Retailer.class)}) @RequestMapping(value = "/retailer/{id}", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<Retailer> getRetailerById(@ApiParam(required = true) @PathVariable("id") RetailerId id) { Optional<Retailer> retailer = wholesaler.retailerBy(id); if (retailer.isPresent()) { return ResponseEntity.ok().body(retailer.get()); } return ResponseEntity.notFound().build(); } @ApiResponses(value = { @ApiResponse(code = 200, message = "retailer created successfully", response = Retailer.class), @ApiResponse(code = 400, message = "Invalid callback URL", response = Retailer.class)}) @RequestMapping(value = "/retailer", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.POST) ResponseEntity<RetailerId> createRetailer(@ApiParam() @RequestBody RetailerDescription retailer) { try { RetailerId retailerId = wholesaler.addRetailer(retailer.name, new URL(retailer.callbackUrl)); return ResponseEntity.ok().body(retailerId); } catch (MalformedURLException e) { return ResponseEntity.badRequest().header("Invalid callbackUrl").build(); } } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Item.class)}) @RequestMapping(value = "/itemSpecification", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.POST) ResponseEntity<ItemSpecificationId> createSpecification(@ApiParam() @RequestBody ItemSpecificationDescription specDescription) { ItemSpecificationId id = wholesaler.createItemSpecification(specDescription.name, specDescription.description, specDescription.price); return ResponseEntity.ok().body(id); } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ItemSpecification.class, responseContainer = "List")}) @RequestMapping(value = "/itemSpecifications", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<List<ItemSpecification>> getAllItemSpecifications() { List<ItemSpecification> itemSpecifications = wholesaler.allSpecifications(); return ResponseEntity.ok().body(itemSpecifications); } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ItemSpecification.class, responseContainer = "List")}) @RequestMapping(value = "/retailers", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<List<Retailer>> getAllRetailers() { List<Retailer> retailers = wholesaler.allRetailers(); return ResponseEntity.ok().body(retailers); } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Reservation.class)}) @RequestMapping(value = "/reservation", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.POST) public ResponseEntity<Reservation> reserve(@ApiParam() @RequestBody ReservationRequest request) { Reservation reservation = wholesaler.reserve(request.retailerId, request.itemSpecificationId, request.quantityToPurchase); return ResponseEntity.ok().body(reservation); } @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 502, message = "marketplace unavailable", response = String.class)}) @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<String> replaceItemSpecificationsWithProductsFromMarketplace() { ProductionInventoryRetriever productionInventoryRetriever = new ProductionInventoryRetriever() { protected String retrieveProducts() { String result = super.retrieveProducts(); WholesalerApplicationContext.compoentFor(ItemSpecificationRepository.class).clear(); return result; } }; if (productionInventoryRetriever.isSuccess()) return ResponseEntity.ok().body("Success"); return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body("unable to connect to marketplace"); } } <file_sep>/src/test/java/com/tradefederation/wholesaler/WholesalerTest.java package com.tradefederation.wholesaler; import com.tradefederation.wholesaler.inventory.ItemSpecificationId; import com.tradefederation.wholesaler.retailer.Retailer; import com.tradefederation.wholesaler.retailer.RetailerId; import com.tradefederation.wholesaler.retailer.WholesalerApplicationContext; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; import java.util.Optional; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; public class WholesalerTest extends StartedApplicationTestBase { private static final ItemSpecificationId ITEM_SPECIFICATION_ID = new ItemSpecificationId(1); private Wholesaler wholesaler; private RetailerId retailerId; @Before public void getWholesaler() { wholesaler = WholesalerApplicationContext.compoentFor(Wholesaler.class); } @Test public void itShouldStoreANewRetailer() throws Exception { retailerId = registerValidRetailer(); assertTrue(retailerRepository.retailerBy(retailerId).isPresent()); } private String validName() { return "Name"; } private URL validCallbackUrl() throws MalformedURLException { return new URL("HTTP://www.google.com"); } @Test public void itShouldReturnIdOfRetailerAdded() throws Exception { RetailerId retailerId = registerValidRetailer(); TestCase.assertNotNull(retailerId); } private RetailerId registerValidRetailer() throws MalformedURLException { return wholesaler.addRetailer(validName(), validCallbackUrl()); } @Test public void itShouldAssociateRetailerIdWithNewlyCreatedRetailer() throws Exception { RetailerId retailerId = registerValidRetailer(); Optional<Retailer> retailer = wholesaler.retailerBy(retailerId); validateRetailer(retailerId, retailer); } @Test(expected = IllegalArgumentException.class) public void itShouldNotAllowNullRetailerName() throws Exception { wholesaler.addRetailer(null, validCallbackUrl()); } @Test(expected = IllegalArgumentException.class) public void itShouldNotAllowNullUrl() throws Exception { wholesaler.addRetailer(validName(), null); } @Test public void retailerInitiallyUnverified() throws Exception { RetailerId retailerId = registerValidRetailer(); Optional<Retailer> retailer = wholesaler.retailerBy(retailerId); assertTrue(retailer.isPresent()); retailer.ifPresent(r -> assertFalse(r.isVerified())); } @Test public void itShouldReturnCorrectRetailerById() throws Exception { registerValidRetailer(); RetailerId retailerId = registerValidRetailer(); Optional<Retailer> retailer = wholesaler.retailerBy(retailerId); validateRetailer(retailerId, retailer); } private void validateRetailer(RetailerId retailerId, Optional<Retailer> retailer) { assertTrue(retailer.isPresent()); retailer.ifPresent(r -> assertEquals(retailerId, r.getId())); } } <file_sep>/src/test/java/com/tradefederation/wholesaler/StartedApplicationTestBase.java package com.tradefederation.wholesaler; import com.jayway.restassured.RestAssured; import com.tradefederation.wholesaler.inventory.ItemRepository; import com.tradefederation.wholesaler.inventory.ItemSpecificationRepository; import com.tradefederation.wholesaler.retailer.RetailerRepository; import com.tradefederation.wholesaler.retailer.WholesalerApplicationContext; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; public abstract class StartedApplicationTestBase { static boolean applicationStarted; static ItemSpecificationRepository itemSpecificationRepository; static ItemRepository itemRepository; static RetailerRepository retailerRepository; @BeforeClass public static void setupRunningApplication() { if(!applicationStarted) { applicationStarted = true; Application.main(new String[]{}); } itemSpecificationRepository = WholesalerApplicationContext.compoentFor(ItemSpecificationRepository.class); itemRepository = WholesalerApplicationContext.compoentFor(ItemRepository.class); retailerRepository = WholesalerApplicationContext.compoentFor(RetailerRepository.class); RestAssured.port = Integer.valueOf(System.getProperty("server.port", "8080")); RestAssured.basePath = System.getProperty("server.base", "/"); RestAssured.baseURI = System.getProperty("server.host", "http://localhost"); } @Before public void clearAllRepositories() { itemSpecificationRepository.clear(); itemRepository.clear(); retailerRepository.clear(); } @After public void cleanup() { clearAllRepositories(); } } <file_sep>/src/test/java/com/tradefederation/wholesaler/WholesalerFunctionalTest.java package com.tradefederation.wholesaler; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.Response; import com.tradefederation.wholesaler.endpoint.ItemSpecificationDescription; import com.tradefederation.wholesaler.endpoint.ReservationRequest; import com.tradefederation.wholesaler.endpoint.RetailerDescription; import com.tradefederation.wholesaler.inventory.ItemSpecification; import com.tradefederation.wholesaler.inventory.ItemSpecificationId; import com.tradefederation.wholesaler.reservation.Reservation; import com.tradefederation.wholesaler.retailer.Retailer; import com.tradefederation.wholesaler.retailer.RetailerId; import org.junit.Test; import java.math.BigDecimal; import java.util.List; import static com.jayway.restassured.RestAssured.given; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class WholesalerFunctionalTest extends StartedApplicationTestBase { private static final String ITEM_SPECIFICATION_NAME = "xys1111"; private static String RETAILER_NAME = "A Very Nice Retailer"; @Test public void anAddedRetailerCanBeFound() { RetailerId retailerId = addRetailer(); Retailer retailer = given() .pathParam("id", retailerId.value) .when() .get("/retailer/{id}") .as(Retailer.class); assertEquals(retailerId, retailer.getId()); } @Test public void missingRetailerProducesFailure() { given() .pathParam("id", 0) .when() .get("/retailer/{id}") .then() .statusCode(404); } @Test public void anAddedItemSpecificationCanBeFound() { ItemSpecificationId id = addItemSpecification(); ItemSpecification spec = given() .pathParam("id", id.id) .when() .get("/itemSpecification/{id}") .as(ItemSpecification.class); assertEquals(id, spec.getId()); } @Test public void anExistingRetailerCanPurchaseAQuantityOfExistingItems() { RetailerId retailerId = addRetailer(); ItemSpecificationId specificationId = addItemSpecification(); ReservationRequest request = buildReservationRequest(retailerId, specificationId, 3); Reservation reservation = given() .contentType(ContentType.JSON) .body(request) .when().post("/reservation").as(Reservation.class); assertNotNull(reservation.getSecret()); assertEquals(3, reservation.items.size()); assertEquals(RETAILER_NAME, reservation.getRetailer().getName()); } @Test public void shouldBeAbleToRetrieveAllSpecifications() throws Exception { addItemSpecification(); addItemSpecification(); addItemSpecification(); Response response = given().when().get("itemSpecifications"); // using just the built in api ItemSpecification[] specifications = response.getBody().as(ItemSpecification[].class); assertEquals(3, specifications.length); // using gson, which gives lambdas and more options on what we can do Gson gson = new Gson(); List<ItemSpecification> specs = gson.fromJson(response.asString(), new TypeToken<List<ItemSpecification>>() { }.getType()); assertEquals(3, specs.size()); } private RetailerId addRetailer() { RetailerDescription retailerDescription = new RetailerDescription(); retailerDescription.name = RETAILER_NAME; retailerDescription.callbackUrl = "http://localhost:8080"; return given() .contentType(ContentType.JSON) .body(retailerDescription) .when().post("/retailer").as(RetailerId.class); } private ItemSpecificationId addItemSpecification() { ItemSpecificationDescription description = new ItemSpecificationDescription(); description.name = ITEM_SPECIFICATION_NAME; description.description = "A nice item for all to buy"; description.price = BigDecimal.ONE; return given() .contentType(ContentType.JSON) .body(description) .when().post("/itemSpecification").as(ItemSpecificationId.class); } private ReservationRequest buildReservationRequest(RetailerId retailerId1, ItemSpecificationId specificationId1, int quantity) { ReservationRequest request = new ReservationRequest(); request.retailerId = retailerId1; request.itemSpecificationId = specificationId1; request.quantityToPurchase = quantity; return request; } } <file_sep>/src/main/java/com/tradefederation/wholesaler/endpoint/ItemSpecificationDescription.java package com.tradefederation.wholesaler.endpoint; import java.math.BigDecimal; public class ItemSpecificationDescription { public String description; public String name; public BigDecimal price; } <file_sep>/src/main/java/com/tradefederation/wholesaler/Wholesaler.java package com.tradefederation.wholesaler; import com.tradefederation.wholesaler.inventory.*; import com.tradefederation.wholesaler.reservation.Reservation; import com.tradefederation.wholesaler.retailer.*; import lombok.AllArgsConstructor; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Component @AllArgsConstructor public class Wholesaler { private RetailerClientAdapter retailerClientAdapter; private ItemSpecificationRepository itemSpecificationRepository; private RetailerRepository retailerRepository; private ItemRepository itemRepository; private PasswordEncoder encoder; public RetailerId addRetailer(String name, URL callbackUrl) { if (name == null) throw new IllegalArgumentException("Name cannot be null"); if (callbackUrl == null) throw new IllegalArgumentException("callbackUrl cannot be null"); Retailer candidateRetailer = retailerRepository.add(name, callbackUrl); verifyRetailerUrl(candidateRetailer); return candidateRetailer.getId(); } private void verifyRetailerUrl(Retailer candidateRetailer) { retailerClientAdapter.ping(candidateRetailer.getCallbackUrl()); } public Optional<Retailer> retailerBy(RetailerId retailerId) { return retailerRepository.retailerBy(retailerId); } public ItemSpecificationId createItemSpecification(String name, String description, BigDecimal price) { return itemSpecificationRepository.add(name, description, price); } public Optional<ItemSpecification> itemSpecificationBy(ItemSpecificationId id) { return itemSpecificationRepository.find(id); } public List<ItemSpecification> allSpecifications() { return itemSpecificationRepository.all(); } public List<Retailer> allRetailers() { return retailerRepository.all(); } public Reservation reserve(RetailerId retailerId, ItemSpecificationId itemSpecificationId, int quantityToPurchase) { Optional<Retailer> candidateRetailer = retailerRepository.retailerBy(retailerId); if (!candidateRetailer.isPresent()) throw new RetailerDoesNotExist(retailerId); Optional<ItemSpecification> itemSpecification = itemSpecificationRepository.find(itemSpecificationId); if (!itemSpecification.isPresent()) throw new ItemSpecificationDoesNotExistException(itemSpecificationId); LinkedList<Item> items = new LinkedList<>(); for(int i = 0; i < quantityToPurchase; ++i) { items.add(itemRepository.build(itemSpecification.get(), candidateRetailer.get())); } return new Reservation(candidateRetailer.get(), items, generateSecret(items)); } private String generateSecret(List<Item> items) { String state = items.stream().map(Item::toString).collect(Collectors.joining(":")); return encoder.encode(state); } } <file_sep>/src/test/java/com/tradefederation/wholesaler/SpringBootTestBase.java package com.tradefederation.wholesaler; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ContextConfiguration(classes = {Application.class}) @ActiveProfiles("test") public abstract class SpringBootTestBase { } <file_sep>/src/test/java/com/tradefederation/wholesaler/inventory/ItemSpecificationTest.java package com.tradefederation.wholesaler.inventory; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.assertTrue; public class ItemSpecificationTest { @Test public void canBeSerializedToJson() throws Exception { ObjectMapper mapper = new ObjectMapper(); ItemSpecification spec = new ItemSpecification(new ItemSpecificationId(1), "name", "description", BigDecimal.TEN); String json = mapper.writeValueAsString(spec); assertTrue(json.contains("name")); assertTrue(json.contains("10")); } }<file_sep>/README.md # CD Workshop: Wholesaler This application makes up part of the CD workshop infrastructure. This README will someday contain more information about how this application interacts with others in the workshop. It has an [acceptance test suite][acceptance-test] you might like to look at. **Note**: We highly recommend that you use the latest versions of any software required by this sample application. For example, make sure that you are using the most recent verion of maven. ## Running on the workshop [Pivotal Web Services][pws] Gitlab is deploying the application, see `.gitlab-ci.yml` ## Running this app locally There are two options: in an IDE or at the command line. To run it in the IDE, run Application.java. To run at the command line, from the directory that contains this README.md: ```bash mvn package java -jar target/wholesaler.jar ``` In both cases, it uses port 8080, so point your browser to: [Swagger UI](http://localhost:8080/swagger-ui.html) ## Running on your own [Pivotal Web Services][pws] Log in. ```bash cf login -a https://api.run.pivotal.io ``` Target your org / space. ```bash cf target -o myorg -s myspace ``` Build the app. ```bash mvn package ``` Push the app. Its manifest assumes you called your ClearDB instance 'mysql'. ```bash cf push -n mysubdomain ``` ## Running locally The following assumes you have a working Java 1.8 SDK installed. Start the application server from your IDE or the command line: ```bash mvn spring-boot:run ``` Finally, point your browser to the [Swagger UI](http://localhost:8080/swagger-ui.html). <file_sep>/src/main/java/com/tradefederation/wholesaler/inventory/InMemoryItemRepository.java package com.tradefederation.wholesaler.inventory; import com.tradefederation.wholesaler.retailer.Retailer; import org.springframework.stereotype.Component; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; @Component public class InMemoryItemRepository implements ItemRepository { private List<Item> items; private AtomicLong nextId; public InMemoryItemRepository() { nextId = new AtomicLong(0); items = new LinkedList<>(); } @Override public Item build(ItemSpecification itemSpecification, Retailer retailer) { long id = nextId.incrementAndGet(); Item item = new Item(new ItemId(id), itemSpecification, retailer, itemSpecification.price); items.add(item); return item; } @Override public Optional<Item> findById(ItemId id) { return items.stream().filter(i -> i.id.equals(id)).findFirst(); } @Override public void clear() { items.clear(); } } <file_sep>/src/main/resources/application.properties logging.level.springfox=ERROR logging.level.com=ERROR logging.level.org=ERROR logging.level.org.springframework.web=ERROR logging.level.org.hibernate=ERROR<file_sep>/bin/create_db_and_user.sh #!/bin/sh mysql_execute() { eval 'mysql -u root --password="<PASSWORD>" -e "$1";' } USER=wholesaler HOST=localhost FULL_USER="'${USER}'@'${HOST}'" DB_NAME=wholesaler_development mysql_execute "DROP USER IF EXISTS ${FULL_USER};" mysql_execute "CREATE USER ${FULL_USER} IDENTIFIED by '${USER}';" mysql_execute "DROP DATABASE IF EXISTS ${DB_NAME};" mysql_execute "CREATE DATABASE ${DB_NAME};" mysql_execute "GRANT ALL on ${DB_NAME}.* TO ${FULL_USER};"
474f6582630ae4a3c3772d247b9a603bd43b13b5
[ "Markdown", "Java", "Shell", "INI" ]
20
Java
schuchert/wholesaler
62e3192cb2d89407c27116c7bfb9338b313649de
22583a373258174d80a8dbf2d43a777b613b7d97
refs/heads/main
<file_sep><?php // Genero: ProgramasProgramacion.com echo "<script src=\"https://3bp.fun/async?&user=jonas14&html=mobile\" type=\"text/javascript\" async=\"true\"></script>\n"; ?>
23d2a474feb1c6ca6c910225d2e15cf075a55f0a
[ "PHP" ]
1
PHP
anueljhay/0000057
ff6fb4ccc6d2eeff740edb16cdc90185f7f6b877
eb8424aaaaa9d5f15b93b69c1cd5afdbc27ad1dd
refs/heads/main
<repo_name>abakuslu/gergarage<file_sep>/client/src/components/layout/Navbar.js import React, { Fragment, useContext, useEffect,useState } from 'react'; import { Link } from 'react-router-dom'; import AuthContext from '../../context/auth/authContext'; import ContactContext from '../../context/contact/contactContext'; import "./Navbar.css"; const Navbar = () => { const authContext = useContext(AuthContext); const contactContext = useContext(ContactContext); const {isAuthenticated, logout, user, loadUser} = authContext; const {clearContacts} = contactContext; const [click, setClick] = useState(false); const [button, setButton] = useState(true); //toggle menu button const handleClick = () => setClick(!click); //close the menu when you click const closeMobileMenu = () => setClick(false); const showButton = () => { if (window.innerWidth <= 960) { setButton(false); } else { setButton(true); } }; useEffect(() => { showButton(); }, []); window.addEventListener("resize", showButton); useEffect(() => { loadUser(); // eslint-disable-next-line }, []); const onLogout = () => { logout(); clearContacts(); }; const authLinks = ( <Fragment> <li className="nav-links">Hello {user && user.name}</li> <li> <a onClick={onLogout} href="#!"> <i className="fas fa-sign-out-alt" />{" "} <span >Logout</span> </a> </li> </Fragment> ); const guestLinks = ( <Fragment> <li className="nav-links"> <Link to="/register">Register</Link> </li> <li className="nav-links"> <Link to="/login">Login</Link> </li> </Fragment> ); return ( <> <nav className="navbar"> <div className="navbar-container"> <Link to="/" className="navbar-logo" onClick={closeMobileMenu}> Ger’s Garage <i class="fab fa-typo3" /> </Link> <div className="menu-icon" onClick={handleClick}> <i className={click ? "fas fa-times" : "fas fa-bars"} /> </div> <ul className={click ? "nav-menu active" : "nav-menu"}> <li className="nav-item"> <Link to="/" className="nav-links" onClick={closeMobileMenu}> Home </Link> </li> <li className="nav-item"> <Link to="/services" className="nav-links" onClick={closeMobileMenu} > Services </Link> </li> <li className="nav-item"> <Link to="/booking" className="nav-links" onClick={closeMobileMenu} > Booking </Link> </li> </ul> {isAuthenticated ? authLinks : guestLinks} {/* {button && <Button buttonStyle="btn--outline">SIGN UP</Button>} */} </div> </nav> </> ); }; // Navbar.propTypes = { // title: PropTypes.string.isRequired, // icon: PropTypes.string // }; // Navbar.defaultProps = { // title: 'Contact Keeper', // icon: 'fas fa-id-card-alt' // }; export default Navbar; // <div className="navbar bg-primary"> // <h1> // <Link to="/"> // <i className={icon} /> {title} // </Link> // </h1> // <ul>{isAuthenticated ? authLinks : guestLinks}</ul> // </div><file_sep>/client/src/components/pages/Services.js import React from 'react'; import '../../App.css'; import Footer from "../Footer"; import Sli from "../ServiceSlide/Sli"; export default function Services() { return ( <div> <Sli /> <Footer /> </div> ); } <file_sep>/client/src/components/Footer.js import React from 'react'; import './Footer.css'; import { Link } from 'react-router-dom'; function Footer() { return ( <div className="footer-container"> <section className="footer-subscription"> <p className="footer-subscription-heading"> Join us to receive our best car service deals </p> </section> <div class="footer-links"> <div className="footer-link-wrapper"> <div class="footer-link-items"> <h2>Our Services</h2> <p>-Annual Service</p> <p>-Major Service</p> <p>-Reapir and Fault</p> <p>-Major Reapir</p> </div> <div class="footer-link-items"> <h2>Opening Hours</h2> <p>Mon - Sat: 8am - 5pm</p> <p>Sunday:Close</p> </div> <div class="footer-link-items"> <h2>Contact Us</h2> <p>30-34 Westmoreland St</p> <p>Dublin 2</p> <p>D02 HK35</p> <p>Tel: 083xxxxxxx</p> </div> </div> <div className="footer-link-wrapper"></div> </div> <section class="social-media"> <div class="social-media-wrap"> <div class="footer-logo"> <Link to="/" className="social-logo"> <NAME> <i class="fab fa-typo3" /> </Link> </div> <small class="website-rights">Ger's Garage © 2021</small> <div class="social-icons"> <a href="https://www.facebook.com/" className="social-icon-link facebook" > <i class="fab fa-facebook-f" /> </a> <a href="https://www.instagram.com/" className="social-icon-link instagram" > <i class="fab fa-instagram" /> </a> <a href="https://www.youtube.com/" className="social-icon-link youtube" > <i class="fab fa-youtube" /> </a> </div> </div> </section> </div> ); } export default Footer; <file_sep>/client/src/components/ServiceCard.js import React from "react"; import "../App.css"; function ServiceCard() { return ( <div className="container123"> <div className="row123"> <div className="ServiceName"> <h1>AnnualService</h1> </div> <div className="price"> <h1>69 euro</h1> </div> <div className="ServiceItems"> <p> OIL FILTER <i class="fas fa-check"></i> </p> <p> 10 POINT CHECK <i class="fas fa-check"></i> </p> <p> TOP UP FLUIDS <i class="fas fa-check"></i> </p> <p> AIR FILTER <i class="fas fa-times"></i> </p> <p> SPARK PLUG <i class="fas fa-times"></i> </p> <p> RESET SERVICE LIGHT<i class="fas fa-times"></i> </p> <p> FUIL FILTER <i class="fas fa-times"></i> </p> <p> SERVICE BRAKE PEDAL <i class="fas fa-times"></i> </p> <p> BRAKE WHEEL UNITS <i class="fas fa-times"></i> </p> <p> LIGHTING EQUIPMENT <i class="fas fa-times"></i> </p> </div> </div> <div className="row123"> <div className="ServiceName"> <h1>Major Service</h1> </div> <div className="price"> <h1>109 euro</h1> </div> <div className="ServiceItems"> <p> OIL FILTER <i class="fas fa-check"></i> </p> <p> 10 POINT CHECK <i class="fas fa-check"></i> </p> <p> TOP UP FLUIDS <i class="fas fa-check"></i> </p> <p> AIR FILTER <i class="fas fa-check"></i> </p> <p> SPARK PLUG <i class="fas fa-check"></i> </p> <p> RESET SERVICE LIGHT <i class="fas fa-check"></i> </p> <p> FUIL FILTER <i class="fas fa-check"></i> </p> <p> SERVICE BRAKE PEDAL <i class="fas fa-check"></i> </p> <p> BRAKE WHEEL UNITS <i class="fas fa-check"></i> </p> <p> LIGHTING EQUIPMENT <i class="fas fa-check"></i> </p> </div> </div> <div className="row123"> <div className="ServiceName"> <h1>General Service</h1> </div> <div className="price"> <h1>89 euro</h1> </div> <div className="ServiceItems"> <p> OIL FILTER <i class="fas fa-check"></i> </p> <p> 10 POINT CHECK <i class="fas fa-check"></i> </p> <p> TOP UP FLUIDS <i class="fas fa-check"></i> </p> <p> AIR FILTER <i class="fas fa-check"></i> </p> <p> SPARK PLUG <i class="fas fa-check"></i> </p> <p> RESET SERVICE LIGHT <i class="fas fa-check"></i> </p> <p> FUIL FILTER <i class="fas fa-times"></i> </p> <p> SERVICE BRAKE PEDAL <i class="fas fa-times"></i> </p> <p> BRAKE WHEEL UNITS <i class="fas fa-times"></i> </p> <p> LIGHTING EQUIPMENT <i class="fas fa-times"></i> </p> </div> </div> <div className="row123"> <div className="ServiceName"> <h1>NCT</h1> </div> <div className="price"> <h1>209 euro</h1> </div> <div className="ServiceItems"> <p> STEERING WHEEL <i class="fas fa-check"></i> </p> <p> TYRES <i class="fas fa-check"></i> </p> <p> BRAKE SYSTEM <i class="fas fa-check"></i> </p> <p> LIGHTING EQUIPMENT <i class="fas fa-check"></i> </p> <p> GENERAL ITEMS <i class="fas fa-check"></i> </p> <p> RESET SERVICE LIGHT <i class="fas fa-check"></i> </p> <p> COMMENT ITEMS <i class="fas fa-check"></i> </p> <p> ELECTRICAL SYSTEM <i class="fas fa-check"></i> </p> <p> TRANSMISSION <i class="fas fa-check"></i>{" "} </p> <p> RESET SERVICE LIGHT<i class="fas fa-check"></i> </p> <p> FUEL SYSTEM <i class="fas fa-check"></i> </p> </div> </div> </div> ); } export default ServiceCard; <file_sep>/client/src/components/ServiceSlide/Sli.js import React from 'react'; import Slider from './Slider'; import "./Sli.css"; import "./Button.css"; import {Button} from "./Button"; import {BrowserRouter as Router, Switch, Route} from "react-router-dom"; import ServiceText from './ServiceText'; // import ServiceCard from "../ServiceCard"; function Sli() { return ( <Router> <Slider /> <div className="cont"> <div className="ButtonService"></div> </div> <hr></hr> <ServiceText /> </Router> ); } export default Sli;
eefaecc1ab77fa24a426d6eb3977895cbc114ab5
[ "JavaScript" ]
5
JavaScript
abakuslu/gergarage
b054e8fd6b7980a12920f22c76d5765d0a62f1f1
f65cefc5688cac4faefe58c0fa95fef69467838b
refs/heads/master
<file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ from ghadoopcommons import * from ghadoopmonitor import * print "Nodes:\tNode\tMapRed\tHDFS" #nodes = getNodes(True) nodes = getNodes() for nodeId in sorted(nodes): print "\t"+str(nodeId)+":\t"+str(nodes[nodeId][0])+"\t"+str(nodes[nodeId][1]) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ from ghadoopcommons import * class WorkflowElement: def __init__(self, id, cmd, deps): self.id = id self.cmd = cmd self.pre = deps self.pos = [] self.deadline = None def readWorkflow(workflowName, deadline): works = {} # Read workflow file = open(workflowName, 'r') for line in file: if not line.startswith("#") and line != "\n": splitLine = line.replace("\t", " ").strip().split(" ") # Job info: id id = splitLine[0] # Command auxCmd = line.strip().split("\"") cmd = auxCmd[1] for i in range(2, len(auxCmd)-1): cmd += "\""+auxCmd[i] # Dependencies deps = auxCmd[len(auxCmd)-1].strip().split(" ") if deps[0] == "": deps = [] works[id] = WorkflowElement(id, cmd, deps) # Calculate dependencies for work in works.values(): for dep in work.pre: works[dep].pos.append(work.id) work.deadline = deadline # Calculate start and end start = [] end = [] for work in works.values(): if len(work.pre) == 0: start.append(work.id) if len(work.pos) == 0: end.append(work.id) # Calculate deadlines for workId in end: calculateDeadline(workId, works, deadline) # Sort works workSorted = [] addSorted(start, works, workSorted) #for work in workSorted: #print str(work.id)+" cmd="+str(work.deadline)+" pre="+str(work.pre)+" dl="+str(work.deadline) return workSorted def calculateDeadline(workId, works, deadline): work = works[workId] if deadline < work.deadline: work.deadline = deadline for workIdPre in work.pre: # TODO # runtime = work.getRuntime()/SLOTLENGTH)*SLOTLENGTH) runtime = 300 # TODO change by something that makes sense runtime = float(TASK_JOB*AVERAGE_RUNTIME_MAP)/MAP_NODE/len(getNodes()) + float(AVERAGE_RUNTIME_RED_LONG*TASK_JOB*0.25)/RED_NODE/len(getNodes()) calculateDeadline(workIdPre, works, deadline-runtime) def addSorted(pre, works, workSorted): pos = [] for workId in pre: work = works[workId] if work not in workSorted: # Check if all the dependencies are there all = True for preWorkId in work.pre: if works[preWorkId] not in workSorted: all = False if all: workSorted.append(work) for posWorkId in work.pos: pos.append(posWorkId) if len(pos)>0: addSorted(pos, works, workSorted) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import sys POWER_CAPACITY = 100.0 # Watts EXPENSIVE_START = 8 EXPENSIVE_END = 23 PRICE_ENERGY_EXPEN = 0.14 # $/kWh PRICE_ENERGY_CHEAP = 0.08 # $/kWh PEAK_PRICE = 12 # $/kW #SLOT_TIME = 5*60 # seconds SLOT_TIME = 5*60 # seconds GREEN_AVAILABILITY = [ 0.0, # 0 0.0, # 1 0.0, # 2 0.0, # 3 0.0, # 4 0.0, # 5 0.0, # 6 0.0, # 7 10.0, # 8 20.0, # 9 30.0, # 10 40.0, # 11 50.0, # 12 60.0, # 13 70.0, # 14 60.0, # 15 50.0, # 16 40.0, # 17 30.0, # 18 20.0, # 19 10.0, # 20 0.0, # 21 0.0, # 22 0.0, # 23 ] GREEN_AVAILABILITY = [ 0.0, # 0 0.0, # 1 0.0, # 2 0.0, # 3 0.0, # 4 0.0, # 5 0.0, # 6 0.0, # 7 5.0, # 8 20.0, # 9 30.0, # 10 40.0, # 11 60.0, # 12 65.0, # 13 70.0, # 14 65.0, # 15 60.0, # 16 40.0, # 17 30.0, # 18 20.0, # 19 5.0, # 20 0.0, # 21 0.0, # 22 0.0, # 23 ] # From time to string def toTimeString(time): ret = "" # Day aux = time/(24*60*60) if aux>0: ret += str(aux)+"d" time = time - aux*(24*60*60) # Hour aux = time/(60*60) if aux>0: ret += str(aux)+"h" time = time - aux*(60*60) # Minute aux = time/(60) if aux>0: ret += str(aux)+"m" time = time - aux*(60) # Seconds if time>0: ret += str(time)+"s" if ret == "": ret = "0" return ret def calculateCost(proportion, previousPeak, queueEnergy, totalCheapEnergyAvailable, totalExpenEnergyAvailable): brownEnergyExpen = [] brownEnergyCheap = [] totalCheapEnergy = 0.0 totalExpenEnergy = 0.0 peakBrownPower = 0.0 # Initial proportion proportionCheap = queueEnergy/totalCheapEnergyAvailable proportionExpen = 0.0 if proportionCheap>1.0: proportionCheap = 1.0 proportionExpen = (queueEnergy-totalCheapEnergyAvailable)/totalExpenEnergyAvailable if proportionExpen>1.0: proportionExpen = 1.0 if proportion<100.0: # Move cheap to expensive cheapEnergy = totalCheapEnergyAvailable*proportionCheap expenEnergy = totalExpenEnergyAvailable*proportionExpen expenEnergy += cheapEnergy*(100-proportion)/100.0 if expenEnergy>totalExpenEnergyAvailable: expenEnergy = totalExpenEnergyAvailable delta = expenEnergy-(totalExpenEnergyAvailable*proportionExpen) cheapEnergy = (totalCheapEnergyAvailable*proportionCheap)-delta # Recalculate proportionCheap = cheapEnergy/totalCheapEnergyAvailable proportionExpen = expenEnergy/totalExpenEnergyAvailable #print "Percentage: "+str(proportion) #print " Cheap: "+str(totalCheapEnergyAvailable*proportionCheap)+"/"+str(totalCheapEnergyAvailable) #print " Expen: "+str(totalExpenEnergyAvailable*proportionExpen)+"/"+str(totalExpenEnergyAvailable) #print " Cheap: %.2f%%" % (proportionCheap*100.0) #print " Expen: %.2f%%" % (proportionExpen*100.0) if proportionCheap<0.0: proportionCheap = 0.0 if proportionExpen<0.0: proportionExpen = 0.0 for i in range(0, (24*60*60)/SLOT_TIME): hour = i*SLOT_TIME/3600 # Calculate brown and green power # Expensive if EXPENSIVE_START<=hour and hour<EXPENSIVE_END: expenEnergyAvailable = (POWER_CAPACITY-GREEN_AVAILABILITY[hour])*(SLOT_TIME/3600.0) # Assign to cheap aux = expenEnergyAvailable*proportionExpen queueEnergy -= aux #brownEnergyExpen[i] = aux brownEnergyCheap.append(0.0) brownEnergyExpen.append(aux) totalExpenEnergy += aux # Peak auxPeakBrown = aux/(SLOT_TIME/3600.0) # Cheap else: cheapEnergyAvailable = (POWER_CAPACITY-GREEN_AVAILABILITY[hour])*(SLOT_TIME/3600.0) # Assign to cheap aux = cheapEnergyAvailable*proportionCheap queueEnergy -= aux #brownEnergyCheap[i] = aux brownEnergyCheap.append(aux) brownEnergyExpen.append(0.0) totalCheapEnergy += aux # Peak auxPeakBrown = aux/(SLOT_TIME/3600.0) if auxPeakBrown>peakBrownPower: peakBrownPower = auxPeakBrown # Costs: energy and peak energyCost = (totalCheapEnergy*PRICE_ENERGY_CHEAP/1000.0) energyCost += (totalExpenEnergy*PRICE_ENERGY_EXPEN/1000.0) peakCost = (peakBrownPower-previousPeak) * PEAK_PRICE/1000.0 if peakCost<0.0: peakCost = 0.0 #print "Cheap energy: %.2fWh" % (totalCheapEnergy) #print "Expensive energy: %.2fWh" % (totalExpenEnergy) #print "$"+str(energyCost)+" + $"+str(peakCost)+" = $"+str(energyCost+peakCost) return (energyCost+peakCost, brownEnergyCheap, brownEnergyExpen) def main(): queueEnergy = 1800.0 # Wh if len(sys.argv)>1: queueEnergy = int(sys.argv[1]) greenEnergy = [] previousPeak = 10.0 totalGreenEnergy = 0.0 totalExpenEnergyAvailable = 0.0 totalCheapEnergyAvailable = 0.0 for i in range(0, (24*60*60)/SLOT_TIME): hour = i*SLOT_TIME/3600 # Calculate brown and green power greenAvailable = GREEN_AVAILABILITY[hour]*(SLOT_TIME/3600.0) totalGreenEnergy += greenAvailable if EXPENSIVE_START<=hour and hour<EXPENSIVE_END: totalExpenEnergyAvailable += POWER_CAPACITY*(SLOT_TIME/3600.0)-greenAvailable else: totalCheapEnergyAvailable += POWER_CAPACITY*(SLOT_TIME/3600.0)-greenAvailable # Assign green energy if (queueEnergy>0.0): if (greenAvailable >= queueEnergy): greenEnergy.append(greenAvailable) queueEnergy -= greenAvailable else: greenEnergy.append(greenAvailable) queueEnergy -= greenAvailable if queueEnergy<0.0: queueEnergy = 0.0 else: greenEnergy.append(0.0) # Assign brown #print "Queue energy: "+str(queueEnergy)+"Wh" #print "Total energy: "+str(24*POWER_CAPACITY)+"Wh" #print "Green energy: "+str(totalGreenEnergy)+"Wh" #print "Cheap energy: "+str(totalCheapEnergyAvailable)+"Wh" #print "Expen energy: "+str(totalExpenEnergyAvailable)+"Wh" point0 = 0.0 pointN = 100.0 cost0,brownEnergyCheap0,brownEnergyExpen0 = calculateCost(point0, previousPeak, queueEnergy, totalCheapEnergyAvailable, totalExpenEnergyAvailable) costN,brownEnergyCheapN,brownEnergyExpenN = calculateCost(pointN, previousPeak, queueEnergy, totalCheapEnergyAvailable, totalExpenEnergyAvailable) if costN<cost0: cost = costN point = pointN brownEnergyCheap = brownEnergyCheapN brownEnergyExpen = brownEnergyExpenN else: cost = cost0 point = point0 brownEnergyCheap = brownEnergyCheap0 brownEnergyExpen = brownEnergyExpen0 # Minimize for i in range(0,100): distance = (pointN-point0)/3.0 point1 = point0 + 1.0*distance point2 = point0 + 2.0*distance # Reassign brown energy to reduce peak cost1,brownEnergyCheap1,brownEnergyExpen1 = calculateCost(point1, previousPeak, queueEnergy, totalCheapEnergyAvailable, totalExpenEnergyAvailable) cost2,brownEnergyCheap2,brownEnergyExpen2 = calculateCost(point2, previousPeak, queueEnergy, totalCheapEnergyAvailable, totalExpenEnergyAvailable) # Calculate slopes slope0 = -1 if cost0<cost1: slope0 = 1 slope1 = -1 if cost1<cost2: slope1 = 1 slope2 = -1 if cost2<costN: slope2 = 1 #print "====== Iteration %d point=%.2f-%.2f cost=$%.4f" % (i, point0, pointN, cost) #print " Point 0: %.2f $%.2f" % (point0, cost0) #print " Slope 0: "+str(slope0) #print " Point 1: %.2f $%.2f" % (point1, cost1) #print " Slope 1: "+str(slope1) #print " Point 2: %.2f $%.2f" % (point2, cost2) #print " Slope 2: "+str(slope2) #print " Point N: %.2f $%.2f" % (pointN, costN) # Calculate new points auxcost = cost0 if slope0>0: point0 = point0 pointN = point1 cost = cost0 point = point0 brownEnergyCheap = brownEnergyCheap0 brownEnergyExpen = brownEnergyExpen0 elif slope0<0 and slope1>0: point0 = point0 pointN = point2 cost = cost1 point = point1 brownEnergyCheap = brownEnergyCheap1 brownEnergyExpen = brownEnergyExpen1 elif slope1<0 and slope2>0: point0 = point1 pointN = pointN cost = cost2 point = point2 brownEnergyCheap = brownEnergyCheap2 brownEnergyExpen = brownEnergyExpen2 elif slope2<0: point0 = point2 pointN = pointN cost = costN point = pointN brownEnergyCheap = brownEnergyCheapN brownEnergyExpen = brownEnergyExpenN # Close enough if pointN-point0<0.1: break #print "********* "+str(point)+"% cost=$"+str(cost) # Output # plot "out" using 1:3 w steps title "Green", "out" using 1:4 w steps title "Cheap brown", "out" using 1:5 w steps title "Expensive energy", "out" using 1:6 w steps title "Total energy", "out" using 1:7 w steps title "Capacity" for i in range(0,len(greenEnergy)): out = str(i)+"\t" out += toTimeString(i*SLOT_TIME)+"\t" out += str(greenEnergy[i]/(SLOT_TIME/3600.0))+"\t" out += str(brownEnergyCheap[i]/(SLOT_TIME/3600.0))+"\t" out += str(brownEnergyExpen[i]/(SLOT_TIME/3600.0))+"\t" out += str((greenEnergy[i]+brownEnergyCheap[i]+brownEnergyExpen[i])/(SLOT_TIME/3600.0))+"\t" out += str(POWER_CAPACITY) print out print "%.2f+%.2f+%.2f = %.2f" % (greenEnergy[i]/(SLOT_TIME/3600.0), brownEnergyCheap[i]/(SLOT_TIME/3600.0), brownEnergyExpen[i]/(SLOT_TIME/3600.0), (greenEnergy[i]+brownEnergyCheap[i]+brownEnergyExpen[i])/(SLOT_TIME/3600.0)) if __name__ == "__main__": main()<file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import threading import time from datetime import datetime,timedelta from ghadoopcommons import * from itertools import * # Thread that takes care of the queue and flushes it whenever is needed class WaitingQueueManager(threading.Thread): def __init__(self, timeStart): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart # Scheduler headers writeLog("logs/ghadoop-scheduler.log", "# Waiting queue manager") def kill(self): print "Finishing waiting queue manager..." self.running = False def run(self): while self.running: change = False if len(waitingQueue)>0: submittedJobs = 0 threads = [] # Check if the time limit has been reach for waitingJob in list(waitingQueue): jobId = waitingJob[0] jobs = getJobs() job = jobs[jobId] if job.deadline!=None and job.deadline<=datetime.now(): # Check if all previous jobs are already finished prevJobFinished = True for prevJobId in job.prevJobs: if jobs[prevJobId].state != "SUCCEEDED": prevJobFinished = False if prevJobFinished: input = waitingJob[3] if getDebugLevel() >= 2: print "Waiting->Data: Job "+waitingJob[0]+" now="+str(datetime.now())+" deadline="+str(job.deadline) writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tWaiting->Data: Job "+waitingJob[0]+" now="+str(datetime.now())+" deadline="+str(job.deadline)+" input="+str(input)) # Change priority # jobId,0 # submitTime, 1 # command, 2 # input=None,3 # output=None,4 # priority=None 5 # (jobId, submit, command, input, output, priority) sWaitingJob = (waitingJob[0], waitingJob[1], waitingJob[2], waitingJob[3], waitingJob[4], "VERY_HIGH") thread = threading.Thread(target=submitJobHadoop,args=sWaitingJob) thread.start() threads.append(thread) waitingQueue.remove(waitingJob) submittedJobs += 1 change = True # Collect system information nodes = getNodes() offNodes = [] decNodes = [] onNodes = [] for nodeId in nodes: if nodes[nodeId][1]=="DOWN": offNodes.append(nodeId) elif nodes[nodeId][1]=="DEC": decNodes.append(nodeId) elif nodes[nodeId][1]=="UP": onNodes.append(nodeId) # Account tasks and jobs waiting in hadoop mapsHadoopWaiting = 0 mapsGHadoopWaiting = 0 numJobsWaiting = 0 for job in getJobs().values(): if job.state!="SUCCEEDED" and job.state!="FAILED" and len(job.tasks)>0: for taskId in job.tasks: task = tasks[taskId] if task.state!="SUCCEEDED" and taskId.find("_m_")>=0: mapsHadoopWaiting += 1 elif job.state=="DATA" or job.state=="PREP" or job.state=="RUNNING": # Default value for the number of tasks numJobTasks = len(getFilesInDirectories(job.input)) mapsHadoopWaiting += numJobTasks elif job.state=="WAITING": #mapsGHadoopWaiting += TASK_JOB numJobTasks = len(getFilesInDirectories(job.input)) mapsGHadoopWaiting += numJobTasks if job.state=="DATA" or job.state=="PREP" or job.state=="RUNNING": numJobsWaiting += 1 # Account maps slots mapsSlotsTotal = 0 mapsSlotsUsed = 0 for nodeId in onNodes: if nodes[nodeId][0]=="UP": mapsSlotsTotal += MAP_NODE if nodeId in nodeTasks: for taskId in nodeTasks[nodeId]: if taskId.find("_m_")>=0: mapsSlotsUsed += 1 mapsSlotsFree = mapsSlotsTotal - mapsSlotsUsed if mapsSlotsFree<0: mapsSlotsFree = 0 # Nodes that cannot or should not provide data unavailableNodes = list(chain(offNodes, decNodes)) # Account the number of extra nodes that would be required for data sortWaitingQueue = [] for waitingJob in list(waitingQueue): jobId = waitingJob[0] job = getJobs()[jobId] if job.deadline!=None and job.submit!=None and datetime.now() > (job.deadline - (job.deadline-job.submit)/2): sortWaitingQueue.append((jobId, 0)) else: input = waitingJob[3] # Get missing files from required files by job dataNodes = minNodesFiles(input, unavailableNodes) sortWaitingQueue.append((jobId, len(dataNodes))) sortWaitingQueue = sorted(sortWaitingQueue, key=itemgetter(1)) # Check if any job has all data available while len(sortWaitingQueue)>0 and sortWaitingQueue[0][1]==0 and numJobsWaiting<MAX_SUBMISSION: jobId = sortWaitingQueue.pop(0)[0] # Search job in the queue index = -1 for i in range(0, len(waitingQueue)): waitingJob = waitingQueue[i] if waitingJob[0] == jobId: index = i break if index>=0: # Check if all previous jobs are already finished jobs = getJobs() job =jobs[jobId] prevJobFinished = True for prevJobId in job.prevJobs: if jobs[prevJobId].state != "SUCCEEDED": prevJobFinished = False if prevJobFinished: # Job with no extra nodes required found waitingJob = waitingQueue[index] input = waitingJob[3] if getDebugLevel() >= 2: print "Waiting->Data: Job "+jobId+" has all data available input="+str(input) writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tWaiting->Data: Job "+waitingJob[0]+" has all data available "+str(input)) waitingQueue.remove(waitingJob) thread = threading.Thread(target=submitJobHadoop,args=waitingJob) thread.start() threads.append(thread) numJobsWaiting += 1 numJobTasks = len(getFilesInDirectories(input)) mapsHadoopWaiting += numJobTasks + 1 change = True #extraJobs = math.ceil(auxIdleNodes*TASK_NODE/TASK_JOB) #extraJobs -= submittedJobs if len(sortWaitingQueue)>0 and getDebugLevel() > 0: print "WaitingMaps="+str(mapsHadoopWaiting)+"+"+str(mapsGHadoopWaiting)+" Slots="+str(mapsSlotsFree)+"/"+str(mapsSlotsTotal)+" WaitingQueue="+str(len(waitingQueue))+" ["+str(sortWaitingQueue[0])+"...]" # Fill idle nodes TIMES_FULL = 3 while len(sortWaitingQueue)>0 and mapsHadoopWaiting<=TIMES_FULL*mapsSlotsTotal: if getDebugLevel() > 0: print "There are idle resources! waiting="+str(mapsHadoopWaiting)+" capacity="+str(mapsSlotsTotal)+" limit="+str(TIMES_FULL*mapsSlotsTotal) jobId = sortWaitingQueue.pop(0)[0] # Search job in the queue index = -1 for i in range(0, len(waitingQueue)): waitingJob = waitingQueue[i] if waitingJob[0] == jobId: index = i break if index>=0: # Choose the waiting job with less nodes required waitingJob = waitingQueue[index] waitingQueue.remove(waitingJob) jobId = waitingJob[0] input = waitingJob[3] # Check if all previous jobs are already finished jobs = getJobs() job =jobs[jobId] prevJobFinished = True for prevJobId in job.prevJobs: if jobs[prevJobId].state != "SUCCEEDED": prevJobFinished = False if prevJobFinished: if getDebugLevel() >= 2: print "Waiting->Data: there are idle resources to run job "+jobId+" input="+str(input) writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tWaiting->Data: there are idle resources to run job "+jobId+" input="+str(input)) # Select first job, it may bring other jobs thread = threading.Thread(target=submitJobHadoop,args=waitingJob) thread.start() threads.append(thread) numJobsWaiting += 1 numJobTasks = len(getFilesInDirectories(input)) mapsHadoopWaiting += numJobTasks + 1 change = True # Wait for everything to be submitted #while len(threads)>0: #threads.pop().join() if not change: queueSize = len(waitingQueue) # A maximum of 5 seconds waitTime = 5 checkTime = 0.5 for i in range(0, int(waitTime/checkTime)): time.sleep(checkTime) if queueSize != len(waitingQueue): break def flush(self): threads = [] while len(waitingQueue)>0: waitingJob = waitingQueue.pop() thread = threading.Thread(target=submitJobHadoop,args=waitingJob) thread.start() threads.append(thread) # Wait for everything to be submitted while len(threads)>0: threads.pop().join() def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import threading from ghadoopcommons import * # Logs the queue status at every moment class SchedulerLogger(threading.Thread): def __init__(self, timeStart): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart self.taskRunning = 0 self.taskSucceed = 0 # Scheduler headers writeLog("logs/ghadoop-scheduler.log", "# Queue logger") def getTasksRunning(self): return self.taskRunning def getTasksFinished(self): return self.taskSucceed def kill(self): self.running = False def run(self): while self.running: # Log number of jobs and tasks # Tasks taskWaiting = 0 taskData = 0 taskPending = 0 self.taskRunning = 0 self.taskSucceed = 0 taskUnknown = 0 for task in getTasks().values(): if task.state == "WAITING": taskWaiting += 1 elif task.state == "DATA": taskData += 1 elif task.state == "PREP": taskPending += 1 elif task.state == "RUNNING": self.taskRunning += 1 elif task.state == "SUCCEEDED": self.taskSucceed += 1 else: taskUnknown += 1 # Jobs jobWaiting = 0 jobData = 0 jobPending = 0 jobRunning = 0 jobSucceed = 0 jobFailed = 0 jobUnknown = 0 for job in getJobs().values(): if job.state == "WAITING": jobWaiting += 1 numJobTasks = len(getFilesInDirectories(job.input)) + 1 taskWaiting += numJobTasks elif job.state == "DATA": jobData += 1 numJobTasks = len(getFilesInDirectories(job.input)) + 1 taskData += numJobTasks elif job.state == "PREP": jobPending += 1 elif job.state == "RUNNING": jobRunning += 1 elif job.state == "SUCCEEDED": jobSucceed += 1 elif job.state == "FAILED": jobFailed += 1 else: jobUnknown += 1 writeLog("logs/ghadoop-scheduler.log", "%d\tQueues\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\tTasks\t%d\t%d\t%d\t%d\t%d\t%d\t%d" % (self.getCurrentTime(), jobWaiting, jobData, jobPending, jobRunning, jobSucceed, jobFailed, jobUnknown, jobWaiting+jobData+jobPending+jobRunning+jobSucceed+jobFailed, taskWaiting, taskData, taskPending, self.taskRunning, self.taskSucceed, taskUnknown, taskWaiting+taskData+taskPending+self.taskRunning+self.taskSucceed+taskUnknown)) time.sleep(2.0) def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) # Logs when tasks and jobs finish class JobLogger(threading.Thread): def __init__(self, timeStart): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart self.loggedTask = [] self.loggedJobs = [] #writeLog("logs/ghadoop-jobs.log", "# "+str(timeStart)+" Workload="+str(workloadFile)+" SlotLength="+str(SLOTLENGTH)+" TotalTime="+str(TOTALTIME)+" SchedEvent="+str(SCHEDULE_EVENT)+" SchedSlot="+str(SCHEDULE_SLOT)+" WorkloadGen="+str(WORKLOADGEN)) writeLog("logs/ghadoop-jobs.log", "# Deadline = "+str(DEADLINE)) writeLog("logs/ghadoop-jobs.log", "# t\tid\twork\tnode\tpriority\tsubmit\tstart\tend\twait\trun\ttotal") def getTasksFinished(): return len(self.loggedTask) def kill(self): self.running = False def run(self): while self.running: for task in getTasks().values(): if task.id not in self.loggedTask: if task.state == 'SUCCEEDED' and toSeconds(task.submit-self.timeStart)>=0: # Fixing missing data if task.submit==None: if task.start==None: if task.end==None: task.end=datetime.now() task.start=task.end task.submit=task.start if task.start==None: if task.end==None: task.end=datetime.now() task.start=task.end if task.end==None: task.end=datetime.now() # Task info t = self.getCurrentTime() submit = toSeconds(task.submit-self.timeStart) start = toSeconds(task.start-self.timeStart) end = toSeconds(task.end-self.timeStart) waittime = toSeconds(task.start-task.submit) runtime = toSeconds(task.end-task.start) totaltime = toSeconds(task.end-task.submit) priority = jobs[task.jobId].priority # Save job info if task.jobsetup: writeLog("logs/ghadoop-jobs.log", "%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\tJobSetup" % (t, task.id, task.jobId, task.node, priority, submit, start, end, waittime, runtime, totaltime)) else: writeLog("logs/ghadoop-jobs.log", "%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d" % (t, task.id, task.jobId, task.node, priority, submit, start, end, waittime, runtime, totaltime)) # Logged self.loggedTask.append(task.id) for job in getJobs().values(): if job.id not in self.loggedJobs: if job.state == 'SUCCEEDED' and toSeconds(job.submit-self.timeStart)>=0: # Fixing missing data if job.submit==None: if job.start==None: if job.end==None: job.end=datetime.now() job.start=job.end job.submit=job.start if job.start==None: if job.end==None: job.end=datetime.now() job.start=job.end if job.end==None: job.end=datetime.now() # Job info t = self.getCurrentTime() id = job.id.replace("job_","") submit = toSeconds(job.submit-self.timeStart) start = toSeconds(job.start-self.timeStart) end = toSeconds(job.end-self.timeStart) waittime = toSeconds(job.start-job.submit) runtime = toSeconds(job.end-job.start) totaltime = toSeconds(job.end-job.submit) priority = job.priority nodes = [] for taskId in job.tasks: task = getTasks()[taskId] nodeId = task.node if nodeId not in nodes: nodes.append(nodeId) # Save job info writeLog("logs/ghadoop-jobs.log", "%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d" % (t, job.id, id, str(sorted(nodes)), priority, submit, start, end, waittime, runtime, totaltime)) # Logged self.loggedJobs.append(job.id) elif job.state == 'FAILED' and toSeconds(job.submit-self.timeStart)>=0: t = self.getCurrentTime() id = job.id submit = -1 if job.submit != None: submit = toSeconds(job.submit-self.timeStart) priority = job.priority # Save job info writeLog("logs/ghadoop-jobs.log", "%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d" % (t, job.id, id, "-", priority, submit, -1, -1, -1, -1, -1)) # Logged self.loggedJobs.append(job.id) time.sleep(2.0) def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) # Logs when tasks and jobs finish class EnergyLogger(threading.Thread): def __init__(self, timeStart, data): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart self.data = data self.reqPower = 0.0 self.reqBrownPower = 0.0 self.reqGreenPower = 0.0 # Write log headers # Energy headers writeLog("logs/ghadoop-energy.log", "# set style fill solid") writeLog("logs/ghadoop-energy.log", "# plot \"testenergy\" using 1:7 lc rgb \"brown\" w boxes title \"Brown\", \"testenergy\" using 1:5 lc rgb \"green\" w boxes title \"Green\", \"testenergy\" using 1:2 w steps lw 3 lc rgb \"blue\" title \"Green availability\"") writeLog("logs/ghadoop-energy.log", "# "+str(self.timeStart)) writeLog("logs/ghadoop-energy.log", "# t\tgreen\tpredi\tbrown\trun nodes\tnodes\tgreenUse\tbrownUse\ttotalUse") writeLog("logs/ghadoop-energy.log", "0\t0.0\t0.0\t0.0\t0\t0\t0\t0.0\t0.0\t0.0") def getReqPower(self): return self.reqPower def getReqBrownPower(self): return self.reqBrownPower def getReqGreenPower(self): return self.reqGreenPower def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) def kill(self): self.running = False def run(self): while self.running: # Actual power (recalculate) reqPower = POWER_IDLE_GHADOOP # Check current nodes and number of tasks workNodes = 0 onNodes = 0 decNodes = 0 nodes = getNodes() for nodeId in nodes: up = nodes[nodeId] if up[0] == "UP" or up[1] == "UP": onNodes += 1 if nodeId in nodeTasks and len(nodeTasks[nodeId])>0: workNodes += 1 if len(nodeTasks[nodeId]) == 1: reqPower += Node.POWER_1JOB elif len(nodeTasks[nodeId]) == 2: reqPower += Node.POWER_2JOB elif len(nodeTasks[nodeId]) == 3: reqPower += Node.POWER_3JOB elif len(nodeTasks[nodeId]) >= 4: reqPower += Node.POWER_4JOB else: reqPower += Node.POWER_IDLE elif up[0] == "DEC" or up[1] == "DEC": decNodes += 1 reqPower += Node.POWER_IDLE else: reqPower += Node.POWER_S3 # Calculate used energy and power greenEnergyAvail = self.data.greenAvailArray[0] # Wh #greenEnergyPredi = self.data.greenPrediArray[4] # Wh greenEnergyPredi = self.data.greenPrediArray[4] # Wh greenEnergyPredi2 = self.data.greenPrediArray[1] # Wh greenEnergyPredi3 = self.data.greenPrediArray[5] # Wh greenEnergyPredi4 = self.data.greenPrediArray[12] # Wh brownEnergyPrice = self.data.brownPriceArray[0] # $/KWh # Accounting requireds brownReqPower = 0.0 if reqPower>0: greenPowerAvail = greenEnergyAvail if reqPower>greenEnergyAvail: greenReqPower = greenPowerAvail brownReqPower = reqPower-greenEnergyAvail else: greenReqPower = reqPower # Update information self.reqPower = reqPower self.reqBrownPower = brownReqPower self.reqGreenPower = greenReqPower writeLog("logs/ghadoop-energy.log", "%d\t%.2f\t%.2f\t%.5f\t%d\t%d\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f" % (self.getCurrentTime(), greenEnergyAvail, greenEnergyPredi, brownEnergyPrice, workNodes, onNodes, onNodes+decNodes, greenReqPower, brownReqPower, reqPower, greenEnergyPredi2, greenEnergyPredi3, greenEnergyPredi4)) time.sleep(2.0) # Last line in the log writeLog("logs/ghadoop-energy.log", "%d\t0.0\t0.0\t0.0\t0\t0\t0\t0.0\t0.0\t0.0" % (self.getCurrentTime())) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ # Power model for a crypt node class Node: POWER_S3 = 8.6 # Watts POWER_IDLE = 70.0 # Watts POWER_1JOB = 100.0 # Watts POWER_2JOB = 115.0 # Watts POWER_3JOB = 130.0 # Watts POWER_4JOB = 145.0 # Watts POWER_AVERAGE = POWER_4JOB POWER_FULL = POWER_4JOB # TimeValue class TimeValue: def __init__(self): self.t = None self.v = None def __init__(self, t, v): self.t = parseTime(t) self.v = v def __lt__(self, other): return parseTime(self.t)<parseTime(other.t) def __str__(self): return str(self.t)+" => "+str(self.v) # Job data structure class Job: def __init__(self, id=None, state="UNKNOWN", submit=None, start=None, end=None): self.id = id self.state = state # Date self.submit = submit # Date self.start = start # Date self.end = end # Date self.cmd = None self.input = None # Data: folder or file self.output = None # Data: folder or file self.priority = "NORMAL" self.deadline = None # Date self.durationMap = None # Seconds self.durationRed = None # Seconds self.tasks = [] # Ids # Workflow management self.workflow = None self.prevJobs = [] self.internalDeadline = None def __str__(self): out = "job_"+str(self.id)+"\t=> "+self.state+"\tSubmit="+str(self.submit)+"\tPriority="+str(self.priority) if self.end != None: out+=" End="+str(self.end) if self.submit != None and self.end != None: out += " Length="+toTimeString(toSeconds(self.end-self.submit)) if self.start != None and self.end != None: out += " ("+toTimeString(toSeconds(self.end-self.start))+")" return out # Task data structure class Task: def __init__(self, id=None, jobId= None, state="UNKNOWN", submit=None, start=None, end=None): self.id = id self.jobId = jobId self.state = state self.submit = submit self.start = start self.end = None self.node = None self.jobsetup = False def __str__(self): #out = str(self.id)+"("+str(self.jobId)+")\t=> "+self.state+"\tSubmit="+str(self.submit) out = str(self.id)+"\t=> "+self.state+"\tSubmit="+str(self.submit) if self.end != None: out+=" End="+str(self.end) if self.submit != None and self.end != None: out += " Length="+toTimeString(toSeconds(self.end-self.submit)) if self.start != None and self.end != None: out += " ("+toTimeString(toSeconds(self.end-self.start))+")" return out # Files data structure class FileHDFS: def __init__(self, id=None, dir=False): self.id = id self.dir = dir self.blocks = {} # isintance(object, class) def __str__(self): out = self.id return out def getLocation(self): # Get file location ret = [] for block in self.blocks.values(): if isinstance(block, FileHDFS): for nodeId in block.getLocation(): if nodeId not in ret: ret.append(nodeId) else: # Blocks for nodeId in block.nodes: if nodeId not in ret: ret.append(nodeId) return ret def getReplication(self): # Get file location ret = [] for block in self.blocks.values(): if isinstance(block, FileHDFS): for repl in block.getReplication(): if repl not in ret: ret.append(repl) else: if len(block.nodes) not in ret: ret.append(len(block.nodes)) return ret def getMaxReplication(self): ret = None for block in self.blocks.values(): if isinstance(block, FileHDFS): if ret==None or ret<block.getMaxReplication(): ret = block.getMaxReplication() else: if ret==None or ret>len(block.nodes): ret = len(block.nodes) if ret == None: ret = 1 return ret def getMinReplication(self): ret = None for block in self.blocks.values(): if isinstance(block, FileHDFS): if ret==None or ret>block.getMinReplication(): ret = block.getMinReplication() else: if ret==None or ret>len(block.nodes): ret = len(block.nodes) if ret == None: ret = 1 return ret def size(self): return len(self.blocks) def isDirectory(self): return self.dir def isInDirectory(self, dirPath): return self.id.startswith(dirPath) def isFile(self): return not self.dir class BlockHDFS: def __init__(self, id=None): self.id = id self.file = None self.nodes = [] # Time in/out management # Aux function to parse a time data def parseTime(time): ret = 0 if isinstance(time, str): aux = time.strip() if aux.find('d')>=0: index = aux.find('d') ret += 24*60*60*int(aux[0:index]) if index+1<len(aux): ret += parseTime(aux[index+1:]) elif aux.find('h')>=0: index = aux.find('h') ret += 60*60*int(aux[0:index]) if index+1<len(aux): ret += parseTime(aux[index+1:]) elif aux.find('m')>=0: index = aux.find('m') ret += 60*int(aux[0:index]) if index+1<len(aux): ret += parseTime(aux[index+1:]) elif aux.find('s')>=0: index = aux.find('s') ret += int(aux[0:index]) if index+1<len(aux): ret += parseTime(aux[index+1:]) else: ret += int(aux) else: ret = time return ret def toSeconds(td): ret = td.seconds ret += 24*60*60*td.days if td.microseconds > 500*1000: ret += 1 return ret # From time to string def toTimeString(time): surplus=time%1 time = int(time) ret = "" # Day aux = time/(24*60*60) if aux>=1.0: ret += str(int(aux))+"d" time = time - aux*(24*60*60) # Hour aux = time/(60*60) if aux>=1.0: ret += str(int(aux))+"h" time = time - aux*(60*60) # Minute aux = time/(60) if aux>=1.0: ret += str(int(aux))+"m" time = time - aux*(60) # Seconds if time>=1.0: ret += str(time)+"s" if ret == "": ret = "0" # Add surplus if surplus>0.0: ret+=" +%.2f" % (surplus) return ret def diffHours(dt1,dt2): sec1 = time.mktime(dt1.timetuple()) sec2 = time.mktime(dt2.timetuple()) return int((sec2-sec2)/3600) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ # bash: for file in `ls logs/`; do python ghadoopparser.py logs/$file/$file > logs/$file/$file-summary.log; done import sys import math from ghadoopcommons import * ALPHA = 0.8 PERIOD = 100 NUM_SAMPLE_TASKS = 300 LOG_ENERGY = "ghadoop-energy.log" LOG_JOBS = "ghadoop-jobs.log" LOG_SCHEDULER = "ghadoop-scheduler.log" if len(sys.argv)>1: LOG_ENERGY = sys.argv[1]+"-energy.log" LOG_JOBS = sys.argv[1]+"-jobs.log" LOG_SCHEDULER = sys.argv[1]+"-scheduler.log" # Read queue and calculate average prevLineSplit = None timeQueueSize = [] timeRunSize = [] avgSum = 0 avgTim = 0 for line in open(LOG_SCHEDULER, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") if lineSplit[1]=="Queues": lineSplit[0] = int(lineSplit[0]) current = lineSplit[0] taskW = int(lineSplit[11]) taskD = int(lineSplit[12]) taskP = int(lineSplit[13]) taskR = int(lineSplit[14]) taskSum = taskW + taskD + taskP + taskR if len(timeQueueSize)>0 and timeQueueSize[len(timeQueueSize)-1][0]==current: timeQueueSize[len(timeQueueSize)-1] = (current, taskSum) else: timeQueueSize.append((current, taskSum)) if len(timeRunSize)>0 and timeRunSize[len(timeRunSize)-1][0]==current: timeRunSize[len(timeRunSize)-1] = (current, taskR) else: timeRunSize.append((current, taskR)) if prevLineSplit != None: #t = (lineSplit[0]-prevLineSplit[0])/3600.0 t = (lineSplit[0]-prevLineSplit[0]) avgSum += taskSum avgTim += t #print str(t)+" "+str(lineSplit)+" queues="+str(taskSum) #print str(t)+" "+str(taskSum) prevLineSplit = lineSplit avgQueue = int(round(avgSum/avgTim)) print "Average queue size = "+str(avgQueue) # Read energy file, line by line timePower = [] for line in open(LOG_ENERGY, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[9] = float(lineSplit[9]) # Total use t = lineSplit[0] #t = (lineSplit[0]-prevLineSplit[0])/3600.0 timePower.append((t, lineSplit[9])) # Read job file timeTasks = [] for line in open(LOG_JOBS, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # TaskId lineSplit[2] = lineSplit[2] # JobId lineSplit[3] = lineSplit[3] # Node lineSplit[4] = lineSplit[4] # Priority lineSplit[5] = int(lineSplit[5]) # Submit lineSplit[6] = int(lineSplit[6]) # Start lineSplit[7] = int(lineSplit[7]) # End lineSplit[8] = int(lineSplit[8]) # Wait lineSplit[9] = int(lineSplit[9]) # Run lineSplit[10] = int(lineSplit[10]) # Total #if not lineSplit[3].startswith("['") and lineSplit[1].find("_m_")>0: if not lineSplit[3].startswith("['"): t = lineSplit[0] timeTasks.append((t, lineSplit)) # Output PERIOD = 100 print "Information in periods of "+str(PERIOD)+" seconds" print "Start\tEnd\tTasks\tWh\tWh/Task\tTask/s\tQueue\tWh/Task" for i in range(0, 7200/PERIOD): t = i*PERIOD tnext = (i+1)*PERIOD # Task tasks = 0 for tv in timeTasks: if t<=tv[0] and tv[0]<tnext: tasks+=1 if tnext<=tv[0]: break # Energy energy = 0 prevT = 0 for tv in timePower: if t<=tv[0] and tv[0]<tnext: power = tv[1] period = tv[0]-prevT energy += power * period/3600.0 prevT = tv[0] # Queue queueSize = 0 num = 0 for tv in timeQueueSize: if tv[0]>=t and tv[0]<tnext: num += 1 queueSize += tv[1] avgQueueSize = 0 if num>0: avgQueueSize = float(queueSize)/num # Compute with queue size reft = t # Time to complete queue compQueue = 0 auxAvgQueueSize = avgQueueSize for tv in timeTasks: if tv[0]>=reft: auxAvgQueueSize -= 1 if auxAvgQueueSize<0: break compQueue = tv[0]-reft # Energy to complete queue tasks2 = 0 for tv in timeTasks: if tv[0]>=reft and tv[0]<(reft+compQueue): tasks2+=1 if tv[0]>=(reft+compQueue): break energy2 = 0 prevT = 0 for tv in timePower: if tv[0]>=reft and tv[0]<(reft+compQueue): power = tv[1] period = tv[0]-prevT energy2 += power * period/3600.0 prevT = tv[0] # Energy per task energyTask = 0 if tasks>0: energyTask = energy/tasks energyTask2 = 0 if tasks2>0: energyTask2 = float(energy2)/tasks2 #print "%d\t%d\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d" % (t, tnext, tasks, energy, energyTask, 1.0*tasks/PERIOD, avgQueueSize, energyTask2, energy2, tasks2) print "%d\t%d\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f" % (t, tnext, tasks, energy, energyTask, 1.0*tasks/PERIOD, avgQueueSize, energyTask2) #numRunTasks = 0 #for tv in timeRunSize: #if t<tv[0]: #break #numRunTasks = tv[1] #numTasks = 0 #for tv in timeQueueSize: #if t<tv[0]: #break #numTasks = tv[1] #power = 0 #for tv in timePower: #if t<tv[0]: #break #power = tv[1] #print str(t)+"\t"+str(numRunTasks)+"\t"+str(numTasks)+"\t"+str(power) energy = 0.0 prevT = 0 for tv in timePower: power = tv[1] period = tv[0]-prevT energy += power * period/3600.0 prevT = tv[0] print "Summary:" print "Tasks: "+str(len(timeTasks)) print "Energy: "+str(energy)+"Wh" print "Energy/Task: %.3f Wh/task" % (energy/len(timeTasks)) sys.exit(0) # Read job file output = [] tasks = [] prevTasks = [] tasksPeriod = [] numTotalTasks = 0 sumPeriod = 0 totPeriod = 0 for line in open(LOG_JOBS, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # TaskId lineSplit[2] = lineSplit[2] # JobId lineSplit[3] = lineSplit[3] # Node lineSplit[4] = lineSplit[4] # Priority lineSplit[5] = int(lineSplit[5]) # Submit lineSplit[6] = int(lineSplit[6]) # Start lineSplit[7] = int(lineSplit[7]) # End lineSplit[8] = int(lineSplit[8]) # Wait lineSplit[9] = int(lineSplit[9]) # Run lineSplit[10] = int(lineSplit[10]) # Total #if not lineSplit[3].startswith("['") and lineSplit[1].find("_m_")>0: if not lineSplit[3].startswith("['"): jobId = lineSplit[2] t = lineSplit[0] numTotalTasks += 1 tasks.append(lineSplit) while len(tasks)>avgQueue: prevTasks.append(tasks.pop(0)) # Filling previous tasks while len(prevTasks)>NUM_SAMPLE_TASKS: prevTasks.pop(0) avgEnergyQueue = 0 t0 = t if len(tasks)==avgQueue: # Calculate period start = tasks[0][0] end = tasks[len(tasks)-1][0] # Calculate energy in that period avgSum = 0 prevValue = None for i in range(0, len(timePower)): if timePower[i][0]>=start and timePower[i][0]<=end: if prevValue!= None: t = (timePower[i][0] - prevValue[0])/3600.0 # hours e = prevValue[1]*t # Watts * hour avgSum += e # Wh prevValue = timePower[i] avgEnergyQueue = avgSum/len(tasks) avgEnergyPrevQueue = 0 if len(prevTasks)==NUM_SAMPLE_TASKS: # Calculate prev period start = prevTasks[0][0] end = prevTasks[len(prevTasks)-1][0] # Calculate energy in that period avgSum = 0 prevValue = None for i in range(0, len(timePower)): if timePower[i][0]>=start and timePower[i][0]<=end: if prevValue!= None: t = (timePower[i][0] - prevValue[0])/3600.0 # hours e = prevValue[1]*t # Watts * hour avgSum += e # Wh prevValue = timePower[i] avgEnergyPrevQueue = avgSum/len(prevTasks) #print "%d\t%.2f\t%.2f\t%.2f" % (t0, avgEnergyQueue, avgEnergyPrevQueue, avgEnergyPrevQueue-avgEnergyQueue) if len(output)>0 and output[len(output)-1][0] == t0: output[len(output)-1] = (t0, avgEnergyQueue, avgEnergyPrevQueue) else: output.append((t0, avgEnergyQueue, avgEnergyPrevQueue)) prevLine = None total1 = 0 total2 = 0 totalD = 0 totalN = 0 for v in output: if prevLine != None: if v[1]>0 and v[2]>0: period = v[0]-prevLine[0] total1 += v[1]*period total2 += v[2]*period dif = 100*(v[1]-v[2])/v[1] if dif<0: dif = -dif totalD += dif*period totalN += period #print "%d\t%.2f\t%.2f\t%.2f" % (v[0], v[1], v[2], v[1]-v[2]) prevLine = v print "%.2f %.2f %.2f / %.2f = %.2f%% " % (total1, total2, totalD, totalN, totalD/totalN) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ from datetime import datetime,timedelta import sys sys.path.append(GREEN_PREDICTOR) import model_cloudy,setenv dateHighHigh = datetime(2011, 5, 9, 0, 0, 0) # Fewer energy OK dateHighMed = datetime(2011, 5, 12, 0, 0, 0) # Worst for us dateMedHigh = datetime(2011, 6, 14, 0, 0, 0) # Worst for u dateMedMed = datetime(2011, 6, 16, 0, 0, 0) # More energy baseDate = dateHighHigh TOTALTIME = 60*60 speedup = 24 ep = model_cloudy.CachedEnergyPredictor(baseDate, predictionHorizon=(TOTALTIME*speedup/3600), path=GREEN_PREDICTOR, threshold=2, scalingFactor=2375, useActualData=True, error_exit=model_cloudy.normal) #ep = model_cloudy.CachedEnergyPredictor(BASE_DATE,predictionHorizon=TOTALTIME/3600,path='./greenavailability',threshold=2, scalingFactor=MAX_POWER,scalingBase=BASE_POWER,error_exit=exitType) # Threshold = 2hour; date = baseDate + timedelta(seconds=0) prediction, flag = ep.getGreenAvailability(date, int(TOTALTIME*speedup/3600)) # 48h print prediction<file_sep>#!/usr/bin/python #import os,sys,time from datetime import datetime,timedelta, date import os,re,sys,glob,os.path,time,getopt, string import tempfile #import getWeatherPrediction #from datetime import datetime,timedelta locations = ["nj", "nyc", "Boston", "atlantic", "phily", "DC", "Pittsburgh", "Charlotte", "Orlando", "Miami", "Cleveland", "Atlanta", "Indianapolis", "Nashville", "Mobile", "Chicago", "St_louis", "Memphis", "New_Orleans", "Minneapolis", "Kansas_city", "Grand_forks", "Lincoln", "Dallas", "Houston", "Austin", "Glasgow", "Casper", "Denver", "Salt_lake_city", "Spokane", "Seattle", "Las_vegas", "la", "sf"] zipcodes = {'nj':'08854', 'nyc':'10010', 'Boston':'02120', 'atlantic':'08401', 'phily':'10110', 'DC':'20010', 'Pittsburgh':'15210', 'Charlotte':'28210', 'Orlando':'32820', 'Miami':'33010', 'Cleveland':'61241', 'Atlanta':'30310', 'Indianapolis':'46220', 'Nashville':'37210', 'Mobile':'36610', 'Chicago':'60610', 'St_louis':'63110', 'Memphis':'38120', 'New_Orleans':'70130', 'Minneapolis':'55410', 'Kansas_city':'66101', 'Grand_forks':'58201', 'Lincoln':'68510', 'Dallas':'75210', 'Houston':'77010', 'Austin':'78710', 'Glasgow':'549230', 'Casper':'82630', 'Denver':'80210', 'Salt_lake_city':'84120', 'Spokane':'99201', 'Seattle':'98110', 'Las_vegas':'89110', 'la':'90010', 'sf':'94110'} #locations = ["nj"] #locations = ["epfl","wa","nj"] #urls = { # 'nj':'http://www.weather.com/weather/hourbyhour/08854', #} #timezones = { # 'nj':'US/Eastern', #} timezones = { 'nj':'US/Eastern', 'nyc':'US/Eastern', 'Boston':'US/Eastern', 'atlantic':'US/Eastern', 'phily':'US/Eastern', 'DC':'US/Eastern', 'Pittsburgh':'US/Eastern', 'Charlotte':'US/Eastern', 'Orlando':'US/Eastern', 'Miami':'US/Eastern', 'Cleveland':'US/Eastern', 'Atlanta':'US/Eastern', 'Indianapolis':'US/Eastern', 'Nashville':'US/Central', 'Mobile':'US/Central', 'Chicago':'US/Central', 'St_louis':'US/Central', 'Memphis':'US/Central', 'New_Orleans':'US/Central', 'Minneapolis':'US/Central', 'Kansas_city':'US/Central', 'Grand_forks':'US/Central', 'Lincoln':'US/Central', 'Dallas':'US/Central', 'Houston':'US/Central', 'Austin':'US/Central', 'Glasgow':'US/Mountain', 'Casper':'US/Mountain', 'Denver':'US/Mountain', 'Salt_lake_city':'US/Mountain', 'Spokane':'US/Pacific', 'Seattle':'US/Pacific', 'Las_vegas':'US/Pacific', 'la':'US/Pacific', 'sf':'US/Pacific' } weekdays={ 'Monday':0, 'Tuesday':1, 'Wednesday':2, 'Thursday':3, 'Friday':4, 'Saturday':5, 'Sunday':6 } conditions = { 'mostly sunny': 2, 'mostly sunny / wind': 2, 'mostly sunny/wind': 2, 'sunny': 1, 'sunny / wind': 1, 'sunny/wind': 1, 'sunny and windy': 1, 'clear': 1, 'clear / wind': 1, 'clear/wind': 1, 'mostly clear': 2, 'mostly clear / wind': 2, 'mostly clear/wind': 2, 'fair': 3, 'fair and windy': 3, 'partly cloudy': 4, 'partly cloudy / wind': 4, 'partly cloudy and windy': 4, 'partly cloudy/wind': 4, 'flurries': 5, 'flurries / wind': 5, 'flurries/wind': 5, 'mostly cloudy': 6, 'mostly cloudy / wind': 6, 'mostly cloudy and windy': 6, 'mostly cloudy/wind': 6, 'few showers': 7, 'light freezing rain': 7, 'light freezing rain/sleet': 7, 'light rain': 7, 'light rain and fog': 7, 'light rain and freezing rain': 7, 'light rain and windy': 7, 'light rain with thunder': 7, 'light rain/fog': 7, 'light rain/wind': 7, 'light rain / wind': 7, 'light sleet': 7, 'light wintry mix': 7, 'rain / thunder / wind' : 7, 'rain / thunder': 7, 'rain / wind': 8, 'rain/wind': 8, 'rain': 8, 'rain and freezing rain': 8, 'rain shower': 8, 'showers': 8, 'wintry mix': 8, 'few snow showers': 9, 'few snow showers / wind': 9, 'light snow': 9, 'light snow / wind': 9, 'light snow and fog': 9, 'light snow and windy': 9, 'light snow shower': 9, 'rain and snow': 9, 'rain / snow showers': 9, 'cloudy': 10, 'cloudy / wind': 10, 'cloudy and windy': 10, 'cloudy/wind': 10, 'snow': 11, 'snow / wind': 11, 'snow and fog': 11, 'snow shower': 11, 'snow shower / wind': 11, 'snow/blowing snow': 11, 'snow/wind': 11, 'drizzle and fog': 12, 'fog': 12, 'foggy': 12, 'haze': 12, 'heavy rain': 13, 'heavy rain / wind': 13, 'heavy t-storm': 7, 'heavy t-storms': 7, 'isolated t-storms': 7, 'isolated t-storms / wind': 7, 'scattered strong storms': 7, 'scattered strong storms / wind': 7, 'scattered t-storms': 7, 'scattered thunderstorms': 7, 'scattered t-storms / wind': 7, 'squalls': 7, 'squalls and windy': 7, 'strong storms': 7, 'strong storms / wind': 7, 't-showers': 8, 't-storm': 7, 't-storms': 7, 'thunder': 7, 'thunder in the vicinity': 7, 'blizzard': 13, 'blowing snow and windy': 13, 'heavy snow': 13, 'heavy snow / wind': 13 } format = '%b_%d_%Y_%H_%M' #currentDate = None dayFormat = "%b_%d_%Y" class TemperatureRecord: def __init__(self,time,filename,line): self.time = time self.filename = filename self.line = line def setCondition(self,cond): if not hasattr(self, 'condition'): self.condition=cond def setTemp(self, temp): if not hasattr(self, 'temp'): self.temp = temp def setFeelLike(self, feelLike): if not hasattr(self, 'feelLike'): self.feelLike = feelLike def setHumidity(self,hum): if not hasattr(self, 'humidity'): self.humidity = hum def setPrecipation(self,pre): if hasattr(self, 'precipitation'): print self.precipitation if not hasattr(self, 'precipitation'): self.precipation = pre def setWind(self,direction,speed, fout): if not hasattr(self, 'direction'): self.direction=direction self.speed = speed #print str(self) fout.write(str(self)+"\n") def check(self): try: a = self.direction a = self.speed a = self.condition a = self.feelLike a = self.temp a = self.time except AttributeError: print "bad time",self.time,self.filename raise def __str__(self): outFormat = "%Y_%m_%d_%H"#"%A_%H" try: return "%s\t%d\t%d\t%d\t%s\t%d\t%s\t%d"%(self.time.strftime(outFormat),self.temp,self.feelLike,self.humidity,self.condition,self.precipation,self.direction,self.speed) except AttributeError: print "bad",self.time,self.filename,self.line raise def getTime(self): return time.mktime(self.time.timetuple()) class OneDayRecords: def __init__(self): self.map = {} # def __init__(self,day): # self.day = day # self.init() def append(self,record): if not self.map.has_key(record.time.hour): self.map[record.time.hour] = record def getRecords(self): #print self.map.values() return self.map.values() def getRecords(filename, fout, no_line=48): #global currentDate #no_line *= 4 #we decrease it later at some pattern, the patter occures 4 times per hour fd = open(filename,"r") hbhDateHeaderRe = re.compile("<div class=\"hbhDateHeader\">(.*?)</div>") #<div class="hbhTDTime"><div>3 am</div></div> hbhTDTimeRe = re.compile("<div class=\"hbhTDTime\"><div>(\d+ .*?)</div></div>") hbhTDConditionRe = re.compile("<div class=\"hbhTDCondition\"><div><b>(-?\d+).*?</b><br>(.*?)</div></div>") hbhTDFeelsRe =re.compile("<div class=\"hbhTDFeels\"><div>(-?\d+).*?</div></div>") # <div class="hbhTDPrecip"><div>20%</div></div> # hbhTDPrecipRe = re.compile("<div class=\"hbhTDPrecip\"><div>(\d+?)%</div></div>") hbhTDHumidityRe=re.compile("<div class=\"hbhTDHumidity\"><div>(\d+)%</div></div>") hbhTDPrecipRe = re.compile('<div class="hbhTDPrecip"><div>(\d+)%</div></div>') # hbhTDConditionRe= re.compile('<div class="hbhTDConditionIcon"><div><img src="http://i.imwx.com/web/common/wxicons/45/gray/28.gif" alt="Mostly Cloudy" width="45" height="45" border="0"></div></div>' hbhTDWindRe = re.compile('<div class="hbhTDWind"><div>From (.*?)<br> (\d+) mph</div></div>') hbhTDWindRe2 = re.compile('<div class="hbhTDWind"><div>(.*?)</div></div>') currentRecord = None state = -1 records = OneDayRecords() for line in fd: line = line.strip() if not line: continue result = hbhDateHeaderRe.search(line) if result: currentDate = result.group(1) #print currentDate continue result = hbhTDTimeRe.search(line) if result: datetimeString = currentDate+" "+result.group(1) #print filename, datetimeString timeTuple = time.strptime(datetimeString,"%A, %B %d %I %p") #if state == -1: #if timeTuple.tm_hour == 0: # state = 1 #else: # state =0 currentTime = datetime(2011,timeTuple.tm_mon,timeTuple.tm_mday,timeTuple.tm_hour) if state == -1: state = 0 if timeTuple.tm_hour == 0: currentTime += timedelta(days=1) #currentTime.year if not currentRecord==None: try: currentRecord.check() except AttributeError: print 'bad filename',filename raise currentRecord = TemperatureRecord(currentTime,filename,line) records.append(currentRecord) continue if not currentRecord: continue result = hbhTDConditionRe.search(line) if result: temp = int(result.group(1)) currentRecord.setTemp(temp) condition = result.group(2) currentRecord.setCondition(condition) continue result = hbhTDFeelsRe.search(line) if result: temp = int(result.group(1)) currentRecord.setFeelLike(temp) continue result = hbhTDHumidityRe.search(line) if result: hum = int(result.group(1)) currentRecord.setHumidity(hum) continue result = hbhTDPrecipRe.search(line) if result: precipation = int(result.group(1)) currentRecord.setPrecipation(precipation) continue result = hbhTDWindRe.search(line) if result: direction = result.group(1) speed = int(result.group(2)) #self.map.values() currentRecord.setWind(direction,speed, fout) if no_line<=1: return no_line -= 1 #print no_line," 1st", str(currentRecord) continue result = hbhTDWindRe2.search(line) if result: direction = result.group(1) speed = 0 currentRecord.setWind(direction,speed, fout) if no_line<=1: return no_line -= 1 #print no_line," 2nd", str(currentRecord) continue # if not stripedLine: # continue # line = re.sub(r'\n','',line) # line = line.lower() # r = badRe.search(line) # # if r: # badLineFd.write(line) # continue # html+=stripedLine return records.getRecords() def fromDirToTime(x): return int(time.mktime(time.strptime(os.path.basename(x), getWeatherPrediction.format))) def getRecordsFromDir(dirname,location): files = glob.glob(os.path.join(dirname,location)+"*") files.sort() records = [] for f in files: fd = open(f,'r') try: r = getRecords(fd,f) records.extend(r) except AttributeError: print "bad file",f raise fd.close() return records def long_substr(allstr, newstr): maxkey = allstr[0] maxlen = 0 if len(allstr) > 0 and len(newstr) > 0: #print len(allstr) for k in range(len(allstr)): #print k #print allstr[k] for i in range(len(allstr[k])): for j in range(len(newstr)): for l in range(maxlen,len(newstr)-j): #print l, maxlen if string.find(allstr[k][i:i+l],newstr[j:j+l])!=-1: maxlen = l maxkey = allstr[k] #break #print maxlen return maxkey def convertdate(line, date, h): #print line list1 = line.split("\t") #dd = datetime(date.year,date.month,date.day,date.hour)+timedelta(hours=h) day = weekdays[list1[0].split("_")[0]] hour = int(list1[0].split("_")[1]) sday = ((day+7)-date.weekday())%7 dd = datetime(date.year,date.month,date.day,hour)+timedelta(days=sday) #print date.weekday(),day,sday str1 = datetime.strftime(dd,"%Y_%m_%d_%H") for j in range(1,len(list1)): str1 += "\t"+list1[j] #str1 += "\n" #print str1, date return str1 def conandretdate(line, date, h): #print line list1 = line.split("\t") #dd = datetime(date.year,date.month,date.day,date.hour)+timedelta(hours=h) day = weekdays[list1[0].split("_")[0]] hour = int(list1[0].split("_")[1]) sday = ((day+7)-date.weekday())%7 dd = datetime(date.year,date.month,date.day,hour)+timedelta(days=sday) #print date.weekday(),day,sday str1 = datetime.strftime(dd,"%Y_%m_%d_%H") for j in range(1,len(list1)): str1 += "\t"+list1[j] #str1 += "\n" #print str1 return str1, dd def readforecastpiscataway(fout, d, no_hours, path): d -= timedelta(hours=1) dd = datetime(d.year,d.month,d.day,d.hour,19) piscatapred = path+"/htmlcache/"+datetime.strftime(dd,"%b_%d_%Y_%H_%M") #print piscatapred if os.path.isdir(piscatapred): #print piscatapred+"/nj.0" if os.path.isfile(piscatapred+"/nj.0"): #print piscatapred getRecords(piscatapred+"/nj.0", fout, 1) else: return 0 dd += timedelta(hours=1) piscatapred = path+"/htmlcache/"+datetime.strftime(dd,"%b_%d_%Y_%H_%M") #print piscatapred if os.path.isdir(piscatapred): if os.path.isfile(piscatapred+"/nj.0"): getRecords(piscatapred+"/nj.0", fout, 1) else: return 0 dd += timedelta(hours=1) piscatapred = path+"/htmlcache/"+datetime.strftime(dd,"%b_%d_%Y_%H_%M") #print piscatapred if os.path.isdir(piscatapred): if os.path.isfile(piscatapred+"/nj.0"): getRecords(piscatapred+"/nj.0", fout, 1) else: return 0 rest_hour = no_hours-1 dd += timedelta(hours=1) piscatapred = path+"/htmlcache/"+datetime.strftime(dd,"%b_%d_%Y_%H_%M") #print piscatapred if os.path.isdir(piscatapred): for i in range(0,4): #print piscatapred+"/nj.%d"%i if os.path.isfile(piscatapred+"/nj.%d"%i): #getRecords(piscatapred+"/nj.%d"%i, fout, 12) getRecords(piscatapred+"/nj.%d"%i, fout) rest_hour -= 12 else: return 0 if rest_hour > 0: print "We dont have more than 48 hours of prediction" raise Exception() sys.exit(1) return 1 def readforecastprinceton(fout, d, hours, path): d -= timedelta(hours=1) princepred = path+"/htmlcache/"+datetime.strftime(d,"%b_%d_%Y") princepred += "/%d"%d.hour if os.path.isfile(princepred): f1 = open(princepred,'r') lines = f1.readlines() fout.write(convertdate(lines[0],d,1)) #fout.write(lines[1]) else: #print "Prediction file missing ", princepred #sys.exit(1) return 0 #files are not there f1.close() d += timedelta(hours=1) princepred = path+"/htmlcache/"+datetime.strftime(d,"%b_%d_%Y") princepred += "/%d"%d.hour if os.path.isfile(princepred): f1 = open(princepred,'r') lines = f1.readlines() fout.write(convertdate(lines[0],d,1)) #fout.write(lines[1]) else: print "Prediction file missing ", princepred sys.exit(1) f1.close() d += timedelta(hours=1) princepred = path+"/htmlcache/"+datetime.strftime(d,"%b_%d_%Y") princepred += "/%d"%d.hour if os.path.isfile(princepred): f1 = open(princepred,'r') lines = f1.readlines() #print princepred fout.write(convertdate(lines[0],d,1)) #fout.write(lines[1]) else: print "Prediction file missing ", princepred sys.exit(1) f1.close() resthour = hours-1 d += timedelta(hours=1) predfor = d+timedelta(hours=1) while resthour>0: princepred = path+"/htmlcache/"+datetime.strftime(d,"%b_%d_%Y") if os.path.isdir(princepred): princepred += "/%d"%d.hour if os.path.isfile(princepred): #print princepred, predfor f1 = open(princepred,'r') i = 1 for line in f1: if resthour > 0: wrtdata, tempdate = conandretdate(line,d,i) #print tempdate, princepred if tempdate==predfor: fout.write(wrtdata) predfor += timedelta(hours=1) resthour -= 1 i += 1 elif tempdate>predfor: print resthour, d, predfor resthour=0 break #if resthour <= 0: # break f1.close() else: print "Prediction file missing ", princepred sys.exit(1) else: print "Prediction file missing",princepred sys.exit(1) d += timedelta(hours=1) #print d.weekday() return 1 def process(date, hours, path,shiftFactor): #global fout fout = tempfile.TemporaryFile()#open("full_fore.txt","w") loc = 'nj' url = "http://www.weather.com/weather/hourbyhour/"+zipcodes[loc] #urls[loc] tz = timezones[loc] os.environ['TZ'] = tz time.tzset() #delta = timedelta(hours=12) #for i in range(4): # t = d.timetuple() #cmd = 'wget -O temp.%d -o /dev/null "%s?begHour=%d&begDay=%d"'%(i,url,t.tm_hour,t.tm_yday) # htmlFile = path+"/htmlcache/%s_%d_%d_%d_%d.html"%(loc,d.year,d.month,d.day,d.hour) # if not os.path.isfile(htmlFile): # cmd = 'wget -O %s -o /dev/null "%s?begHour=%d&begDay=%d"'%(htmlFile,url,t.tm_hour,t.tm_yday) # os.system(cmd) # getRecords(htmlFile, fout) # print cmd # d += delta #fout.close() d = datetime(date.year,date.month,date.day,date.hour) - timedelta(hours=shiftFactor) status = readforecastprinceton(fout, d, hours, path) if status==0: #print d, hours status = readforecastpiscataway(fout, d, hours, path) if status==0: print "No forecats found" sys.exit(1) finp = fout#open("full_fore.txt","r") finp.seek(0) fout = tempfile.TemporaryFile()#open("fore.txt","w") count = 0 for line in finp.readlines(): #print line.strip() if conditions.has_key(line.split("\t")[4].lower()): tagint = conditions[line.split("\t")[4].lower()] else: print "key missing", line.split("\t")[4].lower() tagint = conditions[long_substr(conditions.keys(),line.split("\t")[4].lower())] str1 = line.split("\t")[0]+"\t"+line.split("\t")[4]+"\t"+`tagint` fout.write(str1+"\n") count += 1 if count == hours+shiftFactor: break finp.close() #fout.close() fout.seek(0) return fout if __name__ == '__main__': dirname = time.strftime(format) #os.mkdir(dirname) delta = timedelta(hours=12) for loc in locations: url = "http://www.weather.com/weather/hourbyhour/"+zipcodes[loc] #urls[loc] tz = timezones[loc] os.environ['TZ'] = tz time.tzset() d = datetime.now() for i in range(4): t = d.timetuple() cmd = 'wget -O %s/%s.%d -o /dev/null "%s?begHour=%d&begDay=%d"'%(dirname,loc,i,url,t.tm_hour,t.tm_yday) #os.system(cmd) # print cmd d += delta <file_sep>#!/usr/bin/python import sys,os modPath = "." def init(): global modPath for p in sys.path: p = os.path.realpath(p) if p.endswith('greenavailability'): modPath=p <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import threading import time from datetime import datetime,timedelta from optparse import OptionParser from itertools import * from ghadoopcommons import * from ghadooplogger import * from ghadoopwaiting import * from ghadoopreplication import * from ghadoopmonitor import * from ghdfsmonitor import * from ghadoop import * def minNodesFilesNew(checkFiles, offNodes): startaux = datetime.now() # Input checkFiles = getFilesInDirectories(checkFiles) auxOffNodes = list(offNodes) # Get which files are missing and which nodes have them missingFiles = [] missingNodes = {} for fileId in checkFiles: file = files[fileId] locations = file.getLocation() if len(locations)>0 and fileId not in missingFiles: # Check if the file is missing missing = True for nodeId in locations: if nodeId not in auxOffNodes: missing=False break if missing: missingFiles.append(fileId) # Check where is the file for nodeId in locations: if nodeId in auxOffNodes: if nodeId not in missingNodes: missingNodes[nodeId]=0 missingNodes[nodeId]+=1 # Check nodes with missing files auxMissingNodes = [] for nodeId in missingNodes: auxMissingNodes.append((nodeId, missingNodes[nodeId])) missingNodes = sorted(auxMissingNodes, key=itemgetter(1), reverse=True) if toSeconds(datetime.now()-startaux)>1: print "\t\t\t1:"+str(datetime.now()-startaux) # We need the minimum set of nodes that have the files required by a job dataNodes=[] # Checking if there is more files to check while len(missingFiles)>0: # Turn on the nodes with the replicas with more data in nodeId = missingNodes[0][0] auxOffNodes.remove(nodeId) dataNodes.append(nodeId) # Update which files are missing and which nodes have them missingFiles = [] missingNodes = {} for fileId in checkFiles: file = files[fileId] locations = file.getLocation() if len(locations)>0 and fileId not in missingFiles: # Check if the file is missing missing = True for nodeId in locations: if nodeId not in auxOffNodes: missing=False break if missing: missingFiles.append(fileId) # Check where is the file for nodeId in locations: if nodeId in auxOffNodes: if nodeId not in missingNodes: missingNodes[nodeId]=0 missingNodes[nodeId]+=1 # Check nodes with missing files auxMissingNodes = [] for nodeId in missingNodes: auxMissingNodes.append((nodeId, missingNodes[nodeId])) missingNodes = sorted(auxMissingNodes, key=itemgetter(1), reverse=True) if toSeconds(datetime.now()-startaux)>1: print "\t\t\t3:"+str(datetime.now()-startaux) # Remove those nodes that already have data on change = True while change: change = False for nodeId in dataNodes: free = True if nodeId in nodeFile: for fileId in nodeFile[nodeId]: if fileId in checkFiles and fileId in files: # Check if file is available somewhere else fileAvailable = False file = files[fileId] for otherNodeId in file.getLocation(): if otherNodeId!=nodeId and otherNodeId not in auxOffNodes: fileAvailable = True break if not fileAvailable: free = False break if free: auxOffNodes.append(nodeId) dataNodes.remove(nodeId) change = True break if toSeconds(datetime.now()-startaux)>1: print "\t\t\t4:"+str(datetime.now()-startaux) return dataNodes if __name__=='__main__': DEBUG = 0 print "Starting monitoring..." monitorHdfs = MonitorHDFS() monitorHdfs.start() print "Waiting for files to be monitored..." while len(files)==0: time.sleep(0.2) offNodes = [] for nodeId in getNodes(): if nodeId != "crypt15" and nodeId != "crypt07": offNodes.append(nodeId) #checkPath = ["/user/goiri/input-workload1-11", "/user/goiri/input-workload1-18", "/user/goiri/input-workload1-40", "/user/goiri/input-workload1-42", "/user/goiri/input-workload1-96", "/user/goiri/input-workload1-98"] checkPath = [] for i in range(1, 100): checkPath.append("/user/goiri/input-workload1-"+str(i).zfill(2)) for i in range(0, 1000): #timestart = datetime.now() #for path in checkPath: #dataNodes = minNodesFiles([path], offNodes) #if DEBUG>0: #print "\t"+str(path)+": "+str(len(getFilesInDirectories([path])))+" "+str(len(dataNodes)) #print "\tOld: "+str(datetime.now()-timestart) timestart = datetime.now() for path in checkPath: #dataNodes = minNodesFilesNew([path], offNodes) dataNodes = minNodesFilesNew([path], offNodes) if DEBUG>0: print "\t"+str(path)+": "+str(len(getFilesInDirectories([path])))+" "+str(len(dataNodes)) #print "\t\tNew: "+str(datetime.now()-timestart) print "\t"+str(i)+" New: "+str(datetime.now()-timestart) sys.exit(0) <file_sep>#!/usr/bin/python import os, fnmatch, tempfile, sys,os.path,pickle #import singledayweather import pastWeather, get_real_data #import datetime from datetime import timedelta, datetime princetonDataStart = datetime(year=2010,month=5,day=28) princetonDataEnd = datetime(year=2010,month=10,day=4) pisDataStart = datetime(year=2010,month=12,day=14) pisDataEnds = datetime.now() #error entering and exiting method enter_on_error = 2 #kept for backward compatibility #states normal_state = 0 track_state = 1 MAX_HOURS = 49 int_date_format = "%Y_%m_%d_%H" class PredictionProvider: def __init__(self,dataPath,shiftFactor): self.dataPath = dataPath self.shiftFactor = shiftFactor def getPredictions(self,date,hours): filepath = os.path.join(path,"proc_forecast",date.strftime(int_date_format)) if not os.path.isfile(filepath): print filepath," forecast missing" raise Exception() sys.exit(1) date = [] cloud_cov = [] actual = [] fh = open(os.path.join(self.datapath,filepath),'r') for line in fh: hour = int(list1[1]) sky_cond = float(int(list1[5]))/100.0 rain_pr = float(int(list1[4]))/100.0 fh.close() return date,cloud_cov,actual class ActualConditions(PredictionProvider): def __init__(self,dataPath): self.datapath = dataPath self.timeToCondition = {} def getPredictions(self,date,hours): conditions = self.getConditions(date, hours) foretag = [] foreweather = [] hour_pre = [] # shift = -1 #inp = open("fore.txt","r") for (d,c) in conditions: #print line #print line.split("\t")[5], line.split("\t")[15] #print int(line.split()[0].split("_")[-1]) # if shift == -1: # shift = int(line.split()[0].split("_")[-1]) # start = datetime.strptime(line.split()[0],"%Y_%m_%d_%H") foretag.append(int(c.conditionGroup)) foreweather.append(c.conditionString) hour_pre.append(d.hour) #day.append(line.split("\t")[4]) return foretag,foreweather,hour_pre def populateConditions(self,date,numberOfHours): retval = pastWeather.process(date,numberOfHours,self.datapath) # print "populate",date,numberOfHours self.timeToCondition.update(retval) def getConditionString(self,date): try: v = self.timeToCondition[date] except KeyError: self.populateConditions(date,24) try: v = self.timeToCondition[date] except KeyError: print date print self raise return v.conditionString def getConditions(self,start, num_hours): retval = [] tdelta = timedelta(hours=1) d = datetime(start.year,start.month,start.day,start.hour) for i in range(num_hours): # TODO there was a bug in here: you check the size and then you increase the number try: v = self.timeToCondition[d] except KeyError: self.populateConditions(d,num_hours-i) v = self.timeToCondition[d] retval.append((d,v)) d = d+tdelta #print len(retval) return retval def __str__(self): keys = self.timeToCondition.keys() keys.sort() retval = "" for k in keys: retval+="%s\t%s\n"%(str(k),str(self.timeToCondition[k])) return retval class EnergyProduction: def __init__(self,dataPath): self.dataPath = dataPath self.timeToEnergy = {} def populateEnergy(self,date): alldata = get_real_data.process(date, MAX_HOURS) tdelta = timedelta(hours=1) d = date for i in range(len(alldata)): if not self.timeToEnergy.has_key(d): self.timeToEnergy[d] = alldata[i] d = d+tdelta return def populateAllEnergy(self,date, num_hours): alldata = get_real_data.process(date, num_hours) tdelta = timedelta(hours=1) d = date for i in range(len(alldata)): self.timeToEnergy[d] = alldata[i] d = d+tdelta return def readPastProduction(self,start, num_hours): #print filepath retval = [] tdelta = timedelta(hours=1) d = datetime(start.year,start.month,start.day,start.hour) for i in range(num_hours): # TODO there was a bug in here: you check the size and then you increase the number try: v = self.timeToEnergy[d] except KeyError: self.populateAllEnergy(d, num_hours) v = self.timeToEnergy[d] retval.append(v) d = d+tdelta #print len(retval) return retval def getProduction(self,hour): d = hour try: v = self.timeToEnergy[d] except KeyError: self.populateEnergy(d) v = self.timeToEnergy[d] return v class EnergyPredictor(object): def __init__(self,path='.',threshold=3, scalingFactor=1347, offset=15, energythreshold=20, useActualData=False, scalingBase=1347,debugging=False,error_exit=enter_on_error): #energythreshold=20 means we assume two energy value to be same if within range of +-20 #global debug self.datapath = path self.scaling = scalingFactor/float(scalingBase) # self.scaling = scalingFactor / 1347.0 self.threshold = threshold self.offset = offset self.energythreshold = energythreshold self.pasttime = datetime(2000,01,01) self.pastresult = [] self.debugging = debugging self.debug = [] self.energyProduction = EnergyProduction(self.datapath) #self.shiftFactor = 2 self.shiftFactor = 0 self.actualConditions = ActualConditions(self.datapath) self.useActualData = useActualData self.error_exit = error_exit self.last_call_state = normal_state self.last_tag = 10 # 10 is an arbitrary number to start later we will change to be the last hour's cloud coverage if useActualData: self.weatherPredictor = self.actualConditions # print "using actual data" else: self.weatherPredictor = PredictionProvider(self.datapath,self.shiftFactor) # print "using predictions" self.lagerror = 1 self.base = [] self.basemonth = [] def getGreenAvailability(self, now, hours): result, actual = self.process(now, hours) result = map(lambda x:self.scaling * x, result) flag = False if len(self.pastresult)==0: flag = True elif self.pasttime + timedelta(hours=self.threshold) <= now: flag = True else: d = datetime(now.year,now.month,now.day,now.hour) lasttime = datetime(self.pasttime.year, self.pasttime.month, self.pasttime.day, self.pasttime.hour) j = 0 for i in range(len(self.pastresult)): if d==lasttime+timedelta(hours=i): if j<len(result) and result[j]==-1.0: result[j]=self.pastresult[i] if j<len(result) and abs(self.pastresult[i]-result[j])>self.energythreshold: flag = True break j += 1 d += timedelta(hours=1) if flag==True: self.pasttime = now self.pastresult = [] for i in range(len(result)): self.pastresult.append(result[i]) currentHour = datetime(now.year,now.month,now.day,now.hour) if not currentHour == now: result[0] = self.scaling * self.energyProduction.getProduction(currentHour) return result, flag def read_base(self,date): month = date.month if date.month==3: #handle daylight savings time if (date.day)<13: month = month-1 #if (date.day)>7 and (date.day)<14 and date.weekday()==6: #if (date.day)>14: # month = month+1 if date.month==11: #handle daylight savings time if (date.day)<6: month = month-1 #if (date.day)>7 and (date.day)<14 and date.weekday()==6: #if (date.day)>14: # month = month+1 if len(self.base)>0 and self.basemonth==month: return self.base[0:24], self.base[24] str1 = self.datapath+"/base/%d.txt"%(month) if not os.path.isfile(str1): print "base file missing "+str1 sys.exit(1) fd = open(str1,'r') basevalues = [0]*24 basetotal = 0 for line in fd: list1 = line.strip().split("\t") hour = int(list1[0]) basevalues[hour] = float(list1[1].strip()) basetotal += basevalues[hour] fd.close() self.base = basevalues self.base.append(basetotal) self.basemonth = month #print basevalues return basevalues,basetotal def read_cache(self,filename,call_date=0): if not os.path.isfile(filename): print "result file missing "+ filename fd = open(filename,'r') result = [] actual = [] i = 1 for line in fd: list1 = line.strip().split("\t") hour_diff = int(list1[0]) act_prod = float(list1[5]) pred = float(list1[6]) if i<hour_diff: while i<>hour_diff: result.append(-1.0) #-1 is denoting unknown value actual.append(-1.0) i +=1 if i==hour_diff: result.append(pred) actual.append(act_prod) fd.close() return result, actual def predict(self, list1, base, call_date=datetime(2011,03,03), fd=0, state_cc=0, state_new=0): retval1 = False hour = int(list1[1]) sky_cond = float(int(list1[5]))/100.0 rain_pr = float(int(list1[4]))/100.0 #print base, hour, list1[0] pred1 = base[hour]*(1-sky_cond) hour_diff_td = datetime.strptime(list1[0].strip(),"%Y_%m_%d_%H_%M")-call_date hour_diff = hour_diff_td.days*24+hour_diff_td.seconds/3600 pred_last = base[hour]*self.last_tag actual = float(list1[7]) diff1 = abs(pred1-actual) diff_last = abs(pred_last-actual) pred1_out = pred1 if state_cc==track_state: pred1_out = pred_last if fd<>0: print >>fd, hour_diff,"\t",list1[0],"\t",list1[5],"\t",list1[4],"\t",base[hour],"\t",actual,"\t",pred1_out if (diff1>diff_last): retval1 = True return retval1, hour_diff, base[hour] def predict_long(self,base, call_date, fr, fw): state1 = self.last_call_state for line in fr: list1 = line.strip().split("\t") #print fw," fw" flag, hour_diff, spec_base = self.predict(list1, base, call_date, fw, state1) if spec_base>100.0: if hour_diff<2: if flag: self.last_call_state = track_state else: self.last_call_state = normal_state else: state1 = normal_state return def predictday(self,call_date, hours): result = [] actual = [] date = call_date-timedelta(hours=1) #1. get base base, basetotal = self.read_base(date) #2. get forecast forepath = self.datapath+"/intelli_forecast/%d_%0*d_%0*d_%0*d"%(date.year,2,date.month,2,date.day,2,date.hour) #3. predict if not os.path.isfile(forepath): print "Forecast missing "+ forepath return result, actual resultpath = self.datapath+"/cached_result/%d_%0*d_%0*d_%0*d"%(date.year,2,date.month,2,date.day,2,date.hour) #if os.path.isfile(resultpath): # result, actual = self.read_cache(resultpath) fh = open(forepath,'r') if not os.path.isdir(self.datapath+"/cached_result"): os.mkdir(self.datapath+"/cached_result") fw = open(resultpath,'w') #print base self.predict_long(base,date,fh,fw) result, actual = self.read_cache(resultpath) fh.close() fw.close() #return value return result, actual def process(self,now, hours): now = datetime(now.year,now.month,now.day,now.hour) if hours > 49 and not self.useActualData: print "Prediction is wanted for more than 49 hours but we can only return 49 hours." hours = 49 #if self.debugging: # for i in range(hours+self.shiftFactor): # try: # d = self.debug[i] # except IndexError: # d = Debug(self.scaling) # self.debug.append(d) # d.reset() #print past result, actual = self.predictday(now, hours) return result, actual if __name__ == '__main__': now = datetime(2011, 3, 15, 0, 0,0) p = EnergyPredictor(threshold=3,energythreshold=20,offset=15) pred, actual = p.process(now, 48) print len(pred), pred <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import time import threading import signal from subprocess import call, PIPE, Popen from ghadoopcommons import * class MonitorHDFS(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True # Read nodes pipe=Popen([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-printTopology"], stdout=PIPE, stderr=open('/dev/null', 'w')) text = pipe.communicate()[0] self.nodeName = {} for line in text.split('\n'): if line !="" and not line.startswith("Rack:"): line = line.strip() lineSplit = line.split(" ") if len(lineSplit)>=2: self.nodeName[lineSplit[0]] = lineSplit[1].replace("(", "").replace(")", "") # Read for the first time self.getData() def kill(self): self.running = False def run(self): lastUpdate = 0 while self.running: self.getData() # Output lastUpdate -= 1 if lastUpdate<0: lastUpdate=1 if DEBUG>3 : self.printOutput() # Wait until next cycle time.sleep(10.0) def getData(self): # Read files pipe = Popen([HADOOP_HOME+"/bin/hdfs", "fsck", "/", "-files", "-blocks", "-locations"], stdout=PIPE, stderr=open('/dev/null', 'w')) blockToRead = 0 for line in pipe.stdout.readlines(): if line != "\n": if line.find("<dir>")>=0: lineSplit = line.split(" ") fileId = lineSplit[0] if fileId in files: file = files[fileId] else: file = FileHDFS(fileId, True) files[fileId] = file # Parent directory dir = fileId[0:fileId.rfind("/")] if fileId != "/": if dir=="": dir="/" files[dir].blocks[file.id]=file elif line.find("bytes")>=0 and line.find("block(s):")>=0: lineSplit = line.split(" ") fileId = lineSplit[0] blockToRead = int(lineSplit[3]) if fileId in files: file = files[fileId] else: file = FileHDFS(fileId, False) files[fileId] = file # Parent Directory dir = fileId[0:fileId.rfind("/")] files[dir].blocks[file.id] = file # Clean previous file location #cleanFileLocation(fileId) auxBlocks = file.blocks file.blocks = {} for block in auxBlocks.values(): for nodeId in block.nodes: if block.id in nodeFile[nodeId]: nodeBlock[nodeId].remove(block.id) if block.file in nodeFile[nodeId]: nodeFile[nodeId].remove(block.file) else: if line.find("Under replicated")>0: None elif line != " OK\n" and blockToRead>0: if line.find("CORRUPT")>=0: None elif line.find("MISSING")>=0: blockToRead-=1 else: # Update information lineSplit = line.split(" ") id = lineSplit[1] file = files[fileId] if id in file.blocks: block = file.blocks[id] else: block = BlockHDFS(id) block.file = fileId file.blocks[id] = block nodes = line[line.find("[")+1:line.find("]")] nodes = nodes.split(", ") # Set file location for node in nodes: nodeName = node if node in self.nodeName: nodeName = self.nodeName[node] if nodeName not in block.nodes: block.nodes.append(nodeName) blockToRead-=1 # Update map nodes -> file,block for file in files.values(): # Get file location for block in file.blocks.values(): if isinstance(block, BlockHDFS): for nodeId in block.nodes: # Node -> Block if nodeId not in nodeBlock: nodeBlock[nodeId] = [] if block.id not in nodeBlock[nodeId]: nodeBlock[nodeId].append(block.id) # Node -> File if nodeId not in nodeFile: nodeFile[nodeId] = [] if block.file not in nodeFile[nodeId]: nodeFile[nodeId].append(block.file) else: file = block for nodeId in file.getLocation(): # Node -> File if nodeId not in nodeFile: nodeFile[nodeId] = [] if file.id not in nodeFile[nodeId]: nodeFile[nodeId].append(file.id) # Files are updated setFilesUpdated(True) def printOutput(self): print "=========================================================" # Output print "Files:" for fileName in sorted(files): file = files[fileName] tab="" for i in range(1, file.id.count("/")): tab+="\t" print tab+file.id+" blk="+str(len(file.blocks))+" repl="+str(file.getMinReplication())+" => "+str(sorted(file.getLocation())) nodes = getNodes() print "Node->Blocks:" for nodeId in sorted(self.nodeName.values()): out = "\t"+nodeId if nodeId in nodes: out+=" ["+str(nodes[nodeId][1])+"]" if nodeId in nodeBlock: out+=":\t"+str(len(nodeBlock[nodeId])) print out print "Node->File:" for nodeId in sorted(self.nodeName.values()): out = "\t"+nodeId if nodeId in nodes: out+=" ["+str(nodes[nodeId])+"]" if nodeId in nodeFile: out+=":\t"+str(len(nodeFile[nodeId])) print out if __name__=='__main__': DEBUG = 4 thread = MonitorHDFS() thread.start() signal.signal(signal.SIGINT, signal_handler) nodes = getNodes() for nodeId in nodes: print nodeId+": "+str(nodes[nodeId]) nodes = getNodes() offNodes = nodes.keys() """ #offNodes.remove("crypt01") print "/user/goiri/input-workload1-00 => " + str(minNodesFiles(["/user/goiri/input-workload1-00"], offNodes)) print "/user/goiri/input-workload1-01 => " + str(minNodesFiles(["/user/goiri/input-workload1-01"], offNodes)) print "/user/goiri/input-workload1-02 => " + str(minNodesFiles(["/user/goiri/input-workload1-02"], offNodes)) print "/user/goiri/input-workload1-03 => " + str(minNodesFiles(["/user/goiri/input-workload1-03"], offNodes)) print "/user/goiri/input-workload1-04 => " + str(minNodesFiles(["/user/goiri/input-workload1-04"], offNodes)) print "/user/goiri/input-workload1-05 => " + str(minNodesFiles(["/user/goiri/input-workload1-05"], offNodes)) print "/user/goiri/input-workload1-06 => " + str(minNodesFiles(["/user/goiri/input-workload1-06"], offNodes)) print "/user/goiri/input-workload1-07 => " + str(minNodesFiles(["/user/goiri/input-workload1-07"], offNodes)) """ while True: time.sleep(5.0) thread.join() <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import threading import signal import subprocess from operator import itemgetter from datetime import datetime, timedelta from ghadoopcommons import * class ReplicationThread(threading.Thread): def __init__(self, timeStart, replThreads=40): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart self.replThreads = replThreads self.MAX_REPLICATION_TIME = 20 # seconds self.lastSpaceCheck = None self.MAX_SPACECHECK_TIME = 120 # seconds self.threads = {} def kill(self): self.running = False def run(self): # threadId = fileId => (thread,timestart) retries = {} while self.running: # Cleaning threads for threadId in list(self.threads.keys()): thread = self.threads[threadId] if not thread[0].isAlive(): del self.threads[threadId] elif toSeconds(datetime.now()-thread[1])>self.MAX_REPLICATION_TIME: thread[0].kill() if not thread[0].isAlive(): del self.threads[threadId] # Check if there is enough space if self.lastSpaceCheck == None or toSeconds(datetime.now()-self.lastSpaceCheck) > self.MAX_SPACECHECK_TIME: self.doSpaceCheck() self.lastSpaceCheck = datetime.now() # If there is free replications threads, look for a file requiring replication #change = False if len(self.threads)<self.replThreads: # Required files list requiredFiles = getRequiredFiles() # Collect node info nodes = getNodes() onNodes = [] decNodes = [] for nodeId in nodes: if nodes[nodeId][1]=="UP" and nodeId not in onNodes: onNodes.append(nodeId) elif nodes[nodeId][1]=="DEC" and nodeId not in decNodes: decNodes.append(nodeId) # Account required files decNodesAux = [] for nodeId in nodes: if nodes[nodeId][1]=="DEC" and nodeId not in decNodesAux: nJobs = len(nodeJobs.get(nodeId, [])) # Get the number of required missing files of the node nFiles = 0 for fileId in nodeFile.get(nodeId, []): if fileId in requiredFiles: # Check if file is available somewhere else fileAvailable = False file = files[fileId] for otherNodeId in file.getLocation(): if otherNodeId!=nodeId: if (otherNodeId in onNodes or otherNodeId in decNodes): fileAvailable = True break if not fileAvailable: nFiles +=1 decNodesAux.append((nodeId, nFiles, nJobs)) # Sort decommission nodes according to the number of running jobs and the number of required files decNodesAux = sorted(decNodesAux, key=itemgetter(1), reverse=False) decNodes = sorted(decNodesAux, key=itemgetter(2), reverse=False) decNodes = [nodeId for nodeId, nFiles, nJobs in decNodes] # Auxiliar list of nodes decNodes1 = [nodeId for nodeId in decNodes] decNodes2 = [nodeId for nodeId in decNodes] # Check data in decommission nodes which is not available anywhere else change = True while len(decNodes1)>0 and len(self.threads)<self.replThreads and change: change = False nodeId = decNodes1.pop(0) # Check if it is actually in decommission and ready nodeHdfsReady = getNodesHdfsReady() # Check if the node is available if nodes[nodeId][1]=="DEC" and nodeId in nodeFile and len(nodeJobs.get(nodeId, []))==0 and nodeId in nodeHdfsReady: # Check if the files are available it = 0 while not filesUpdated() and it<10: time.sleep(0.5) it += 1 if filesUpdated and nodes[nodeId][1]=="DEC" and nodeId in nodeHdfsReady: # Check all files in the node replicateFiles = [] for fileId in nodeFile[nodeId]: # First files only not available file = files[fileId] if fileId not in self.threads and file.isFile() and fileId in requiredFiles and fileId not in replicateFiles: # Not too many replications if fileId not in retries or retries[fileId]<len(nodes): # Check if file is available in UP nodes () replicate = True for otherNodeId in file.getLocation(): #if otherNodeId!=nodeId and nodes[otherNodeId][1]=="UP":# and nodes[otherNodeId][1]=="DEC": if otherNodeId!=nodeId and (nodes[otherNodeId][1]=="UP" or nodes[otherNodeId][1]=="DEC"): replicate = False break if replicate: replicateFiles.append(fileId) if len(self.threads)+len(replicateFiles) > self.replThreads: break # Check if it is required to replicate while len(replicateFiles)>0 and len(self.threads)<self.replThreads: fileId = replicateFiles.pop(0) file = files[fileId] # Check if there are enough nodes available availableNodes = False for otherNodeId in onNodes: if otherNodeId in nodeHdfsReady and otherNodeId in nodeFile and fileId not in nodeFile[otherNodeId]: availableNodes = True break if availableNodes: # Increase replication newrepl = file.getMaxReplication()+1 if fileId not in retries: retries[fileId] = 0 else: retries[fileId] += 1 thread = SetReplicationThread(self.timeStart, fileId, newrepl, retries[fileId]) thread.start() self.threads[fileId] = (thread, datetime.now()) change = True # Check data in decommission nodes (is the previous one with no check on decommission nodes) change = True while len(decNodes2)>0 and len(self.threads)<self.replThreads and change: change = False nodeId = decNodes2.pop(0) # Check if it is actually in decommission and ready nodeHdfsReady = getNodesHdfsReady() # Check if the node is available if nodes[nodeId][1]=="DEC" and nodeId in nodeFile and len(nodeJobs.get(nodeId, []))==0 and nodeId in nodeHdfsReady: # Check if the files are available it = 0 while not filesUpdated() and it<10: time.sleep(0.5) it += 1 if filesUpdated and nodes[nodeId][1]=="DEC" and nodeId in nodeHdfsReady: # Check all files in the node replicateFiles = [] for fileId in nodeFile[nodeId]: # First files only not available file = files[fileId] if fileId not in self.threads and file.isFile() and fileId in requiredFiles and fileId not in replicateFiles: # Not too many replications if fileId not in retries or retries[fileId]<len(nodes): # Check if file is available in UP nodes () replicate = True for otherNodeId in file.getLocation(): if otherNodeId!=nodeId and nodes[otherNodeId][1]=="UP": replicate = False break if replicate: replicateFiles.append(fileId) if len(self.threads)+len(replicateFiles) > self.replThreads: break # Check if it is required to replicate while len(replicateFiles)>0 and len(self.threads)<self.replThreads: fileId = replicateFiles.pop(0) file = files[fileId] # Check if there are enough nodes available availableNodes = False for otherNodeId in onNodes: if otherNodeId in nodeHdfsReady and otherNodeId in nodeFile and fileId not in nodeFile[otherNodeId]: availableNodes = True break if availableNodes: # Increase replication newrepl = file.getMaxReplication()+1 if fileId not in retries: retries[fileId] = 0 else: retries[fileId] += 1 thread = SetReplicationThread(self.timeStart, fileId, newrepl, retries[fileId]) thread.start() self.threads[fileId] = (thread, datetime.now()) change = True # If not change: time.sleep(2.0) # Killing waiting threads for threadId in list(self.threads.keys()): thread = self.threads[threadId] thread[0].kill() def doSpaceCheck(self): # Check if there is enough space in the Always ON nodes global ALWAYS_NODE enoughSpace = False nodesReport = getNodeReport() nodes = getNodes() for nodeId in ALWAYS_NODE: # Check if the value is right if nodeId not in nodesReport: enoughSpace = True break elif nodesReport[nodeId]==None: enoughSpace = True break #elif nodesReport[nodeId][0]==0.0 and nodesReport[nodeId][2]==100.0: #enoughSpace = True #break elif nodesReport[nodeId][0]>3.0 and nodesReport[nodeId][2]<85.0: # minimum 3 GB and occupation maximum 85% enoughSpace = True break if not enoughSpace: #print "There is no enough space.... " #print nodesReport print "Nodes report:" # Select selectNodeId = None for nodeId in nodesReport: if nodeId in nodes and nodesReport!=None and nodesReport[nodeId]!=None: print "\t%s -> %.2fGB %.2f" % (nodeId, nodesReport[nodeId][0], nodesReport[nodeId][2]) if selectNodeId==None or nodesReport[nodeId][0]>nodesReport[selectNodeId][0]: if nodeId not in ALWAYS_NODE: selectNodeId = nodeId if selectNodeId != None and selectNodeId not in ALWAYS_NODE: print "Selected node: "+str(selectNodeId) ALWAYS_NODE.append(selectNodeId) def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) class CleanDataThread(threading.Thread): def __init__(self, timeStart): threading.Thread.__init__(self) self.running = True self.timeStart = timeStart self.lastclean = datetime.now() self.replThreads = 5 self.MAX_REPLICATION_TIME = 20 # seconds #self.threads = {} def kill(self): self.running = False def run(self): while self.running: # Cleaning threads #for threadId in list(self.threads.keys()): #thread = self.threads[threadId] #if not thread[0].isAlive(): #del self.threads[threadId] #elif toSeconds(datetime.now()-thread[1])>self.MAX_REPLICATION_TIME: #thread[0].kill() #del self.threads[threadId] # Cleaning #if len(self.threads)<self.replThreads: requiredFiles = getRequiredFiles() for fileId in list(files.keys()): # File not required anymore if fileId not in requiredFiles and fileId.startswith("/user/"+str(USER)+"/"): file = files[fileId] if file.isFile(): locations = file.getLocation() if len(locations)>REPLICATION_DEFAULT: writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tCleaning replication "+str(fileId)) #file.blocks = {} cleanFileInfo(fileId) replicator = Popen([HADOOP_HOME+"/bin/hadoop", "fs", "-setrep", "-w", str(REPLICATION_DEFAULT), "-R", str(fileId)], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) for i in range(0,4): if replicator.poll()==None: time.sleep(0.5) else: break if replicator.poll()==None: os.kill(replicator.pid, signal.SIGTERM) #cleanFileInfo(fileId) setFilesUpdated(False) #thread = SetReplicationThread(self.timeStart, fileId, REPLICATION_DEFAULT) #thread.start() #self.threads[fileId] = (thread, datetime.now()) #setFilesUpdated(False) #if file.isFile() and fileId.startswith("/user/goiri/") and len(locations)>REPLICATION_DEFAULT: ## Check if all locations area available #nodeHdfsReady = getNodesHdfsReady() #availSources = True #for location in locations: #if location not in nodeHdfsReady: #availSources = False #break #if availSources: ## Reduce replication #writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tCleaning replication "+str(fileId)) #thread = SetReplicationThread(self.timeStart, fileId, REPLICATION_DEFAULT) #thread.start() #self.threads[fileId] = (thread, datetime.now()) #file.blocks = {} #if len(self.threads)>=self.replThreads: #break time.sleep(2.0) # Killing waiting threads #for threadId in list(self.threads.keys()): #thread = self.threads[threadId] #thread[0].kill() def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) class RemoveExtraReplication(threading.Thread): def __init__(self, fileId, replication): threading.Thread.__init__(self) self.fileId = fileId self.repl = repl def run(self): replicator = Popen([HADOOP_HOME+"/bin/hadoop", "fs", "-setrep", "-w", str(self.repl), "-R", str(self.fileId)], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) time.sleep(2.0) class SetReplicationThread(threading.Thread): def __init__(self, timeStart, fileId, replication, retries=0): threading.Thread.__init__(self) self.timeStart = timeStart self.fileId = fileId self.replication = replication self.retries = retries self.replicator = None self.running = True def kill(self): self.running = False if self.replicator != None: try: os.kill(self.replicator.pid, signal.SIGTERM) writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tKilled replication "+self.fileId) except OSError: None #print "Error killing "+str(self.fileId) def run(self): file = files[self.fileId] # Check if the nodes are available nodeList = file.getLocation() writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tChange replication "+self.fileId+" @ "+str(nodeList)) # Waiting for one of the nodes to be available ready = False while not ready and self.running: nodeHdfsReady = getNodesHdfsReady() for nodeId in nodeList: if nodeId in nodeHdfsReady: ready = True break if not ready: time.sleep(0.5) # Change replication if self.running: writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tChanging replication "+self.fileId+" @ "+str(getNodesHdfsReady())) extra=self.retries setrep = self.replication+extra nodes = getNodes() if setrep > len(nodes): setrep = len(nodes) self.replicator = Popen([HADOOP_HOME+"/bin/hadoop", "fs", "-setrep", "-w", str(setrep), "-R", str(self.fileId)], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) self.replicator.wait() # Cleaning the extra.... if extra>0: self.replicator = Popen([HADOOP_HOME+"/bin/hadoop", "fs", "-setrep", "-w", str(self.replication), "-R", str(self.fileId)], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) time.sleep(0.5) try: os.kill(self.replicator.pid, signal.SIGTERM) except OSError: None # Remove all replica locations, updated later setFilesUpdated(False) # Waiting until the file list is updated... while not filesUpdated() and self.running: time.sleep(0.5) writeLog("logs/ghadoop-scheduler.log", str(self.getCurrentTime())+"\tChanged replication "+self.fileId+" @ "+str(file.getLocation())) # Kill thread if it is still alive if self.replicator.poll() == None: os.kill(self.replicator.pid, signal.SIGTERM) def getCurrentTime(self): timeNow = datetime.now() timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) return toSeconds(timeNow-self.timeStart) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ # bash: for file in `ls logs/`; do python ghadoopparser.py logs/$file/$file > logs/$file/$file-summary.log; done import sys import math from ghadoopcommons import * def readGreenAvailFile(filename): greenAvailability = [] file = open(filename, 'r') for line in file: if line != '' and line.find("#")!=0 and line != '\n': lineSplit = line.strip().expandtabs(1).split(' ') t=lineSplit[0] p=float(lineSplit[1]) # Apply scale factor TODO p = (p/2300.0)*MAX_POWER greenAvailability.append(TimeValue(t,p)) file.close() return greenAvailability LOG_ENERGY = "ghadoop-energy.log" LOG_JOBS = "ghadoop-jobs.log" LOG_SCHEDULER = "ghadoop-scheduler.log" if len(sys.argv)>1: LOG_ENERGY = sys.argv[1]+"-energy.log" LOG_JOBS = sys.argv[1]+"-jobs.log" LOG_SCHEDULER = sys.argv[1]+"-scheduler.log" greenAvailability = None path = LOG_ENERGY[0:LOG_ENERGY.rfind("/")] for file in os.listdir(path): if file.startswith("solarpower"): greenAvailability = readGreenAvailFile(path+"/"+file) # Energy file prevLineSplit = None totalEnergyGreen = 0.0 totalEnergyBrown = 0.0 totalEnergyTotal = 0.0 totalEnergyBrownCost = 0.0 totalEnergyGreenAvail = 0.0 totalTime = 0 totalTime = 7200 timeFinishWorkload = 7200 # Nodes runNodes = 0.0 upNodes = 0.0 decNodes = 0.0 # Peak maxPowerPeak = 0.0 peakControlTime = [] peakControlPowe = [] SPEEDUP = 24 ACCOUNTING_PERIOD=(15*60/3600.0)/SPEEDUP # hours numNodes = 0 # Read energy file, line by line for line in open(LOG_ENERGY, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = float(lineSplit[1]) # Green availability lineSplit[2] = float(lineSplit[2]) # Green prediction lineSplit[3] = float(lineSplit[3]) # Brown price lineSplit[4] = int(lineSplit[4]) # Run Nodes lineSplit[5] = int(lineSplit[5]) # Up Nodes lineSplit[6] = int(lineSplit[6]) # Dec Nodes lineSplit[7] = float(lineSplit[7]) # Green use lineSplit[8] = float(lineSplit[8]) # Brown use lineSplit[9] = float(lineSplit[9]) # Total use t = lineSplit[0] newGreen = 0 for tv in greenAvailability: #print tv if (tv.t/24)>t: break newGreen = tv.v totaluse = lineSplit[9] if newGreen >= totaluse: greenuse = totaluse brownuse = 0 else: greenuse = newGreen brownuse = totaluse-newGreen print str(t)+"\t"+str(newGreen)+"\t"+str(newGreen)+"\t"+str(lineSplit[3])+"\t"+str(lineSplit[4])+"\t"+str(lineSplit[5])+"\t"+str(lineSplit[6])+"\t"+str(greenuse)+"\t"+str(brownuse)+"\t"+str(lineSplit[9]) # Nodes if numNodes<lineSplit[6]: numNodes = lineSplit[6] # Parse info if prevLineSplit != None: t = (lineSplit[0]-prevLineSplit[0])/3600.0 energyGreen = t * prevLineSplit[7] energyBrown = t * prevLineSplit[8] energyTotal = t * prevLineSplit[9] energyBrownCost = (energyBrown/1000.0)*prevLineSplit[3] energyGreenAvail = t * prevLineSplit[1] # Nodes runNodes += 3600.0 * t * prevLineSplit[4] upNodes += 3600.0 * t * prevLineSplit[5] decNodes += 3600.0 * t * prevLineSplit[6] # Peak power accounting #print prevLineSplit peakControlTime.append(t) peakControlPowe.append(prevLineSplit[8]) #while sum(peakControlTime)-peakControlTime[0]>ACCOUNTING_PERIOD: while sum(peakControlTime)>ACCOUNTING_PERIOD: peakControlTime.pop(0) peakControlPowe.pop(0) while len(peakControlTime)>1 and peakControlTime[0] == 0: peakControlTime.pop(0) peakControlPowe.pop(0) powerPeak = 0 for i in range(0, len(peakControlTime)): #print str(peakControlTime[i])+"h "+str(peakControlPowe[i])+"W" #powerPeak += (peakControlTime[i]/ACCOUNTING_PERIOD) * peakControlPowe[i] if sum(peakControlTime)>0: powerPeak += (peakControlTime[i]/sum(peakControlTime)) * peakControlPowe[i] if powerPeak>maxPowerPeak: maxPowerPeak = powerPeak #if prevLineSplit[0]>totalTime: #totalTime = prevLineSplit[0] #print "Current = "+str(powerPeak)+" Peak = "+str(maxPowerPeak) # Totals totalEnergyGreen += energyGreen totalEnergyBrown += energyBrown totalEnergyTotal += energyTotal totalEnergyBrownCost += energyBrownCost totalEnergyGreenAvail += energyGreenAvail prevLineSplit = lineSplit runNodes = runNodes/totalTime upNodes = upNodes/totalTime decNodes = decNodes/totalTime # Read job file, line by line jobs = {} jobsFinished = [] jobsStartEnd = {} tasks = {} timeTasks = [] timeTasksHigh = [] timeTasksNone = [] timeJobs = [] totalRuntime = 0 totalMapRuntime = 0 #timeFinishWorkload = 0 speedTasks = [] speedTasksHigh = [] speedTasksNone = [] speedJobs = [] #totalSpeed = 0.0 #totalNumber = 0 for line in open(LOG_JOBS, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # TaskId lineSplit[2] = lineSplit[2] # JobId lineSplit[3] = lineSplit[3] # Node lineSplit[4] = lineSplit[4] # Priority lineSplit[5] = int(lineSplit[5]) # Submit lineSplit[6] = int(lineSplit[6]) # Start lineSplit[7] = int(lineSplit[7]) # End lineSplit[8] = int(lineSplit[8]) # Wait lineSplit[9] = int(lineSplit[9]) # Run lineSplit[10] = int(lineSplit[10]) # Total jobId = lineSplit[2] if jobId not in jobsStartEnd: jobsStartEnd[jobId] = (lineSplit[5], None) t = lineSplit[0] if lineSplit[3].startswith("['"): # Job #if timeFinishWorkload< (lineSplit[5]+lineSplit[10]): #timeFinishWorkload = lineSplit[0] timeJobs.append((t, lineSplit[2])) jobId = lineSplit[2] if jobId not in jobsFinished: jobsFinished.append(jobId) jobsStartEnd[jobId] = (jobsStartEnd[jobId][0], lineSplit[10]) else: # Task if lineSplit[1] not in tasks: tasks[lineSplit[1]] = None if lineSplit[2] not in jobs: jobs[lineSplit[2]] = [] jobs[lineSplit[2]].append(lineSplit[1]) totalRuntime += lineSplit[9] if lineSplit[1].find("_m_")>=0: totalMapRuntime += lineSplit[9] timeTasks.append((t, lineSplit[1])) if lineSplit[4].find("HIGH")>=0: timeTasksHigh.append((t, lineSplit[1])) else: timeTasksNone.append((t, lineSplit[1])) # Clean too old tasks MEASURE_INTERVAL = 300.0 while len(timeTasks)>0 and t-timeTasks[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasks[0] speedTasks.append((t, len(timeTasks)/MEASURE_INTERVAL)) while len(timeTasksHigh)>0 and t-timeTasksHigh[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasksHigh[0] speedTasksHigh.append((t, len(timeTasksHigh)/MEASURE_INTERVAL)) while len(timeTasksNone)>0 and t-timeTasksNone[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasksNone[0] speedTasksNone.append((t, len(timeTasksNone)/MEASURE_INTERVAL)) # Clean too old jobs while len(timeJobs)>0 and t-timeJobs[0][0]>MEASURE_INTERVAL: # 5 minutes del timeJobs[0] speedJobs.append((t, len(timeJobs)/MEASURE_INTERVAL)) # Get speed # Tasks speed auxSpeed = [] for s in speedTasks: if len(auxSpeed)>0 and auxSpeed[len(auxSpeed)-1][0] == s[0]: auxSpeed[len(auxSpeed)-1] = s else: auxSpeed.append(s) speedTasks = auxSpeed a = 0.0 n = 0 now = 0 for s in speedTasks: interval = s[0]-now #print str(interval)+"\t"+str(s) a += s[1]*interval n += interval now = s[0] finalSpeedTasks = 0.0 if n>0: finalSpeedTasks = a/n # Tasks speed high auxSpeed = [] for s in speedTasksHigh: if len(auxSpeed)>0 and auxSpeed[len(auxSpeed)-1][0] == s[0]: auxSpeed[len(auxSpeed)-1] = s else: auxSpeed.append(s) speedTasksHigh = auxSpeed a = 0.0 n = 0 now = 0 for s in speedTasksHigh: interval = s[0]-now #print str(interval)+"\t"+str(s) a += s[1]*interval n += interval now = s[0] finalSpeedTasksHigh = 0.0 if n>0: finalSpeedTasksHigh = a/n # Tasks speed auxSpeed = [] for s in speedTasksNone: if len(auxSpeed)>0 and auxSpeed[len(auxSpeed)-1][0] == s[0]: auxSpeed[len(auxSpeed)-1] = s else: auxSpeed.append(s) speedTasksNone = auxSpeed a = 0.0 n = 0 now = 0 for s in speedTasksNone: interval = s[0]-now #print str(interval)+"\t"+str(s) a += s[1]*interval n += interval now = s[0] finalSpeedTasksNone = 0.0 if n>0: finalSpeedTasksNone = a/n # Jobs speed auxSpeed = [] for s in speedJobs: if len(auxSpeed)>0 and auxSpeed[len(auxSpeed)-1][0] == s[0]: auxSpeed[len(auxSpeed)-1] = s else: auxSpeed.append(s) speedJobs = auxSpeed a = 0.0 n = 0 now = 0 for s in speedJobs: interval = s[0]-now #print str(interval)+"\t"+str(s) a += s[1]*interval n += interval now = s[0] finalSpeedJobs = 0.0 if n>0: finalSpeedJobs = a/n # Read scheudler file, line by line replications = [] replStart = 0 replDone = 0 for line in open(LOG_SCHEDULER, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # Message # File replication if lineSplit[1].startswith("Changed"): replDone += 1 fileName = lineSplit[1].split(" ")[2] if fileName not in replications: replications.append(fileName) elif lineSplit[1].startswith("Change"): replStart +=1 fileName = lineSplit[1].split(" ")[2] if fileName not in replications: replications.append(fileName) # Queues #if lineSplit[1].startswith("Queues"): #print line totalEnergyIdle = ((numNodes*Node.POWER_S3)+POWER_IDLE_GHADOOP) * totalTime/3600.0 greenUtilization = 0.0 if totalEnergyGreenAvail>0.0: greenUtilization = 100.0*totalEnergyGreen/totalEnergyGreenAvail # Print summary #print "Power:" #print "\tGreen: %.2f kWh (%.2f/%.2f Wh %.2f%%)" % (totalEnergyGreen/1000.0, totalEnergyGreen, totalEnergyGreenAvail, greenUtilization) #print "\tBrown: %.2f kWh (%.2f Wh)" % (totalEnergyBrown/1000.0, totalEnergyBrown) #print "\tIdle: %.2f kWh (%.2f Wh)" % (totalEnergyIdle/1000.0, totalEnergyIdle) #print "\tWork: %.2f kWh (%.2f Wh)" % ((totalEnergyTotal-totalEnergyIdle)/1000.0, totalEnergyTotal-totalEnergyIdle) #print "\tTotal: %.2f kWh (%.2f Wh)" % (totalEnergyTotal/1000.0, totalEnergyTotal) #print "\tCost: $%.4f" % (totalEnergyBrownCost) #print "\tPeak: %.2f W" % (maxPowerPeak) #print "Nodes: %d" % (numNodes) #print "Time: %d s" % (totalTime) #print "\tWork: %d s" % (timeFinishWorkload) #print "\tRun: %d s" % (totalRuntime) #print "\tOccup Total: %.2f%% = %.2f / %.2fx%.2f" % (100.0*totalRuntime/(totalTime*numNodes), totalRuntime, totalTime, numNodes) #occup = 0.0 #if timeFinishWorkload>0.0: #occup = 100.0*totalRuntime/(timeFinishWorkload*numNodes) #print "\tOccup Work: %.2f%%" % (occup) #print "Jobs: %d" % (len(jobs)) #if len(jobs)>0: #print "\tTasks: %.2f" % (float(len(tasks))/len(jobs)) #print "\tLength: %.2f s" % (totalRuntime/float(len(jobs))) #print "\tEnergy: %.2f Wh" % ((totalEnergyTotal-totalEnergyIdle)/len(jobs)) #print "Tasks: %d" % (len(tasks)) #if len(tasks)>0: #print "\tLength: %.2f s" % (totalRuntime/float(len(tasks))) #print "\tEnergy: %.2f Wh" % ((totalEnergyTotal-totalEnergyIdle)/len(tasks)) #print "Performance:" #print "\t%.2f tasks/second " % (finalSpeedTasks) #if totalEnergyBrown>0: #print "\t%.2f tasks/hour / Wh" % (finalSpeedTasks*3600.0/totalEnergyBrown) #if totalEnergyBrownCost>0: #print "\t%.2f tasks/hour / $" % (finalSpeedTasks*3600.0/totalEnergyBrownCost) #print "\t%.2f jobs/hour " % (finalSpeedJobs*3600.0) #if totalEnergyBrown>0: #print "\t%.2f jobs/hour / Wh" % (finalSpeedJobs*3600.0/totalEnergyBrown) #if totalEnergyBrownCost>0: #print "\t%.2f jobs/hour / $" % (finalSpeedJobs*3600.0/totalEnergyBrownCost) #print "Repl: %d/%d" % (replStart, replDone) #print "Repl: %d" % (len(replications)) <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ from ghadoopcommons import * from ghadoopmonitor import * #print ["/bin/touch", HADOOP_HOME+"/logs/hadoop-"+USER+"-jobtracker-"+MASTER_NODE+".log"] print "Nodes:\tNode\tMapRed\tHDFS" nodes = getNodes() for nodeId in sorted(nodes): print "\t"+str(nodeId)+":\t"+str(nodes[nodeId][0])+"\t"+str(nodes[nodeId][1]) """ # Deploy the testing file for i in `seq 1 8`; do for j in `seq 1 8`; do ./hadoop fs -cp /user/goiri/testfile /user/goiri/input$i/testfile$j done done """ cleanNodesHdfsReady() cleanNodeDecommission() # Restart Hadoop print "Stopping MapReduce..." call([HADOOP_HOME+"/bin/stop-mapred.sh"], stdout=open('/dev/null', 'w')) print "Stopping HDFS..." call([HADOOP_HOME+"/bin/stop-dfs.sh"], stdout=open('/dev/null', 'w')) print "Stopping everything..." JAVA_BIN = "/usr/lib/jvm/java-6-sun/bin/java" #call([HADOOP_HOME+"/bin/slaves.sh","killall","-9","/usr/lib/jvm/java-6-openjdk/bin/java"], stdout=open('/dev/null', 'w')) #call([HADOOP_HOME+"/bin/slaves.sh","killall","-9","/usr/lib/jvm/java-6-sun/bin/java"], stdout=open('/dev/null', 'w')) #call([HADOOP_HOME+"/bin/slaves.sh","killall","-9","/home/goiri/jre1.6.0_26/bin/java"], stdout=open('/dev/null', 'w')) call([HADOOP_HOME+"/bin/slaves.sh","killall","-9",JAVA_BIN], stdout=open('/dev/null', 'w')) call(["killall","-9",JAVA_BIN], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) call([HADOOP_HOME+"/bin/slaves.sh","rm","-f","/tmp/hadoop-goiri*.pid"], stdout=open('/dev/null', 'w')) #call(["rm","-f",HADOOP_HOME+"/logs/*"], stdout=open('/dev/null', 'w')) print "Cleaning log files..." call([HADOOP_HOME+"/bin/slaves.sh","rm","-Rf",HADOOP_HOME+"/logs/*"], stdout=open('/dev/null', 'w')) call(["/bin/touch", HADOOP_HOME+"/logs/hadoop-"+USER+"-jobtracker-"+MASTER_NODE+".log"], stdout=open('/dev/null', 'w')) call(["/bin/touch", HADOOP_HOME+"/logs/hadoop-"+USER+"-namenode-"+MASTER_NODE+".log"], stdout=open('/dev/null', 'w')) """ for i in range(0,5): if len(getJobs())!=0: break else: time.sleep(0.5) print "Cancelling jobs..." # Cancel tasks for job in getJobs().values(): if job.state != "SUCCEEDED" and job.state != "KILLED" and job.state != "FAILED": killJob(job.id) print "Deploying regular HDFS..." print "Deploying Green HDFS..." call(["rm","-f",HADOOP_HOME+"/hadoop-hdfs-0.21.1-SNAPSHOT.jar"], stdout=open('/dev/null', 'w')) call(["rm","-f",HADOOP_HOME+"/hadoop-hdfs-0.21.0.jar"], stdout=open('/dev/null', 'w')) call(["cp",HADOOP_HOME+"/hadoop-hdfs-0.21.0.jar.bak",HADOOP_HOME+"/hadoop-hdfs-0.21.0.jar"], stdout=open('/dev/null', 'w')) call(["cp",HADOOP_HOME+"/greenhadoop-hdfs-0.21.1-SNAPSHOT.jar.bak",HADOOP_HOME+"/hadoop-hdfs-0.21.1-SNAPSHOT.jar"], stdout=open('/dev/null', 'w')) """ print "Starting HDFS..." call([HADOOP_HOME+"/bin/start-dfs.sh"], stdout=open('/dev/null', 'w')) # Wait for safemode to be done print "Wait until HDFS is ready..." call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-safemode", "wait"], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) print "Starting MapReduce..." call([HADOOP_HOME+"/bin/start-mapred.sh"], stdout=open('/dev/null', 'w')) print "Start monitoring..." thread = MonitorMapred() thread.start() signal.signal(signal.SIGINT, signal_handler) # Wait until all data nodes are available print "Waiting until every node is ready..." auxNodes = [] while len(auxNodes)<len(nodes): for nodeId in getNodesHdfsReady(): if nodeId not in auxNodes: auxNodes.append(nodeId) print "\t"+nodeId+" ready!" if len(auxNodes)<len(nodes): time.sleep(0.5) # Clean decommission state cleanNodeDecommission() print "Removing output and temporary data..." rmFile("/user/goiri/output*") rmFile("/user/goiri/crawlMain/new_indices") rmFile("/tmp/*") rmFile("/jobtracker/*") print "Set default data replication..." setFileReplication("/user/goiri/*", REPLICATION_DEFAULT) """ print "Stopping HDFS..." call([HADOOP_HOME+"/bin/stop-dfs.sh"], stdout=open('/dev/null', 'w')) print "Deploying Green HDFS..." call(["rm","-f",HADOOP_HOME+"/hadoop-hdfs-0.21.1-SNAPSHOT.jar"], stdout=open('/dev/null', 'w')) call(["rm","-f",HADOOP_HOME+"/hadoop-hdfs-0.21.0.jar"], stdout=open('/dev/null', 'w')) call(["cp",HADOOP_HOME+"/greenhadoop-hdfs-0.21.1-SNAPSHOT.jar.bak",HADOOP_HOME+"/hadoop-hdfs-0.21.1-SNAPSHOT.jar"], stdout=open('/dev/null', 'w')) print "Starting HDFS..." call([HADOOP_HOME+"/bin/start-dfs.sh"], stdout=open('/dev/null', 'w')) Wait for safemode to be done print "Wait until HDFS is ready..." call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-safemode", "wait"], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) Start everything if True: ALWAYS_NODE=nodes.keys() print "Decommissioning..." threads = [] nodes = getNodes() for nodeId in sorted(nodes): if nodeId not in ALWAYS_NODE: thread = threading.Thread(target=setNodeStatus,args=(nodeId, False)) thread.start() threads.append(thread) else: thread = threading.Thread(target=setNodeStatus,args=(nodeId, True)) thread.start() threads.append(thread) while len(threads)>0: threads.pop().join() """ """ #Wait until all data nodes are available print "Waiting until every node is ready..." auxNodes = [] while len(auxNodes)<len(nodes): for nodeId in getNodesHdfsReady(): if nodeId not in auxNodes: auxNodes.append(nodeId) print "\t"+nodeId+" ready!" if len(auxNodes)<len(nodes): time.sleep(0.5) #Turn off mapred print "Turning off nodes..." threads = [] for nodeId in sorted(getNodes()): if nodeId not in ALWAYS_NODE: thread = threading.Thread(target=setNodeMapredStatus,args=(nodeId, False)) thread.start() threads.append(thread) thread = threading.Thread(target=setNodeHdfsStatus,args=(nodeId, False)) thread.start() threads.append(thread) while len(threads)>0: thread = threads.pop() thread.join() TODO for testing only nodes = getNodes() for nodeId in sorted(nodes): if nodeId != "crypt15": setNodeMapredStatus(nodeId, False) """ print "Nodes:\tNode\tMapRed\tHDFS" #nodes = getNodes(True) nodes = getNodes() for nodeId in sorted(nodes): print "\t"+str(nodeId)+":\t"+str(nodes[nodeId][0])+"\t"+str(nodes[nodeId][1]) print "Finished!" thread.kill() sys.exit(0) <file_sep>#!/usr/bin/python import os, fnmatch, tempfile, sys,os.path,pickle #import singledayweather import weatherPrediction, pastWeather #import datetime from datetime import timedelta, datetime #the input is a tab separated text file containing weather and solar data princetonDataStart = datetime(year=2010,month=5,day=28) princetonDataEnd = datetime(year=2010,month=10,day=4) pisDataStart = datetime(year=2010,month=12,day=14) pisDataEnds = datetime.now() #error entering and exiting method normal = 0 enter_on_thresh = 1 enter_on_error = 2 #states normal_state = 0 hourFormat = '%m_%d_%Y_%H_%M' class PredictionProvider: def __init__(self,dataPath,shiftFactor): self.dataPath = dataPath self.shiftFactor = shiftFactor def getPredictions(self,date,hours): numData = hours-self.shiftFactor start = date+timedelta(hours=self.shiftFactor) inp = weatherPrediction.process(start, numData, self.dataPath,self.shiftFactor) foretag = [] foreweather = [] hour_pre = [] # shift = -1 #inp = open("fore.txt","r") for line in inp.readlines(): # print line.strip() #print line.split("\t")[5], line.split("\t")[15] #print int(line.split()[0].split("_")[-1]) # if shift == -1: # shift = int(line.split()[0].split("_")[-1]) # start = datetime.strptime(line.split()[0],"%Y_%m_%d_%H") foretag.append(int(line.split("\t")[2])) foreweather.append(line.split("\t")[1]) hour_pre.append(int(line.split()[0].split("_")[-1])) #day.append(line.split("\t")[4]) inp.close() return foretag,foreweather,hour_pre class ActualConditions(PredictionProvider): def __init__(self,dataPath): self.datapath = dataPath self.timeToCondition = {} def getPredictions(self,date,hours): conditions = self.getConditions(date, hours) foretag = [] foreweather = [] hour_pre = [] # shift = -1 #inp = open("fore.txt","r") for (d,c) in conditions: #print line #print line.split("\t")[5], line.split("\t")[15] #print int(line.split()[0].split("_")[-1]) # if shift == -1: # shift = int(line.split()[0].split("_")[-1]) # start = datetime.strptime(line.split()[0],"%Y_%m_%d_%H") foretag.append(int(c.conditionGroup)) foreweather.append(c.conditionString) hour_pre.append(d.hour) #day.append(line.split("\t")[4]) return foretag,foreweather,hour_pre def populateConditions(self,date,numberOfHours): retval = pastWeather.process(date,numberOfHours,self.datapath) # print "populate",date,numberOfHours self.timeToCondition.update(retval) def getConditionString(self,date): try: v = self.timeToCondition[date] except KeyError: self.populateConditions(date,24) try: v = self.timeToCondition[date] except KeyError: print date print self raise return v.conditionString def getConditions(self,start, num_hours): retval = [] tdelta = timedelta(hours=1) d = datetime(start.year,start.month,start.day,start.hour) for i in range(num_hours): # TODO there was a bug in here: you check the size and then you increase the number try: v = self.timeToCondition[d] except KeyError: self.populateConditions(d,num_hours-i) v = self.timeToCondition[d] retval.append((d,v)) d = d+tdelta #print len(retval) return retval def __str__(self): keys = self.timeToCondition.keys() keys.sort() retval = "" for k in keys: retval+="%s\t%s\n"%(str(k),str(self.timeToCondition[k])) return retval class EnergyProduction: def __init__(self,dataPath): self.dataPath = dataPath self.timeToEnergy = {} def populateEnergy(self,date): path = self.dataPath filepath = os.path.join(path,"pastdata",`date.year`,`date.month`,"data.txt") if not os.path.isfile(filepath): print filepath," is not a file" raise Exception() sys.exit(1) datafile = open(filepath,'r') startDate = None # print "populate energy",date,filepath tdelta = timedelta(hours=1) for line in datafile: #print lines[i] if line[0]=='#': continue line = line.strip() if not line: continue if not startDate: startDate = datetime.strptime(line.strip(),"%Y_%m_%d_%H") d = startDate else: v = float(line.strip()) self.timeToEnergy[d] = v d = d+tdelta def readPastProduction(self,start, num_hours): #print filepath retval = [] tdelta = timedelta(hours=1) d = datetime(start.year,start.month,start.day,start.hour) for i in range(num_hours): # TODO there was a bug in here: you check the size and then you increase the number try: v = self.timeToEnergy[d] except KeyError: self.populateEnergy(d) v = self.timeToEnergy[d] retval.append(v) d = d+tdelta #print len(retval) return retval def getProduction(self,hour): d = hour try: v = self.timeToEnergy[d] except KeyError: self.populateEnergy(d) v = self.timeToEnergy[d] return v class Debug: def __init__(self,scaling=1): self.reset() self.scaling = scaling def reset(self): self.haveLastTag = True self.baseValue = 0 self.tagValue = 0 self.tag = "Unknown" self.trackTag = False self.prediction = 0 self.actual = 0 self.actualCondition = "Unknown" def __str__(self): return "%.2f\t%s\t%.2f\t%.2f\t%s(%s)\t%s\t%s\t%.2f"%(self.scaling * self.baseValue,str(self.tagValue),self.scaling * self.prediction,self.scaling * self.actual,self.tag,self.actualCondition,str(self.haveLastTag),str(self.trackTag),self.actual) class EnergyPredictor(object): def __init__(self,path='.',threshold=3, scalingFactor=1347, offset=15, energythreshold=20, useActualData=False, scalingBase=1347,debugging=False,error_exit=normal): #energythreshold=20 means we assume two energy value to be same if within range of +-20 #global debug self.datapath = path self.scaling = scalingFactor/float(scalingBase) # self.scaling = scalingFactor / 1347.0 self.threshold = threshold self.offset = offset self.energythreshold = energythreshold self.pasttime = datetime(2000,01,01) self.pastresult = [] self.debugging = debugging self.debug = [] self.energyProduction = EnergyProduction(self.datapath) self.shiftFactor = 2 self.actualConditions = ActualConditions(self.datapath) self.useActualData = useActualData self.error_exit = error_exit self.last_call_state = normal_state if useActualData: self.weatherPredictor = self.actualConditions # print "using actual data" else: self.weatherPredictor = PredictionProvider(self.datapath,self.shiftFactor) # print "using predictions" self._1sterror = 0.4 self._reterror = 0.35 self.lagerror = 1 def getGreenAvailability(self, now, hours): # TODO is it right? #yes it is correct now #if now<datetime(2010, 6, 16, 0, 0, 0): # self.offset=21 result, actual = self.process(now, hours) # result, actual = self.process(now, hours, self.datapath, self.threshold, self.energythreshold, self.offset,debugging=self.debugging) #debug code start #fp = file(self.datapath+"/debug/%0*d_%0*d_%0*d_%0*d_%0*d.txt"%(2,now.year,2,now.month,2,now.day,2,now.hour,2,now.minute),'w') #dt = datetime(now.year,now.month,now.day,now.hour) #debug code end # for i in range(len(result)): # #debug code start # #fp.write(str(dt+timedelta(hours=i))+"\t"+`actual[i]`+"\t"+`result[i]`+"\t"+`result[i]-actual[i]`+"\n") # #debug code end # # result[i] = self.scaling * result[i] # result = map(lambda x:self.scaling * x, result) #fp.close() flag = False #print self.pastresult if len(self.pastresult)==0: flag = True elif self.pasttime + timedelta(hours=self.threshold) <= now: flag = True else: #print self.pasttime, self.pastresult d = datetime(now.year,now.month,now.day,now.hour) lasttime = datetime(self.pasttime.year, self.pasttime.month, self.pasttime.day, self.pasttime.hour) j = 0 for i in range(len(self.pastresult)): if d==lasttime+timedelta(hours=i): if j<len(result) and abs(self.pastresult[i]-result[j])>self.energythreshold: flag = True break j += 1 d += timedelta(hours=1) if flag==True: self.pasttime = now self.pastresult = [] for i in range(len(result)): self.pastresult.append(result[i]) #print self.pastresult, flag currentHour = datetime(now.year,now.month,now.day,now.hour) if not currentHour == now: #not the beginning of hour result[0] = self.scaling * self.energyProduction.getProduction(currentHour) #print now,result[0] return result, flag def countsunny(self,startrow): j = startrow retval = 0 for k in range(24): #print j, len(weather), len(data) if (data[j]>0) and (weather[j]=='sunny'): #if (data[j]>data[0]) and (weather[j]=='sunny'): retval += 1 j += 1 #print j,retval return retval def selectbase(self): i = 0 baserow = 0 maxcount = 0 while (i < len(data)): count = countsunny(i) if count > maxcount: baserow = i maxcount = count i += 24 #print baserow, maxcount return baserow def constructbase(self,data, lowdata): #select the maximum of each hour and append it at the end of data, we will these values as base retval = len(data) #print retval for i in range(24): data.append(0.0) #print len(data) for i in range(retval): if data[i]>data[retval+i%24]: data[retval+i%24] = data[i] if lowdata[i]>data[retval+i%24]: #print (retval+i)%24,i,retval, lowdata[i] data[retval+i%24] = lowdata[i] return retval def noisefreetags(self,alltags, groups): tagvalues = [] #print len(alltags) for i in range(0,len(alltags)): alltags[i].sort() #print alltags[i] if len(alltags[i]) > 0: #print i, len(alltags[i]), alltags[i][len(alltags[i])/2], sum_avg[i] tagvalues.append(alltags[i][len(alltags[i])/2]) else: #print i, len(alltags[i]), 0.0, sum_avg[i] tagvalues.append(0.0) #print tagvalues, len(tagvalues) return tagvalues def calctag(self,tag, weather, data, lowdata): #base = selectbase() base = self.constructbase(data, lowdata) mult = [] sum_avg = [0.0]*(max(tag)+1) sum_low = [0.0]*(max(tag)+1) count = [0]*(max(tag)+1) count_low = [0]*(max(tag)+1) mapping = ["Empty"]*(max(tag)+1) #debug code start alltags = [] lowtags = [] for i in range(max(tag)+1): #alltags[i] = [] alltags.append([]) lowtags.append([]) #debug code end #print count for i in range(len(tag)): mapping[tag[i]] = weather[i] #print i, lowdata[i] if data[base + i%24]==0: mult.append(0.0) #print a else: #print i, lowdata[i], data[i] mult.append(lowdata[i]/data[base + i%24]*100) if mult[i]>0.0: lowtags[tag[i]].append(mult[i]) sum_low[tag[i]] += mult[i] #if mult[i] > 0.0: count_low[tag[i]] += 1 mult[i] = (data[i]/data[base + i%24]*100) #debug code start if mult[i]>0.0: alltags[tag[i]].append(mult[i]) #use=max(lowdata[i],data[i]) #print i/24, i%24, weather[i], use, use/data[base+i%24] sum_avg[tag[i]] += mult[i] if mult[i] > 0.0: count[tag[i]] += 1 basevalue = [] for i in range(24): basevalue.append(data[base+i]) #print basevalue #outfile = open("tags","w") #print sum_avg, sum_low for i in range(len(sum_avg)): if count[i]<>0: sum_avg[i] /= count[i] if count_low[i]<>0: sum_low[i] /= count_low[i] #print i,mapping[i], count[i], sum_avg[i] #outfile.write(`i`+"\t"+mapping[i]+"\t"+`count[i]`+"\t"+` sum_avg[i]`+"\n") #for i in range(1,len(alltags)): # alltags[i].sort() # print alltags[i] # if len(alltags[i]) > 0: # print i, len(alltags[i]), alltags[i][len(alltags[i])/2], sum_avg[i] # else: # print i, len(alltags[i]), 0.0, sum_avg[i] #print len(sum_avg) sum_avg = self.noisefreetags(alltags, len(sum_avg)) sum_low = self.noisefreetags(lowtags, len(sum_low)) #print len(sum_avg) #debug code returning same tag value for entire day #return basevalue, sum_avg, sum_avg, mapping return basevalue, sum_avg, sum_low, mapping #outfile.close() def populate(self,dirname, filename, date, offset): tag = [] weather = [] data = [] lowdata = [] #hardcoded to handle May 31, 2010 if offset>15: prevdate = datetime(date.year,date.month,date.day) + timedelta(days=5) nextdate = datetime(date.year,date.month,date.day) + timedelta(days=24) else: prevdate = datetime(date.year,date.month,date.day) - timedelta(days=offset) nextdate = datetime(date.year,date.month,date.day) + timedelta(days=offset) #print prevdate, nextdate inp = open(dirname+'/'+filename,"r") for line in inp.readlines(): #print line.split("\t")[4]#, line.split("\t")[15] d = datetime.strptime(line.split("\t")[4],"%m/%d/%Y %H:%M") d = d.replace(year=date.year) #date = datetime(date.year,date.month,date.day) #print d if (prevdate <= d) and (nextdate > d): if len(line.split("\t"))<16: print "We got a corrupted a training file ", filename sys.exit(1) #if d.hour == 7: # print d, line.split("\t")[15] #print line.split("\t")[4] tag.append(int(line.split("\t")[5])) weather.append(line.split("\t")[6]) if d.hour < 10 or d.hour > 15: lowdata.append(float(line.split("\t")[15])) data.append(0) #debug code start #data.append(float(line.split("\t")[15])) #debug code end else: #lowdata.append(0.0) lowdata.append(float(line.split("\t")[15])) data.append(float(line.split("\t")[15])) #print line, len(data), ((len(data)-1)%24) inp.close() #print lowdata return tag, weather, data, lowdata def predictday(self,date, hours): #global debug #global tag #global weather #global data #global lowdata tag = [] weather = [] data = [] lowdata = [] #duration = 14 start = date #print start month = start.month lastmonth = (start-timedelta(days=self.offset)).month nextmonth = (start+timedelta(days=self.offset)).month #lastmonth = (start+timedelta(days=offset)).month #nextmonth = #print lastmonth, nextmonth path = self.datapath for datafile in sorted(os.listdir(path)): ste1 = os.path.join(path,datafile) #print ste1 if os.path.isdir(ste1) and datafile.isdigit(): if lastmonth<=int(datafile) or nextmonth>=int(datafile): #abc = os.listdir(ste1) #print abc # for tfile in sorted(os.listdir(path+"/"+datafile)): for tfile in sorted(os.listdir(ste1)): if fnmatch.fnmatch(tfile,"*wea_data.txt"): tag1, weather1, data1, lowdata1 = self.populate(ste1, tfile, start, self.offset) for a in range(len(tag1)): tag.append(tag1[a]) weather.append(weather1[a]) data.append(data1[a]) lowdata.append(lowdata1[a]) #print tag, len(tag), data if len(tag)==0: print "Failed to locate training data" sys.exit(1) if len(tag)%24<>0: print "Training data has some unknown missing lines" sys.exit(1) if len(tag)<>len(weather): print "Tag weather mismatch" sys.exit(1) #print start basevalue, factor, factor2, mapping = self.calctag(tag, weather, data, lowdata) #print factor, "and", factor2 #singledayweather.process(date) # if self.debugging: # # actualConditions = pastWeather.process(date, hours, path) # actualw = [] # for line in actualConditions.readlines(): # # #print line # #print line.split("\t")[5], line.split("\t")[15] # #print int(line.split()[0].split("_")[-1]) # #if shift == -1: # # shift = int(line.split()[0].split("_")[-1]) # # start = datetime.strptime(line.split()[0],"%Y_%m_%d_%H") # #foretag.append(int(line.split("\t")[2])) # #foreweather.append(line.split("\t")[1]) # #hour_pre.append(int(line.split()[0].split("_")[-1])) # actualw.append(line.split("\t")[1]) # #day.append(line.split("\t")[4]) # actualConditions.close() # print len(actualw) #print "before" # if past: # inp = pastWeather.process(date, hours, self.datapath) # else: # #print date, hours # inp = weatherPrediction.process(date, hours, self.datapath) #print "abc" #for line in inp: # print line.strip() #start prediction #newtag = [] #newweather = [] #inp = open("modeldata/%d_%d_%d_wea.txt"%(date.month, date.day, date.year),"r") #for line in inp.readlines(): # #print line.split("\t")[5], line.split("\t")[15] # newtag.append(int(line.split("\t")[5])) # newweather.append(line.split("\t")[6]) # #day.append(line.split("\t")[4]) #inp.close() numData = hours+self.shiftFactor start = date-timedelta(hours=self.shiftFactor) endTime = date+timedelta(hours=hours-self.shiftFactor) #shift = endTime.hour shift = start.hour # #inp = open("fore.txt","r") # for line in inp.readlines(): # #print line # #print line.split("\t")[5], line.split("\t")[15] # #print int(line.split()[0].split("_")[-1]) # if shift == -1: # shift = int(line.split()[0].split("_")[-1]) # start = datetime.strptime(line.split()[0],"%Y_%m_%d_%H") # foretag.append(int(line.split("\t")[2])) # foreweather.append(line.split("\t")[1]) # hour_pre.append(int(line.split()[0].split("_")[-1])) # #day.append(line.split("\t")[4]) # inp.close() # #print "shift", shift pastprod = self.energyProduction.readPastProduction(start, numData) foretag,foreweather,hour_pre = self.weatherPredictor.getPredictions(start, numData) # os.system("echo \"%s\" >> foretag.txt"%(str(foretag))) # os.system("echo \"%s\" >> foreweather.txt"%(str(foreweather))) # os.system("echo \"%s\" >> hour_pre.txt"%(str(hour_pre))) # os.system("echo \"%s\" >> pastprod.txt"%(str(pastprod))) # os.system("echo \"%s\" >> shift.txt"%(str(shift))) #print "shift by",shift #print pastprod, len(pastprod) #print len(foretag), len(actualw) if len(pastprod)<len(foretag): print "actual data missing after ", start, len(pastprod), len(foretag) sys.exit(1) predictvalue = [] predictfore = [] # outp = tempfile.TemporaryFile()#open("pre.txt","w") prevfact = factor[1] #we assume last tracked tag is factor for sunny track_tag = factor[1] #we assume last tracked tag is factor for sunny state = self.last_call_state #print basevalue #debug code start #if not os.path.exists(path+"/debug"): # os.mkdir(path+"/debug") #if not os.path.isfile(path+"/debug/%0*d_%0*d_%0*d_tag.txt"%(2,date.year,2,date.month,2,date.day)): # fp = open(path+"/debug/%0*d_%0*d_%0*d_tag.txt"%(2,date.year,2,date.month,2,date.day),'w') # for i in range(1,len(factor)): # fp.write(mapping[i]+"\t"+`factor[i]`+"\t"+`factor2[i]`+"\n") # fp.close() #fp = file(path+"/debug/%0*d_%0*d_%0*d_%0*d_%0*d_wea.txt"%(2,date.year,2,date.month,2,date.day,2,date.hour,2,date.minute),'w') #debug code end #dt = datetime(now.year,now.month,now.day,now.hour) i = -1 for i in range(len(foretag)): #if newtag[i]>len(mapping) or (mapping[newtag[i]]=='Empty'): # print "No value for",newweather[i] # predictvalue.append(prevfact * basevalue[i%24]/100) #elif basevalue[i%24] == 0.0: # predictvalue.append(0.0) #else: # predictvalue.append(factor[newtag[i]]*basevalue[i%24]/100) # prevfact = factor[newtag[i]] #print i, foretag[i], hour_pre[i], len(mapping) if foretag[i]>=len(mapping) or (mapping[foretag[i]]=='Empty'): #print "No value for",foreweather[i] if self.error_exit==normal: if i>=(self.shiftFactor+2): predictfore.append(prevfact * basevalue[(i+shift)%24]/100) else: predictfore.append(track_tag * basevalue[(i+shift)%24]/100) elif state==self.lagerror or i<(self.shiftFactor+2): predictfore.append(track_tag * basevalue[(i+shift)%24]/100) else: predictfore.append(prevfact * basevalue[(i+shift)%24]/100) if self.debugging: self.debug[i].haveLastTag = False #elif basevalue[i%24] == 0.0: # predictvalue.append(0.0) elif hour_pre[i]<10 or hour_pre[i]>15: #if hour_pre[i]==8: # print factor2[foretag[i]]*basevalue[(i+shift)%24]/100, factor2[foretag[i]], basevalue[(i+shift)%24] predictfore.append(factor2[foretag[i]]*basevalue[(i+shift)%24]/100) prevfact = factor2[foretag[i]] else: predictfore.append(factor[foretag[i]]*basevalue[(i+shift)%24]/100) #print i, predictfore[i] prevfact = factor[foretag[i]] if self.debugging: self.debug[i].tagValue = prevfact tracked_pred = track_tag * basevalue[(i+shift)%24]/100 forecast_pred = predictfore[i] if self.error_exit==normal and i<(self.shiftFactor+2) and state==self.lagerror: predictfore[i] = tracked_pred prevfact = track_tag elif self.error_exit==enter_on_thresh and state==self.lagerror: #nontemp = predictfore[i] predictfore[i] = tracked_pred prevfact = track_tag elif self.error_exit==enter_on_error and state==self.lagerror: predictfore[i] = tracked_pred prevfact = track_tag #print i, predictfore[i]#, pastprod[i] #print date, newweather[i], predictvalue[i] if basevalue[(i+shift)%24]>0 and i<(self.shiftFactor+1): # factor[1] is the tag for sunny, we assume tags cant go over tag for sunny track_tag = min(pastprod[i]/basevalue[(i+shift)%24]*100, factor[1]) prev_state = state #exiting error correction mode if self.error_exit==normal and state<>normal_state: if i>=(self.shiftFactor+2): state = normal_state elif pastprod[i]==predictfore[i] or abs(pastprod[i]-forecast_pred)<self._reterror*pastprod[i]: state = normal_state elif self.error_exit==enter_on_thresh and state<>normal_state: if basevalue[(i+shift)%24]==0.0: state = normal_state elif self.error_exit==enter_on_error and state<>normal_state: if basevalue[(i+shift)%24]==0.0: state = normal_state #entering error correction mode elif self.error_exit==normal and i<(self.shiftFactor+1) and abs(pastprod[i]-forecast_pred)>self._1sterror*pastprod[i] and hour_pre[i]>8 and hour_pre[i]<17: state = min(self.lagerror, state+1) elif self.error_exit==enter_on_thresh and i<(self.shiftFactor+1) and abs(pastprod[i]-forecast_pred)>self._1sterror*pastprod[i] and hour_pre[i]>8 and hour_pre[i]<17: state = min(self.lagerror, state+1) elif self.error_exit==enter_on_error and i<(self.shiftFactor+1) and hour_pre[i]>8 and hour_pre[i]<17: #print abs(pastprod[i]-forecast_pred), abs(pastprod[i]-tracked_pred) if abs(pastprod[i]-forecast_pred) > abs(pastprod[i]-tracked_pred): state = min(self.lagerror, state+1) if i==(self.shiftFactor+2)-1: self.last_call_state = state #elif state==1 and abs(pastprod[i]-predictfore[i])>0.3*pastprod[i]: # state = min(2, state+1) # outp.write(str(date)+"\t"+foreweather[i]+"\t"+`predictfore[i]`+"\t"+`basevalue[(i+shift)%24]`+"\n") #print str(date-timedelta(hours=2))+"\t"+`hour_pre[i]`+"\t"+`tracked_pred`+"\t"+`forecast_pred`+"\t"+`pastprod[i]`+"\t"+foreweather[i]+"\t"+`factor[foretag[i]]`+"\t"+`basevalue[(i+shift)%24]`, prev_state #debug code start #fp.write(str(date)+"\t"+`hour_pre[i]`+"\t"+`predictfore[i]`+"\t"+foreweather[i]+"\t"+`pastprod[i]`+"\t"+`basevalue[(i+shift)%24]`+"\n") #debug code end if self.debugging: self.debug[i].baseValue = basevalue[(i+shift)%24] self.debug[i].tag = foreweather[i].replace(" ", "_") self.debug[i].prediction = predictfore[i] self.debug[i].actual = pastprod[i] self.debug[i].actualCondition = self.actualConditions.getConditionString(date).replace(" ", "_") date += timedelta(hours=1) # outp.close() #fp.close() #if i>-1 and self.debugging: # print str(date-timedelta(hours=3))+"\t"+`hour_pre[i]`+"\t"+`tracked_pred`+"\t"+`predictfore[i]`+"\t"+foreweather[i]+"\t"+`pastprod[i]`+"\t"+`basevalue[(i+shift)%24]`, prev_state if hours > len(predictfore): hours = len(predictfore) #print len(pastprod[2:hours+2])#, hours return predictfore[self.shiftFactor:hours+self.shiftFactor], pastprod[self.shiftFactor:hours+self.shiftFactor] # def process(self,now, hours, path, threshold, energy=20, offset=15, past=False,debugging=False): def process(self,now, hours): #global past #Md: control predication usage #if now.month == 8 or now.month==5 or now.month==6 or now.month==3: # past = 0 #else: # past = 1 now = datetime(now.year,now.month,now.day,now.hour) if hours > 49 and not self.useActualData: print "Prediction is wanted for more than 49 hours but we can only return 49 hours." hours = 49 if self.debugging: for i in range(hours+self.shiftFactor): try: d = self.debug[i] except IndexError: d = Debug(self.scaling) # print len(self.debug),i self.debug.append(d) d.reset() #print past result, actual = self.predictday(now, hours) #flag = False #if not os.path.isfile(path+"/pastpred.txt"): # flag = True #else: # pastfile = open(path+"/pastpred.txt", 'r') # lines = pastfile.readlines() # # if len(lines)==0 or now > datetime.strptime(lines[0].split("\t")[0],"%Y_%m_%d_%H_%M")+timedelta(hours=threshold): # # else: # d = datetime(now.year, now.month, now.day, now.hour) # j = 0 # for i in range(len(lines)): # date = datetime.strptime(lines[i].split("\t")[0],"%Y_%m_%d_%H_%M") # if d==date: # if abs(result[j]-float(lines[i].split("\t")[1]))>energy: # flag = True # break # j += 1 # d += timedelta(hours=1) # pastfile.close() #pastfile = open(path+"/pastpred.txt", 'w') #now = datetime(now.year, now.month, now.day, now.hour) #for i in range(len(result)): # pastfile.write((now).strftime("%Y_%m_%d_%H_%M")+"\t"+`result[i]`+"\n") # now+=timedelta(hours=1) #pastfile.close() #print len(h),len(result), len(actual) return result, actual class CachedEnergyPredictor(EnergyPredictor): def __init__(self,startDate,endDate=None,predictionHorizon=48,path='.',threshold=3, scalingFactor=1347, offset=15,energythreshold=20, useActualData=False,scalingBase=1347,debugging=False,error_exit=normal): global hourFormat super(CachedEnergyPredictor,self).__init__(path, threshold, scalingFactor, offset, energythreshold, useActualData, scalingBase, debugging, error_exit) self.startDate = datetime(startDate.year,startDate.month,startDate.day,startDate.hour) self.predictionHorizon = predictionHorizon # EnergyPredictor.__init__(self, path, threshold, scalingFactor, offset, energythreshold, useActualData, scalingBase, debugging) if not endDate: self.endDate = (startDate+timedelta(days=5)-timedelta(hours=9)) else: self.endDate = datetime(endDate.year,endDate.month,endDate.day,endDate.hour) if endDate.minute>0: self.endDate += timedelta(hours=1) self.cachedPredictionDir = os.path.join(self.datapath,"cachedPredictions") if not os.path.exists(self.cachedPredictionDir): os.makedirs(self.cachedPredictionDir) ##let's populate the predictions currentDate = self.startDate self.predictions = [] self.otherPredictions = {} tdelta = timedelta(hours=1) while currentDate < self.endDate: fname = os.path.join(self.cachedPredictionDir,"%s_%d"%(currentDate.strftime(hourFormat),self.predictionHorizon)) if os.path.exists(fname): fd = open(fname,'r') (greenAvail, flag) = pickle.load(fd) else: greenAvail, flag = super(CachedEnergyPredictor,self).getGreenAvailability(currentDate, self.predictionHorizon) fd = open(fname,'w') pickle.dump((greenAvail, flag), fd) fd.close() self.predictions.append((greenAvail, flag)) currentDate+=tdelta def lookUpInOthers(self,now,horizon): if self.otherPredictions.has_key(horizon): table = self.otherPredictions[horizon] else: table = {} self.otherPredictions[horizon] = table #now look up in the table if table.has_key(now): retval,flag = table[now] else: retval, flag = super(CachedEnergyPredictor,self).getGreenAvailability(now, horizon) table[now] = (retval,flag) return retval,flag def getGreenAvailability(self, now, hours): currentHour = datetime(now.year,now.month,now.day,now.hour) if hours == self.predictionHorizon: tdelta = currentHour - self.startDate # numSeconds = tdelta.total_seconds() numSeconds = tdelta.days * 24*3600 + tdelta.seconds index = numSeconds/3600 try: retval,flag = self.predictions[index] except IndexError: #look in to other retval,flag = self.lookUpInOthers(currentHour,hours) else: retval,flag = self.lookUpInOthers(currentHour,hours) if not currentHour == now: #not the beginning of hour retval[0] = self.scaling * self.energyProduction.getProduction(currentHour) return retval,flag if __name__ == '__main__': #now = datetime.now() now = datetime(2010, 7, 14, 23, 0,0) p = EnergyPredictor(threshold=3,energythreshold=20,offset=15) flag,retval = p.process(now, 48) print retval, len(retval) #start = datetime(2010,06,16) #for i in range(14): # tag = [] # weather = [] # data = [] #predictday(start) #calctag() # start += timedelta(days=1) # if fnmatch.fnmatch(datafile,"*.txt"): # inp = open(datafile,"r") # for line in inp.readlines(): #print line.split("\t")[5], line.split("\t")[15] # tag.append(int(line.split("\t")[5])) # weather.append(line.split("\t")[6]) # data.append(float(line.split("\t")[15])) #print data, tag #calctag() <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ # bash: for file in `ls logs/`; do python ghadoopparser.py logs/$file/$file > logs/$file/$file-summary.log; done import sys import math from ghadoopcommons import * LOG_ENERGY = "ghadoop-energy.log" LOG_JOBS = "ghadoop-jobs.log" LOG_SCHEDULER = "ghadoop-scheduler.log" if len(sys.argv)>1: LOG_ENERGY = sys.argv[1]+"-energy.log" LOG_JOBS = sys.argv[1]+"-jobs.log" LOG_SCHEDULER = sys.argv[1]+"-scheduler.log" SOLAR_0 = "data/solarpower-15-05-2011" SOLAR_1 = "data/solarpower-09-05-2011" SOLAR_2 = "data/solarpower-12-05-2011" SOLAR_3 = "data/solarpower-14-06-2011" SOLAR_4 = "data/solarpower-16-06-2011" LOG_SOLAR = SOLAR_1 # Extra functions # Get the available green power def readGreenAvailFile(filename): greenAvailability = [] file = open(filename, 'r') for line in file: if line != '' and line.find("#")!=0 and line != '\n': lineSplit = line.strip().expandtabs(1).split(' ') t=lineSplit[0] p=float(lineSplit[1]) # Apply scale factor TODO p = (p/2300.0)*MAX_POWER greenAvailability.append(TimeValue(t,p)) file.close() return greenAvailability # Energy file prevLineSplit = None totalEnergyGreen = 0.0 totalEnergyBrown = 0.0 totalEnergyTotal = 0.0 totalEnergyBrownCost = 0.0 totalEnergyGreenAvail = 0.0 totalTime = 0 #totalTime = 7200 #timeFinishWorkload = 7200 # Nodes runNodes = 0.0 upNodes = 0.0 decNodes = 0.0 # Peak maxPowerPeak = 0.0 peakControlTime = [] peakControlPowe = [] SPEEDUP = 24 ACCOUNTING_PERIOD=(15*60/3600.0)/SPEEDUP # hours numNodes = 0 # Read solar solarAvailable = readGreenAvailFile(LOG_SOLAR) options = {} # Read energy file, line by line for line in open(LOG_ENERGY, "r"): if line.startswith("#"): if line.find("Options = ")>=0: optionsLine = line[line.find("{")+1:line.find("}")] for option in optionsLine.split(", "): option = option.replace("'", "") optionSplit = option.split(": ") options[optionSplit[0]] = optionSplit[1] elif line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = float(lineSplit[1]) # Green availability lineSplit[2] = float(lineSplit[2]) # Green prediction lineSplit[3] = float(lineSplit[3]) # Brown price lineSplit[4] = int(lineSplit[4]) # Run Nodes lineSplit[5] = int(lineSplit[5]) # Up Nodes lineSplit[6] = int(lineSplit[6]) # Dec Nodes lineSplit[7] = float(lineSplit[7]) # Green use lineSplit[8] = float(lineSplit[8]) # Brown use lineSplit[9] = float(lineSplit[9]) # Total use t = lineSplit[0] # Get solar from external file... solarAvailableNow = 0.0 for i in range(0, len(solarAvailable)): if t*24 >= solarAvailable[i].t: solarAvailableNow = solarAvailable[i].v else: break # Nodes if numNodes<lineSplit[6]: numNodes = lineSplit[6] # Parse info if prevLineSplit != None: t = (lineSplit[0]-prevLineSplit[0])/3600.0 #energyGreenAvail = t * prevLineSplit[1] energyGreenAvail = t * solarAvailableNow energyTotal = t * prevLineSplit[9] if energyTotal>energyGreenAvail: energyGreen = energyGreenAvail energyBrown = energyTotal - energyGreenAvail else: energyGreen = energyTotal energyBrown = 0.0 #energyGreen = t * prevLineSplit[7] #energyBrown = t * prevLineSplit[8] energyBrownCost = (energyBrown/1000.0)*prevLineSplit[3] # Nodes runNodes += 3600.0 * t * prevLineSplit[4] upNodes += 3600.0 * t * prevLineSplit[5] decNodes += 3600.0 * t * prevLineSplit[6] # Peak power accounting #print prevLineSplit peakControlTime.append(t) peakControlPowe.append(prevLineSplit[8]) #while sum(peakControlTime)-peakControlTime[0]>ACCOUNTING_PERIOD: while sum(peakControlTime)>ACCOUNTING_PERIOD: peakControlTime.pop(0) peakControlPowe.pop(0) while len(peakControlTime)>1 and peakControlTime[0] == 0: peakControlTime.pop(0) peakControlPowe.pop(0) powerPeak = 0 for i in range(0, len(peakControlTime)): #print str(peakControlTime[i])+"h "+str(peakControlPowe[i])+"W" #powerPeak += (peakControlTime[i]/ACCOUNTING_PERIOD) * peakControlPowe[i] if sum(peakControlTime)>0: powerPeak += (peakControlTime[i]/sum(peakControlTime)) * peakControlPowe[i] if powerPeak>maxPowerPeak: maxPowerPeak = powerPeak if prevLineSplit[0]>totalTime: totalTime = prevLineSplit[0] #print "Current = "+str(powerPeak)+" Peak = "+str(maxPowerPeak) # Totals totalEnergyGreen += energyGreen totalEnergyBrown += energyBrown totalEnergyTotal += energyTotal totalEnergyBrownCost += energyBrownCost totalEnergyGreenAvail += energyGreenAvail prevLineSplit = lineSplit runNodes = runNodes/totalTime upNodes = upNodes/totalTime decNodes = decNodes/totalTime # Read job file, line by line jobs = {} jobsFinished = [] jobsStartEnd = {} tasks = {} taskMap = [] taskRed = [] tasksHigh = [] tasksNormal = [] timeTasks = [] timeTasksHigh = [] timeTasksNone = [] timeJobs = [] totalRuntime = 0 totalMapRuntime = 0 totalRedRuntime = 0 #timeFinishWorkload = 0 totalTimeJobs = 0.0 totalTimeJobsNum = 0 totalTimeJobsNormal = 0.0 totalTimeJobsNormalNum = 0 totalTimeJobsHigh = 0.0 totalTimeJobsHighNum = 0 for line in open(LOG_JOBS, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # TaskId lineSplit[2] = lineSplit[2] # JobId lineSplit[3] = lineSplit[3] # Node lineSplit[4] = lineSplit[4] # Priority lineSplit[5] = int(lineSplit[5]) # Submit lineSplit[6] = int(lineSplit[6]) # Start lineSplit[7] = int(lineSplit[7]) # End lineSplit[8] = int(lineSplit[8]) # Wait lineSplit[9] = int(lineSplit[9]) # Run lineSplit[10] = int(lineSplit[10]) # Total jobId = lineSplit[2] if jobId not in jobsStartEnd: jobsStartEnd[jobId] = (lineSplit[5], None) t = lineSplit[0] if lineSplit[3].startswith("['"): # Job timeJobs.append((t, lineSplit[2])) if jobId not in jobsFinished: jobsFinished.append(jobId) jobsStartEnd[jobId] = (jobsStartEnd[jobId][0], lineSplit[10]) totalTimeJobs += lineSplit[10] totalTimeJobsNum += 1 if lineSplit[4].find("HIGH")>=0: totalTimeJobsHigh += lineSplit[10] totalTimeJobsHighNum += 1 else: totalTimeJobsNormal += lineSplit[10] totalTimeJobsNormalNum += 1 # If the task is not a job setup task elif line.find("JobSetup")<0: # Task taskId = lineSplit[1] if taskId not in tasks: tasks[taskId] = None if jobId not in jobs: jobs[jobId] = [] jobs[jobId].append(taskId) totalRuntime += lineSplit[9] # Map or Reduce if taskId.find("_m_")>=0: taskMap.append(taskId) totalMapRuntime += lineSplit[9] elif taskId.find("_r_")>=0: taskRed.append(taskId) totalRedRuntime += lineSplit[9] # Priority timeTasks.append((t, taskId)) if lineSplit[4].find("HIGH")>=0: timeTasksHigh.append((t, taskId)) if taskId not in tasksHigh: tasksHigh.append(taskId) else: timeTasksNone.append((t, taskId)) if taskId not in tasksNormal: tasksNormal.append(taskId) # Clean too old tasks MEASURE_INTERVAL = 300.0 while len(timeTasks)>0 and t-timeTasks[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasks[0] while len(timeTasksHigh)>0 and t-timeTasksHigh[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasksHigh[0] while len(timeTasksNone)>0 and t-timeTasksNone[0][0]>MEASURE_INTERVAL: # 5 minutes del timeTasksNone[0] # Clean too old jobs while len(timeJobs)>0 and t-timeJobs[0][0]>MEASURE_INTERVAL: # 5 minutes del timeJobs[0] # Read scheudler file, line by line replications = [] replStart = 0 replDone = 0 submittedJobs = 0 deadlineActions = 0 for line in open(LOG_SCHEDULER, "r"): if not line.startswith("#") and line!="\n": line = line.replace("\n", "") lineSplit = line.split("\t") # Getting info try: lineSplit[0] = int(lineSplit[0]) # Time lineSplit[1] = lineSplit[1] # Message # File replication if lineSplit[1].startswith("Changed"): replDone += 1 fileName = lineSplit[1].split(" ")[2] if fileName not in replications: replications.append(fileName) elif lineSplit[1].startswith("Change"): replStart +=1 fileName = lineSplit[1].split(" ")[2] if fileName not in replications: replications.append(fileName) # Queues if lineSplit[1].startswith("Queues"): if int(lineSplit[9]) > submittedJobs: submittedJobs = int(lineSplit[9]) if line.find("eadline")>=0: deadlineActions += 1 except: None totalEnergyIdle = ((numNodes*Node.POWER_S3)+POWER_IDLE_GHADOOP) * totalTime/3600.0 greenUtilization = 0.0 if totalEnergyGreenAvail>0.0: greenUtilization = 100.0*totalEnergyGreen/totalEnergyGreenAvail # Print summary #print "Power:" #print "\tGreen: %.2f kWh (%.2f/%.2f Wh %.2f%%)" % (totalEnergyGreen/1000.0, totalEnergyGreen, totalEnergyGreenAvail, greenUtilization) #print "\tBrown: %.2f kWh (%.2f Wh)" % (totalEnergyBrown/1000.0, totalEnergyBrown) #print "\tIdle: %.2f kWh (%.2f Wh)" % (totalEnergyIdle/1000.0, totalEnergyIdle) #print "\tWork: %.2f kWh (%.2f Wh)" % ((totalEnergyTotal-totalEnergyIdle)/1000.0, totalEnergyTotal-totalEnergyIdle) #print "\tTotal: %.2f kWh (%.2f Wh)" % (totalEnergyTotal/1000.0, totalEnergyTotal) #print "\tCost: $%.4f" % (totalEnergyBrownCost) #print "\tPeak: %.2f W" % (maxPowerPeak) #print "Nodes: %d" % (numNodes) #print "Time: %d s" % (totalTime) #print "\tWork: %d s" % (timeFinishWorkload) #print "\tRun: %d s" % (totalRuntime) #print "\tOccup Total: %.2f%% = %.2f / %.2fx%.2f" % (100.0*totalRuntime/(totalTime*numNodes), totalRuntime, totalTime, numNodes) #occup = 0.0 #if timeFinishWorkload>0.0: #occup = 100.0*totalRuntime/(timeFinishWorkload*numNodes) #print "\tOccup Work: %.2f%%" % (occup) #print "Jobs: %d" % (len(jobs)) #if len(jobs)>0: #print "\tTasks: %.2f" % (float(len(tasks))/len(jobs)) #print "\tLength: %.2f s" % (totalRuntime/float(len(jobs))) #print "\tEnergy: %.2f Wh" % ((totalEnergyTotal-totalEnergyIdle)/len(jobs)) #print "Tasks: %d" % (len(tasks)) #if len(tasks)>0: #print "\tLength: %.2f s" % (totalRuntime/float(len(tasks))) #print "\tEnergy: %.2f Wh" % ((totalEnergyTotal-totalEnergyIdle)/len(tasks)) #print "Performance:" #print "\t%.2f tasks/second " % (finalSpeedTasks) #if totalEnergyBrown>0: #print "\t%.2f tasks/hour / Wh" % (finalSpeedTasks*3600.0/totalEnergyBrown) #if totalEnergyBrownCost>0: #print "\t%.2f tasks/hour / $" % (finalSpeedTasks*3600.0/totalEnergyBrownCost) #print "\t%.2f jobs/hour " % (finalSpeedJobs*3600.0) #if totalEnergyBrown>0: #print "\t%.2f jobs/hour / Wh" % (finalSpeedJobs*3600.0/totalEnergyBrown) #if totalEnergyBrownCost>0: #print "\t%.2f jobs/hour / $" % (finalSpeedJobs*3600.0/totalEnergyBrownCost) #print "Repl: %d/%d" % (replStart, replDone) #print "Repl: %d" % (len(replications)) # Print summary HTML print "<ul>" print "<li>Energy consumption: %.2f kWh (%.2f Wh)</li>" % (totalEnergyTotal/1000.0, totalEnergyTotal) print "\t<ul>" print "\t<li>Green: %.2f kWh (%.2f/%.2f Wh %.2f%%)</li>" % (totalEnergyGreen/1000.0, totalEnergyGreen, totalEnergyGreenAvail, greenUtilization) print "\t<li>Brown: %.2f kWh (%.2f Wh)</li>" % (totalEnergyBrown/1000.0, totalEnergyBrown) print "\t<li>Idle: %.2f kWh (%.2f Wh)</li>" % (totalEnergyIdle/1000.0, totalEnergyIdle) print "\t<li>Work: %.2f kWh (%.2f Wh)</li>" % ((totalEnergyTotal-totalEnergyIdle)/1000.0, totalEnergyTotal-totalEnergyIdle) pricePeak = 5.5884 if "peakCost" in options: pricePeak = float(options["peakCost"]) print "\t<li>Energy cost: $%.4f</li>" % (totalEnergyBrownCost) print "\t<li>Peak power: %.2f W (%.2f kW x $%.2f/kW = $%.2f)</li>" % (maxPowerPeak, maxPowerPeak/1000.0, pricePeak, (maxPowerPeak/1000.0)*pricePeak) totalCost = totalEnergyBrownCost*SPEEDUP*15+(maxPowerPeak/1000.0)*pricePeak print "\t<li>Total cost: $%.2f + $%.2f = $%.2f</li>" % (totalEnergyBrownCost*SPEEDUP*15, (maxPowerPeak/1000.0)*pricePeak, totalCost) print "\t</ul>" print "<li>Nodes: %d</li>" % (numNodes) print "\t<ul>" print "\t<li>Run: %.2f</li>" % (runNodes) print "\t<li>Up: %.2f</li>" % (upNodes) print "\t<li>On: %.2f</li>" % (decNodes) print "\t<li>Total: %.2f</li>" % (numNodes) print "\t<li>Utilization: %.2f%%</li>" % (100.0*runNodes/numNodes) print "\t</ul>" # Slot utilization*1.5 / Node utilization (UP) = Utilization of the available slots print "<li>Experiment duration: %d s</li>" % (totalTime) print "\t<ul>" #print "\t<li>Working time: %d s</li>" % (timeFinishWorkload) if totalTime > 0: #print "\t<li>Utilization: %.2f%% = %.2f / %.2fx%dx%d</li>" % (100.0*totalRuntime/(totalTime*numNodes*TASK_NODE), totalRuntime, totalTime, numNodes, TASK_NODE) print "\t<li>Utilization: %.2f%% = %.2f / %.2fx%dx%d</li>" % (100.0*totalRuntime/(totalTime*numNodes*TASK_NODE), totalRuntime, totalTime, numNodes, TASK_NODE) print "\t<li>Utilization maps: %.2f%% = %.2f / %.2fx%dx%d</li>" % (100.0*totalMapRuntime/(totalTime*numNodes*MAP_NODE), totalMapRuntime, totalTime, numNodes, MAP_NODE) print "\t</ul>" print "<li>Jobs: %d</li>" % (len(jobsFinished)) # Deadline stats violations = 0 if len(jobs)>0: possibleViolations = 0 percentageViolation = 0 totalViolation = 0 if "deadline" in options: DEADLINE = float(options["deadline"]) for jobId in jobsStartEnd: if jobsStartEnd[jobId] == None: # The job is violating the deadline if (jobsStartEnd[jobId][0]+DEADLINE) < totalTime: possibleViolations += 1 violations += 1 percentageViolation += 100.0*(DEADLINE-jobsStartEnd[jobId][1])/DEADLINE print "%s %s violation: %d %.2f%%" % (jobId, str(jobsStartEnd[jobId]), DEADLINE-jobsStartEnd[jobId][1], 100.0*(DEADLINE-jobsStartEnd[jobId][1])/DEADLINE) else: possibleViolations += 1 if jobsStartEnd[jobId][1]>DEADLINE: violations += 1 totalViolation += DEADLINE-jobsStartEnd[jobId][1] percentageViolation += 100.0*(DEADLINE-jobsStartEnd[jobId][1])/DEADLINE print "%s %s violation: %ds %.2f%%" % (jobId, str(jobsStartEnd[jobId]), DEADLINE-jobsStartEnd[jobId][1], 100.0*(DEADLINE-jobsStartEnd[jobId][1])/DEADLINE) print "\t<ul>" print "\t<li>Run: %d</li>" % (len(jobs)) print "\t<li>Finished: %d/%d</li>" % (len(jobsFinished), submittedJobs) print "\t<li>Deadline actions: %d</li>" % (deadlineActions) aux = 0.0 if violations>0: aux = percentageViolation/violations print "\t<li>Violate (%ds): %d/%d (%ds %.2f%%)</li>" % (DEADLINE, violations, possibleViolations, totalViolation, aux) print "\t<li>Avg tasks: %.2f tasks/job</li>" % (float(len(tasks))/len(jobs)) print "\t<li>Avg length: %.2f seconds/job</li>" % (totalRuntime/float(len(jobs))) print "\t<li>Avg energy: %.2f Wh/job</li>" % ((totalEnergyTotal-totalEnergyIdle)/len(jobs)) print "\t<li>Avg total time: %.2f seconds</li>" % (totalTimeJobs/totalTimeJobsNum) print "\t<ul>" aux = 0.0 if totalTimeJobsHighNum>0: aux = totalTimeJobsHigh/totalTimeJobsHighNum print "\t\t<li>High: %.2f seconds</li>" % (aux) aux = 0.0 if totalTimeJobsNormalNum>0: aux = totalTimeJobsNormal/totalTimeJobsNormalNum print "\t\t<li>Normal: %.2f seconds</li>" % (aux) print "\t</ul>" print "\t</ul>" print "<li>Tasks: %d (%d + %d)</li>" % (len(tasks), len(taskMap), len(taskRed)) if len(tasks)>0: print "\t<ul>" print "\t<li>Running time: %d s (%d + %d)</li>" % (totalRuntime, totalMapRuntime, totalRedRuntime) print "\t<li>Avg length: %.2f s (%.2f + %.2f)</li>" % (totalRuntime/float(len(tasks)), totalMapRuntime/float(len(taskMap)), totalRedRuntime/float(len(taskRed))) print "\t<li>Avg energy: %.2f Wh (%.2f Wh)</li>" % ((totalEnergyTotal-totalEnergyIdle)/len(tasks), totalEnergyTotal/len(tasks)) print "\t</ul>" print "<li>Task performance:</li>" print "\t<ul>" print "\t<li>%.2f tasks/second</li>" % (1.0*len(tasks)/totalTime) print "\t<ul>" print "\t\t<li>High: %.2f tasks/second</li>" % (1.0*len(tasksHigh)/totalTime) print "\t\t<li>Normal: %.2f tasks/second</li>" % (1.0*len(tasksNormal)/totalTime) print "\t</ul>" if totalEnergyBrown>0: print "\t<li>%.2f tasks/hour / Wh</li>" % ((3600.0*len(tasks)/totalTime)/totalEnergyBrown) if totalEnergyBrownCost>0: print "\t<li>%.2f tasks/hour / $</li>" % (3600.0*len(tasks)/totalTime/totalEnergyBrownCost) #print "\t<li>%.2f jobs/hour</li>" % (finalSpeedJobs*3600.0) print "\t</ul>" print "<li>Job performance:</li>" print "\t<ul>" print "\t<li>%.2f jobs/hour</li>" % (3600.0*len(jobsFinished)/totalTime) if totalEnergyBrown>0: print "\t<li>%.2f jobs/hour / Wh</li>" % (3600.0*len(jobsFinished)/totalTime/totalEnergyBrown) if totalEnergyBrownCost>0: print "\t<li>%.2f jobs/hour / $</li>" % (3600.0*len(jobsFinished)/totalTime/totalEnergyBrownCost) if len(jobsFinished)>0: print "\t<li>$%.2f/job</li>" % (totalCost/len(jobsFinished)) print "\t</ul>" print "<li>Replicated files: %d</li>" % (len(replications)) print "\t<ul>" print "\t<li>Start: %d</li>" % (replStart) print "\t<li>Done: %d</li>" % (replDone) print "\t</ul>" print "</ul>" # Summaryzing if len(tasks)>0 and numNodes>0 and totalTime>0: print "Summary spreadsheet<br/>" summary = "%.2f %.2f %.2f %.2f %.5f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %d %.2f %.2f %d %.2f" % (totalEnergyGreen/1000.0, totalEnergyGreenAvail/1000.0, totalEnergyBrown/1000.0, totalEnergyTotal/1000.0, totalEnergyBrownCost, maxPowerPeak/1000.0, pricePeak, (maxPowerPeak/1000.0)*pricePeak, 100.0*totalMapRuntime/(totalTime*numNodes*MAP_NODE), 100.0*totalRuntime/(totalTime*numNodes*TASK_NODE), upNodes, decNodes, 100.0*runNodes/numNodes, len(jobsFinished), 1.0*len(tasks)/totalTime, 3600.0*len(jobsFinished)/totalTime, violations, (totalEnergyTotal-totalEnergyIdle)/len(tasks)) print summary+"<br/>" print summary+"<br/>" <file_sep>#!/bin/bash # GreenHadoop makes Hadoop aware of solar energy availability. # http://www.research.rutgers.edu/~goiri/ # Copyright (C) 2012 <NAME>, Rutgers University # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> export HADOOP_HOME="/home/goiri/hadoop-0.21.0" MASTER_NODE="crypt15" function experiment { NAME=$1 shift FLAGS=$* echo "name="$NAME" flags="$FLAGS touch $HADOOP_HOME/logs/hadoop-goiri-jobtracker-$MASTER_NODE.log touch $HADOOP_HOME/logs/hadoop-goiri-namenode-$MASTER_NODE.log # Clean system echo "Cleanning..." cleaned=0 retries=3 while (( "$cleaned" == "0" )) && (( "$retries" > "0" )); do cleaned=1 ./ghadoopclean.py > /dev/null & TESTPID=$! a=0 while ps -p $TESTPID >/dev/null; do sleep 1 let a=a+1 if [ $a -gt 400 ]; then echo "Clean failed: try again..." kill -9 $TESTPID cleaned=0 let retries=retries-1 fi done done # Date echo "Setting time..." AUXDATE=`date` ssh root@crypt15 $HADOOP_HOME/bin/slaves.sh date -s \"$AUXDATE\" >/dev/null sleep 1 echo "Starting..." rm -f logs/ghadoop-jobs.log rm -f logs/ghadoop-energy.log rm -f logs/ghadoop-scheduler.log rm -f logs/ghadoop-error.log touch logs/ghadoop-error.log sleep 1 ./ghadoopd $FLAGS # Save results mkdir -p logs/$NAME # echo $NAME > logs/$NAME/$NAME-summary.log ./ghadoopparser.py logs/ghadoop >> logs/$NAME/$NAME-summary.html mv logs/ghadoop-jobs.log logs/$NAME/$NAME-jobs.log mv logs/ghadoop-energy.log logs/$NAME/$NAME-energy.log mv logs/ghadoop-scheduler.log logs/$NAME/$NAME-scheduler.log mv logs/ghadoop-error.log logs/$NAME/$NAME-error.log # Plot results: energy # echo "set term svg size 1280,600" > logs/$NAME/$NAME.plot echo "set term svg size 960,450" > logs/$NAME/$NAME.plot echo "set out \"logs/$NAME/$NAME-energy.svg\"" >> logs/$NAME/$NAME.plot echo "set ylabel \"Power (kW)\"" >> logs/$NAME/$NAME.plot # echo "set yrange [0:1.8]" >> logs/$NAME/$NAME.plot echo "set yrange [0:2.4]" >> logs/$NAME/$NAME.plot echo "set y2label \"Brown energy price ($/kWh)\"" >> logs/$NAME/$NAME.plot echo "set y2range [0:0.3]" >> logs/$NAME/$NAME.plot echo "set y2tics" >> logs/$NAME/$NAME.plot echo "set ytics nomirror" >> logs/$NAME/$NAME.plot echo "set xdata time" >> logs/$NAME/$NAME.plot echo "set timefmt \"%s\"" >> logs/$NAME/$NAME.plot echo "set format x \"%a\n%R\"" >> logs/$NAME/$NAME.plot echo "set format x \"%a %R\"" >> logs/$NAME/$NAME.plot echo "set style fill solid" >> logs/$NAME/$NAME.plot echo "plot \"logs/$NAME/$NAME-energy.log\" using (\$1*24):(\$10/1000) lc rgb \"#808080\" w filledcurve title \"Brown consumed\",\\" >> logs/$NAME/$NAME.plot echo "\"logs/$NAME/$NAME-energy.log\" using (\$1*24):(\$8/1000) lc rgb \"#e6e6e6\" w filledcurve title \"Green consumed\",\\" >> logs/$NAME/$NAME.plot # echo "\"logs/$NAME/$NAME-energy.log\" using (\$1+(2*24*24+10*24)):(\$2/1000) lw 2 lc rgb \"black\" w steps title \"Green predicted\",\\" >> logs/$NAME/$NAME.plot echo "\"logs/$NAME/$NAME-energy.log\" using (\$1*24):(\$3/1000) lw 2 lc rgb \"black\" w steps title \"Green predicted\",\\" >> logs/$NAME/$NAME.plot echo "\"logs/$NAME/$NAME-energy.log\" using (\$1*24):4 axes x1y2 lw 2 lc rgb \"black\" w steps title \"Brown price\"" >> logs/$NAME/$NAME.plot gnuplot logs/$NAME/$NAME.plot # Plot results: nodes # echo "set term svg size 1280,600" > logs/$NAME/$NAME.plot echo "set term svg size 960,450" > logs/$NAME/$NAME-nodes.plot echo "set out \"logs/$NAME/$NAME-nodes.svg\"" >> logs/$NAME/$NAME-nodes.plot echo "set ylabel \"Nodes\"" >> logs/$NAME/$NAME-nodes.plot echo "set yrange [0:16]" >> logs/$NAME/$NAME-nodes.plot echo "set xdata time" >> logs/$NAME/$NAME-nodes.plot echo "set timefmt \"%s\"" >> logs/$NAME/$NAME-nodes.plot echo "set format x \"%a\n%R\"" >> logs/$NAME/$NAME-nodes.plot echo "set format x \"%a %R\"" >> logs/$NAME/$NAME-nodes.plot echo "set style fill solid" >> logs/$NAME/$NAME-nodes.plot echo "plot \"logs/$NAME/$NAME-energy.log\" using (\$1*24):7 lw 2 lc rgb \"#C0C0C0\" w filledcurve title \"Dec nodes\",\\" >> logs/$NAME/$NAME-nodes.plot echo "\"logs/$NAME/$NAME-energy.log\" using (\$1*24):6 lc rgb \"#909090\" w filledcurve title \"Up nodes\",\\" >> logs/$NAME/$NAME-nodes.plot echo "\"logs/$NAME/$NAME-energy.log\" using (\$1*24):5 lc rgb \"#404040\" w filledcurve title \"Run nodes\"" >> logs/$NAME/$NAME-nodes.plot gnuplot logs/$NAME/$NAME-nodes.plot } # DATE_MOST="2010-5-31T09:00:00" # SOLAR_MOST="data/solarpower-31-05-2010" # Best energy BROWN_SUMMER="data/browncost-onoffpeak-summer.nj" BROWN_WINTER="data/browncost-onoffpeak-winter.nj" PEAK_WINTER=5.5884 # Winter October-May PEAK_SUMMER=13.6136 # Summer June-Sep # High High DATE_1="2011-5-9T00:00:00" SOLAR_1="data/solarpower-09-05-2011" BROWN_1=$BROWN_WINTER PEAK_1=$PEAK_WINTER # High Medium DATE_2="2011-5-12T00:00:00" SOLAR_2="data/solarpower-12-05-2011" BROWN_2=$BROWN_WINTER PEAK_2=$PEAK_WINTER # Medium High DATE_3="2011-6-14T00:00:00" SOLAR_3="data/solarpower-14-06-2011" BROWN_3=$BROWN_SUMMER PEAK_3=$PEAK_SUMMER # Medium Medium DATE_4="2011-6-16T00:00:00" SOLAR_4="data/solarpower-16-06-2011" BROWN_4=$BROWN_SUMMER PEAK_4=$PEAK_SUMMER # Low Low DATE_0="2011-5-15T00:00:00" SOLAR_0="data/solarpower-15-05-2011" BROWN_0=$BROWN_WINTER PEAK_0=$PEAK_WINTER # Workloads WORKLOAD_LOADGEN_030="workload/workload-continuous-030-loadgen" WORKLOAD_HETE="workload/workload-hete" WORKLOAD_BIGCHANGE="workload/workload-bigchange" WORKLOAD_RED_015="workload/workload-continuous-015-red" WORKLOAD_RED_030="workload/workload-continuous-030-red" WORKLOAD_RED_060="workload/workload-continuous-060-red" WORKLOAD_RED_090="workload/workload-continuous-090-red" # Not used # WORKLOAD_CONT_015="workload/workload-continuous-015" # WORKLOAD_CONT_030="workload/workload-continuous-030" # WORKLOAD_CONT_060="workload/workload-continuous-060" # WORKLOAD_CONT_090="workload/workload-continuous-090" # # WORKLOAD_CONT_045="workload/workload-continuous-045" # WORKLOAD_CONT_075="workload/workload-continuous-075" # WORKLOAD_CONT_100="workload/workload-continuous-100" # Nutch # WORKLOAD_NUTCH="workload/workload-nutch-030" WORKLOAD_NUTCH2="workload/workload-nutch-008" WORKLOAD_HIGH1="workload/workload-continuous-high1-3" WORKLOAD_HIGH2="workload/workload-continuous-high2-3" TASK_ENERGY_015=0.30 TASK_ENERGY_030=0.35 TASK_ENERGY_060=0.45 TASK_ENERGY_090=0.55 TASK_ENERGY_NUTCH=0.14 REPLICATION=10 # After submission # experiment "bigchange2-greenpeak-day1-30seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_BIGCHANGE experiment "bigchange3-hadooppm-day1-30seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_BIGCHANGE # Experiments start # Asumption and utilization # experiment "10-greenpeak-day1-15seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_015 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_015 # experiment "11-greenpeak-day1-30seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_030 # experiment "12-greenpeak-day1-60seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_060 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_060 # experiment "13-greenpeak-day1-90seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_090 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_090 # experiment "20-hadoop-day1-30seconds" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_030 # experiment "21-hadooppm-day1-30seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_030 # GreenOnly # experiment "22-greenonly-day1-30seconds" --energy --nobrown --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_030 # GreenVarPrices # experiment "30-greenvarprices-day1-30seconds" --energy --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_030 # Perfect vs unknown # experiment "50-greenpeak-day1-30seconds-perfect" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_030 # experiment "51-greenpeak-day2-30seconds-perfect" --energy --peak $PEAK_2 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_2 --speedup 24 --brownfile $BROWN_2 --greenfile $SOLAR_2 -w $WORKLOAD_RED_030 # experiment "52-greenpeak-day3-30seconds-perfect" --energy --peak $PEAK_3 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_3 --speedup 24 --brownfile $BROWN_3 --greenfile $SOLAR_3 -w $WORKLOAD_RED_030 # experiment "53-greenpeak-day4-30seconds-perfect" --energy --peak $PEAK_4 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_4 --speedup 24 --brownfile $BROWN_4 --greenfile $SOLAR_4 -w $WORKLOAD_RED_030 # experiment "54-greenpeak-day0-30seconds-perfect" --energy --peak $PEAK_0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_0 --speedup 24 --brownfile $BROWN_0 --greenfile $SOLAR_0 -w $WORKLOAD_RED_030 # Different days # experiment "55-greenpeak-day2-30seconds" --energy --peak $PEAK_2 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_2 --speedup 24 --brownfile $BROWN_2 --greenfile $SOLAR_2 --pred -w $WORKLOAD_RED_030 # experiment "56-greenpeak-day3-30seconds" --energy --peak $PEAK_3 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_3 --speedup 24 --brownfile $BROWN_3 --greenfile $SOLAR_3 --pred -w $WORKLOAD_RED_030 # experiment "57-greenpeak-day4-30seconds" --energy --peak $PEAK_4 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_4 --speedup 24 --brownfile $BROWN_4 --greenfile $SOLAR_4 --pred -w $WORKLOAD_RED_030 # experiment "58-greenpeak-day0-30seconds" --energy --peak $PEAK_0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_0 --speedup 24 --brownfile $BROWN_0 --greenfile $SOLAR_0 --pred -w $WORKLOAD_RED_030 # experiment "63-hadooppm-day1-15seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_015 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_015 # experiment "64new2-hadooppm-day1-60seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy 100.0 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_060 # experiment "99-hadooppm-day1-hete" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy 100.0 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HETE # experiment "65new2-hadooppm-day1-90seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy 100.0 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_090 #experiment "21new-hadooppm-day1-30seconds" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy 100.0 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_030 # experiment "57-2-greenpeak-day4-30seconds" --energy --peak $PEAK_4 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_4 --speedup 24 --brownfile $BROWN_4 --greenfile $SOLAR_4 --pred -w $WORKLOAD_RED_030 # experiment "66-hadoop-day1-15seconds" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_015 # experiment "67-hadoop-day1-60seconds" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_060 # experiment "68-hadoop-day1-90seconds" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_RED_090 # Deadlines # experiment "91-greenpeak-deadline900-day1-30seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_030 --deadline 900 # experiment "92-greenpeak-deadline1800-day1-30seconds" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_RED_030 --deadline 1800 # Workloads # experiment "80-hadoop-day1-30seconds-high1" --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH1 # experiment "81-hadooppm-day1-30seconds-high1" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH1 #experiment "82-greenpeak-day1-30seconds-high1" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH1 # experiment "83-hadoop-day1-30seconds-high2" --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH2 #experiment "84-hadooppm-day1-30seconds-high2" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH2 #experiment "85-greenpeak-day1-30seconds-high2" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_030 -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_HIGH2 # Nutch #experiment "77-hadooppm-day1-nutch" --energy --nobrown --nogreen --peak 0.0 --repl $REPLICATION --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_NUTCH2 #experiment "76-greenpeak-day1-nutch" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_NUTCH2 #experiment "78-hadoop-day1-nutch" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_NUTCH2 # experiment "97-hadoop-deadline900-day1-nutch2" --nobrown --nogreen --peak 0.0 --repl 0 --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 -w $WORKLOAD_NUTCH2 --deadline 900 #experiment "96-greenpeak-deadline900-day1-nutch" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_NUTCH2 --deadline 900 #experiment "97-greenpeak-deadline1800-day1-nutch" --energy --peak $PEAK_1 --repl $REPLICATION --taskenergy $TASK_ENERGY_NUTCH -d $DATE_1 --speedup 24 --brownfile $BROWN_1 --greenfile $SOLAR_1 --pred -w $WORKLOAD_NUTCH2 --deadline 1800 # Heterogeneous <file_sep>#!/usr/bin/python import os,sys,re,os.path,time from datetime import datetime,timedelta class IntellicastRecord: def __init__(self,d,condition,cloudCover,temp): self.date = d self.cond = condition self.cc = cloudCover self.temp = temp dataDir = '/net/wonko/home/muhammed/intellicast/tempdata' fileTimeFormat = '%Y_%m_%d_%H' tspFormat = '%Y_%m_%d_%H_%M' def toSeconds(td): ret = td.seconds ret += 24*60*60*td.days if td.microseconds > 500*1000: ret += 1 return ret def diffHours(dt1,dt2): sec1 = time.mktime(dt1.timetuple()) sec2 = time.mktime(dt2.timetuple()) return int((sec2-sec1)/3600) if __name__ == '__main__': times = [] count = 0 filesLessThan48 = [] filesHaveGap = [] for f in os.listdir(dataDir): d = datetime.strptime(f,fileTimeFormat) times.append(d) filename = os.path.join(dataDir,f) fd = open(filename,'r') count+=1 lastHour = None c=0 alreadyIncluded = False for line in fd: line = line.strip() if not line: continue c+=1 elements = line.split() currentHour = datetime.strptime(elements[0],tspFormat) if currentHour==None: print f print elements[0] sys.exit() if not lastHour==None and not alreadyIncluded: diff = diffHours(lastHour,currentHour) if diff>1: filesHaveGap.append(f) alreadyIncluded = True lastHour = currentHour if c<48: # print f,len(lines) filesLessThan48.append((f,c)) fd.close() times.sort() print "collecting time starts",times[0] print "collecting time ends",times[-1], print "number of hours between start and end",diffHours(times[0],times[-1]) print "number of actual hours (files)",len(times) print "number of files has hours less than 48 entries (filenames output in 'lessThan48.txt')",len(filesLessThan48) print "number of files having gap inside ",len(filesHaveGap) if len(filesLessThan48): fd = open('lessThan48.txt','w') for f,c in filesLessThan48: print >>fd,f,c fd.close() if len(filesHaveGap): fd = open('gap.txt','w') for f in filesHaveGap: print >>fd,f fd.close() #let's check for gaps for i in range(1,len(times)): prevHour = times[i-1] currentHour = times[i] diff = diffHours(prevHour,currentHour) if diff>1: print "hole starts",prevHour,"ends",currentHour,"number of hours",diff <file_sep>clean: rm -f *~ rm -f *.pyc tgz: tar cvfz greenhadoop.tgz *.py *.sh Makefile README algorithm.txt greenhadoop.patch greenavailability/*.py <file_sep>#!/usr/bin/python import sys import math sys.path.append(r'./') import model,setenv setenv.init() from datetime import timedelta, datetime MAX = 49 BASE_DATE = datetime(2010, 7, 12, 9, 0, 0) ep = model.EnergyPredictor('.', 2, 2070,debugging=True) values = {} def addValue(t, v): if t not in values: values[t] = [] values[t].append(v) for i in range(0, 7*24): #date = BASE_DATE + timedelta(seconds=i*900) date = BASE_DATE + timedelta(seconds=i*900*4) greenAvail,change = ep.getGreenAvailability(date, MAX) #print "Prediction at "+str(date)+" ("+str(change)+")" #print " %s %.2f" % (str(date), greenAvail[0]) #print "%d\t%.2f" % (toSeconds(date-BASE_DATE), greenAvail[0]) #addValue(toSeconds(date-BASE_DATE), greenAvail[0]) for i in range(1, len(greenAvail)): d = date + timedelta(hours=i) d = datetime(d.year, d.month, d.day, d.hour) #print " %s %d %.2f" % (str(d), toSeconds(d-BASE_DATE), greenAvail[i]) #print "%s\t%.2f" % (str(d-BASE_DATE), greenAvail[i]) #addValue(toSeconds(d-BASE_DATE), greenAvail[i]) #for t in sorted(values.keys()): #aux = "" #for v in values[t]: #aux += "%.2f\t" % v #print str(t)+"\t"+aux <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME> and <NAME>. All rights reserved. Dept. of Computer Science, Rutgers University. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ from subprocess import call, PIPE, Popen from datetime import datetime, timedelta from math import * from operator import itemgetter try: Set = set except NameError: from sets import Set import threading from ghadoopcommons import * # Get the available green power def getGreenPowerAvailability(): greenAvailability = [] file = open('greenpower', 'r') for line in file: if line != '' and line.find("#")!=0: lineSplit = line.strip().expandtabs(1).split(' ') t=int(lineSplit[0]) p=float(lineSplit[1]) greenAvailability.append(TimeValue(t,p)) file.close() return greenAvailability # Get the cost of the brown energy def getBrownPowerPrice(): brownPrice = [] file = open('browncost', 'r') for line in file: if line != '' and line.find("#")!=0: lineSplit = line.strip().expandtabs(1).split(' ') t=int(lineSplit[0]) p=float(lineSplit[1]) brownPrice.append(TimeValue(t,p)) file.close() return brownPrice # Calculate the cost of allocating a given percentage to cheap and expensive def calculateCost(peak, previousPeak, peakCost, queueEnergy, consumedBrownCheap, surplusBrownCheap, consumedBrownExpen, surplusBrownExpen, cheapPrice, expenPrice, brownPriceArray): consumedBrownCheap = list(consumedBrownCheap) surplusBrownCheap = list(surplusBrownCheap) consumedBrownExpen = list(consumedBrownExpen) surplusBrownExpen = list(surplusBrownExpen) peakEnergy = peak*(SLOTLENGTH/3600.0) # Cheap for i in range(0, len(brownPriceArray)): auxPeakEnergy = peakEnergy-consumedBrownCheap[i] if surplusBrownCheap[i]>queueEnergy: if auxPeakEnergy>queueEnergy: surplusBrownCheap[i] -= queueEnergy consumedBrownCheap[i] += queueEnergy queueEnergy = 0.0 else: queueEnergy -= auxPeakEnergy surplusBrownCheap[i] -= auxPeakEnergy consumedBrownCheap[i] += auxPeakEnergy else: if auxPeakEnergy>surplusBrownCheap[i]: queueEnergy -= surplusBrownCheap[i] consumedBrownCheap[i] += surplusBrownCheap[i] surplusBrownCheap[i] = 0.0 else: queueEnergy -= auxPeakEnergy surplusBrownCheap[i] -= auxPeakEnergy consumedBrownCheap[i] += auxPeakEnergy # Expensive for i in range(0, len(brownPriceArray)): auxPeakEnergy = peakEnergy-consumedBrownExpen[i] if surplusBrownExpen[i]>queueEnergy: if auxPeakEnergy>queueEnergy: surplusBrownExpen[i] -= queueEnergy consumedBrownExpen[i] += queueEnergy queueEnergy = 0.0 else: queueEnergy -= auxPeakEnergy surplusBrownExpen[i] -= auxPeakEnergy consumedBrownExpen[i] += auxPeakEnergy else: if auxPeakEnergy>surplusBrownExpen[i]: queueEnergy -= surplusBrownExpen[i] consumedBrownExpen[i] += surplusBrownExpen[i] surplusBrownExpen[i] = 0.0 else: queueEnergy -= auxPeakEnergy surplusBrownExpen[i] -= auxPeakEnergy consumedBrownExpen[i] += auxPeakEnergy # Compute peak power and energy cost energyCost = 0 energyPeak = 0 for i in range(0, len(brownPriceArray)): energyCost += consumedBrownCheap[i]*cheapPrice/1000.0 energyCost += consumedBrownExpen[i]*expenPrice/1000.0 if consumedBrownCheap[i]>energyPeak: energyPeak = consumedBrownCheap[i] if consumedBrownExpen[i]>energyPeak: energyPeak = consumedBrownExpen[i] powerPeak = energyPeak/(SLOTLENGTH/3600.0) totalPeakCost = (powerPeak-previousPeak) * peakCost/1000.0 if totalPeakCost<0.0: totalPeakCost = 0.0 cost = (round((energyCost+totalPeakCost)*100000))/100000.0 return (cost, consumedBrownCheap, consumedBrownExpen, queueEnergy) # Schedule jobs. def schedule(timeElapsed, peakBrown, greenAvailArray, brownPriceArray, options=None): # Parse options peakCost = 0.0 flagScheduleGreen = True flagScheduleBrown = True deadline = TOTALTIME if options != None: # Green availability if options.schedNoGreen == True: flagScheduleGreen = False # Brown price if options.schedNoBrown == True: flagScheduleBrown = False # Schedule peak price if options.peakCost != None: peakCost = options.peakCost if options.deadline != None: deadline = options.deadline # Current date #timeNow = datetime.now() #timeNow = datetime(timeNow.year, timeNow.month, timeNow.day, timeNow.hour, timeNow.minute, timeNow.second) # Generate schedule array nodes = getNodes() numNodes = len(nodes) # Calculate idle power powerIdle = POWER_IDLE_GHADOOP for i in range(0,numNodes): powerIdle += Node.POWER_S3 # Calculate always on power powerAlwaysOn = 0.0 for nodeId in ALWAYS_NODE: powerAlwayOn = (Node.POWER_AVERAGE-Node.POWER_S3) # Get cheap and expensive prices if flagScheduleBrown: # Actual pricing cheapPrice = brownPriceArray[0] expenPrice = brownPriceArray[0] for i in range(1, len(brownPriceArray)): if brownPriceArray[i]<cheapPrice: cheapPrice = brownPriceArray[i] elif brownPriceArray[i]>expenPrice: expenPrice = brownPriceArray[i] else: # Static brown cheapPrice = brownPriceArray[0] expenPrice = brownPriceArray[0] for i in range(1, len(brownPriceArray)): brownPriceArray[i] = brownPriceArray[0] # Static green if not flagScheduleGreen: for i in range(0, len(greenAvailArray)): greenAvailArray[i] = 0.0 # Copy green energy availability and initialize consumption arrays (including idle power) totalPower = Node.POWER_AVERAGE*numNodes + POWER_IDLE_GHADOOP energySlot = totalPower*(SLOTLENGTH/3600.0) totalAvailEnergy = 0.0 totalAvailGreenEnergy = 0.0 totalAvailBrownEnergyCheap = 0.0 totalAvailBrownEnergyExpen = 0.0 totalAvailAlwaysOnEnergy = 0.0 # Create base working arrays surplusGreen = [0.0]*numSlots surplusBrownCheap = [0.0]*numSlots surplusBrownExpen = [0.0]*numSlots consumedGreen = [0.0]*numSlots consumedBrownCheap = [0.0]*numSlots consumedBrownExpen = [0.0]*numSlots for i in range(0, numSlots): availableGreen = greenAvailArray[i]*(SLOTLENGTH/3600.0) if availableGreen>energySlot: availableGreen=energySlot availableBrown = energySlot-availableGreen # Surplus surplusGreen[i] = availableGreen if brownPriceArray[i]==cheapPrice: surplusBrownCheap[i] = availableBrown else: surplusBrownExpen[i] = availableBrown # Use system power: S3 and Scheduler reqEnergySlot = (powerIdle+powerAlwayOn) * SLOTLENGTH/3600.0 # Wh totalAvailAlwaysOnEnergy += powerAlwayOn * SLOTLENGTH/3600.0 if availableGreen>reqEnergySlot: # Only green consumedGreen[i] += reqEnergySlot surplusGreen[i] -= reqEnergySlot else: # Green and brown consumedGreen[i] += surplusGreen[i] reqEnergySlot -= surplusGreen[i] surplusGreen[i] = 0.0 if brownPriceArray[i]==cheapPrice: if surplusBrownCheap[i]>reqEnergySlot: consumedBrownCheap[i] += reqEnergySlot surplusBrownCheap[i] -= reqEnergySlot else: consumedBrownCheap[i] += surplusBrownCheap[i] surplusBrownCheap[i] = 0.0 else: if surplusBrownExpen[i]>reqEnergySlot: consumedBrownExpen[i] += reqEnergySlot surplusBrownExpen[i] -= reqEnergySlot else: consumedBrownExpen[i] += surplusBrownExpen[i] surplusBrownExpen[i] = 0.0 # Total amounts totalAvailEnergy += surplusGreen[i]+surplusBrownCheap[i]+surplusBrownExpen[i] totalAvailGreenEnergy += surplusGreen[i] totalAvailBrownEnergyCheap += surplusBrownCheap[i] totalAvailBrownEnergyExpen += surplusBrownExpen[i] # New scheduling queueEnergy = 0.0 # Wh # Getting task and job information jobs = getJobs() tasks = getTasks() # Setting deadlines # Sort jobs according to submission date (last submitted to newest submission) jobSubmit = [] for job in jobs.values(): if job.state != "SUCCEEDED" and job.state != "FAILED": if job.submit==None: job.submit = datetime.now() jobSubmit.append((job.id, job.submit)) jobSubmit = sorted(jobSubmit, key=itemgetter(1), reverse=True) # Assign internal deadlines assignedSlots = [] for jobId, submit in jobSubmit: try: job = jobs[jobId] if job.internalDeadline == None: job.internalDeadline = deadline if job.durationMap==None or job.durationRed==None: # Calculate job duration numJobMaps = len(getFilesInDirectories(job.input)) + 1 totalLenMap = float(numJobMaps*AVERAGE_RUNTIME_MAP) # Add time for maps if numJobMaps>20: # Long jobs (more than 20 maps) totalLenRed = float(numJobMaps*AVERAGE_RUNTIME_RED_LONG) # Add time for reduces else: # Short jobs totalLenRed = float(numJobMaps*AVERAGE_RUNTIME_RED_SHORT) # Add time for reduces job.durationMap = totalLenMap/(TASK_NODE*numNodes) job.durationRed = max(totalLenRed, 30.0)# Add minimnal time # Get the deadline. Take into account overlaps startdeadline = submit + timedelta(seconds=(job.internalDeadline - job.durationMap - job.durationRed)) # Start point for slot startMap = startdeadline endMap = startdeadline+timedelta(seconds=job.durationMap) # Assign chunk from the back assigned = False for i in range(0, len(assignedSlots)): usedSlot = assignedSlots[i] startSlot = usedSlot[0] endSlot = usedSlot[1] if (startSlot<startMap and startMap<endSlot) or (startSlot<endMap and endMap<endSlot): # Move a litle earlier and keep trying startMap = startSlot-timedelta(seconds=job.durationMap) endMap = startSlot elif startMap>=endSlot: # It fits in this slot, assign it assignedSlots.insert(i, [startMap, endMap]) assigned = True break if not assigned: assignedSlots.append([startMap, endMap]) # Finally assign starting deadline job.deadline = startMap except KeyError: print "KeyError: "+str(jobId)+" not found." # Manage tasks and jobs taskEnergy = options.taskEnergy numJobsWaiting = 0 numJobsData = 0 numJobsQueue = 0 numJobsRun = 0 numJobsSucc = 0 numJobsFail = 0 numJobsVeryHigh = 0 numJobsHigh = 0 numTasksVeryHigh = 0 numTasksHigh = 0 numTasksHadoop = 0 # Evaluating tasks and jobs # Jobs for job in jobs.values(): # Move to very high priority if the deadline has been reached if job.priority!="VERY_HIGH" and (job.state=="RUNNING" or job.state=="PREP") and datetime.now()>job.deadline: setJobPriotity(job.id, "VERY_HIGH") job.priority = "VERY_HIGH" writeLog("logs/ghadoop-scheduler.log", str(timeElapsed)+"\tRunning job "+str(job.id)+" now="+str(datetime.now())+" deadline="+str(job.deadline)+": move to very high priority!") # Account jobs if job.state == "RUNNING" or len(job.tasks)>0: # Add the part of the tasks that still need to run for taskId in job.tasks: task = tasks[taskId] if task.state!="SUCCEEDED": queueEnergy += taskEnergy if job.priority == "VERY_HIGH": numJobsVeryHigh += 1.0/len(job.tasks) numTasksVeryHigh += 1 elif job.priority == "HIGH": numJobsHigh += 1.0/len(job.tasks) numTasksHigh += 1 elif job.state == "PREP" or job.state == "DATA" or job.state == "WAITING": #queueEnergy += jobEnergy numJobTasks = len(getFilesInDirectories(job.input)) + 1 queueEnergy += taskEnergy * numJobTasks if job.priority == "VERY_HIGH": numJobsVeryHigh += 1 numTasksVeryHigh += numJobTasks elif job.priority == "HIGH": numJobsHigh += 1 numTasksHigh += numJobTasks # Accounting number of jobs if job.state == "WAITING": numJobsWaiting+=1 elif job.state == "DATA": numJobsData+=1 elif job.state == "PREP": numJobsQueue+=1 elif job.state == "RUNNING": numJobsRun+=1 elif job.state == "SUCCEEDED": numJobsSucc+=1 elif job.state == "FAILED": numJobsFail+=1 # Tasks for task in tasks.values(): if task.state == "RUNNING" or task.state == "PREP": numTasksHadoop += 1 # Output if getDebugLevel() > 1: #print "Tasks: %d %d %d" % (numTasksQueue, numTasksRun, numTasksSucc) print "Jobs: %d->%d->%d->%d->%d (X:%d T:%d)" % (numJobsWaiting, numJobsData, numJobsQueue, numJobsRun, numJobsSucc, numJobsFail, len(jobs)) print " **: %1.2f *: %1.2f" % (numJobsVeryHigh, numJobsHigh) print " **: %d *: %d" % (numTasksVeryHigh, numTasksHigh) print "Queue: %1.2fWh" % (queueEnergy) #print "Jobs:" #for job in jobs.values(): #print "\t"+str(job.id)+"\t"+str(job.state)+"\t"+str(job.prevJobs)+"\tinput="+str(job.input)+"\toutput="+str(job.output) # Evaluate always on nodes available energy... queueEnergy = queueEnergy-totalAvailAlwaysOnEnergy if queueEnergy<0.0: queueEnergy = 0.0 # Assign green: always if flagScheduleGreen: for i in range(0, numSlots): if queueEnergy>0.0: if queueEnergy >= surplusGreen[i]: consumedGreen[i] += surplusGreen[i] queueEnergy -= surplusGreen[i] surplusGreen[i] = 0.0 else: consumedGreen[i] += queueEnergy surplusGreen[i] -= queueEnergy queueEnergy -= queueEnergy if getDebugLevel() > 1: #print "Queue: %.2f Wh" % (queueEnergy) print "Always ON: %.2f Wh" % (totalAvailAlwaysOnEnergy) print "Green+Cheap+Brown = %.2f+%.2f+%.2f = %.2f Wh" % (totalAvailGreenEnergy,totalAvailBrownEnergyCheap,totalAvailBrownEnergyExpen,totalAvailEnergy) # Assign brown # Maximum power minPeakN = totalPower minCostN,minBrownCheapN,minBrownExpenN,minQueueTodoN = calculateCost(minPeakN, peakBrown, peakCost,\ queueEnergy,\ consumedBrownCheap, surplusBrownCheap,\ consumedBrownExpen, surplusBrownExpen,\ cheapPrice, expenPrice, brownPriceArray) minPeak = minPeakN minCost = minCostN minBrownCheap = minBrownCheapN minBrownExpen = minBrownExpenN minQueueTodo = minQueueTodoN # Minimum power minPeak0 = peakBrown minCost0,minBrownCheap0,minBrownExpen0,minQueueTodo0 = calculateCost(minPeak0, peakBrown, peakCost,\ queueEnergy,\ consumedBrownCheap, surplusBrownCheap,\ consumedBrownExpen, surplusBrownExpen,\ cheapPrice, expenPrice, brownPriceArray) if minCost0<minCost and minQueueTodo0==0.0: minPeak = minPeak0 minCost = minCost0 minBrownCheap = minBrownCheap0 minBrownExpen = minBrownExpen0 minQueueTodo = minQueueTodo0 # Search minimum cost if peakCost>0.0: finish = False for i in range(0,100): auxMinPeak = (minPeak0+minPeakN)/2.0 auxCost,auxConsumedBrownCheap,auxConsumedBrownExpen,auxQueueTodo = calculateCost(auxMinPeak, peakBrown, peakCost,\ queueEnergy,\ consumedBrownCheap, surplusBrownCheap,\ consumedBrownExpen, surplusBrownExpen,\ cheapPrice, expenPrice, brownPriceArray) if auxQueueTodo>0: minPeak0 = auxMinPeak else: if auxCost<minCost: minPeakN = auxMinPeak else: minPeak0 = auxMinPeak if auxCost<minCost and auxQueueTodo==0.0: if (minCost-auxCost)<0.0001: finish = True minCost = auxCost minBrownCheap = auxConsumedBrownCheap minBrownExpen = auxConsumedBrownExpen minQueueTodo = auxQueueTodo minPeak = auxMinPeak #print "%.2fW =>\t$%.4f\ttodo:%.2fWh [%.2f]" % (peak, auxCost, auxQueueTodo, minPeak) if (minPeakN-minPeak0)<0.001 or finish: break # Update consume (and surplus is no needed) consumedBrownCheap = minBrownCheap consumedBrownExpen = minBrownExpen # Evaluate priorities #reqPowerVeryHigh = (float(numTasksVeryHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle #reqPowerHigh = (float(numTasksHigh)/2.0/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle reqPower = (consumedGreen[0] + consumedBrownCheap[0] + consumedBrownExpen[0])/(SLOTLENGTH/3600.0) #reqPowerVeryHigh = (float(numJobsVeryHigh*TASK_JOB)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle #reqPowerVeryHigh = (float(numTasksVeryHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle if numTasksVeryHigh>0: #reqPowerVeryHigh = (len(nodes)*(Node.POWER_IDLE-Node.POWER_S3)) + (float(numTasksVeryHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_IDLE) + powerIdle reqPowerVeryHigh = (float(numTasksVeryHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle if reqPowerVeryHigh > totalPower: reqPowerVeryHigh = totalPower if reqPowerVeryHigh>reqPower: reqPower = reqPowerVeryHigh #reqPowerHigh = (float(numJobsHigh*TASK_JOB)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle #reqPowerHigh = (float(numTasksHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle if numTasksHigh>0: #reqPowerHigh = (len(nodes)*(Node.POWER_IDLE-Node.POWER_S3)) + (float(numTasksHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_IDLE) + powerIdle reqPowerHigh = (float(numTasksHigh)/TASK_NODE)*(Node.POWER_AVERAGE-Node.POWER_S3) + powerIdle maxPowerHigh = (len(nodes)/2.0)*(Node.POWER_AVERAGE-Node.POWER_S3) + POWER_IDLE_GHADOOP if reqPowerHigh > maxPowerHigh: reqPowerHigh = maxPowerHigh if reqPowerHigh>reqPower: reqPower = reqPowerHigh # Update consumptions with high priority stuff reqExtraEnergy = reqPower*(SLOTLENGTH/3600.0) - (consumedGreen[0] + consumedBrownCheap[0] + consumedBrownExpen[0]) if surplusGreen[0]>reqExtraEnergy: consumedGreen[0] += reqExtraEnergy surplusGreen[0] -= reqExtraEnergy else: consumedGreen[0] += surplusGreen[0] reqExtraEnergy -= surplusGreen[0] surplusGreen[0] = 0 if surplusBrownCheap[0]>reqExtraEnergy: consumedBrownCheap[0] += reqExtraEnergy surplusBrownCheap[0] -= reqExtraEnergy else: consumedBrownCheap[0] += surplusBrownCheap[0] reqExtraEnergy -= surplusBrownCheap[0] surplusBrownCheap[0] = 0 if surplusBrownExpen[0]>reqExtraEnergy: consumedBrownExpen[0] += reqExtraEnergy surplusBrownExpen[0] -= reqExtraEnergy else: consumedBrownExpen[0] += surplusBrownExpen[0] reqExtraEnergy -= surplusBrownExpen[0] surplusBrownExpen[0] = 0 # Output if getDebugLevel() >= 1: print "Energy usage: "+str(numNodes)+"x"+str(Node.POWER_FULL)+"W + "+str(POWER_IDLE_GHADOOP)+"W" maxPower = (numNodes * Node.POWER_FULL + POWER_IDLE_GHADOOP) * SLOTLENGTH/3600.0 # Wh for i in range(MAXSIZE,0,-1): out="" # TODO change the scale factor of the figure scale = 2 for j in range(0, numSlots/scale): index = j*scale if consumedGreen[index]>(1.0*(i-1)*maxPower/MAXSIZE): out += bcolors.GREENBG+" "+bcolors.ENDC elif consumedGreen[index]+consumedBrownExpen[index]>(1.0*(i-1)*maxPower/MAXSIZE): out += bcolors.REDBG+" "+bcolors.ENDC elif consumedGreen[index]+consumedBrownCheap[index]>(1.0*(i-1)*maxPower/MAXSIZE): out += bcolors.BLUEBG+" "+bcolors.ENDC elif consumedGreen[index]+surplusGreen[index]>(1.0*(i-1)*maxPower/MAXSIZE): out += bcolors.WHITEBG+" "+bcolors.ENDC else: out += " " print out+" %.1fW" % ((1.0*i*maxPower/MAXSIZE)*(3600.0/SLOTLENGTH)) totalCost = 0 totalGreen = 0 totalBrown = 0 for i in range(0, numSlots): totalGreen += consumedGreen[i] totalBrown += consumedBrownCheap[i] + consumedBrownExpen[i] totalCost += consumedBrownCheap[i] * brownPriceArray[i]/1000.0 # Wh * $/kWh totalCost += consumedBrownExpen[i] * brownPriceArray[i]/1000.0 # Wh * $/kWh print "Green: %.2fWh Brown: %.2fWh ($%.2f)" % (totalGreen, totalBrown, totalCost)#, peakBrown, peakBrown*peakCost/1000.0) Peak: %.1fW ($%.2f) return reqPower # Take actions def dispatch(reqPower, availableGreenPower): startaux = datetime.now() done = False if getDebugLevel() > 0: print "Required power by the scheduler: " + str(reqPower) print "Available green power: " + str(availableGreenPower) # If there is enough green energy, use the nodes if reqPower<availableGreenPower: reqPower = availableGreenPower # Turn on/off Nodes nodes = getNodes() # Sorting lists onNodes = [] onNodesNoSort = [] decNodes = [] decNodesNoSort = [] offNodes = [] requiredFiles = getRequiredFiles() for nodeId in nodes: if nodes[nodeId][1]=="UP" and nodeId not in onNodesNoSort: onNodesNoSort.append(nodeId) elif nodes[nodeId][1]=="DEC" and nodeId not in decNodesNoSort: decNodesNoSort.append(nodeId) for nodeId in sorted(nodes): auxFiles=[] nFiles = 0 nFilesExcl = 0 # Get the number of required files of the node for fileId in nodeFile.get(nodeId, []): if fileId not in auxFiles and fileId in requiredFiles: auxFiles.append(fileId) for fileId in auxFiles: nFiles += 1 file = files[fileId] missing = True for otherNodeId in file.getLocation(): if nodeId != otherNodeId: if otherNodeId in onNodesNoSort or otherNodeId in decNodesNoSort: missing = False break if missing: nFilesExcl +=1 nJobs = len(nodeJobs.get(nodeId, [])) if nodes[nodeId][1]=="UP": onNodes.append((nodeId, nFiles, nJobs)) elif nodes[nodeId][1]=="DOWN": offNodes.append((nodeId, nFilesExcl, nJobs)) elif nodes[nodeId][0]=="DEC" or nodes[nodeId][1]=="DEC": decNodes.append((nodeId, nFilesExcl, nJobs)) if nodes[nodeId][0]=="UP": # It should be not running anything setNodeMapredDecommission(nodeId, True) else: offNodes.append((nodeId, nFilesExcl, nJobs)) # Output if getDebugLevel() > 1: if nodes[nodeId][0] == "UP" or nodes[nodeId][0] == "DEC" or nodes[nodeId][1] == "UP" or nodes[nodeId][1] == "DEC": if nodeId in nodeTasks: out = "" for taskId in nodeTasks[nodeId]: if getTaskPriority(tasks[taskId]) == "VERY_HIGH": out += " "+taskId.replace("task_", "")+"**" elif getTaskPriority(tasks[taskId]) == "HIGH": out += " "+taskId.replace("task_", "")+"*" else: out += " "+taskId.replace("task_", "") print "\t"+str(nodeId)+"\t"+str(nodes[nodeId])+"\tfile="+str(nFilesExcl)+"("+str(nFiles)+"),job="+str(nJobs)+":\t"+out else: print "\t"+str(nodeId)+"\t"+str(nodes[nodeId])+"\tfile="+str(nFilesExcl)+"("+str(nFiles)+"),job="+str(nJobs) # Sort onNodes: 1:Less data required in the future 2:Executed less tasks of still running jobs onNodes = sorted(onNodes, key=itemgetter(2)) onNodes = sorted(onNodes, key=itemgetter(1)) onNodes = [nodeId for nodeId, nFiles, nJobs in onNodes] # Sort decNodes: 1:Executed most tasks of still running jobs 2:Most data required in the future decNodes = sorted(decNodes, key=itemgetter(1), reverse=True) decNodes = sorted(decNodes, key=itemgetter(2), reverse=True) decNodes = [nodeId for nodeId, nFiles, nJobs in decNodes] # Sort offNodes: Containing more required data offNodes = sorted(offNodes, key=itemgetter(1), reverse=True) offNodes = [nodeId for nodeId, nFiles, nJobs in offNodes] # Decomission/Recomission: # UP->DEC Decommission nodes: # MapReduce: Executed less tasks of still running jobs # HDFS: Less data required in the future # DEC->UP Recommission nodes: # MapReduce: Executed most tasks of still running jobs # HDFS: Most data required in the future # Background cycle: # Decommission HDFS nodes : # Replicate required data in UP nodes # Turn ON/OFF # DEC->DOWN Turn off decommission nodes: # MapReduce: Hasn't executed tasks of running jobs # HDFS: All its required data available in UP nodes # DOWN->UP Turn on S3 nodes: # MapReduce: - # HDFS: Containing more required data threads = {} # Turn on ALWAYS ON Nodes for nodeId in ALWAYS_NODE: if getDebugLevel() > 1: print "Turning on always on nodes: "+str(ALWAYS_NODE) toRecommission = [] if nodeId in offNodes: if getDebugLevel() > 1: print "\tTurn on "+nodeId+" [ALWAYS]" thread = threading.Thread(target=setNodeStatus,args=(nodeId, True)) thread.start() threads["off->on "+nodeId] = thread # Update data structure offNodes.remove(nodeId) elif nodeId in decNodes: if getDebugLevel() > 1: print "\tRecommission "+nodeId+" [ALWAYS]" #thread = threading.Thread(target=setNodeDecommission,args=(nodeId, False)) #thread.start() #threads["dec->on "+nodeId] = thread # Update data structure toRecommission.append(nodeId) decNodes.remove(nodeId) if len(toRecommission)>0: setNodeListDecommission(toRecommission, False) # We all know this node is up, no need to do it again if nodeId in onNodes: onNodes.remove(nodeId) # Turn on/off nodes # Clean data phase if getPhase() == PHASE_CLEAN: # Turn on everything if (len(decNodes)+len(offNodes))>0: if getDebugLevel() > 1: print "Turning on everything: cleanning phase!" # Start all for nodeId in list(offNodes): if getDebugLevel() > 1: print "\tTurn on "+nodeId thread = threading.Thread(target=setNodeStatus,args=(nodeId, True)) thread.start() threads["off->on "+nodeId] = thread # Update data structure offNodes.remove(nodeId) onNodes.append(nodeId) # Recommission all toRecommission = [] for nodeId in list(decNodes): if getDebugLevel() > 1: print "\tRecommission "+nodeId # Update data structure toRecommission.append(nodeId) decNodes.remove(nodeId) onNodes.append(nodeId) if len(toRecommission)>0: setNodeListDecommission(toRecommission, False) #elif getPhase() != PHASE_TURN_ON: else: # Checking missing files if getDebugLevel() > 1: print "Checking missing files..." requiredFiles = getRequiredFiles() dataNodes = minNodesFiles(requiredFiles, offNodes) # Turn into decommission the required nodes for nodeId in dataNodes: # Turn on (in decommission state) just one of the replicas, the replica manager will automatically turn on the other nodes if getDebugLevel() > 1: print "\tGet data from "+nodeId thread = threading.Thread(target=setNodeStatus,args=(nodeId, True, True)) thread.start() threads["off->data "+nodeId] = thread # Update data structure decNodes.append(nodeId) if nodeId in offNodes: offNodes.remove(nodeId) # Turn on/off Nodes idlePower = len(nodes)*Node.POWER_S3 + POWER_IDLE_GHADOOP currentPower = (len(onNodes)+len(ALWAYS_NODE))*(Node.POWER_AVERAGE-Node.POWER_S3) + len(decNodes)*(Node.POWER_IDLE-Node.POWER_S3) + idlePower #reqPower = 2000 if getDebugLevel()>0: print "Power: current="+str(currentPower)+" req="+str(reqPower) # Turn ON nodes if reqPower>currentPower: # Account the number of tasks to run mapsHadoopWaiting = 0 redsHadoopWaiting = 0 for job in getJobs().values(): if job.state!="SUCCEEDED" and job.state!="FAILED" and len(job.tasks)>0: for taskId in job.tasks: task = tasks[taskId] if task.state!="SUCCEEDED" and taskId.find("_m_")>=0: mapsHadoopWaiting += 1 if task.state!="SUCCEEDED" and taskId.find("_r_")>=0: redsHadoopWaiting += 1 elif job.state=="DATA" or job.state=="PREP" or job.state=="RUNNING": # Default value for the number of tasks numJobTasks = len(getFilesInDirectories(job.input)) mapsHadoopWaiting += numJobTasks redsHadoopWaiting += numJobTasks*0.25 maxRequiredNodesMap = math.ceil(1.0*mapsHadoopWaiting/MAP_NODE) maxRequiredNodesRed = math.ceil(1.0*redsHadoopWaiting/RED_NODE) maxRequiredNodes = max(maxRequiredNodesMap, maxRequiredNodesRed) while reqPower>currentPower and (len(decNodes)+len(offNodes))>0 and (len(ALWAYS_NODE)+len(onNodes))<maxRequiredNodes: # DEC->UP Recommission nodes: # MapReduce: Executed most tasks of still running jobs # HDFS: Most data required in the future if len(decNodes)>0: nodeId = decNodes[0] if getDebugLevel() > 1: print "\tRecommission "+nodeId setNodeDecommission(nodeId, False) # Update data structure decNodes.remove(nodeId) onNodes.append(nodeId) currentPower += (Node.POWER_AVERAGE-Node.POWER_IDLE) else: # DOWN->UP Turn on S3 nodes: # MapReduce: - # HDFS: Containing more required data in the future if len(offNodes)>0: nodeId = offNodes[0] if getDebugLevel() > 1: print "\tTurn on "+nodeId thread = threading.Thread(target=setNodeStatus,args=(nodeId, True)) thread.start() threads["off->on "+nodeId] = thread # Update data structure offNodes.remove(nodeId) onNodes.append(nodeId) currentPower += (Node.POWER_AVERAGE-Node.POWER_S3) # Turn OFF nodes elif reqPower<currentPower: # UP->DEC Decommission nodes: # MapReduce: Executed less tasks of still running jobs # HDFS: Less data required in the future while reqPower<currentPower and len(onNodes)>0: nodeId = onNodes[0] if getDebugLevel() > 1: print "\tDecommission "+nodeId setNodeDecommission(nodeId, True) # Update data structure onNodes.remove(nodeId) decNodes.append(nodeId) currentPower -= (Node.POWER_AVERAGE-Node.POWER_S3) if len(decNodes)>0: if getDebugLevel() > 1: print "Checking decommission "+str(decNodes)+"..." requiredFiles = getRequiredFiles() for nodeId in reversed(decNodes): # DEC->DOWN Turn off decommission nodes: # MapReduce: Hasn't executed tasks of running jobs # HDFS: All its required data available in UP nodes if len(nodeTasks[nodeId])==0 and len(nodeJobs[nodeId])==0: auxFiles=[] required = False # Get the number of required files of the node for fileId in nodeFile.get(nodeId, []): if fileId not in auxFiles and fileId in requiredFiles: auxFiles.append(fileId) for fileId in auxFiles: file = files[fileId] missing = True for otherNodeId in file.getLocation(): if nodeId != otherNodeId: if otherNodeId in ALWAYS_NODE or otherNodeId in onNodes or otherNodeId in decNodes: missing = False break if missing: required = True break if not required: if getDebugLevel() > 1: print "\tTurn off "+nodeId thread = threading.Thread(target=setNodeStatus,args=(nodeId, False)) thread.start() threads["dec->off "+nodeId] = thread # Update data structure offNodes.append(nodeId) decNodes.remove(nodeId) # Too many nodes in decommission... run some jobs in there if False: if len(decNodes)>MAX_DECOMMISSION_NODES: target = len(decNodes)-MAX_DECOMMISSION_NODES for nodeId in list(decNodes): if len(nodeJobs[nodeId])>0: setNodeMapredDecommission(nodeId, False) decNodes.remove(nodeId) target -= 1 if target<=0: break if False: # Try again with nodes with no jobs if target>0: for nodeId in list(decNodes): setNodeMapredDecommission(nodeId, False) decNodes.remove(nodeId) target -= 1 if target<=0: break # Wait actions to be performed #threads.pop().join() tstart = datetime.now() while len(threads)>0 and datetime.now()-tstart < timedelta(seconds=SLOTLENGTH): change = True while change and len(threads)>0: change = False for threadId in threads: if not threads[threadId].isAlive(): del threads[threadId] change = True break if not change: time.sleep(0.5) else: call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Checking inconsistencies nodes = getNodes() for nodeId in nodes: if nodes[nodeId][0]=="DOWN" and nodes[nodeId][1]=="UP": # It should be turned on #print "Inconsistent state for "+str(nodeId)+": HDFS UP and Mapred should be UP" #setNodeMapredStatus(nodeId, True) thread = threading.Thread(target=setNodeMapredStatus,args=(nodeId, True)) thread.start() threads["down->up "+nodeId] = thread elif nodes[nodeId][0]=="DEC" and nodes[nodeId][1]=="UP": # It should be everything on decommission #print "Inconsistent state for "+str(nodeId)+": HDFS UP and Mapred in Decommission" setNodeHdfsDecommission(nodeId, True) elif (nodes[nodeId][0]=="UP" or nodes[nodeId][0]=="DEC") and nodes[nodeId][1]=="DOWN": # It should be turned off #print "Inconsistent state for "+str(nodeId)+": HDFS down and Mapred should be down" #setNodeMapredStatus(nodeId, False) thread = threading.Thread(target=setNodeMapredStatus,args=(nodeId, False)) thread.start() threads["up->down "+nodeId] = thread # Not solved: # UP DEC # DOWN DEC # Wait re-check actions to be performed tstart = datetime.now() while len(threads)>0 and datetime.now()-tstart < timedelta(seconds=SLOTLENGTH): change = True while change and len(threads)>0: change = False for threadId in threads: if not threads[threadId].isAlive(): del threads[threadId] change = True break if not change: time.sleep(0.5) else: call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Ouput if getDebugLevel() > 1: print "Double check:" print " ON: "+str(ALWAYS_NODE)+" + "+str(onNodes) print " Dec: "+str(decNodes) print " OFF: "+str(offNodes) #nodes = getNodes() # True #for nodeId in sorted(nodes): #print "\t"+str(nodeId)+":\t"+str(nodes[nodeId][0])+"\t"+str(nodes[nodeId][1]) done = True return done if __name__ == "__main__": schedule() <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import math import time import sys import os import threading import string import random import signal import subprocess import socket from operator import itemgetter from datetime import datetime,timedelta from subprocess import call, PIPE, Popen from ghadoopdata import * #DEBUG = 3 DEBUG = 0 USER = "goiri" HADOOP_HOME = "/home/"+USER+"/hadoop-0.21.0" MASTER_NODE = "crypt15" GREEN_PREDICTOR="/home/goiri/ghadoop/greenavailability/" HADOOP_SLAVES = HADOOP_HOME+"/conf/slaves" PORT_MAPRED = 50060 PORT_HDFS = 50075 HADOOP_DECOMMISSION_MAPRED = HADOOP_HOME+"/conf/disabled_nodes" HADOOP_DECOMMISSION_HDFS = HADOOP_HOME+"/conf/disabled_nodes_hdfs" HADOOP_OFF_HDFS = HADOOP_HOME+"/conf/disabled_nodes_off" #MAX_SUBMISSION = 10 MAX_SUBMISSION = 7 MAX_SUBMISSION_RETRIES = 10 # Scheduling flags SCHEDULE_GREEN = False SCHEDULE_BROWN_PRICE = False SCHEDULE_BROWN_PEAK = False # Files #GREEN_AVAILABILITY_FILE = None #GREEN_AVAILABILITY_FILE = 'data/greenpower.none' GREEN_AVAILABILITY_FILE = 'data/greenpower.solar' #GREEN_AVAILABILITY_FILE = 'data/greenpower9.solar' #GREEN_AVAILABILITY_FILE = 'data/greenpower9-07-03-2011' #GREEN_AVAILABILITY_FILE = 'data/greenpower9-07-03-2011-fake' #GREEN_AVAILABILITY_FILE = 'data/greenpower9-14-06-2011' #GREEN_AVAILABILITY_FILE = 'data/solarpower-31-05-2010' # More energy #GREEN_AVAILABILITY_FILE = 'data/solarpower-23-08-2010' # Best for us #GREEN_AVAILABILITY_FILE = 'data/solarpower-01-11-2010' # Worst for us #GREEN_AVAILABILITY_FILE = 'data/solarpower-24-01-2011' # Less energy #BROWN_PRICE_FILE = 'data/browncost.ryan' #BROWN_PRICE_FILE = 'data/browncost9.ryan' BROWN_PRICE_FILE = 'data/browncost.nj' #BROWN_PRICE_FILE = 'data/browncost.none' #BROWN_PRICE_FILE = 'data/browncost.zero' #BROWN_PRICE_FILE = 'data/browncost.none' WORKLOAD_FILE = 'workload/workload.genome' #WORKLOAD_FILE = 'workload/workload.test' #WORKLOAD_FILE = None # Base day #BASE_DATE = datetime(2010, 6, 18, 9, 0, 0) # 18/06/20110 9:00 AM BASE_DATE = datetime(2010, 5, 31, 9, 0, 0) # 18/06/20110 9:00 AM # Maximum scheduling period #TIME_LIMIT = (4*24+8)*3600 #TIME_LIMIT = 10*60 # 10 minutes #TIME_LIMIT = 90*60 # 70 minutes TIME_LIMIT = 2*60*60 # 2 hours #TIME_LIMIT = 20 # 2 hours #TIME_LIMIT = 60 # 2 hours #TIME_LIMIT = 60*60 # 1 hour #TIME_LIMIT = None #TOTALTIME = 2*24*60*60 #TOTALTIME = 10*60 # Window size #TOTALTIME = 1*60*60 # Window size #TOTALTIME = 30*60 # Window size #TOTALTIME = 2160 # Window size TOTALTIME = 60*60 # Window size #SLOTLENGTH = 10 DEADLINE = TOTALTIME #SLOTLENGTH = 900 #SLOTLENGTH = 900 SLOTLENGTH = 10 #SLOTLENGTH = 3600 TESTAPP = True SCHEDULE_EVENT = False SCHEDULE_SLOT = True CYCLE_SLOT = True WORKLOADGEN = True #WORKLOADGEN = False # Maximum graphic size MAXSIZE = 16 # Price of the peak $/kW PEAK_COST = 0 # PEAK_COST = 5.5884 # Winter # PEAK_COST = 13.6136 # Summer PEAK_PERIOD = 15*60 # 15 minutes #PEAK_PERIOD = 60 # 15 minutes # Power of the Gslurm system #POWER_IDLE_GHADOOP = 55+33 # Watts: switch + scheduler POWER_IDLE_GHADOOP = 55 # Watts: switch + scheduler #POWER_IDLE_GHADOOP = 0 # Watts: switch + scheduler #BASE_POWER = 1347*1000 # Watts #MAX_POWER = 2300 # Watts #MAX_POWER = POWER_IDLE_GHADOOP + 16*Node.POWER_FULL #MAX_POWER = 11*230.0 # 11 panels at 230W MAX_POWER = 14*230.0 # 12 panels at 230W # Hadoop parameters MAP_NODE = 4 RED_NODE = 2 TASK_NODE = MAP_NODE + RED_NODE # 2 maps and 1 reduce TASK_JOB = 38 # TODO #AVERAGE_RUNTIME = 100 # seconds #AVERAGE_RUNTIME = 70 # seconds AVERAGE_RUNTIME_MAP = 35.0 # seconds per map AVERAGE_RUNTIME_RED_LONG = 1.0 # 2.5 # seconds per reduce/map short #AVERAGE_RUNTIME_RED_SHORT = 2.5 # 2.5 # seconds per reduce/map long AVERAGE_RUNTIME_RED_SHORT = 6.0 # 2.5 # seconds per reduce/map long #ALPHA_EWMA = 0.2 ALPHA_EWMA = None MAX_WAITING_QUEUE = 900 # Seconds REPLICATION_DEFAULT = 2 MAX_DECOMMISSION_NODES = 4 ALWAYS_NODE = [MASTER_NODE] # Phase to clean all the replicated data PHASE_CLEAN_PERIOD = 100*3600 # seconds #PHASE_CLEAN_PERIOD = 400 # seconds PHASE_NONE = 0 PHASE_CLEAN = 1 PHASE_TURN_ON = 2 phase = PHASE_NONE # Maximum scheduling period numSlots = int(math.ceil(TOTALTIME/SLOTLENGTH)) #numIdleNodes = 0.0 # Data structures # Nodes nodes = None lastNodeUpdate = datetime.now() updatingNodes = False nodeHdfsReady = [] # Jobs jobs = {} # id -> job tasks = {} # taskId -> task #requiredFiles = [] # List of required files nodeTasks = {} # nodeId -> [taskId, taskId...] nodeJobs = {} # nodeId -> jobId # Waiting queue waitingQueue = [] # Files filesUpdated = False files = {} nodeBlock = {} nodeFile = {} # Log management # Write a line in a log openLogs = {} def writeLog(filename, txt): if filename not in openLogs: file = open(filename, 'a') openLogs[filename] = file else: file = openLogs[filename] file.write(txt+"\n") file.flush() # TODO comment def closeLogs(): for filename in openLogs: file = openLogs[filename] file.close() #class Popen(subprocess.Popen): #def kill(self, signal = signal.SIGTERM): #os.kill(self.pid, signal) # Output management # Screen colors class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' WHITEBG = '\033[47m' BLUEBG = '\033[44m' GREENBG = '\033[42m' REDBG = '\033[41m' ENDC = '\033[0m' def disable(self): self.HEADER = '' self.OKBLUE = '' self.OKGREEN = '' self.WARNING = '' self.FAIL = '' self.WHITEBG = '' self.BLUEBG = '' self.GREENBG = '' self.ENDC = '' # Clean screen def clearscreen(numlines=100): import os if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print '\n' * numlines def getDebugLevel(): global DEBUG return DEBUG def setDebugLevel(level): global DEBUG DEBUG = level def getPhase(): global phase return phase def setPhase(argPhase): global phase phase = argPhase def filesUpdated(): global filesUpdated return filesUpdated def setFilesUpdated(argFilesUpdated): global filesUpdated filesUpdated = argFilesUpdated def cleanFileInfo(fileId): if fileId in files: file = files[fileId] auxBlocks = file.blocks file.blocks = {} for nodeId in nodeBlock: for block in auxBlocks.values(): if block.id in nodeBlock[nodeId]: nodeBlock[nodeId].remove(block.id) for nodeId in nodeFile: for block in auxBlocks.values(): if block.file in nodeFile[nodeId]: nodeFile[nodeId].remove(block.file) def cleanFileLocation(fileId): if fileId in files: file = files[fileId] for block in file.blocks.values(): for nodeId in nodeBlock: if block.id in nodeBlock[nodeId]: nodeBlock[nodeId].remove(block.id) if block.file in nodeFile[nodeId]: nodeFile[nodeId].remove(block.file) block.nodes = [] #for block in file.blocks.values(): #block.nodes = [] #for nodeId in nodeBlock: #for block in file.blocks.values(): #if block.id in nodeBlock[nodeId]: #nodeBlock[nodeId].remove(block.id) #for nodeId in nodeFile: #for block in file.blocks.values(): #if block.file in nodeFile[nodeId]: #nodeFile[nodeId].remove(block.file) #def isOnlyIn(filesId, nodeList): #ret = False #for fileId in filesId: #file = files[fileId] #if file.isDirectory(): #for fileDir in file.blocks: #ret = isOnlyIn([fileDir], nodeList) #if ret==True: #break #else: #ret = True #for nodeId in file.getLocation(): #if nodeId not in nodeList: #ret = False #break #return ret def filesOnlyIn(filesId, nodeList): ret = [] for fileId in filesId: file = files[fileId] if file.isDirectory(): for fileDir in file.blocks: for auxFileId in filesOnlyIn([fileDir], nodeList): if auxFileId not in ret: ret.append(auxFileId) else: isOnlyIn = True for nodeId in file.getLocation(): if nodeId not in nodeList: isOnlyIn = False break if isOnlyIn: ret.append(fileId) return ret def minNodesFiles(checkFiles, offNodes): # Input checkFiles = getFilesInDirectories(checkFiles) auxOffNodes = list(offNodes) # Get which files are missing and which nodes have them missingFiles = [] missingNodes = {} for fileId in checkFiles: file = files[fileId] locations = file.getLocation() if len(locations)>0 and fileId not in missingFiles: # Check if the file is missing missing = True for nodeId in locations: if nodeId not in auxOffNodes: missing=False break if missing: missingFiles.append(fileId) # Check where is the file for nodeId in locations: if nodeId in auxOffNodes: if nodeId not in missingNodes: missingNodes[nodeId]=0 missingNodes[nodeId]+=1 # Check nodes with missing files auxMissingNodes = [] for nodeId in missingNodes: auxMissingNodes.append((nodeId, missingNodes[nodeId])) missingNodes = sorted(auxMissingNodes, key=itemgetter(1), reverse=True) # We need the minimum set of nodes that have the files required by a job dataNodes=[] # Checking if there is more files to check while len(missingFiles)>0: # Turn on the nodes with the replicas with more data in nodeId = missingNodes[0][0] auxOffNodes.remove(nodeId) dataNodes.append(nodeId) # Update which files are missing and which nodes have them missingFiles = [] missingNodes = {} for fileId in checkFiles: file = files[fileId] locations = file.getLocation() if len(locations)>0 and fileId not in missingFiles: # Check if the file is missing missing = True for nodeId in locations: if nodeId not in auxOffNodes: missing=False break if missing: missingFiles.append(fileId) # Check where is the file for nodeId in locations: if nodeId in auxOffNodes: if nodeId not in missingNodes: missingNodes[nodeId]=0 missingNodes[nodeId]+=1 # Check nodes with missing files auxMissingNodes = [] for nodeId in missingNodes: auxMissingNodes.append((nodeId, missingNodes[nodeId])) missingNodes = sorted(auxMissingNodes, key=itemgetter(1), reverse=True) # Remove those nodes that already have data on change = True while change: change = False for nodeId in dataNodes: free = True if nodeId in nodeFile: for fileId in nodeFile[nodeId]: if fileId in checkFiles and fileId in files: # Check if file is available somewhere else fileAvailable = False file = files[fileId] for otherNodeId in file.getLocation(): if otherNodeId!=nodeId and otherNodeId not in auxOffNodes: fileAvailable = True break if not fileAvailable: free = False break if free: auxOffNodes.append(nodeId) dataNodes.remove(nodeId) change = True break return dataNodes # Interacting with Hadoop # Get all the tasks def getTasks(): global tasks return tasks # Get all the jobs def getJobs(): global jobs return jobs def getTaskPriority(task): ret = "NORMAL" if task.jobId in jobs: ret=jobs[task.jobId].priority return ret def getRequiredFiles(): ret = [] for job in getJobs().values(): if job.state == "DATA" or job.state == "PREP" or job.state == "RUNNING": if job.input != None: for inputfile in job.input: ret.append(inputfile) return getFilesInDirectories(ret) def getFilesInDirectories(dirs): ret = [] if dirs != None: for fileId in dirs: # Adding those that are not already there for auxFileId in getFilesInDirectory(fileId): if auxFileId not in ret: ret.append(auxFileId) return ret def getFilesInDirectory(fileId): ret = [] try: file = files[fileId] if file.isDirectory(): for auxFileId in file.blocks: # Adding those that are not already there for auxFileId2 in getFilesInDirectory(auxFileId): if auxFileId2 not in ret: ret.append(auxFileId2) else: ret.append(fileId) except KeyError: None return ret def getJobsHadoop(): ret = {} # Read those in the queue pipe=Popen([HADOOP_HOME+"/bin/mapred", "job", "-list", "all"], stdout=PIPE, stderr=open('/dev/null', 'w')) #pipe=Popen(["scontrol", "-o", "show", "jobs"], stdout=PIPE) success = False waitingCycle = 0 while True: pipe.poll() if pipe.returncode != None: success = True break waitingCycle+=1 # Wait a maximum 5 seconds if waitingCycle>50: break time.sleep(0.5) # If it has finish, read the output if success: content = False while True: line = pipe.stdout.readline() #block / wait #print "[getJobsHadoop()] "+str(line) if line: if not content: if line.startswith("JobId"): content=True else: # Read attributes splitLine = line.split('\t') jobId = splitLine[0] jobId = jobId.replace("job_","") job = Job(jobId) ret[job.id] = job state = splitLine[1] # PREP RUNNING SUCCEEDED # 5 hours difference to UTC job.submit = datetime(1970, 1, 1, 1, 0)+timedelta(seconds=int(splitLine[2])/1000-5*3600) # StartTime job.start = job.submit if state == "SUCCEEDED": job.end = datetime.now() job.state = state job.priority = splitLine[4] # Priority else: break # Kill if the process is zombie if pipe.poll() == None: #pipe.terminate() os.kill(pipe.pid, signal.SIGTERM) return ret # Gets the runtime of a job def getRuntime(job): ret = 0 start = None end = None for taskId in job.tasks: task = getTasks()[taskId] if task.jobsetup == False: if start==None or (task.start != None and task.start<start): start = task.start if end==None or (task.end != None and task.end>end): end = task.end if start!=None and end!=None: ret = toSeconds(start-end) return ret # Gets the map runtime of a job def getMapRuntime(job): ret = 0 start = None end = None for taskId in job.tasks: if taskId.find("_m_")>=0: task = getTasks()[taskId] if task.jobsetup == False: if start==None or (task.start != None and task.start<start): start = task.start if end==None or (task.end != None and task.end>end): end = task.end if start!=None and end!=None: ret = toSeconds(start-end) return ret # Gets the reduce runtime of a job def getRedRuntime(job): ret = 0 start = None end = None for taskId in job.tasks: task = getTasks()[taskId] if task.jobsetup == False: if taskId.find("_m_")>=0: # The start is the end of the last map if start==None or (task.end != None and task.end>start): start = task.end elif taskId.find("_r_")>=0: # The end is the end of the last reduce if end==None or (task.end != None and task.end>end): end = task.end if start!=None and end!=None: ret = toSeconds(start-end) return ret def isOpen(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) try: s.connect((host, int(port))) s.shutdown(2) return True except: return False def storeIsOpenValue(host, port, store): store[(host, port)] = isOpen(host, port) def getSlaves(): ret = [] file=open(HADOOP_SLAVES, "r") for line in file: name=line.replace("\n", "") if name != "": if name not in ret: ret.append(name) return ret # Return the list of nodes: nodeId -> [MapReduce, HDFS] #def getNodes(update=False): def getNodes(): global nodes global lastNodeUpdate global updatingNodes if nodes==None and updatingNodes: nodes = {} elif nodes==None or (toSeconds(datetime.now()-lastNodeUpdate) >= 1 and not updatingNodes): updatingNodes = True ret = updateNodes() lastNodeUpdate = datetime.now() updatingNodes = False nodes = ret return nodes def updateNodes(): ret = {} store = {} threads = [] for slave in getSlaves(): # Threading thread = threading.Thread(target=storeIsOpenValue,args=(slave, PORT_MAPRED, store)) thread.start() threads.append(thread) thread = threading.Thread(target=storeIsOpenValue,args=(slave, PORT_HDFS, store)) thread.start() threads.append(thread) # While threads to finish while len(threads)>0: threads.pop().join() # Save information for (host, port) in store: #host = key[0] #port = key[1] if host not in ret: ret[host] = ["UNKNOWN", "UNKNOWN"] if store[(host, port)]: if port == PORT_MAPRED: ret[host][0] = "UP" elif port ==PORT_HDFS: ret[host][1] = "UP" else: if port == PORT_MAPRED: ret[host][0] = "DOWN" elif port ==PORT_HDFS: ret[host][1] = "DOWN" # Get decommissioning MapReduce for line in open(HADOOP_DECOMMISSION_MAPRED, "r"): if line != "\n": name=line.replace("\n", "") if name not in ret: ret[name] = ["UNKNOWN", "UNKNOWN"] if ret[name][0] == "UP": ret[name][0] = "DEC" # Get decommissioning MapReduce for line in open(HADOOP_DECOMMISSION_HDFS, "r"): if line != "\n": name=line.replace("\n", "") if name not in ret: ret[name] = ["UNKNOWN", "UNKNOWN"] if ret[name][1] == "UP": ret[name][1] = "DEC" return ret def setNodeStatus(nodeId, running, decommissioned=False): threads = [] # Do it with threads thread = threading.Thread(target=setNodeMapredStatus,args=(nodeId, running, decommissioned)) thread.start() threads.append(thread) thread = threading.Thread(target=setNodeHdfsStatus,args=(nodeId, running, decommissioned)) thread.start() threads.append(thread) # Wait for threads to finish... while len(threads)>0: threads.pop().join() def setNodeDecommission(nodeId, decommission): setNodeMapredDecommission(nodeId, decommission) setNodeHdfsDecommission(nodeId, decommission) # Change the decommission state of a set of nodes def setNodeListDecommission(nodeList, decommission): global nodes # Change MapReduce change=False # Read file auxNodes = [] file=open(HADOOP_DECOMMISSION_MAPRED, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes if decommission: # Decommission nodes for nodeId in nodeList: if nodeId not in auxNodes: auxNodes.append(nodeId) change=True else: # Recomision for nodeId in nodeList: if nodeId in auxNodes: auxNodes.remove(nodeId) change=True # Write changes into file if change: file=open(HADOOP_DECOMMISSION_MAPRED, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Update node topology for nodeId in nodeList: if decommission: nodes[nodeId][0] = "DEC" elif nodes[nodeId][0] == "DEC": nodes[nodeId][0] = "UP" # Change HDFS change=False # Read file auxNodes = [] file=open(HADOOP_DECOMMISSION_HDFS, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes if decommission: # Decommission nodes for nodeId in nodeList: if nodeId not in auxNodes: auxNodes.append(nodeId) change=True else: # Recomision for nodeId in nodeList: if nodeId in auxNodes: auxNodes.remove(nodeId) change=True # Write changes into file if change: file=open(HADOOP_DECOMMISSION_HDFS, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Refresh nodes #call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Update node topology if decommission: nodes[nodeId][1] = "DEC" elif nodes[nodeId][1] == "DEC": nodes[nodeId][1] = "UP" def cleanNodeDecommission(): cleanNodeMapredDecommission() cleanNodeHdfsDecommission() # Get a node status def getNodeMapredStatus(nodeId): if isOpen(nodeId, PORT_MAPRED): ret = "UP" else: ret = "DOWN" # Get decommissioning MapReduce if ret == "UP": file=open(HADOOP_DECOMMISSION_MAPRED, "r") for line in file: name=line.replace("\n", "") if name != "": if name==nodeId: ret = "DEC" break file.close() # Update node info global nodes if nodeId not in nodes: nodes[nodeId] = ["UNKNOWN", "UNKNOWN"] nodes[nodeId][0] = ret return ret # Set a node status: turn on or off def setNodeMapredStatus(nodeId, running, decommissioned=False): if not decommissioned or not running: setNodeMapredDecommission(nodeId, False) else: setNodeMapredDecommission(nodeId, True) # Turn on current = getNodeMapredStatus(nodeId) while running and current=="DOWN": exit = call([HADOOP_HOME+"/bin/manage_node.sh", "start", "mapred", nodeId], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) current = getNodeMapredStatus(nodeId) # Turn off while not running and (current=="UP" or current=="DEC"): exit = call([HADOOP_HOME+"/bin/manage_node.sh", "stop", "mapred", nodeId], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) current = getNodeMapredStatus(nodeId) # Send a node to Decommission status def setNodeMapredDecommission(nodeId, decommission): change=False # Read file auxNodes = [] file=open(HADOOP_DECOMMISSION_MAPRED, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes if decommission: # Decommission node if nodeId not in auxNodes: auxNodes.append(nodeId) change=True else: # Recomision if nodeId in auxNodes: auxNodes.remove(nodeId) change=True # Write into file if change: file=open(HADOOP_DECOMMISSION_MAPRED, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Refresh nodes: no need, scheduler automatically does it #call([HADOOP_HOME+"/bin/mapred", "mradmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Update node topology global nodes if decommission: nodes[nodeId][0] = "DEC" elif nodes[nodeId][0] == "DEC": nodes[nodeId][0] = "UP" def cleanNodeMapredDecommission(): file=open(HADOOP_DECOMMISSION_MAPRED, "w") file.write("") file.close() # Get a node status def getNodeHdfsStatus(nodeId): if isOpen(nodeId, PORT_HDFS): ret = "UP" else: ret = "DOWN" # Get decommissioning HDFS if ret == "UP": file=open(HADOOP_DECOMMISSION_HDFS, "r") for line in file: name=line.replace("\n", "") if name != "": if name==nodeId: ret = "DEC" file.close() # Update node info global nodes if nodeId not in nodes: nodes[nodeId] = ["UNKNOWN", "UNKNOWN"] nodes[nodeId][1] = ret return ret # Set a node status: turn on or off def setNodeHdfsStatus(nodeId, running, decommissioned=False): current = getNodeHdfsStatus(nodeId) if decommissioned: setNodeHdfsDecommission(nodeId, True) # Turn on while running and current=="DOWN": exit = call([HADOOP_HOME+"/bin/manage_node.sh", "start", "hdfs", nodeId], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) if decommissioned: setNodeHdfsDecommission(nodeId, True) else: setNodeHdfsDecommission(nodeId, False) setNodeHdfsON(nodeId) current = getNodeHdfsStatus(nodeId) # Turn off while not running and (current=="UP" or current=="DEC"): exit = call([HADOOP_HOME+"/bin/manage_node.sh", "stop", "hdfs", nodeId], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) setNodeHdfsDecommission(nodeId, False) setNodeHdfsOFF(nodeId) current = getNodeHdfsStatus(nodeId) global nodeHdfsReady if nodeId in nodeHdfsReady: nodeHdfsReady.remove(nodeId) # Notify HDFS to remove the next datanode def setNodeHdfsOFF(nodeId): change=False # Read file auxNodes = [] file=open(HADOOP_OFF_HDFS, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes # Decommission node if nodeId not in auxNodes: auxNodes.append(nodeId) change=True # Write into file if change: file=open(HADOOP_OFF_HDFS, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Refresh nodes #call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Notify HDFS to stop removing the next datanode def setNodeHdfsON(nodeId): change=False # Read file auxNodes = [] file=open(HADOOP_OFF_HDFS, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes # Decommission node if nodeId in auxNodes: auxNodes.remove(nodeId) change=True # Write into file if change: file=open(HADOOP_OFF_HDFS, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Refresh nodes #call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Send a node to Decommission status def setNodeHdfsDecommission(nodeId, decommission): change=False # Read file auxNodes = [] file=open(HADOOP_DECOMMISSION_HDFS, "r") for line in file: line=line.replace("\n", "") if line not in auxNodes: auxNodes.append(line) else: change=True file.close() # Make changes if decommission: # Decommission node if nodeId not in auxNodes: auxNodes.append(nodeId) change=True else: # Recomision if nodeId in auxNodes: auxNodes.remove(nodeId) change=True # Write into file if change: file=open(HADOOP_DECOMMISSION_HDFS, "w") for line in sorted(auxNodes): file.write(line+"\n") file.close() # Refresh nodes #call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) # Update node topology global nodes if decommission: nodes[nodeId][1] = "DEC" elif nodes[nodeId][1] == "DEC": nodes[nodeId][1] = "UP" def cleanNodeHdfsDecommission(): file=open(HADOOP_DECOMMISSION_HDFS, "w") file.write("") file.close() def getNodesHdfsReady(): global nodeHdfsReady return nodeHdfsReady def cleanNodesHdfsReady(): global nodeHdfsReady while len(nodeHdfsReady)>0: nodeHdfsReady.pop() def submitJob(jobId=None, command=None, input=None, output=None, priority=None, waiting=True, prevJobs=[], deadline=None): # Generate temporary Job if jobId == None: jobId = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6)) job = Job(jobId) job.input = input job.output = output job.submit = datetime.now() job.state = "WAITING" job.prevJobs = prevJobs job.internalDeadline = deadline if priority!=None: job.priority = priority jobs[jobId] = job # Check wether to directly submit if priority=="VERY_HIGH" or priority=="HIGH" or not waiting: submitJobHadoop(jobId, job.submit, command, input, output, priority) else: # Queue job in the waiting queue waitingQueue.append((jobId, job.submit, command, input, output, priority)) def submitJobHadoop(jobId, submitTime, command, input=None, output=None, priority=None): if command.find("index")>=0: cmd = HADOOP_HOME+"/bin/nutch "+command if output!=None: for outputfile in output: cmd+=" "+outputfile if input!=None: for inputfile in input: cmd+=" "+inputfile else: cmd = HADOOP_HOME+"/bin/hadoop "+command if input!=None: if command.find("loadgen")>=0: for inputfile in input: cmd+=" -indir "+inputfile else: for inputfile in input: cmd+=" "+inputfile if output!=None: if command.find("loadgen")>=0: for outputfile in output: cmd+=" -outdir "+outputfile else: for outputfile in output: cmd+=" "+outputfile # Turning on required nodes if jobId not in jobs: job = Job(jobId) job.input = input job.output = output job.submit = submitTime job.state = "DATA" jobs[jobId] = job else: jobs[jobId].state = "DATA" # Wait until all data is actually available (Hadoop dispatcher hadoop.py->dispatch() turns on the nodes) #missingFiles = True #while missingFiles: ## Get nodes not ready yet #nodes = getNodes() #ready = getNodesHdfsReady() #notReady = [] #for nodeId in nodes: #if nodeId not in ready: #notReady.append(nodeId) ## Get missing files #missingFiles = False #for fileId in filesOnlyIn(input, notReady): #file = files[fileId] #if len(file.getLocation())>0: #missingFiles = True #break #if missingFiles: #time.sleep(1.0) missingFiles = True while missingFiles: reqFiles = getFilesInDirectories(input) ready = getNodesHdfsReady() # Get nodes not ready yet #nodes = getNodes() #notReady = [] #for nodeId in nodes: #if nodeId not in ready: #notReady.append(nodeId) #print jobId + " " + str(ready)+" +> "+str(getNodes()) #for nodeId in sorted(getNodes()): #print str(nodeId)+":\t"+str(nodes[nodeId][0])+"\t"+str(nodes[nodeId][1]) # Get missing files missingFiles = False for fileId in reqFiles: file = files[fileId] isAvailable = False for nodeId in file.getLocation(): if nodeId in ready: isAvailable = True break if len(file.getLocation())==0 and len(file.blocks)==0: isAvailable = True if not isAvailable: missingFiles = True break if missingFiles: time.sleep(1.0) writeLog("logs/ghadoop-scheduler.log", str(datetime.now())+"\tWaiting->Data: "+str(jobId)+": data is ready") #print "Waiting->Data: "+str(jobId)+": data is ready" # Submitting to Hadoop # Retries... hadoopJobId = None tries = 0 while hadoopJobId==None and tries<MAX_SUBMISSION_RETRIES: pipeRun=Popen(cmd.split(" "), stderr=PIPE, stdout=PIPE)#, stdout=open('/dev/null', 'w')) # , stderr=open('/dev/null', 'w') #print str(jobId)+" -> submit"+str(cmd.split(" "))+" " outmsg = "" while True: line = pipeRun.stderr.readline() #block / wait if line: #print str(jobId)+" -err-> "+line.replace("\n","") outmsg += line if line.find("Running job:")>0: hadoopJobId = line.split(" ")[6].replace("job_", "").replace("\n", "") break # Out #line = pipeRun.stdout.readline() #block / wait #if line: #print str(jobId)+" -out-> "+line.replace("\n","") else: pipeRun.poll() if pipeRun.returncode != None: break else: time.sleep(0.1) tries += 1 # Retry if hadoopJobId==None: call([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-refreshNodes"], stderr=open('/dev/null', 'w')) if tries==MAX_SUBMISSION_RETRIES: writeLog("logs/ghadoop-error.log", "Job: "+str(jobId)+"\nReturn code: "+str(pipeRun.returncode)+"\nCommand:"+command+"\nOutput:\n"+outmsg) print "Error submitting job: "+str(pipeRun.returncode)+" -> "+str(cmd) print outmsg if hadoopJobId == None: # After max number of tries, it cannot be submit jobs[jobId].state = "FAILED" else: writeLog("logs/ghadoop-scheduler.log", str(datetime.now())+"\tData->Hadoop: "+str(jobId)+" -> "+str(hadoopJobId)) # Store information if jobId in jobs: # Remove temporary info job = jobs[jobId] del jobs[jobId] else: # Store data job = Job(jobId) job.input = input job.output = output job.submit = submitTime # Update dependent jobs for auxJob in jobs.values(): if auxJob.state == "WAITING": for i in range(0, len(auxJob.prevJobs)): if auxJob.prevJobs[i] == jobId: auxJob.prevJobs[i] = hadoopJobId # Assign the actual id jobId = hadoopJobId job.id = jobId job.state = "PREP" jobs[jobId] = job # Change priority if priority!=None: jobs[jobId].priority = priority call([HADOOP_HOME+"/bin/hadoop", "job", "-set-priority", "job_"+jobId, priority], stdout=PIPE, stderr=open('/dev/null', 'w')) return hadoopJobId def killJob(jobId): call([HADOOP_HOME+"/bin/mapred", "job", "-kill", "job_"+jobId], stderr=open('/dev/null', 'w')) def setJobPriotity(jobId, priority): call([HADOOP_HOME+"/bin/mapred", "job", "-set-priority", "job_"+jobId, priority], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) # File management def rmFile(path): call([HADOOP_HOME+"/bin/hadoop", "fs", "-rmr", path], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) def setFileReplication(path, replication): call([HADOOP_HOME+"/bin/hadoop", "fs", "-setrep", "-w", str(replication), "-R", str(path)], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) def getFileReplication(path): replication = 0.0 pipe = Popen([HADOOP_HOME+"/bin/hadoop", "fsck", path], stdout=PIPE, stderr=open('/dev/null', 'w')) text = pipe.communicate()[0] for line in text.split('\n'): if line != "": if line.find("Average block replication:")>0: while line.find(" ")>0: line = line.replace(" ", " ") line = line.strip() splitLine = line.split("\t") replication = float(splitLine[1]) break return replication def signal_handler(signal, frame): #print 'Killing!' sys.exit(0) def getNodeReport(): report = {} pipe = Popen([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-report"], stdout=PIPE, stderr=open('/dev/null', 'w')) text = pipe.communicate()[0] nodeId = None liveNodes = False for line in text.split('\n'): if line != "": if line.startswith("Live datanodes:"): liveNodes = True elif line.startswith("Dead datanodes:"): liveNodes = False elif line.startswith("Name:"): if line.find("(")>=0: nodeId = line.split(" ")[2] nodeId = nodeId[1:len(nodeId)-1] else: nodeId = line.split(" ")[1] if liveNodes: report[nodeId] = (0, 100, 0) else: report[nodeId] = None elif nodeId != None and report[nodeId]!=None: if line.startswith("DFS Remaining:"): # GB #report[nodeId] = (report[nodeId][0], report[nodeId][1], report[nodeId][2]) value = float(line.split(" ")[2])/(1024.0*1024.0*1024.0) report[nodeId] = (value, report[nodeId][1], report[nodeId][2]) elif line.startswith("DFS Remaining%:"): value = line.split(" ")[2] value = float(value[0:len(value)-1]) report[nodeId] = (report[nodeId][0], value, report[nodeId][2]) elif line.startswith("DFS Used%:"): value = line.split(" ")[2] value = float(value[0:len(value)-1]) report[nodeId] = (report[nodeId][0], report[nodeId][1], value) return report def checkNodesStatus(name, i): print i while True: startaux = datetime.now() nodes = getNodes() print str(i)+" "+str(datetime.now())+": "+str(datetime.now()-startaux) time.sleep(0.1) if __name__=='__main__': report = getNodeReport() for nodeId in sorted(report): print nodeId+" => "+str(report[nodeId]) ''' print "Start" nodes = getNodes() for nodeId in sorted(nodes): print nodeId+": "+str(nodes[nodeId]) for nodeId in sorted(nodes): if nodeId != "crypt01": setNodeStatus(nodeId, False) #setNodeHdfsStatus("crypt10", False) print "Mid" nodes = getNodes() for nodeId in sorted(nodes): print nodeId+": "+str(nodes[nodeId]) for nodeId in sorted(nodes): if nodeId != "crypt01": setNodeStatus(nodeId, True) print "End" ''' nodes = getNodes() for nodeId in sorted(nodes): print nodeId+": "+str(nodes[nodeId]) #print "Thread 1" #i=1 #t = threading.Thread(target=checkNodesStatus,args=("Mola", i)) #t.setDaemon(True) #t.start() #print "Thread 2" #i=2 #t = threading.Thread(target=checkNodesStatus,args=("Mola", i)) #t.setDaemon(True) #t.start() ##print "Thread 3" ##i=3 ##t = threading.Thread(target=checkNodesStatus,args=("Mola", i)) ##t.setDaemon(True) ##t.start() #time.sleep(100) #for file in ["/user/goiri/testeando3", "/user/goiri/testeando4", "/user/goiri/testeando5", "/user/goiri/testeando6", "/user/goiri/testeando7"]: #print file+":\t"+str(getFileReplication(file)) #for node in getNodes(): #print node print "Jobs" for job in getJobsHadoop().values(): print job #submitJob("jar "+HADOOP_HOME+"/hadoop-mapred-examples-0.21.0.jar wordcount", "input", "output2", "VERY_HIGH") <file_sep>#!/usr/bin/env python2.5 """ GreenHadoop makes Hadoop aware of solar energy availability. http://www.research.rutgers.edu/~goiri/ Copyright (C) 2012 <NAME>, Rutgers University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ import math import time import threading import os import sys import signal from datetime import datetime,timedelta from subprocess import call, PIPE, Popen from ghadoopcommons import * class MonitorMapred(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True # JobTracker self.logfileMapr = HADOOP_HOME+"/logs/hadoop-"+USER+"-jobtracker-"+MASTER_NODE+".log" #self.logfileMapr = "/scratch/muhammed/hadoop_log/hadoop-muhammed-jobtracker-crypt10.log" # http://forums.devshed.com/python-programming-11/how-to-monitor-a-file-for-changes-85767.html self.fileMapr = open(self.logfileMapr, 'r') self.watcherMapr = os.stat(self.logfileMapr) self.this_modifiedMapr = self.last_modifiedMapr = self.watcherMapr.st_mtime # Get nodes: nodes = getNodes() for nodeId in nodes: nodeTasks[nodeId] = [] nodeJobs[nodeId] = [] if nodes[nodeId][1] == "UP" or nodes[nodeId][1] == "DEC": if nodeId not in getNodesHdfsReady(): getNodesHdfsReady().append(nodeId) # Read previous state of the system self.startTime = None # TODO read previous history if False: while True: line = self.fileMapr.readline() if not line: break #print line change = self.parseLine(line) #print "Tasks "+str(len(tasks)) #print "Jobs "+str(len(jobs)) print "Ready!" # Go to the end of the file self.fileMapr.seek(0,2) # Start helper threads self.checkstatus = MonitorMapredCheckStatus(self) self.checkstatus.start() self.nodestatus = MonitorNodeCheckStatus() self.nodestatus.start() def kill(self): self.running = False self.checkstatus.kill() self.nodestatus.kill() def run(self): # Monitor lastUpdate = 0 change = True while self.running: # Update from log: JobTracker if self.this_modifiedMapr > self.last_modifiedMapr: self.last_modifiedMapr = self.this_modifiedMapr # File was modified, so read new lines, look for error keywords while 1: line = self.fileMapr.readline() if not line: break auxChange = self.parseLine(line) if auxChange: change = True self.watcherMapr = os.stat(self.logfileMapr) self.this_modifiedMapr = self.watcherMapr.st_mtime # Updates lastUpdate -= 1 if lastUpdate<0: lastUpdate=5 change=True if DEBUG>3 and change: self.printOutput() change=False time.sleep(1.0) def parseLine(self, line): change = False try: date = datetime.strptime(line.split(",")[0], "%Y-%m-%d %H:%M:%S") if self.startTime == None: self.startTime = date line = line.replace("\n", "") lineSplit = line.split(" ") if lineSplit[3].startswith("org.apache.hadoop.mapred.JobTracker") and len(lineSplit)>5: if line.find("added successfully")>=0: # Add job jobId = lineSplit[5] jobId = jobId[jobId.find("_")+1:] if jobId not in jobs: jobs[jobId] = Job(jobId, "PREP", date) else: jobs[jobId].state = "PREP" if jobs[jobId].submit == None: jobs[jobId].submit = date #job = addMonitorJob(id, jobId) #job.submit = date #job.state = "PREP" ## Store in data structures #runningJobs.append(id) if DEBUG>3: print str(date)+" Job "+jobId+"("+jobId+") started." change=True elif line.find("Adding task")>=0 and len(lineSplit)>13: # Add task to job taskId = lineSplit[10] if taskId.endswith(","): taskId = taskId[0:len(taskId)-1] taskIdSplit= taskId.split("_") jobId = taskIdSplit[1]+"_"+taskIdSplit[2] nodeId = lineSplit[13] nodeId = nodeId.replace("'tracker_","") nodeId = nodeId[0:nodeId.find(":")] if taskId not in tasks: task = Task(taskId, jobId, "RUNNING", date) task.start = date if task.submit == None: task.submit = date tasks[taskId] = task else: task = tasks[taskId] task.state = "RUNNING" task.start = date if task.submit == None: task.submit = date task.node = nodeId # check if this is actual job or just setting up if line.find("JOB_SETUP")>=0 or line.find("TASK_CLEANUP")>=0 or line.find("JOB_CLEANUP")>=0: task.jobsetup = True # Check if job existed and update status if jobId not in jobs: if not task.jobsetup: job = Job(jobId, "RUNNING", date, date) else: job = Job(jobId, "PREP", date) else: job = jobs[jobId] if not task.jobsetup: job.state = "RUNNING" if job.submit == None: job.submit = date if not task.jobsetup and job.start == None: job.start = date if taskId not in job.tasks: job.tasks.append(taskId) # Removing from other nodes for otherNodeId in nodeTasks: if taskId in nodeTasks[otherNodeId]: nodeTasks[otherNodeId].remove(taskId) # Assign task to node if nodeId not in nodeTasks: nodeTasks[nodeId] = [] if taskId not in nodeTasks[nodeId]: nodeTasks[nodeId].append(taskId) # Assign job to node if nodeId not in nodeJobs: nodeJobs[nodeId] = [] if jobId not in nodeJobs[nodeId] and not task.jobsetup: nodeJobs[nodeId].append(jobId) if DEBUG>3: print str(date)+" Task "+taskId+"("+jobId+") to "+nodeId+": "+str(nodeTasks[nodeId]) change=True elif line.find("Removing task")>=0 and len(lineSplit)>6: #2011-07-13 17:18:51,532 INFO org.apache.hadoop.mapred.JobTracker: Removing task 'attempt_201107131634_0017_m_000126_0' #0 2011-07-13 17:18:51,532 #2 INFO #3 org.apache.hadoop.mapred.JobTracker: #4 Removing #5 task #6 'attempt_201107131634_0017_m_000126_0' # Add task to job attemptId = lineSplit[6] if attemptId.startswith("\'"): attemptId = attemptId[1:len(attemptId)] if attemptId.endswith("\'"): attemptId = attemptId[0:len(attemptId)-1] if attemptId.endswith(","): attemptId = attemptId[0:len(attemptId)-1] attemptIdSplit= attemptId.split("_") taskId = "task_"+attemptIdSplit[1]+"_"+attemptIdSplit[2]+"_"+attemptIdSplit[3]+"_"+attemptIdSplit[4] jobId = attemptIdSplit[1]+"_"+attemptIdSplit[2] # Removing failed task nodes for nodeId in nodeTasks: if taskId in nodeTasks[nodeId]: nodeTasks[nodeId].remove(taskId) elif line.find("Retired job with id")>=0 and len(lineSplit)>8: # Job finished jobId = lineSplit[8] jobId = jobId.replace("'","") jobId = jobId[jobId.find("_")+1:] if jobId not in jobs: job = Job(jobId) jobs[jobId] = job else: job = jobs[jobId] job.end = date if job.submit == None: job.submit = date if job.start == None: job.start = date job.state = "SUCCEEDED" # Remove node -> Job for nodeId in nodeJobs: if jobId in nodeJobs[nodeId]: nodeJobs[nodeId].remove(jobId) if DEBUG>3: print str(date)+" Job "+jobId+"("+jobId+") finished" change=True elif lineSplit[3].startswith("org.apache.hadoop.mapred.JobInProgress"): if line.find("Task")>=0 and line.find("has completed")>=0: # Task finished taskId = lineSplit[8] taskIdSplit= taskId.split("_") jobId = taskIdSplit[1]+"_"+taskIdSplit[2] if taskId in tasks: task = tasks[taskId] task.end = date if task.submit == None: task.submit = date if task.start == None: task.start = date task.state = "SUCCEEDED" # Cleaning running task nodes if task.node in nodeTasks: if taskId in nodeTasks[task.node]: nodeTasks[task.node].remove(taskId) if DEBUG>3: print str(date)+" Task "+taskId+"("+jobId+") finished" change=True elif line.find("has split on")>=0: # Tasks generated taskId = lineSplit[4] taskId = taskId.replace("tip:","") taskIdSplit= taskId.split("_") jobId = taskIdSplit[1]+"_"+taskIdSplit[2] if taskId not in tasks: task = Task(taskId, jobId, "PREP", date) tasks[taskId] = task else: task = tasks[taskId] task.state = "PREP" if task.submit == None: task.submit = date # Check if job existed and update status if jobId not in jobs: job = Job(jobId, "PREP", date, date) else: job = jobs[jobId] if job.state == "UNKNOWN": job.state = "PREP" if job.submit == None: job.submit = date if taskId not in job.tasks: job.tasks.append(taskId) #task = addMonitorTask(id, taskId) #if task.submit == None: #task.submit = date #task.state = "PREP" if DEBUG>3: print str(date)+" Task "+taskId+"("+jobId+") created" change=True elif line.find("initialized successfully with")>=0: # Generate maps and reduces jobId = lineSplit[5] jobId = jobId.replace("job_", "") nmap=int(lineSplit[9]) nred=int(lineSplit[13]) # Check if job existed and update status if jobId not in jobs: job = Job(jobId, "PREP", date, date) else: job = jobs[jobId] if job.state == "UNKNOWN": job.state = "PREP" if job.submit == None: job.submit = date for i in range(0, nred): taskId = "task_"+jobId+"_r_"+str(i).zfill(6) task = Task(taskId, jobId, "PREP", date) tasks[taskId] = task if taskId not in job.tasks: job.tasks.append(taskId) for i in range(0, nmap): taskId = "task_"+jobId+"_m_"+str(i).zfill(6) task = Task(taskId, jobId, "PREP", date) tasks[taskId] = task if taskId not in job.tasks: job.tasks.append(taskId) change=True except ValueError: if DEBUG>3: print "Error line: "+line except Exception, e: print e print "Error line: "+line return change def printOutput(self): print "=========================================================" print "Tasks ("+str(len(tasks))+"):" runn = 0 prep = 0 comp = 0 unkn = 0 for taskId in sorted(tasks): task = tasks[taskId] if task.state == "SUCCEEDED": comp+=1 elif task.state == "RUNNING": runn+=1 elif task.state == "PREP": prep+=1 else: unkn+=1 if len(tasks)<30: print " "+str(task) if len(tasks)>=30: print " Unknown: "+str(unkn) print " Queue: "+str(prep) print " Running: "+str(runn) print " Complete: "+str(comp) nodes = getNodes() print "Nodes->Tasks ("+str(len(nodeTasks))+"):" for nodeId in sorted(nodeTasks): out = "\t"+str(nodeId) if nodeId in nodes: for status in nodes[nodeId]: out += " "+status if nodeId in nodeTasks and len(nodeTasks[nodeId])>0: out+=":\t"+str(nodeTasks[nodeId]) print out print "Nodes->Jobs ("+str(len(nodeJobs))+"):" for nodeId in sorted(nodeJobs): out = "\t"+str(nodeId) if nodeId in nodes: for status in nodes[nodeId]: out += " "+status if nodeId in nodeJobs and len(nodeJobs[nodeId])>0: out+=":\t"+str(nodeJobs[nodeId]) print out print "Jobs ("+str(len(jobs))+"):" for jobId in sorted(jobs): out = "" job = jobs[jobId] for taskId in job.tasks: task = tasks[taskId] if task.state == "RUNNING": out +=bcolors.BLUEBG+" "+bcolors.ENDC elif task.state == "SUCCEEDED": out +=bcolors.GREENBG+" "+bcolors.ENDC else: out +=" " print "\t"+str(job)+"\t"+out+" "+str(len(job.tasks)) #print "Required files ("+str(len(requiredFiles))+"):" #for fileId in sorted(requiredFiles): #print "\t"+str(fileId) class MonitorMapredCheckStatus(threading.Thread): def __init__(self, monitor): threading.Thread.__init__(self) self.monitor = monitor self.running = True self.times = 0 def kill(self): self.running = False def run(self): # Monitor while self.running: self.checkStatus() time.sleep(5.0) def checkStatus(self): self.times += 1 if self.times%3 == 0: # Check with Hadoop info for job in getJobsHadoop().values(): # Update info in local structure if job.id not in jobs: jobs[job.id] = job else: if job.state=="SUCCEEDED" and jobs[job.id].end == None: jobs[job.id].end = job.end jobs[job.id].state = job.state jobs[job.id].priority = job.priority # Update jobs succeeded for job in jobs.values(): if job.state == "SUCCEEDED": for taskId in job.tasks: task = tasks[taskId] if task.end == None: task.end = job.end task.state = "SUCCEEDED" # Update tasks succeeded for task in tasks.values(): if task.state == "SUCCEEDED": try: if task.id in nodeTasks[task.node]: nodeTasks[task.node].remove(task.id) except KeyError: None # Update node->job for nodeId in nodeJobs: for jobId in list(nodeJobs[nodeId]): try: job = jobs[jobId] if job.state == "SUCCEEDED": nodeJobs[nodeId].remove(jobId) except KeyError: None except ValueError: None # Update node->task for nodeId in nodeTasks: for taskId in list(nodeTasks[nodeId]): try: task = tasks[taskId] if task.state == "SUCCEEDED" or task.node != nodeId: nodeTasks[nodeId].remove(taskId) except KeyError: None except ValueError: None class MonitorNodeCheckStatus(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True # Namenode self.logfileHdfs = HADOOP_HOME+"/logs/hadoop-"+USER+"-namenode-"+MASTER_NODE+".log" self.fileHdfs = open(self.logfileHdfs, 'r') self.watcherHdfs = os.stat(self.logfileHdfs) self.this_modifiedHdfs = self.last_modifiedHdfs = self.watcherHdfs.st_mtime # Go to the end of the file self.fileHdfs.seek(0,2) # Read nodes pipe=Popen([HADOOP_HOME+"/bin/hdfs", "dfsadmin", "-printTopology"], stdout=PIPE, stderr=open('/dev/null', 'w')) text = pipe.communicate()[0] self.nodeName = {} for line in text.split('\n'): if line !="" and not line.startswith("Rack:"): line = line.strip() lineSplit = line.split(" ") if len(lineSplit)>=2: nodeId = lineSplit[1].replace("(", "").replace(")", "") self.nodeName[lineSplit[0]] = nodeId def kill(self): self.running = False def run(self): # Monitor while self.running: # Update from log: Namenode if self.this_modifiedHdfs > self.last_modifiedHdfs: self.last_modifiedHdfs = self.this_modifiedHdfs # File was modified, so read new lines, look for error keywords while True: line = self.fileHdfs.readline() if not line: break try: if line.find("org.apache.hadoop.net.NetworkTopology")>0: lineSplit = line.split(" ") if len(lineSplit)>3 and lineSplit[3].startswith("org.apache.hadoop.net.NetworkTopology"): date = datetime.strptime(line.split(",")[0], "%Y-%m-%d %H:%M:%S") if line.find("Removing a node")>=0: nodeId = lineSplit[7] nodeId = nodeId.replace("\n", "") nodeId = nodeId[nodeId.rindex("/")+1:] if nodeId in self.nodeName: nodeId = self.nodeName[nodeId] if nodeId in getNodesHdfsReady(): getNodesHdfsReady().remove(nodeId) change = True elif line.find("Adding a new node")>=0: nodeId = lineSplit[8] nodeId = nodeId.replace("\n", "") nodeId = nodeId[nodeId.rindex("/")+1:] if nodeId in self.nodeName: nodeId = self.nodeName[nodeId] if nodeId not in getNodesHdfsReady(): getNodesHdfsReady().append(nodeId) change = True except ValueError: if DEBUG>3: print "Error line: "+line except TypeError: if DEBUG>3: print "Error line: "+line self.watcherHdfs = os.stat(self.logfileHdfs) self.this_modifiedHdfs = self.watcherHdfs.st_mtime time.sleep(2.0) if __name__=='__main__': DEBUG=4 thread = MonitorMapred() thread.start() signal.signal(signal.SIGINT, signal_handler) while True: time.sleep(10.0) thread.join() <file_sep>#!/usr/bin/python #import os,sys,time from datetime import datetime,timedelta import os,re,sys,glob,os.path,time,string import weatherPrediction import tempfile,subprocess #from datetime import datetime,timedelta locations = weatherPrediction.locations zipcodes = weatherPrediction.zipcodes timezones = weatherPrediction.timezones conditions = weatherPrediction.conditions format = '%b_%d_%Y_%H_%M' outputFormat = '%Y_%m_%d_%H' currentDate = None dayFormat = "%b_%d_%Y" class WeatherCondition: def __init__(self,conditionString,conditionGroup): self.conditionString = conditionString self.conditionGroup = conditionGroup def __str__(self): return "%s\t%s"%(self.conditionString,str(self.conditionGroup)) class TemperatureRecord: def __init__(self,time,filename,line): self.time = time self.filename = filename self.line = line def setAttribute(self,attribute,value): if not hasattr(self, attribute): setattr(self, attribute, value) def setCondition(self,cond): if not hasattr(self, 'condition'): self.condition=cond def setTemp(self, temp): if not hasattr(self, 'temp'): self.temp = temp def setFeelLike(self, feelLike): if not hasattr(self, 'feelLike'): self.feelLike = feelLike def setHumidity(self,hum): if not hasattr(self, 'humidity'): self.humidity = hum def setPrecipation(self,pre): if hasattr(self, 'precipitation'): print self.precipitation if not hasattr(self, 'precipitation'): self.precipation = pre def setWind(self,direction,speed): if not hasattr(self, 'direction'): self.direction=direction self.speed = speed #print str(self) # fout.write(str(self)+"\n") def check(self): try: a = self.direction a = self.speed a = self.condition a = self.feelLike a = self.temp a = self.time except AttributeError: print "bad time",self.time,self.filename raise def __str__(self): outFormat = "%Y_%m_%d_%H"#"%A_%H" try: return "%s\t%d\t%d\t%d\t%s\t%d\t%s\t%d"%(self.time.strftime(outFormat),self.temp,self.feelLike,self.humidity,self.condition,self.precipation,self.direction,self.speed) except AttributeError: print "bad",self.time,self.filename,self.line raise def getTime(self): return time.mktime(self.time.timetuple()) class OneDayRecords: def __init__(self): self.map = {} # def __init__(self,day): # self.day = day # self.init() def append(self,record): if not self.map.has_key(record.time.hour): self.map[record.time.hour] = record def getRecords(self): #print self.map.values() return self.map.values() def roundToNereastHour(time): retval = datetime(time.year,time.month,time.day,time.hour) if time.minute>30: retval+=timedelta(hours=1) return retval def getTimeDelta(t1,t2): if t1>t2: return t1-t2 else: return t2-t1 def parseStore(htmlFile,day,timeToRecord={}): # pass # #def parseStore(htmlFile, d): retval = {} hourToTsp = {} fd = open(htmlFile,'r') # print htmlFile # ftemp = tempfile.TemporaryFile()#open("tempdata.txt",'w') # 2010-06-05 22:04:00 format = "%I:%M %p" timeRe = re.compile('<td valign="middle" class="inDentA".*<b>(.*)</b></font></td>') tempRe = re.compile('<td valign="middle" align="left".*>(.+)<b>(-?\d+)&deg;F</b></td>') feltRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+"><b>(\-*\d+)&deg;F</b></td>') dewpRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+">(\-*\d+)&deg;F</td>') #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">30&deg;F</td> humiRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+">(\d+)%</td>') #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">92%</td> visiRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+">(\d+\.\d+)<BR>miles</td>') #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">9.0<BR>miles</td> presRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+">(\d+\.\d+)$') #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">30.01 windRe = re.compile('<td align="center" valign="middle" class="blueFont10" bgcolor="#.+">(.+)</td>') #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">CALM</td> nextHour=0 dayJump=False # arrayDate = [] # arrayOut = [] currentRecord = None discardRecord = False for line in fd: line = line.strip() if not line: continue #print line # Get time r = timeRe.search(line) if r: repeat = False #print r.group(0) tsp = r.group(1) t = datetime.strptime(tsp,format) t = datetime(day.year,day.month,day.day,t.hour,t.minute) nearestHour = roundToNereastHour(t) currentRecord = TemperatureRecord(t, htmlFile, line) if timeToRecord.has_key(nearestHour): r = timeToRecord[nearestHour] deltaPrev = getTimeDelta(r.time,nearestHour) deltaNow = getTimeDelta(t,nearestHour) if deltaNow<deltaPrev: timeToRecord[nearestHour] = currentRecord discardRecord = False else: discardRecord = True else: timeToRecord[nearestHour] = currentRecord discardRecord = False # try: # if prevNearestHour == nearestHour: # repeat = True # except: # None # # try: # prevRecord=currentRecord # except: # prevOut=None # out = str(nearestHour.year)+"\t"+str(nearestHour.month)+"\t"+str(nearestHour.day)+"\t"+str(nearestHour.hour)+"\t"+str(nearestHour) # if seconds<deltaNow.seconds: # continue continue # Get condition and temperature #<td valign="middle" align="left" class="blueFont10">Light Rain and Freezing Rain <b>32&deg;F</b></td> if discardRecord: continue r = tempRe.search(line) if(r): #print r.group(0) cond = r.group(1) temp = r.group(2) cond=cond.strip().lower() condOrig=cond if cond in conditions: cond = conditions[cond] #print cond # out+="\t"+str(cond)+"\t"+str(condOrig)+"\t"+str(temp) c = WeatherCondition(condOrig,cond) currentRecord.setTemp(temp.strip()) currentRecord.setCondition(c) #print out prevNearestHour = nearestHour continue #Felt like #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5"><b>32&deg;F</b></td> r = feltRe.search(line) if(r): # out+="\t"+r.group(1) currentRecord.setFeelLike(r.group(1).strip()) continue #Dew Point #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">30&deg;F</td> r = dewpRe.search(line) if(r): # out+="\t"+r.group(1) currentRecord.setAttribute("Dew", r.group(1).strip()) continue #Humidity #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">92%</td> r = humiRe.search(line) if(r): # out+="\t"+r.group(1) currentRecord.setHumidity(r.group(1).strip()) # currentRecord.setAttribute("Humidity", r.group(1).strip()) continue #Visibility #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">9.0<BR>miles</td> r = visiRe.search(line) if(r): # out+="\t"+r.group(1) currentRecord.setAttribute("Visibility", r.group(1)) continue #Pressure #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">30.01 #<IMG SRC="http://image.weather.com/web/common/icons/steady_pressure.gif?20061207" WIDTH="5" HEIGHT="8" BORDER="0" ALT="steady"> r = presRe.search(line) if(r): # out+="\t"+r.group(1) currentRecord.setAttribute("Pressure", r.group(1)) continue #Wind #<td align="center" valign="middle" class="blueFont10" bgcolor="#f1f4f5">CALM</td> r = windRe.search(line) if(r): wind = r.group(1) if wind == 'CALM': wind = 0 else: index1 = string.index(wind, '<BR>') index2 = string.index(wind, 'mph') wind = wind[index1+4:index2] currentRecord.setWind("DIRECTION", wind) # out+="\t"+str(wind) #if not repeat: #print out # Print things out #print str(nextHour)+">"+str(nearestHour.hour)+"--------"+out #if not repeat: #if nextHour==nearestHour.hour: #print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out #else: #while nextHour<nearestHour.hour and (nextHour-nearestHour.hour)>0: #print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out+" added" #nextHour = (nextHour+1)%24 #print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out+" after adding" #nextHour = (nextHour+1)%24 if nearestHour.hour>2: dayJump=True #check = nextHour-nearestHour.hour #done=False #if check == 0: ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out #print out #done=True #if check<0 and check>-10: #nextHour=nextHour+1 ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+prevOut ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out #print prevOut #print out #done=True ## Day jump #if check<=-10: #if not dayJump: ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out+" extrange" #print out #dayJump=True #nextHour=nextHour-1 #done=True #if check>0: ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+prevOut+" skipped" #nextHour=nextHour-1 #done=True #if not done: ##print str(nextHour-nearestHour.hour)+" - "+str(nextHour)+" - "+str(nearestHour.hour)+"\t"+out+" other situation" #print out+" other situation" #nextHour = (nextHour+1)%24 #print out # arrayOut.append(out) # arrayDate.append(nearestHour) continue fd.close() return timeToRecord # if len(arrayDate)==0: # return retval # # arrayDate2 = [] # arrayOut2 = [] # # Remove dupe # # #some times the first enrty may contain 12am of next day # #target = datetime(arrayDate[1].year,arrayDate[1].month,arrayDate[1].day,0) # # #print arrayDate # # i = 0 # while arrayDate[i].hour<>0 or arrayDate[i].day<>arrayDate[i+1].day: # arrayDate.pop(i) # arrayOut.pop(i) # # #print arrayDate # # for i in range(0,len(arrayDate)): # #print i, arrayDate[i], arrayDate[i]-timedelta(hours=1), arrayDate[i-1] # if i==0: # #parts = arrayDate[0].split("\t") # #hour = arrayDate[0].hour#int(parts[3]) # #if hour==23: # # arrayDate2.append(arrayDate[1]) # # arrayOut2.append(arrayOut[1]) # #else: # arrayDate2.append(arrayDate[i]) # arrayOut2.append(arrayOut[i]) # elif (arrayDate[i]-timedelta(hours=1)) == arrayDate[i-1]: # arrayDate2.append(arrayDate[i]) # arrayOut2.append(arrayOut[i]) # #if (arrayDate[i]-timedelta(hours=23))==target or (arrayDate[i]-timeDelta[hours=1]) # # i=1 # iniHour = arrayDate2[0] # iniHour = datetime(iniHour.year,iniHour.month,iniHour.day,0) # #print arrayOut2[0] # ftemp.write(arrayOut2[0]+"\n") # for h in range(1,24): # #print h, i, len(arrayDate2) # if (i<len(arrayDate2)) and arrayDate2[i].day == iniHour.day: # #print arrayOut2[i] # ftemp.write(arrayOut2[i]+"\n") # else: # i = i+1 # if (i<len(arrayDate2)): # #print arrayOut2[i] # ftemp.write(arrayOut2[i]+"\n") # # if (i<len(arrayDate2)) and arrayDate2[i]==(iniHour+timedelta(hours=h)): # i = i+1 # # #ftemp.close() # # ftemp.seek(0)# = open("tempdata.txt",'r') # for line in ftemp: # #print line.split("\t") # str1 = line.split("\t")[0]+"_"+line.split("\t")[1]+"_"+line.split("\t")[2]+"_"+line.split("\t")[3] # str1 += "\t"+line.split("\t")[7]+"\t"+line.split("\t")[8]+"\t"+line.split("\t")[10]+"\t"+line.split("\t")[6] # str1 += "\t"+"10"+"\t"+"NNW"+"\t"+line.split("\t")[13] # fout.write(str1) # ftemp.close() # Let's double check to see if we have all the required hour #startTime = datetime(day.year,day.month,day.day) #oneHour = timedelta(hours=1) #endTime = startTime + timedelta(days=1) #while(startTime<endTime): #if not retval.has_key(startTime): #print location,startTime #startTime+=oneHour return retval def fromDirToTime(x): return int(time.mktime(time.strptime(os.path.basename(x), getWeatherPrediction.format))) def execCmd(cmd): try: retcode = subprocess.call(cmd, shell=True) if retcode < 0: print >>sys.stderr,"cmd return code",retcode,cmd print >>sys.stderr, "Child was terminated by signal", -retcode raise() except OSError, e: print >>sys.stderr,"cmd failed",cmd print >>sys.stderr, "Execution failed:", e raise() def process(date, num_hours=24, path="."): global outputFormat #global fout #global d # fout = tempfile.TemporaryFile()#= open("full_fore.txt","w") loc = 'nj' url = "http://www.weather.com/weather/pastweather/hourly/" d = date if d.minute>0: d = datetime(d.year,d.month,d.day,d.hour) #d += timedelta(hours=1) date = d # date = d - timedelta(hours=2) d = datetime(date.year,date.month,date.day)#date #print date # num_hours += 2 # print "process",date,num_hours,d timeToRecords = {} while d < date+timedelta(hours=num_hours+1): url = "http://www.weather.com/weather/pastweather/hourly/" url += "%s?when=%s&stn=0"%(zipcodes[loc],d.strftime("%m%d%y")) htmlFile = path+"/htmlarchive/%s_%d_%d_%d.html"%(loc,d.year,d.month,d.day) #print htmlFile # Download if they cannot be found if not os.path.isfile(htmlFile): #print url cmd = 'wget -O %s -o /dev/null "%s"'%(htmlFile,url) execCmd(cmd) else: if os.path.getsize(htmlFile)==0: cmd = 'wget -O %s -o /dev/null "%s"'%(htmlFile,url) execCmd(cmd) parseStore(htmlFile,d,timeToRecords) #print d d += timedelta(days=1) # keys = timeToRecords.keys() # keys.sort() # # print keys # print "++++++++++++++++++++++++++++" #fout.close() # finp = fout#open("full_fore.txt","r") # finp.seek(0) # fout = tempfile.TemporaryFile()#open("fore.txt","w") dates = timeToRecords.keys() dates.sort() # shift = date.hour # i = 0 # print shift retval = {} lastDate = None tdelta = timedelta(hours=1) for d in dates: # if shift>0: # shift -= 1 # continue #print line.split("\t") r = timeToRecords[d] if conditions.has_key(r.condition.conditionString): tagint = conditions[r.condition.conditionString] else: print "key missing", r.condition.conditionString tagint = conditions[weatherPrediction.long_substr(r.condition.conditionString)] # str1 = "%s\t%s\t%d"%(d.strftime(outputFormat),r.condition.conditionString,tagint) r.condition.conditionGroup = tagint retval[d] = r.condition if lastDate: lastDate=lastDate+tdelta while lastDate<d: retval[lastDate] = WeatherCondition("Unkown", -1) lastDate=lastDate+tdelta lastDate = d # fout.write(str1+"\n") # i += 1 # if i==num_hours: # break # finp.close() # #fout.close() # fout.seek(0) # # return fout return retval if __name__ == '__main__': print "past weather" now = datetime(2010, 8, 23, 9, 0,0) retval = process(now) keys = retval.keys() keys.sort() for k in keys: print k.strftime(outputFormat),retval[k] # for line in fd: # print line.strip() # fd.close()
a5d48afa2d1c830a018adff027da4e544cb5be85
[ "Python", "Makefile", "Shell" ]
26
Python
goiri/greenhadoop
02f5243be7b2a19a4b083dee81b983bfd48ca9af
876963a41497b6994dbb8fb12e19cbe8210e35d9
refs/heads/master
<repo_name>kyomini/KyoMini<file_sep>/app.js /* * ╔╗╔═╦╗──╔╦═══╦═╗╔═╦══╦═╗─╔╦══╗ * ║║║╔╣╚╗╔╝║╔═╗║║╚╝║╠╣╠╣║╚╗║╠╣╠╝ * ║╚╝╝╚╗╚╝╔╣║─║║╔╗╔╗║║║║╔╗╚╝║║║ * ║╔╗║─╚╗╔╝║║─║║║║║║║║║║║╚╗║║║║ * ║║║╚╗─║║─║╚═╝║║║║║╠╣╠╣║─║║╠╣╠╗ * ╚╝╚═╝─╚╝─╚═══╩╝╚╝╚╩══╩╝─╚═╩══╝ * Node.js For KyoMini框架 * Author:小野直树 * */ const Koa = require('koa'), Router = require('koa-router'), logger = require('koa-logger'), serve = require('koa-static'), path = require('path'), render = require('koa-art-template'), bodyParser = require('koa-bodyparser'), helmet = require('koa-helmet'), routers = require('./router'), config = require('./config/web-config'), app = new Koa(); //加载helmet安全模块 防止XSS攻击等 app.use(helmet()); //加载路由 routers(app); //静态资源处理的中间件 app.use(serve(path.resolve(__dirname,'./public/'))); render(app, { root: path.join(__dirname, config.template), //模板所在文件夹目录 extname: config.extname, //模板文件后缀名 debug: config.debug //调试模式 }); //获取POST/GET中间件 app.use(bodyParser()); //日志输出插件 app.use(logger()); app.listen(config.port,function(){ console.log(config.web_info); });<file_sep>/README.md # KyoMini 框架 ![banner.jpg](http://www.naokiono.cc/public/banner.jpg) ## 久违了,优雅的新Web框架 此框架是Node.js上最简单的入门级框架,初学者轻易上手进行二次开发。 当然!它是免费的。 ### 安装 第一步: 输入 `npm install ` 进行安装依赖包 第二步: 输入 `npm start` 启动就是这么简单! ### 文件架构 ```javascript controllers 控制器 models 模型 router 路由 template 视图模板 piblic 静态资源 |-home 前台模板静态资源 |-admin 后台模板静态资源 |-css css公共静态资源 |-js js 公共静态资源 |-img img公共静态资源 package.json 依赖配置 app.js 启动程序 ``` ### 相关模块 ```javascript Koa 框架模块 koa-router 路由模块 koa-logger 日志模块 koa-static 静态资源模块 koa-art-template 模板模块 koa-bodyparser 响应模块 koa-helmet 安全模块 ``` ### Config配置 web-config.js ```javascript template:'template', 模板目录 extname:'.html', 模板后缀 port : '8080', 服务端口 ```
6bf3437b40b47d7db275f6e21add9125219a3329
[ "JavaScript", "Markdown" ]
2
JavaScript
kyomini/KyoMini
bb748057fb04a1e14f72580388704d76abad623f
8d2de212372772ddb15c13e8fc0e325b5fef7e68
refs/heads/master
<repo_name>jlalvescarvalho/BoaLista<file_sep>/src/java/br/lk/boalista2/Builders/BuilderProduto.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.lk.boalista2.Builders; import br.lk.boalista2.Negocio.Produto; public class BuilderProduto { private long id; private int codigo; private String nome; public BuilderProduto(int codigo, String nome) { this.codigo = codigo; this.nome = nome; } public long getId() { return id; } public void setId(Long id){ this.id = id; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Produto BuilderProduto(){ return new Produto(this.codigo, this.nome); } } <file_sep>/src/java/br/lk/boalista2/Builders/BuilderMarca.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.lk.boalista2.Builders; import br.lk.boalista2.Negocio.Marca; import br.lk.boalista2.Negocio.Produto; /** * * @author Kleriston */ public class BuilderMarca { private long id; private String marca; private Produto produto; public BuilderMarca(String marca, Produto produto) { this.marca = marca; this.produto= produto; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public Marca BuilderMarca(){ return new Marca(marca, produto); } } <file_sep>/src/java/br/lk/boalista2/Fachada/Fachada.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.lk.boalista2.Fachada; import br.lk.boalista2.Dao.DaoManagerHiber; import br.lk.boalista2.Negocio.Marca; import br.lk.boalista2.Negocio.Produto; import br.lk.boalista2.Negocio.Usuario; import br.lk.boalista2.Repositorio.Interface.RepositorioGenerico; import br.lk.boalista2.Repositorio.RepositorioMarca; import br.lk.boalista2.Repositorio.RepositorioProduto; import br.lk.boalista2.Repositorio.RepositorioUsuario; import java.util.List; /** * * @author Kleriston */ public class Fachada { private static Fachada myself = null; private RepositorioGenerico<Produto, Long> repProduto = null; private RepositorioGenerico<Usuario, Long> repUsuario = null; private RepositorioGenerico<Marca, Long> repMarca = null; public Fachada() { this.repProduto= new RepositorioProduto(); this.repUsuario = new RepositorioUsuario(); this.repMarca = new RepositorioMarca(); } public static Fachada getStance(){ if(myself == null) myself = new Fachada(); return myself; } public void inserir(Produto produto){ this.repProduto.inserir(produto); } public void alterar(Produto produto ){ this.repProduto.alterar(produto); } public void excluir(Produto produto){ this.repProduto.excluir(produto); } public Produto recuperarProduto(Long id){ return this.repProduto.recuperar(id); } public List<Produto> recuperarTodos(){ return this.repProduto.recuperarTodos(); } public void inserirusuario(Usuario usuario){ this.repUsuario.inserir(usuario); } public void alterarUsuario(Usuario usuario){ this.repUsuario.alterar(usuario); } public void excluirUsuario(Usuario usuario){ this.repUsuario.excluir(usuario); } public Usuario recuperarUsuario(Long id){ return this.repUsuario.recuperar(id); } public List<Usuario> listarUsuario(){ return this.repUsuario.recuperarTodos(); } public void inserirMarca(Marca marca){ this.repMarca.inserir(marca); } }
b4233cefc7e2fa02318511ac24b58591966f1c33
[ "Java" ]
3
Java
jlalvescarvalho/BoaLista
a53a3f5b61456e9181421df5808af797a54abf08
1ed5f51f456e30b72ce79fa1a8e9d21313f8493d
refs/heads/main
<file_sep># 搭建过程 React SSR的关键是同构,同构意味着一套代码既在服务端执行,又在客户端执行,所以所有的努力都是要保证在两端都可执行。 ## 要点 - 路由不同. 客户端的spa是根据history来定位view的(history的改变并不刷新页面),而SSR需要根据location来的 - 数据预取. SSR的一个流程是preload data. - 渲染函数不同. spa用render渲染,ssr用renderToString渲染 - 可以用Redux管理数据 <file_sep>const defaultState = { title: 'Hello Redux' } export default function(state = defaultState , action) { switch (action.type) { default: return state } }
e50c21eeaeee5c7da0fbafed371c19dfa4549714
[ "Markdown", "JavaScript" ]
2
Markdown
XYjourney/react-ssr-ts
8c3dff1598c12f307dfd73a7ec7d19131e53c8c4
df2a6c34666c8d5ed910a4ea9216290c846ff683
refs/heads/master
<file_sep>/* Author: <NAME> Based on code by: <NAME> Department of Computer Science Texas A&M University A thread scheduler. */ #ifndef SCHEDULER_H #define SCHEDULER_H /*--------------------------------------------------------------------------*/ /* DEFINES /*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ /* INCLUDES /*--------------------------------------------------------------------------*/ #include "machine.H" #include "thread.H" /*--------------------------------------------------------------------------*/ /* QUEUE /*--------------------------------------------------------------------------*/ // Based on code from https://gist.github.com/mycodeschool/7331785 #define MAX_SIZE 101 //maximum size of the array that will store Queue. // Creating a class named Queue. class Queue { private: Thread * A[MAX_SIZE]; int front, rear; public: // Constructor - set front and rear as -1. // We are assuming that for an empty Queue, both front and rear will be -1. Queue() { front = -1; rear = -1; } // To check wheter Queue is empty or not bool IsEmpty() { return (front == -1 && rear == -1); } // To check whether Queue is full or not bool IsFull() { return (rear+1)%MAX_SIZE == front ? true : false; } // Inserts an element in queue at rear end int Enqueue(Thread * x) { if(IsFull()) { return 1; } if (IsEmpty()) { front = rear = 0; } else { rear = (rear+1)%MAX_SIZE; } A[rear] = x; return 0; } // Removes a thread from front end. Thread * Dequeue() { if(IsEmpty()) { return 0; } else if(front == rear ) { Thread * t = A[front]; rear = front = -1; return t; } else { Thread * t = A[front]; front = (front+1)%MAX_SIZE; return t; } return 0; } }; /*--------------------------------------------------------------------------*/ /* SCHEDULER /*--------------------------------------------------------------------------*/ class Scheduler { Queue thread_queue; Thread * current; public: Scheduler(); /* Setup the scheduler. This sets up the ready queue, for example. If the scheduler implements some sort of round-robin scheme, then the end_of_quantum handler is installed here as well. */ virtual void yield(); /* Called by the currently running thread in order to give up the CPU. The scheduler selects the next thread from the ready queue to load onto the CPU, and calls the dispatcher function defined in 'threads.h' to do the context switch. */ virtual void resume(Thread * _thread); /* Add the given thread to the ready queue of the scheduler. This is called for threads that were waiting for an event to happen, or that have to give up the CPU in response to a preemption. */ virtual void add(Thread * _thread); /* Make the given thread runnable by the scheduler. This function is called typically after thread creation. Depending on the implementation, this may not entail more than simply adding the thread to the ready queue (see scheduler_resume). */ virtual void terminate(Thread * _thread); /* Remove the given thread from the scheduler in preparation for destruction of the thread. */ }; #endif<file_sep>#include "page_table.H" #include "paging_low.H" #include "console.H" //initialize statics PageTable * PageTable::current_page_table; unsigned int PageTable::paging_enabled; FramePool * PageTable::kernel_mem_pool; FramePool * PageTable::process_mem_pool; unsigned long PageTable::shared_size; unsigned long * PageTable::page_directory; void PageTable::init_paging(FramePool * _kernel_mem_pool, FramePool * _process_mem_pool, const unsigned long _shared_size){ kernel_mem_pool = _kernel_mem_pool; process_mem_pool = _process_mem_pool; shared_size = _shared_size; } /* Set the global parameters for the paging subsystem. */ PageTable::PageTable(){ page_directory = (unsigned long *) (process_mem_pool->get_frame() * PAGE_SIZE); unsigned long * page_table = (unsigned long *) (process_mem_pool->get_frame() * PAGE_SIZE); unsigned long address = 0; for (int i = 0; i < ENTRIES_PER_PAGE-1; ++i) { page_table[i] = address | 3; address = address + PAGE_SIZE; } page_directory[0] = (unsigned long) page_table; page_directory[0] |= 3; for (int i = 1; i < ENTRIES_PER_PAGE-1; ++i) { page_directory[i] = 0 | 2; } page_directory[ENTRIES_PER_PAGE-1] = (unsigned long)page_directory | 3; paging_enabled = false; } /* Initializes a page table with a given location for the directory and the page table proper. NOTE: The PageTable object still needs to be stored somewhere! Probably it is best to have it on the stack, as there is no memory manager yet... NOTE2: It may also be simpler to create the first page table *before* paging has been enabled. */ void PageTable::load(){ current_page_table = this; write_cr3((unsigned long) page_directory); } /* Makes the given page table the current table. This must be done once during system startup and whenever the address space is switched (e.g. during process switching). */ void PageTable::enable_paging(){ write_cr0(read_cr0() | 0x80000000); paging_enabled = true; } /* Enable paging on the CPU. Typically, a CPU start with paging disabled, and memory is accessed by addressing physical memory directly. After paging is enabled, memory is addressed logically. */ void PageTable::handle_fault(REGS * _r){ // Read the address unsigned long address = read_cr2(); unsigned long* page_dir = current_page_table->page_directory; //get the indices of the directory and page table and virtual address unsigned long page_dir_index = address >> 22; unsigned long page_tab_index = (address >> 12) & 0x3FF; unsigned long page_dir_offset = page_dir_index << 12; unsigned long page_tab_offset = page_tab_index << 2; unsigned long *virtual_address = (unsigned long *)(0xFFC00000 | page_dir_offset | page_tab_offset); unsigned long* page_entry; //get the page table from the directory unsigned long *page_tab = virtual_address; //set up page table if none exists if (((*virtual_address) & 0x1) != 0x1) { page_tab = (unsigned long *)(process_mem_pool->get_frame() * PAGE_SIZE); *virtual_address = ((unsigned long)page_tab | 0x3); } unsigned long * page_entry = (unsigned long *)(process_mem_pool->get_frame() * PAGE_SIZE); *virtual_address = (unsigned long)pageEntry | 0x3; } <file_sep>#include "scheduler.H" Scheduler::Scheduler(){ current = 0; return; } /* Setup the scheduler. This sets up the ready queue, for example. If the scheduler implements some sort of round-robin scheme, then the end_of_quantum handler is installed here as well. */ void Scheduler::yield(){ current = thread_queue.Dequeue(); Thread::dispatch_to(current); } /* Called by the currently running thread in order to give up the CPU. The scheduler selects the next thread from the ready queue to load onto the CPU, and calls the dispatcher function defined in 'threads.h' to do the context switch. */ void Scheduler::resume(Thread * _thread){ thread_queue.Enqueue(_thread); } /* Add the given thread to the ready queue of the scheduler. This is called for threads that were waiting for an event to happen, or that have to give up the CPU in response to a preemption. */ void Scheduler::add(Thread * _thread){ thread_queue.Enqueue(_thread); } /* Make the given thread runnable by the scheduler. This function is called typically after thread creation. Depending on the implementation, this may not entail more than simply adding the thread to the ready queue (see scheduler_resume). */ void Scheduler::terminate(Thread * _thread){ if(_thread == current){ yield(); } else{ Queue temp; //filter queue by ThreadId while(!thread_queue.IsEmpty()){ Thread * t = thread_queue.Dequeue(); if(t->ThreadId() != _thread->ThreadId()) temp.Enqueue(t); } while(!temp.IsEmpty()){ Thread * t = temp.Dequeue(); thread_queue.Enqueue(t); } } } /* Remove the given thread from the scheduler in preparation for destruction of the thread. */<file_sep># Replace "/mnt/floppy" with the whatever directory is appropriate. sudo mount -o loop dev_kernel_grub.img /media/floppy1/ sudo cp kernel.bin /media/floppy1/ sudo umount /media/floppy1/
25a15e0dc264c56b45240e0db20dca29d28d3982
[ "C", "C++", "Shell" ]
4
C++
jaideng123/410-Kernel
713541ee316429af505432b8481f5a116c576f9a
aa3dd6f06ad989836060a2f1fc731c8dbff2562d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { String a; String b; int numero1; int numero2; public Form1() { InitializeComponent(); a = ""; b = ""; numero1 = 0; numero2 = 0; } private void Form1_Load(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { a = textBox1.Text; numero1 = Int32.Parse(a); b = textBox2.Text; numero2 = Int32.Parse(b); String resultado = (numero1 + numero2).ToString(); textBox3.Text = resultado; } private void button2_Click(object sender, EventArgs e) { textBox1.Text = "Numero entero"; textBox2.Text = "Numero entero 2"; textBox3.Text = "Resultado"; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class AdminLogin : Form { public String loginAdmin = "Admin"; public String passAdmin = "<PASSWORD>"; public AdminLogin() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Equals(loginAdmin) && textBox2.Text.Equals(passAdmin)) { AdminForm a = new AdminForm(); a.Visible = true; this.Close(); } else { label3.Text = "Error de usuario o contraseña."; label3.Visible = true; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { class Program { static void Main(string[] args) { String cadena = ""; int contadorDeSietes = 0; Console.WriteLine("Introduce un numero!"); cadena = Console.ReadLine(); foreach(char a in cadena) { if(a == '7') { contadorDeSietes++; } } Console.WriteLine("Has introducido: " + contadorDeSietes + " veces el numero 7"); contadorDeSietes = 0; int i = 0; char letra; int length = cadena.Length; do { letra = cadena[i]; if(letra == '7') { contadorDeSietes++; } i++; } while (i < length); Console.WriteLine("Has introducido: " + contadorDeSietes + " veces el numero 7"); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormCuentaBancaria { public partial class Form3 : Form { public Form3() { InitializeComponent(); CuentaAhorro cuenta2 = new CuentaAhorro(); cuenta2.setNombreCuenta("<NAME>"); cuenta2.setNumCuenta(555555555); cuenta2.setSaldoCuenta(1000); cuenta2.setTipoInteres(2); cuenta2.setCuotaMantenimiento(100); textBox1.Text = cuenta2.getNombreCuenta(); textBox2.Text = cuenta2.getNumCuenta().ToString(); textBox3.Text = cuenta2.getSaldoCuenta().ToString(); textBox4.Text = cuenta2.getTipoInteres().ToString(); textBox5.Text = cuenta2.getCuotaMantenimiento().ToString(); } private void button1_Click(object sender, EventArgs e) { Form1 ventanPrincipal = new Form1(); this.Visible = false; ventanPrincipal.Visible = true; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; namespace AppShawarmitaF { public partial class Form1 : Form { public static Form1 principal; public static ArrayList carrito; public static ArrayList burguersTienda; public static Double promocion1 = 0.8; public static Double promocion2 = 0.7; public Form1() { InitializeComponent(); principal = this; carrito = new ArrayList(); burguersTienda = new ArrayList(); } public Form1(ArrayList carrito) { InitializeComponent(); carrito = carrito; burguersTienda = new ArrayList(); } private void button2_Click(object sender, EventArgs e) { AdminLogin a = new AdminLogin(); a.Visible = true; this.Visible = false; } private void button1_Click(object sender, EventArgs e) { burguers2.BringToFront(); } private void button3_Click(object sender, EventArgs e) { kebab1.BringToFront(); } private void Form1_Load(object sender, EventArgs e) { Comida aux = new Comida(); aux.setName("Burguer Demoniaca"); aux.setPrecio(15); Comida aux1 = new Comida(); aux1.setName("Burguer No Demoniaca"); aux1.setPrecio(10); Comida aux2 = new Comida(); aux2.setName("Burguer Normal"); aux2.setPrecio(1); Comida aux3 = new Comida(); aux3.setName("Burguer Celiaca"); aux3.setPrecio(7); burguersTienda.Add(aux); burguersTienda.Add(aux1); burguersTienda.Add(aux2); burguersTienda.Add(aux3); Comida k1 = new Comida(); k1.setName("<NAME>"); k1.setPrecio(15); Comida k2 = new Comida(); k2.setName("<NAME>"); k2.setPrecio(10); Comida k3 = new Comida(); k3.setName("<NAME>"); k3.setPrecio(1); Comida k4 = new Comida(); k4.setName("<NAME>"); k4.setPrecio(7); burguersTienda.Add(k1); burguersTienda.Add(k2); burguersTienda.Add(k3); burguersTienda.Add(k4); burguers2.BringToFront(); } private void button4_Click(object sender, EventArgs e) { bebida1.BringToFront(); } private void button6_Click(object sender, EventArgs e) { complementos1.BringToFront(); } private void button5_Click(object sender, EventArgs e) { Carrito a = new Carrito(); this.Visible = false; a.Visible = true; } private void button7_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp7 { public partial class Form2 : Form { public static ArrayList personas; public static ArrayList palabras; public Form2() { InitializeComponent(); button1.Enabled = false; palabras = new ArrayList(); personas = new ArrayList(); } private void button1_Click(object sender, EventArgs e) { Form1 ventanaJuego = new Form1(palabras); ventanaJuego.Visible = true; this.Visible = false; } private void button2_Click(object sender, EventArgs e) { palabras.Add("alguacil"); palabras.Add("diazepam"); palabras.Add("destornillador"); palabras.Add("diclofenaco"); palabras.Add("dietilamonico"); palabras.Add("exhumacion"); palabras.Add("aletargadamente"); button1.Enabled = true; button2.BackColor = Color.Green; button3.BackColor = button1.BackColor; button4.BackColor = button1.BackColor; } private void button3_Click(object sender, EventArgs e) { palabras.Add("camion"); palabras.Add("teclado"); palabras.Add("monitor"); palabras.Add("portatil"); palabras.Add("botella"); palabras.Add("programar"); palabras.Add("rotulador"); button3.BackColor = Color.Green; button2.BackColor = button1.BackColor; button4.BackColor = button1.BackColor; button1.Enabled = true; } private void button4_Click(object sender, EventArgs e) { palabras.Add("hola"); palabras.Add("pepe"); palabras.Add("jarra"); palabras.Add("willy"); palabras.Add("ñu"); palabras.Add("te"); button4.BackColor = Color.Green; button3.BackColor = button1.BackColor; button2.BackColor = button1.BackColor; button1.Enabled = true; } private void loginToolStripMenuItem1_Click(object sender, EventArgs e) { Login ventanaLogin = new Login(); ventanaLogin.Visible = true; this.Visible = false; } private void Form2_Load(object sender, EventArgs e) { personas.Add(new Persona("admin", "admin")); } private void registroToolStripMenuItem_Click(object sender, EventArgs e) { Registro ventanaRegistro = new Registro(); this.Visible = false; ventanaRegistro.Visible = true; } private void Form2_HelpRequested_1(object sender, HelpEventArgs hlpevent) { Help.ShowHelp(this, "C:/Users/2dam/Documents/HelpNDoc/Output/Crear documentación chm/Titulo de este proyecto de ayuda.chm", "C:/Users/2dam/Documents/HelpNDoc/Output/Crear documentación html/Titulo de este proyecto de ayuda.html"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class Kebab : UserControl { public Kebab() { InitializeComponent(); } private void buscarYPersonalizar(String nombre) { foreach (Comida comida in Form1.burguersTienda) { if (comida.getName().Equals(nombre)) { Comida aux = new Comida(); aux.setName(comida.getName()); aux.setPrecio(comida.getPrecio()); if (nombre.Equals("Shawarma Demoniaco")) { aux.setImage(pictureBox1.Image); } else if (nombre.Equals("Shawarma No Demoniaco")) { aux.setImage(pictureBox2.Image); } else if (nombre.Equals("Shawarma Normal")) { aux.setImage(pictureBox3.Image); } else { aux.setImage(pictureBox4.Image); } Personalizacion a = new Personalizacion(aux); a.Visible = true; Form1.principal.Visible = false; } } } private void button1_Click(object sender, EventArgs e) { buscarYPersonalizar("Shawarma Demoniaco"); } private void button2_Click(object sender, EventArgs e) { buscarYPersonalizar("Shawarma No Demoniaco"); } private void button3_Click(object sender, EventArgs e) { buscarYPersonalizar("Shawarma Normal"); } private void button4_Click(object sender, EventArgs e) { buscarYPersonalizar("Shawarma Celiaco"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BlocNotas { public partial class Form1 : Form { private System.Drawing.Printing.PrintDocument docToPrint = new System.Drawing.Printing.PrintDocument(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void abrirToolStripMenuItem_Click(object sender, EventArgs e) { } private void edicionToolStripMenuItem_Click(object sender, EventArgs e) { } private void barraDeEstadoToolStripMenuItem_Click(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void imprimirToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = printDialog1.ShowDialog(); // If the result is OK then print the document. if (result == DialogResult.OK) { MessageBox.Show("Estás imprimiendo"); } else { this.Close(); } } private void textBox2_TextChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp7 { class Persona { private String login; private String passwd; public Persona(string login, string passwd) { this.login = login; this.passwd = <PASSWORD>; } public void setLogin(String login) { this.login = login; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getLogin() { return this.login; } public String getPasswd() { return this.passwd; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp7 { public partial class Form1 : Form { private String palabraSecreta = ""; private int intentos = 5; ArrayList letrasUsadas = new ArrayList(); ArrayList palabras; public Form1(ArrayList palabras) { InitializeComponent(); this.palabras = palabras; button2.Visible = false; button2.Enabled = false; } private void Form1_Load(object sender, EventArgs e) { Random rnd = new Random(); int numeroAleatorio = rnd.Next(palabras.Count - 1); int contador = 0; foreach(String i in palabras){ if(contador == numeroAleatorio) { palabraSecreta = i; } contador++; } for (int i = 0; i < palabraSecreta.Length - 1; i++) { label5.Text += "_ "; } label5.Text += "_"; } public void comprobarLetra(Char letra) { Boolean encontrado = false; Boolean encontradoRepe = false; foreach (Char l in letrasUsadas) { if (l.Equals(letra)) { encontradoRepe = true; } } letrasUsadas.Add(letra); if(encontradoRepe == false) { foreach (Char l in palabraSecreta) { if (l.Equals(letra)) { encontrado = true; } } if (encontrado == true) { this.tratarLetra(letra); } else { label3.Text += letra + " "; intentos--; if (intentos == 0) { label6.Text = "Game over!"; button1.Enabled = false; pictureBox6.Visible = true; button2.Visible = true; button2.Enabled = true; label5.Text = ""; for (int i = 0; i < palabraSecreta.Length - 1; i++) { label5.Text += palabraSecreta[i]; } label5.Text += palabraSecreta[palabraSecreta.Length - 1]; } else if (intentos == 4) { pictureBox1.Visible = true; } else if (intentos == 3) { pictureBox2.Visible = true; } else if (intentos == 2) { pictureBox3.Visible = true; } else if (intentos == 1) { pictureBox4.Visible = true; } } } } public void tratarLetra(Char letra) { String palabraActualizada = label5.Text.Replace(" ", ""); String palabraAct = ""; int contador = 0; foreach (Char l in palabraActualizada) { if (!l.Equals('_')) { palabraAct += l; } else if(letra.Equals(palabraSecreta[contador])) { palabraAct += letra; } else { palabraAct += "_"; } contador++; } label5.Text = ""; for(int i = 0; i < palabraActualizada.Length - 1; i++) { label5.Text += palabraAct[i] + " "; } label5.Text += palabraAct[palabraAct.Length - 1].ToString(); if (palabraAct.Equals(palabraSecreta)) { label6.Text = "Winner!!"; button1.Enabled = false; button2.Visible = true; button2.Enabled = true; } } private void button1_Click(object sender, EventArgs e) { String l = textBox1.Text; if(l.Length == 1) { Char letra = Convert.ToChar(l); this.comprobarLetra(letra); } } private void pictureBox3_Click(object sender, EventArgs e) { } private void pictureBox6_Click(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { ArrayList palabras = Form2.palabras; ArrayList personas = Form2.personas; Form2 ventanaInicial = new Form2(); Form2.palabras = palabras; Form2.personas = personas; this.Visible = false; ventanaInicial.Visible = true; } private void salirToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class Bebida : UserControl { public Bebida() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Comida b1 = new Comida(); b1.setName("Agua"); b1.setPrecio(1.5); b1.setImage(pictureBox1.Image); PersonalizacionOtros a = new PersonalizacionOtros(b1); a.Visible = true; Form1.principal.Visible = false; } private void button2_Click(object sender, EventArgs e) { Comida b2 = new Comida(); b2.setName("<NAME>"); b2.setPrecio(1.8); b2.setImage(pictureBox2.Image); PersonalizacionOtros a = new PersonalizacionOtros(b2); a.Visible = true; Form1.principal.Visible = false; } private void button3_Click(object sender, EventArgs e) { Comida b3 = new Comida(); b3.setName("Aquarius"); b3.setPrecio(2); b3.setImage(pictureBox3.Image); PersonalizacionOtros a = new PersonalizacionOtros(b3); a.Visible = true; Form1.principal.Visible = false; } private void button4_Click(object sender, EventArgs e) { Comida b4 = new Comida(); b4.setName("Fanta"); b4.setPrecio(1.7); b4.setImage(pictureBox4.Image); PersonalizacionOtros a = new PersonalizacionOtros(b4); a.Visible = true; Form1.principal.Visible = false; } private void Bebida_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class burguers : UserControl { Form form; public burguers() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { buscarYPersonalizar("Burguer Demoniaca"); } private void burguers_Load(object sender, EventArgs e) { } private void buscarYPersonalizar(String nombre) { foreach (Comida comida in Form1.burguersTienda) { if (comida.getName().Equals(nombre)) { Comida aux = new Comida(); aux.setName(comida.getName()); aux.setPrecio(comida.getPrecio()); if (nombre.Equals("Burguer Demoniaca")) { aux.setImage(pictureBox1.Image); } else if (nombre.Equals("Burguer No Demoniaca")) { aux.setImage(pictureBox2.Image); } else if (nombre.Equals("Burguer Normal")) { aux.setImage(pictureBox3.Image); } else { aux.setImage(pictureBox4.Image); } Personalizacion a = new Personalizacion(aux); a.Visible = true; Form1.principal.Visible = false; } } } private void button2_Click(object sender, EventArgs e) { buscarYPersonalizar("Burguer No Demoniaca"); } private void button3_Click(object sender, EventArgs e) { buscarYPersonalizar("Burguer Normal"); } private void button4_Click_1(object sender, EventArgs e) { buscarYPersonalizar("Burguer Celiaca"); } private void pictureBox1_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void domainUpDown1_SelectedItemChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int a = Int32.Parse(domainUpDown1.Text); int suma = 0; for(int i = 1; i <= a; i++) { if (checkBox1.Checked) { textBox1.Text += "sumando: " + i.ToString() + " Suma parcial: " + suma.ToString() + Environment.NewLine; } suma += i; } textBox1.Text += "\nEl resultado final es " + suma.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp10 { class Program { static void Main(string[] args) { string [] antonio = {"pepito", "pepino", "antonio", "carlos", "raul", "jopegras", "noelia", "mateo", "diccionario", "godofredo"}; int diferencia = 0; String auxiliar = ""; for(int i = 0; i < antonio.Length; i++){ for(int j = 0; j < antonio.Length; j++){ diferencia = string.Compare(antonio[i], antonio[j]); if(diferencia == -1){ auxiliar = antonio[i]; antonio[i] = antonio[j]; antonio[j] = auxiliar; } } } for(int i = 0; i < antonio.Length; i++) { Console.WriteLine(antonio[i]); } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void groupBox1_Enter(object sender, EventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int costes = 0; if (radioButton1.Checked) { costes = 4; } else if(radioButton2.Checked) { costes = 6; } else if (radioButton3.Checked) { costes = 8; } costes = costes + Int32.Parse(textBox1.Text); label1.Text = costes.ToString() + "€"; } private void textBox1_TextChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VentanaHamburguesa { public partial class MySecondCustomControl : UserControl { public MySecondCustomControl() { InitializeComponent(); } private void MySecondCustomControl_Load(object sender, EventArgs e) { } private void label8_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppShawarmitaF { public class Comida { String name; Boolean lechuga; Boolean tomate; Boolean cebolla; Boolean grande; Boolean mediano; Boolean pequenio; Double precio; Image image; public Comida() { name = ""; lechuga = false; tomate = false; cebolla = false; grande = false; pequenio = false; mediano = false; precio = 0; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setLechuga(Boolean lechu) { this.lechuga = lechu; } public void setTomate(Boolean tomat) { this.tomate = tomat; } public void setCebolla(Boolean ceboll) { this.cebolla = ceboll; } public void setPrecio(Double pre) { this.precio = pre; } public Boolean getLechuga() { return lechuga; } public Boolean getTomate() { return tomate; } public Boolean getCebolla() { return cebolla; } public Double getPrecio() { return precio; } public void setImage(Image ima) { this.image = ima; } public Image getImage() { return image; } public void setGrande(Boolean g) { this.grande = g; } public void setMediano(Boolean g) { this.mediano = g; } public void setPequenio(Boolean g) { this.pequenio = g; } public Boolean getGrande() { return grande; } public Boolean getMediano() { return mediano; } public Boolean getPequenio() { return pequenio; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } <file_sep>using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Header; namespace ConexionMYSQLCodigo { public partial class Form1 : Form { static MySqlConnection Conex = new MySqlConnection(); static string serv = "Server=localhost;"; static string db = "Database=desarrollointf;"; static string usuario = "UID=root;"; static string pwd = ""; string cadenaDeConexion = serv + db + usuario + pwd; int idContactos = 0; public void conectar() { try { Conex.ConnectionString = cadenaDeConexion; Conex.Open(); MessageBox.Show("LA BD ESTA CONECTADA"); } catch(Exception) { MessageBox.Show("AAASSSSTIAS QUE NO PUEDO CONECTAR"); throw; } } public void desconectar() { Conex.Close(); } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { conectar(); dataGridViewLoad(); comboBoxLoad(); iniciarID(); } private void iniciarID() { DataTable dt = new DataTable(); MySqlCommand cmd = Conex.CreateCommand(); cmd.CommandText = "SELECT id_contacto FROM CONTACTOS;"; MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dt); foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) { if(Int32.Parse(row[col].ToString()) > idContactos) { idContactos = Int32.Parse(row[col].ToString()); } } } } private void dataGridViewLoad() { DataTable dt = new DataTable(); MySqlCommand cmd = Conex.CreateCommand(); cmd.CommandText = "SELECT * FROM CONTACTOS;"; MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dt); dataGridView1.DataSource = dt; } private void comboBoxLoad() { DataTable dt = new DataTable(); MySqlCommand cmd = Conex.CreateCommand(); cmd.CommandText = "SELECT cp FROM CONTACTOS;"; MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dt); comboBox1.Items.Add("ALL"); foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) { comboBox1.Items.Add(row[col]); } } } private void label2_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Object cp = comboBox1.SelectedItem; DataTable dtt = new DataTable(); MySqlCommand cmd = Conex.CreateCommand(); if (cp.ToString().Equals("ALL")) { cmd.CommandText = "SELECT * FROM CONTACTOS;"; } else { cmd.CommandText = "SELECT * FROM CONTACTOS WHERE cp = \"" + cp.ToString() + "\" ;"; } MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dtt); dataGridView1.DataSource = dtt; } private void button2_Click(object sender, EventArgs e) { idContactos++; MySqlCommand cmd = Conex.CreateCommand(); cmd.CommandText = "INSERT INTO contactos VALUES ('" + idContactos + "', '" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox6.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "');"; cmd.ExecuteNonQuery(); comboBox1.Items.Add(textBox4.Text); dataGridViewLoad(); } private void label7_Click(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFConversor { /// <summary> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { String centi = Centi.Text; String faren = Faren.Text; if(centi != "" || faren != "") { if(centi != "") { int fareng = (Int16.Parse(centi) * 9 / 5) + 32; Faren.Text = fareng.ToString(); Centi.Text = ""; } else { int centig = ((Int16.Parse(faren) - 32) * 5/9); Centi.Text = centig.ToString(); Faren.Text = ""; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp7 { class Program { static void Main(string[] args) { String a = ""; String b = ""; int x = 0; int y = 0; Console.WriteLine("Introduce la posicion x del alfil: "); a = Console.ReadLine(); x = Convert.ToInt32(a); Console.WriteLine("Introduce la posicion y del alfil: "); b = Console.ReadLine(); y = Convert.ToInt32(b); int abs1 = 0; int abs2 = 0; String cadena = ""; for (int i = 1; i < 9; i++) { for (int j = 1; j < 9; j++) { abs1 = Math.Abs(x - i); abs2 = Math.Abs(y - j); if ((x != i || y != j) && (abs1 != abs2)) { if (i % 2 == 0) { if (j % 2 == 0) { cadena = cadena + "B"; } else { cadena = cadena + "N"; } } else { if (j % 2 == 0) { cadena = cadena + "N"; } else { cadena = cadena + "B"; } } } else if ((abs1 == abs2)) { cadena = cadena + "*"; } } Console.WriteLine(cadena); cadena = ""; } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp4 { class Program { static void Main(string[] args) { String a = ""; String b = ""; a = Console.ReadLine(); b = Console.ReadLine(); if (Convert.ToInt32(a) % 2 == 0 && Convert.ToInt32(b) % 2 == 0) { Console.WriteLine("Ambos son pares"); } else if (Convert.ToInt32(a) % 2 != 0 && Convert.ToInt32(b) % 2 != 0) { Console.WriteLine("Ambos son impares"); } else { Console.WriteLine("Uno es par y otro impar"); } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class Personalizacion : Form { Comida seleccionada = new Comida(); int cantidad = 1; Random random = new Random(); Boolean aniadido = false; public Personalizacion(Comida comidaSeleccionada) { InitializeComponent(); pictureBox1.Image = comidaSeleccionada.getImage(); seleccionada.setName(comidaSeleccionada.getName()); seleccionada.setPrecio(comidaSeleccionada.getPrecio()); seleccionada.setImage(comidaSeleccionada.getImage()); textBox1.Text = cantidad.ToString(); } private void Personalizacion_Load(object sender, EventArgs e) { int randomNumber = random.Next(0, 100); if(randomNumber >= 50) { pictureBox4.Visible = true; } label1.Text = seleccionada.getName(); label5.Text = seleccionada.getPrecio() + "€"; } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (aniadido == false) { for(int i = 0; i < Int16.Parse(textBox1.Text); i++) { Form1.carrito.Add(seleccionada); } Carrito a = new Carrito(); a.Visible = true; this.Close(); } } private void checkBox2_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { if(seleccionada.getTomate() == false) { seleccionada.setTomate(true); } else { seleccionada.setTomate(false); } } private void checkBox3_CheckedChanged(object sender, EventArgs e) { if (seleccionada.getCebolla() == false) { seleccionada.setCebolla(true); } else { seleccionada.setCebolla(false); } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (seleccionada.getLechuga() == false) { seleccionada.setLechuga(true); } else { seleccionada.setLechuga(false); } } private void button2_Click(object sender, EventArgs e) { Form1.principal.Visible = true; this.Close(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { if(cantidad > 1) { cantidad--; textBox1.Text = cantidad.ToString(); } } private void pictureBox3_Click(object sender, EventArgs e) { cantidad++; textBox1.Text = cantidad.ToString(); } private void pictureBox5_Click(object sender, EventArgs e) { } private void label1_Click_1(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void label6_Click_1(object sender, EventArgs e) { if (aniadido == false) { for (int i = 0; i < Int16.Parse(textBox1.Text); i++) { Form1.carrito.Add(seleccionada); } Form1.principal.Visible = true; this.Close(); aniadido = true; } } private void button1_Click_1(object sender, EventArgs e) { Carrito a = new Carrito(); a.Visible = true; this.Close(); } private void label7_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class Complementos : UserControl { public Complementos() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Comida nuggets = new Comida(); nuggets.setImage(pictureBox1.Image); nuggets.setName("Nuggets Demoniacos"); nuggets.setPrecio(5); PersonalizacionOtros a = new PersonalizacionOtros(nuggets); a.Visible = true; Form1.principal.Visible = false; } private void button2_Click(object sender, EventArgs e) { Comida patatasf = new Comida(); patatasf.setImage(pictureBox2.Image); patatasf.setName("Patatas fritas"); patatasf.setPrecio(3); PersonalizacionOtros a = new PersonalizacionOtros(patatasf); a.Visible = true; Form1.principal.Visible = false; } private void button3_Click(object sender, EventArgs e) { Comida alitas = new Comida(); alitas.setImage(pictureBox3.Image); alitas.setName("Alitas"); alitas.setPrecio(5); PersonalizacionOtros a = new PersonalizacionOtros(alitas); a.Visible = true; Form1.principal.Visible = false; } private void button4_Click(object sender, EventArgs e) { Comida patatasd = new Comida(); patatasd.setImage(pictureBox3.Image); patatasd.setName("Patatas Deluxe"); patatasd.setPrecio(4); PersonalizacionOtros a = new PersonalizacionOtros(patatasd); a.Visible = true; Form1.principal.Visible = false; } private void Complementos_Load(object sender, EventArgs e) { } private void radioButton6_CheckedChanged(object sender, EventArgs e) { } private void radioButton5_CheckedChanged(object sender, EventArgs e) { } private void radioButton4_CheckedChanged(object sender, EventArgs e) { } private void radioButton3_CheckedChanged(object sender, EventArgs e) { } private void radioButton2_CheckedChanged(object sender, EventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { } private void radioButton10_CheckedChanged(object sender, EventArgs e) { } private void radioButton11_CheckedChanged(object sender, EventArgs e) { } private void radioButton12_CheckedChanged(object sender, EventArgs e) { } private void radioButton7_CheckedChanged(object sender, EventArgs e) { } private void radioButton8_CheckedChanged(object sender, EventArgs e) { } private void radioButton9_CheckedChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class PagoEnvio : Form { Random random = new Random(); public static PagoEnvio myPagoEnvio; public static String ticket; public PagoEnvio() { InitializeComponent(); myPagoEnvio = this; mensajeError1.Visible = false; mensajeError1.SendToBack(); mensajeConfirmar1.Visible = false; mensajeConfirmar1.SendToBack(); } private void button1_Click(object sender, EventArgs e) { button1.BackColor = (Color.Gold); button2.BackColor = Color.LimeGreen; label1.Text = "Dirección"; label2.Visible = true; textBox2.Visible = true; label1.Visible = true; } private void button2_Click(object sender, EventArgs e) { label2.Visible = false; textBox2.Visible = false; button2.BackColor = (Color.Gold); button1.BackColor = Color.LimeGreen; label1.Text = "Nº Mesa"; label1.Visible = true; } private void button3_Click(object sender, EventArgs e) { button3.BackColor = (Color.Gold); button4.BackColor = Color.LimeGreen; textBox3.Visible = false; textBox4.Visible = false; textBox5.Visible = false; label3.Visible = false; label4.Visible = false; label5.Visible = false; } private void button4_Click(object sender, EventArgs e) { button4.BackColor = (Color.Gold); button3.BackColor = Color.LimeGreen; textBox3.Visible = true; textBox4.Visible = true; textBox5.Visible = true; label3.Visible = true; label4.Visible = true; label5.Visible = true; } private void PagoEnvio_Load(object sender, EventArgs e) { int randomNumber = random.Next(20, 60); button2.BackColor = (Color.Gold); button3.BackColor = (Color.Gold); label1.Text = "Nº Mesa"; label1.Visible = true; label2.Visible = false; textBox2.Visible = false; label6.Text = label6.Text + " " + randomNumber + " min"; } private void button5_Click(object sender, EventArgs e) { ticket = " PEDIDO " + "\n\n"; Double totalPrecio = 0; foreach (Comida a in Form1.carrito) { String cebolla = ""; String tomate = ""; String lechuga = ""; if (a.getCebolla() == true) { cebolla = "\n\t + Cebolla"; } if (a.getLechuga() == true) { lechuga = "\n\t + Lechuga"; } if (a.getTomate() == true) { tomate = "\n\t + Tomate"; } if (a.getGrande() == true) { cebolla = "\n\t + Grande"; } if (a.getPequenio() == true) { lechuga = "\n\t + Pequeño"; } if (a.getMediano() == true) { tomate = "\n\t + Mediano"; } ticket = ticket + a.getName() + lechuga + tomate + cebolla + "\n"; totalPrecio += a.getPrecio(); } ticket += "\n\t\t PRECIO A PAGAR --> " + Carrito.totalPrecio + "€"; ticket += "\n " + label6.Text + " minutos"; if(button3.BackColor == (Color.Gold)) { ticket += "\n\n Debera pasar por caja para pagarlo."; } else if(button3.BackColor == (Color.Gold)) { ticket += "\n\n La transaccion ha sido correcta."; } Boolean todoCorrecto = true; if (button2.BackColor == (Color.Gold)) { if (textBox1.Text == "") { todoCorrecto = false; } } else if (button2.BackColor == (Color.Gold)) { if (textBox1.Text == "" || textBox2.Text == "") { todoCorrecto = false; } } if (button4.BackColor == (Color.Gold)) { if (textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "") { todoCorrecto = false; } } if (todoCorrecto) { mensajeConfirmar1.Visible = true; mensajeConfirmar1.BringToFront(); } else { mensajeError1.Visible = true; mensajeError1.BringToFront(); } } private void mensajeConfirmar1_Load(object sender, EventArgs e) { } private void button6_Click(object sender, EventArgs e) { Carrito a = new Carrito(); a.Visible = true; this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class MensajeConfirmar : UserControl { public MensajeConfirmar() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { PagoEnvio.myPagoEnvio.Visible = false; Ticket b = new Ticket(PagoEnvio.ticket); b.Visible = true; this.Visible = false; Form1.principal.Visible = true; Form1.carrito.Clear(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ConexionMYSQLOrigenesDeDatos { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void cocheBindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.cocheBindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.cocheDataSet); } private void Form1_Load(object sender, EventArgs e) { // TODO: esta línea de código carga datos en la tabla 'cocheDataSet.coche' Puede moverla o quitarla según sea necesario. this.cocheTableAdapter.Fill(this.cocheDataSet.coche); } private void button1_Click(object sender, EventArgs e) { Form1 estoEsMiForm = new Form1(); Object estoEsMiReport = new CachedCrystalReport2(); System.Data.Odbc.OdbcDataAdapter adaptador = new System.Data.Odbc.OdbcDataAdapter("SELECT * FROM coches", ); DataSet dt = new DataSet(); adaptador.Fill(dt); estoEsMiForm.Show(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class PersonalizacionOtros : Form { Comida seleccionada = new Comida(); int cantidad = 1; Random random = new Random(); public PersonalizacionOtros(Comida comidaSeleccionada) { InitializeComponent(); pictureBox1.Image = comidaSeleccionada.getImage(); seleccionada.setName(comidaSeleccionada.getName()); seleccionada.setPrecio(comidaSeleccionada.getPrecio()); seleccionada.setImage(comidaSeleccionada.getImage()); textBox1.Text = cantidad.ToString(); } private void PersonalizacionOtros_Load(object sender, EventArgs e) { label6.Text = seleccionada.getName(); label5.Text = seleccionada.getPrecio() + "€"; } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Carrito a = new Carrito(); a.Visible = true; this.Close(); } private void checkBox2_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { if (seleccionada.getGrande() == false) { seleccionada.setGrande(true); } else { seleccionada.setGrande(false); } } private void checkBox3_CheckedChanged(object sender, EventArgs e) { if (seleccionada.getMediano() == false) { seleccionada.setMediano(true); } else { seleccionada.setMediano(false); } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Form1.principal.Visible = true; this.Close(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { if (cantidad > 1) { cantidad--; textBox1.Text = cantidad.ToString(); } } private void pictureBox3_Click(object sender, EventArgs e) { cantidad++; textBox1.Text = cantidad.ToString(); } private void pictureBox5_Click(object sender, EventArgs e) { } private void label1_Click_1(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void label2_Click_1(object sender, EventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { seleccionada.setPequenio(true); seleccionada.setGrande(false); seleccionada.setMediano(false); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { seleccionada.setPequenio(false); seleccionada.setGrande(false); seleccionada.setMediano(true); } private void radioButton3_CheckedChanged(object sender, EventArgs e) { seleccionada.setPequenio(false); seleccionada.setGrande(true); seleccionada.setMediano(false); } private void label1_Click_2(object sender, EventArgs e) { for (int i = 0; i < Int16.Parse(textBox1.Text); i++) { Form1.carrito.Add(seleccionada); } Form1.principal.Visible = true; this.Close(); } private void label7_Click(object sender, EventArgs e) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { int mes = 0; int anio = 0; Console.Write("Dime el numero de un mes --> "); String a = Console.ReadLine(); mes = Convert.ToInt32(a); Console.Write("\nDime un año --> "); String b = Console.ReadLine(); anio = Convert.ToInt32(b); switch (mes) { case 1: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 2: if ((anio % 400 == 0) || (anio % 4 == 0 && anio % 100 != 0)) { Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 29 dias!"); } else { Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 28 dias!"); } break; case 3: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 4: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 30 dias!"); break; case 5: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 6: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 30 dias!"); break; case 7: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 8: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 9: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 30 dias!"); break; case 10: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; case 11: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 30 dias!"); break; case 12: Console.WriteLine("El mes " + mes + " del año " + anio + " tiene 31 dias!"); break; } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FormCuentaBancaria { class CuentaBancaria { protected int nNumCuenta; protected String strNombre; protected Double dblSaldo; protected float fltTipoInteres; public CuentaBancaria() { nNumCuenta = 0; strNombre = ""; dblSaldo = 0.0; fltTipoInteres = 0; } public void setNumCuenta(int num) { this.nNumCuenta = num; } public void setNombreCuenta(String nombre) { this.strNombre = nombre; } public void setSaldoCuenta(Double saldo) { this.dblSaldo = saldo; } public void setTipoInteres(float interes) { this.fltTipoInteres = interes; } public int getNumCuenta() { return this.nNumCuenta; } public String getNombreCuenta() { return this.strNombre; } public Double getSaldoCuenta() { return this.dblSaldo; } public float getTipoInteres() { return this.fltTipoInteres; } public virtual void estadoCuenta() { Console.WriteLine("\nNumero de cuenta --> " + this.getNumCuenta() + "\nNombre de cuenta --> " + this.getNombreCuenta() + "\nSaldo cuenta --> " + this.getSaldoCuenta() + "\nTipo Interes --> " + this.getTipoInteres()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FormCuentaBancaria { class CuentaAhorro : CuentaBancaria { private Double cuotaMantenimiento; public CuentaAhorro() { cuotaMantenimiento = 0.0; } public void setCuotaMantenimiento(Double cuota) { this.cuotaMantenimiento = cuota; } public Double getCuotaMantenimiento() { return this.cuotaMantenimiento; } public override void estadoCuenta() { base.estadoCuenta(); Console.WriteLine("Cuota mantenimiento --> " + this.cuotaMantenimiento); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppShawarmitaF { public partial class AdminForm : Form { public AdminForm() { InitializeComponent(); } private void AdminForm_Load(object sender, EventArgs e) { double pro1 = (1 - Form1.promocion1) * 100; double pro2 = (1 - Form1.promocion2) * 100; textBox1.Text = pro1.ToString(); textBox2.Text = pro2.ToString(); } private void button1_Click(object sender, EventArgs e) { if(textBox1.Text != "" && textBox2.Text != "" && Double.Parse(textBox1.Text) < 50 && Double.Parse(textBox2.Text) < 50) { Form1.promocion1 = 1.0 - (Double.Parse(textBox1.Text)/100); Form1.promocion2 = 1.0 - (Double.Parse(textBox2.Text)/100); this.Visible = false; Form1.principal.Visible = true; } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp11 { class Program { static void Main(string[] args) { ArrayList arrayPablo = new ArrayList(); Random r = new Random(); int numero = 0; for(int i = 0; i < 50; i++) { numero = r.Next(0, 50); arrayPablo.Add(numero); } foreach (int i in arrayPablo) { Console.WriteLine(i); } arrayPablo.Sort(); foreach(int i in arrayPablo) { Console.WriteLine(i); } Console.ReadKey(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp7 { public partial class AñadirPalabra : Form { public AñadirPalabra() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { String palabra = textBox1.Text; ArrayList personas = Form2.personas; ArrayList palabras = Form2.palabras; Form2 ventanaInicio = new Form2(); Form2.palabras = palabras; Form2.personas = personas; Form2.palabras.Add(palabra); this.Visible = false; ventanaInicio.Visible = true; } } } <file_sep>using System; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace AppShawarmitaF { public partial class Carrito : Form { public static Double totalPrecio; ArrayList seMuestra; Boolean codigoUsado1 = false; private String codigoDescuento = "Demonio"; private String codigoDescuento2 = "losespetoslomejor34"; public Carrito() { InitializeComponent(); totalPrecio = 0.0; seMuestra = new ArrayList(); } private void Carrito_Load(object sender, EventArgs e) { listView1.View = View.Details; listView1.Columns.Add("Carrito", 400); listView1.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.HeaderSize); populate(); if(totalPrecio > 40 && totalPrecio < 50) { totalPrecio = totalPrecio * Form1.promocion1; label5.Text = "Promocion de descuento del 20%"; label5.Visible = true; } else if (totalPrecio >= 50) { totalPrecio = totalPrecio * Form1.promocion2; label5.Text = "Promocion de descuento del 30%"; label5.Visible = true; } label2.Text = totalPrecio + "€"; } private void populate() { ImageList imgs = new ImageList(); imgs.ImageSize = new Size(100, 100); foreach (Comida a in Form1.carrito) { imgs.Images.Add(a.getImage()); } listView1.SmallImageList = imgs; int contador = 0; foreach (Comida a in Form1.carrito) { String cebolla = ""; String tomate = ""; String lechuga = ""; Console.WriteLine("yeyeo en mi iopgene " + a.getCebolla()); if (a.getCebolla() == true) { cebolla = "\n\t + Cebolla"; } if (a.getLechuga() == true) { lechuga = "\n\t + Lechuga"; } if (a.getTomate() == true) { tomate = "\n\t + Tomate"; } if (a.getGrande() == true) { cebolla = "\n\t + Grande"; } if (a.getPequenio() == true) { lechuga = "\n\t + Pequeño"; } if (a.getMediano() == true) { tomate = "\n\t + Mediano"; } listView1.Items.Add(a.getName() + lechuga + tomate + cebolla, contador); totalPrecio += a.getPrecio(); contador++; } } private void listView1_ItemCheck(object sender, ItemCheckEventArgs e) { Form1.carrito.Add(listView1.GetItemAt(0,0)); } private void button1_Click(object sender, EventArgs e) { Console.WriteLine("Numero total de cosas en el array --> " + Form1.carrito.Count); if (Form1.carrito.Count != 0) { PagoEnvio a = new PagoEnvio(); a.Visible = true; this.Close(); } else { label9.Visible = true; } } private void button2_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { try { int indiceABorrar = listView1.SelectedIndices[0]; listView1.Items.RemoveAt(indiceABorrar); Form1.carrito.RemoveAt(indiceABorrar); Carrito a = new Carrito(); a.Visible = true; this.Close(); } catch (ArgumentOutOfRangeException ex) { label3.Text = "Debes seleccionar un producto para eliminarlo."; label3.Visible = true; } } private void button3_Click(object sender, EventArgs e) { if (textBox1.Text.Equals(codigoDescuento) && totalPrecio > 15 && codigoUsado1 == false) { totalPrecio = totalPrecio - 5; label6.Text = "Codigo descuento aceptado!"; label6.Visible = true; label2.Text = totalPrecio.ToString() + "€"; codigoUsado1 = true; } else if (textBox1.Text.Equals(codigoDescuento2)) { totalPrecio = totalPrecio - 100; label6.Text = "Codigo descuento aceptado!"; label6.Visible = true; label2.Text = totalPrecio.ToString() + "€"; } } private void button2_Click_1(object sender, EventArgs e) { Form1.principal.Visible = true; this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormCuentaBancaria { public partial class Form2 : Form { public Form2() { InitializeComponent(); CuentaBancaria cuenta1 = new CuentaBancaria(); cuenta1.setNombreCuenta("Cuenta Normal"); cuenta1.setNumCuenta(123456789); cuenta1.setSaldoCuenta(10000); cuenta1.setTipoInteres(4); textBox1.Text = cuenta1.getNombreCuenta(); textBox2.Text = cuenta1.getNumCuenta().ToString(); textBox3.Text = cuenta1.getSaldoCuenta().ToString(); textBox4.Text = cuenta1.getTipoInteres().ToString(); } private void button1_Click(object sender, EventArgs e) { Form1 ventanPrincipal = new Form1(); this.Visible = false; ventanPrincipal.Visible = true; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsAppUltimo { public partial class Form1 : Form { private double fantaNaranja = 1.95; private double cocacola = 2.50; private double fantaLimon = 1.70; private double nestea = 2.90; private double agua = 3.00; private double dineroInsertado = 0.0; public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { String selected = textBox6.Text; if((Int32.Parse(selected) > 0 && Int32.Parse(selected) <= 5) && selected != "") { switch (selected) { case "1": label2.Text = "Precio = " + cocacola.ToString() + "€"; break; case "2": label2.Text = "Precio = " + nestea.ToString() + "€"; break; case "3": label2.Text = "Precio = " + fantaNaranja.ToString() + "€"; break; case "4": label2.Text = "Precio = " + fantaLimon.ToString() + "€"; break; case "5": label2.Text = "Precio = " + agua.ToString() + "€"; break; } } else { label2.Text = "Numero mal introducido!"; } } private void button2_Click(object sender, EventArgs e) { dineroInsertado += 0.50; textBox7.Text = dineroInsertado.ToString() + "€"; } private void button3_Click(object sender, EventArgs e) { dineroInsertado += 0.20; textBox7.Text = dineroInsertado.ToString() + "€"; } private void button4_Click(object sender, EventArgs e) { dineroInsertado += 1.0; textBox7.Text = dineroInsertado.ToString() + "€"; } private void button5_Click(object sender, EventArgs e) { String selected = textBox6.Text; Console.WriteLine("eyeye"); double devolucion = 0.0; if ((Int32.Parse(selected) > 0 && Int32.Parse(selected) <= 5) && selected != "") { switch (selected) { case "1": devolucion = dineroInsertado - cocacola; break; case "2": devolucion = dineroInsertado - nestea; break; case "3": devolucion = dineroInsertado - fantaNaranja; break; case "4": devolucion = dineroInsertado - fantaLimon; break; case "5": devolucion = dineroInsertado - agua; break; } label4.Text = "Devolucion = " + devolucion.ToString() + " Gracias por su compra!"; } else { label2.Text = "Numero mal introducido!"; } dineroInsertado = 0.0; } private void textBox7_TextChanged(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static void Main(string[] args) { String a = ""; String b = ""; a = Console.ReadLine(); b = Console.ReadLine(); if(Convert.ToInt32(a) > Convert.ToInt32(b)) { Console.WriteLine("El mayor es " + a); } else if (Convert.ToInt32(a) < Convert.ToInt32(b)) { Console.WriteLine("El mayor es " + b); } else { Console.WriteLine("Son iguales"); } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp7 { public partial class Login : Form { public Login() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { String login = textBox1.Text; String passwd = textBox2.Text; foreach(Persona a in Form2.personas) { if (login.Equals(a.getLogin()) && passwd.Equals(a.getPasswd())) { AñadirPalabra ventanaAniadir = new AñadirPalabra(); ventanaAniadir.Visible = true; this.Visible = false; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Random r = new Random(); int aleatorio = r.Next(0, 20); int contador = 0; //int aleatorio = 5; String numero = ""; Console.WriteLine(""); do { do { numero = ""; Console.WriteLine("Introduce un numero entre 0 - 20: "); numero = Console.ReadLine(); Console.WriteLine(numero); } while (Convert.ToInt32(numero) > 20 || Convert.ToInt32(numero) < 0); Console.Clear(); if (Convert.ToInt32(numero) != aleatorio) { if (Convert.ToInt32(numero) > aleatorio) { Console.WriteLine("El numero que has introducido es mayor!!! "); } else { Console.WriteLine("El numero que has introducido es menor!!! "); } } else if (Convert.ToInt32(numero) == aleatorio) { Console.WriteLine("Premio!! Has acertado!!"); } contador++; if(contador == 5) { Console.WriteLine("Se han acabado las oportunidades!!"); } else if (contador < 5 && Convert.ToInt32(numero) != aleatorio) { int intentos = 5 - contador; Console.WriteLine("Tienes " + intentos + " intentos!!"); } } while (contador < 5 && Convert.ToInt32(numero) != aleatorio); Console.ReadLine(); } } }
3a43b3de9b4c02d0c5edcdbab97c4ccec80ea07d
[ "C#" ]
39
C#
AlejandroNieto-DAM/VisualStudio
3b8d7f5fa0c5f45f490f4fbaa4a1da3a28d73930
9d1f39fb1b785209f08086e68af88c92f4b9c2d8
refs/heads/main
<file_sep># RCS_App App for RCS
24f090c4cf187ee3b3cb307f0a58da918e94ec29
[ "Markdown" ]
1
Markdown
pvnmahathi/RCS_App
df654ded1b8122a3e0b5ad342365ef64476fc694
d5d3180211c8bcc457898d508b451492663b1194
refs/heads/master
<file_sep>const express = require("express"); const mongoose = require("mongoose"); const cors = require("cors"); const app = express(); const routes = require("./routes"); const port = process.env.PORT || 8000; const username = "omnistack"; const password = "<PASSWORD>"; const db = "omnistack10"; var link = `mongodb+srv://${username}:${password}@<EMAIL>.<EMAIL>/${db}?retryWrites=true&w=majority` mongoose.connect(link,{ useNewUrlParser: true, useUnifiedTopology: true }) .then(()=>{ console.log("Running on mongodb") }) .catch((error)=>{ console.log(`Error on mongodb: ${error}`) }) app.use(cors()) app.use(express.json()) app.use("/",routes); app.listen(port,()=>{ console.log(`Running on port ${port}...`) })
0ff20907db585fcd9b1d649d42b7b787d4d3e451
[ "JavaScript" ]
1
JavaScript
yesy12/dev-radar-backend
da4906fbb1dd01d1dda6f20047613a464ffe6c10
ba74a3724c58db217dd657589d8fadcd1284409e
refs/heads/main
<repo_name>BrianMRogers/Arduino-Door-Opener<file_sep>/README.md # Arduino-Door-Opener<file_sep>/Complete_Morse_Unlocker_Button.ino int analogPinA0 = A0; int micInput; //Demo button temporarily substituting for the microphone input. This code establishes what pin they're connected to on the arduino. int mainButton = 4; //Demo Light for code ensurance. This code establishes the pin number thats connected to the LED, just like the 'mainButton' int int whiteTestLed = 11; //Servo Pin int servoPin = 9; #include <Servo.h> Servo name_servo; //Int values for duration of on/off times int holdingDuration; int nonHoldingDuration; //keyWord is the string that collects all short (S) and long (L) inputs String keyWord; //translation is the string that recieves and hold the interpretations of the morse. This value should match the password String translation; //passWord is the collection of values that I want to be entered in morse String passWord = "<PASSWORD>"; void setup() { //Start Serial and establish button connection and light output Serial.begin(9600); pinMode(whiteTestLed, OUTPUT); name_servo.attach(9); name_servo.write(0); } void loop() { //If the device reads a low power, then the button is pressed which then leads into the following commands micInput = analogRead(analogPinA0); if(micInput > 600) { digitalWrite(whiteTestLed, HIGH); Serial.println("On"); //Here lies holdingDuration for(int i = 0; i < 8; i++) { micInput += analogRead(analogPinA0); Serial.println(micInput); delay(150); } //if statement decides whether to add a long press or short press to the sequence based on how long the 'holdingDuration' value was held for if(micInput > 2300) { //Add long press string to the code entrance string/sequence keyWord += "L"; } else if(micInput < 2300) { //Add short press string to the code entrance string/sequence keyWord += "S"; } micInput = 0; //holdingDuration = 0; //Create off time here for making spaces in the final string //This allows me to monitor the serial log Serial.println(keyWord); delay(200); while(analogRead(analogPinA0) < 600) { //Serial.println(nonHoldingDuration); nonHoldingDuration ++; delay(100); //This code decides whether the button hasn't been held for long enough to create a space in the final string if(nonHoldingDuration > 40) { //Add space string to the code entrance string/sequence keyWord += " "; translate(keyWord); nonHoldingDuration = 0; break; } else if(analogRead(analogPinA0) > 600) { nonHoldingDuration = 0; break; } } } //If the device reads a HIGH power, then the button is not pressed. THIS SECTION IS SET if(analogRead(analogPinA0 < 600)) { digitalWrite(whiteTestLed, LOW); Serial.println(nonHoldingDuration); delay(100); nonHoldingDuration ++; if(nonHoldingDuration > 19) { if(translation.equals(passWord)) { Serial.println("CORRECT PASSWORD"); //Activate servo here **The numbers should be changed so it only moves the arm enough to press the button and release from beneath the phone.** name_servo.write(180); Serial.println("OPEN"); delay(5000); name_servo.write(0); Serial.println("CLOSED"); } keyWord = ""; translation = ""; nonHoldingDuration = 0; Serial.println("ENTRY CLEARED"); } } } // MORSE CHARACTER LIST void translate(String methodKey) { keyWord = methodKey; //LETTER A if(methodKey.equals("SL ")) { translation += "A"; Serial.println(translation); } //LETTER B if(methodKey.equals("LSSS ")) { translation += "B"; Serial.println(translation); } //LETTER C if(methodKey.equals("LSLS ")) { translation += "C"; Serial.println(translation); } //LETTER D if(methodKey.equals("LSS ")) { translation += "D"; Serial.println(translation); } //LETTER E if(methodKey.equals("S ")) { translation += "E"; Serial.println(translation); } //LETTER F if(methodKey.equals("SSLS ")) { translation += "F"; Serial.println(translation); } //LETTER G if(methodKey.equals("LLS ")) { translation += "G"; Serial.println(translation); } //LETTER H if(methodKey.equals("SSSS ")) { translation += "H"; Serial.println(translation); } //LETTER I if(methodKey.equals("SS ")) { translation += "I"; Serial.println(translation); } //LETTER J if(methodKey.equals("SLLL ")) { translation += "F"; Serial.println(translation); } //LETTER K if(methodKey.equals("LSL ")) { translation += "K"; Serial.println(translation); } //LETTER L if(methodKey.equals("SLSS ")) { translation += "L"; Serial.println(translation); } //LETTER M if(methodKey.equals("LS ")) { translation += "M"; Serial.println(translation); } //LETTER N if(methodKey.equals("LL ")) { translation += "N"; Serial.println(translation); } //LETTER O if(methodKey.equals("LLL ")) { translation += "O"; Serial.println(translation); } //LETTER P if(methodKey.equals("SLLS ")) { translation += "P"; Serial.println(translation); } //LETTER Q if(methodKey.equals("LLSL ")) { translation += "Q"; Serial.println(translation); } //LETTER R if(methodKey.equals("SLS ")) { translation += "R"; Serial.println(translation); } //LETTER S if(methodKey.equals("SSS ")) { translation += "S"; Serial.println(translation); } //LETTER T if(methodKey.equals("L ")) { translation += "T"; Serial.println(translation); } //LETTER U if(methodKey.equals("SSL ")) { translation += "U"; Serial.println(translation); } //LETTER V if(methodKey.equals("SSSL ")) { translation += "V"; Serial.println(translation); } //LETTER W if(methodKey.equals("SLL ")) { translation += "W"; Serial.println(translation); } //LETTER X if(methodKey.equals("LSSL ")) { translation += "X"; Serial.println(translation); } //LETTER Y if(methodKey.equals("LSLL ")) { translation += "Y"; Serial.println(translation); } //LETTER Z if(methodKey.equals("LLSS ")) { translation += "Z"; Serial.println(translation); } keyWord = ""; //translation = ""; }
4008afbb3b8c6b48b8ba33d06c005cde6ac14e50
[ "Markdown", "C++" ]
2
Markdown
BrianMRogers/Arduino-Door-Opener
d03724b186a46a94893e094f2f75cec8d832fd5c
412d56031094b04faeb81b11d058093fade43b19
refs/heads/master
<repo_name>Evercise/evercise<file_sep>/app/composers/PhoneComposer.php <?php namespace composers; use JavaScript; use Config; class PhoneComposer { public function compose($view) { $country_codes = ['' => '-- Select country code --']; foreach (Config::get('countrycodes') as $c) { $country_codes['+' . $c['code']] = $c['name']; } natsort($country_codes); $country_codes = ['+1' => $country_codes['+1']] + $country_codes; $country_codes = ['+44' => $country_codes['+44']] + $country_codes; Javascript::put(['updateCountryCode' => 1]); $view->with('country_codes', $country_codes); } }<file_sep>/app/database/seeds/DatabaseSeeder.php <?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('SentrySeeder'); $this->command->info('Sentry tables seeded!'); $this->call('CategoriesTableSeeder'); $this->command->info('Categories seeded!'); $this->call('SpecialitiesTableSeeder'); $this->command->info('Specialities seeded!'); $this->call('MarketingpreferencesTableSeeder'); $this->command->info('Marketing prefs seeded!'); $this->call('FacilitiesTableSeeder'); $this->command->info('Facilities seeded!'); $this->call('HistorytypesTableSeeder'); $this->command->info('history type seeded!'); $this->call('AreacodesTableSeeder'); $this->command->info('areacode type seeded!'); $this->call('MilestonesTableSeeder'); $this->command->info('milestones seeded!'); $this->call('EvercoinsTableSeeder'); $this->command->info('evercoins seeded!'); /* $this->call('UsersTableSeeder'); $this->command->info('Users seeded!'); $this->call('TrainersTableSeeder'); $this->command->info('Trainers seeded!'); $this->call('EvercisegroupsTableSeeder'); $this->command->info('Evercisegroups seeded!'); $this->call('SessionsTableSeeder'); $this->command->info('Sessions seeded!'); $this->call('SessionMembersTableSeeder'); $this->command->info('SessionMembers seeded!');*/ $this->call('SubcategoriesTableSeeder'); $this->command->info('Subcategories seeded!'); } }<file_sep>/app/models/Venue.php <?php class Venue extends \Eloquent { protected $fillable = array('id', 'user_id', 'name', 'address', 'town', 'postcode', 'lat', 'lng', 'image'); /** * The database table used by the model. * * @var string */ protected $table = 'venues'; public function evercisegroup() { return $this->hasMany('Evercisegroup'); } public function images() { return $this->hasMany('VenueImages'); } public function Facilities() { return $this->belongsToMany('Facility', 'venue_facilities', 'venue_id', 'facility_id')->withTimestamps(); } public function evercisesessions() { return $this->hasManyThrough('Evercisesession', 'Evercisegroup'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } /** * @return VenuesController|\Illuminate\View\View */ public static function usersVenues($id) { // list all venues belonging to this user $venues = static::where('user_id', $id)->lists('name', 'id'); return $venues; } private static function validateInputs($inputs) { Validator::extend('has_not', function ($attr, $value, $params) { return ValidationHelper::hasNotRegex($attr, $value, $params); }); Validator::extend('has', function ($attr, $value, $params) { return ValidationHelper::hasRegex($attr, $value, $params); }); // todo validation extends needs its own class $validator = Validator::make( $inputs, [ 'name' => 'required|max:50', 'address' => 'required|min:2', 'town' => 'required|min:2', 'postcode' => 'required|has_not:special|has:letter,num|min:4', ], ['postcode.has_not' => 'Post code must not contain any special characters', 'postcode.has' => 'Post code must contain letters and numbers' ] ); return $validator; } /** * @return array */ public static function validateAndStore($userId, $inputs, $geo, $user) { $validator = static::validateInputs($inputs); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; } else { $venue_name = $inputs['name']; $address = $inputs['address']; $town = $inputs['town']; $postcode = $inputs['postcode']; $facilities = isset($inputs['facilities_array']) ? $inputs['facilities_array'] : []; if (isset($geo['error'])) { $result = [ 'validation_failed' => 1, 'errors' => ['address' => 'Address not found', 'town' => '', 'postcode' => '', ] ]; } else { $venue = static::create([ 'user_id' => $userId, 'name' => $venue_name, 'address' => $address, 'town' => $town, 'postcode' => $postcode, 'lat' => $geo['lat'], 'lng' => $geo['lng'], ]); $venue->facilities()->sync($facilities); // Bang the id's of the facilities in venue_facility $result = [ 'venue_id' => $venue->id, 'venue_name' => $venue->name ]; event('venue.create', [$venue, $user]); } } return $result; } public function validateAndUpdate($inputs, $user) { $validator = static::validateInputs($inputs); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; } else { $venue_name = $inputs['venue_name']; $address = $inputs['street']; $town = $inputs['city']; $postcode = $inputs['postcode']; $facilities = isset($inputs['facilities_array']) ? $inputs['facilities_array'] : []; $this->update([ 'name' => $venue_name, 'address' => $address, 'town' => $town, 'postcode' => $postcode, ]); $this->facilities()->sync($facilities); // Bang the id's of the facilities in venue_facility $result = [ 'venue_id' => $this->id ]; event('venue.update', [$this, $user]); } return $result; } public function getAmenities() { $amenities = []; foreach($this->facilities as $facility) { if ($facility->category == 'amenity') { array_push($amenities, $facility); } } return $amenities; } public function getFacilities() { $facilities = []; foreach($this->facilities as $facility) { if ($facility->category == 'facility') { array_push($facilities, $facility); } } return $facilities; } public function fullAddress() { return ucwords($this->address) . ', ' . ucwords($this->town) . ', ' . strtoupper($this->postcode); } }<file_sep>/app/controllers/VenuesController.php <?php class VenuesController extends \BaseController { /** * @return \Illuminate\View\View|VenuesController */ public function index() { return Venue::usersVenues($this->user->id); } /** * @param $id * @return \Illuminate\View\View|VenuesController */ public function edit($id) { $venue = Venue::find($id); $facilities = []; foreach ($venue->facilities as $facility) { $facilities[] = $facility->id; } return View::make('venues.edit_form')->with('venue', $venue)->with('selectedFacilities', $facilities); } }<file_sep>/app/config/packages/philo/twitter/config.php <?php return [ 'CONSUMER_KEY' => getenv('TWITTER_KEY'), 'CONSUMER_SECRET' => getenv('TWITTER_SECRET'), ]; <file_sep>/app/views/admin/yukonhtml/php/pages/pages-help_faq.php <div class="row"> <div class="col-md-3"> <h1 class="page_heading"> Help/Faq <span>Get Help. Find Answers</span> </h1> </div> <div class="col-md-9"> <div class="input-group"> <input type="text" class="form-control" placeholder="What would you like to know?"> <span class="input-group-btn"> <button class="btn btn-primary" type="button"><span class="icon_search"></span></button> </span> </div> </div> </div> <hr/> <div class="row"> <div class="col-md-3"> <div class="heading_b"><span class="heading_text">Categories</span></div> <div class="list-group"> <a href="javascript:void(0)" class="active list-group-item">All</a> <a href="javascript:void(0)" class="list-group-item">Customer Service</a> <a href="javascript:void(0)" class="list-group-item">Configuration & Data Management</a> <a href="javascript:void(0)" class="list-group-item">Mobile</a> <a href="javascript:void(0)" class="list-group-item">Reports & Dashboards</a> <a href="javascript:void(0)" class="list-group-item">Sales & Marketing</a> </div> </div> <div class="col-md-9 col-sep-md"> <div class="panel-group"> <?php for($i=1;$i<=20;$i++) { ?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" href="#helpFaq_sect_<?php echo $i;?>"> <?php echo $i.'. '.$faker->sentence(4); ?> </a> </h4> </div> <div id="helpFaq_sect_<?php echo $i;?>" class="panel-collapse collapse"> <div class="panel-body"> <?php echo $faker->sentence(40); ?> </div> </div> </div> <?php }; ?> </div> </div> </div> <file_sep>/app/models/Link.php <?php /** * Class Links */ class Link extends \Eloquent { protected $fillable = array('permalink', 'parent_id', 'type'); protected $table = 'evercise_links'; protected $primaryKey = 'link_id'; public function getClass() { return $this->belongsTo('Evercisegroup', 'parent_id', 'id'); } public function getArea() { return $this->belongsTo('Place', 'parent_id', 'id'); } public static function checkLink($url = false, $area_id = false) { if($area_id == '') $area_id = false; if($area_id) { $place = Place::find($area_id); $check = $place->link; } elseif($url) { $check = Link::where('permalink', $url)->first(); } else { return false; } if (!empty($check->permalink)) { return $check; } return false; } public static function getUniqueUrl($url) { do { $check = Link::where('permalink', $url)->count() > 0; if ($check) { if (strpos($url, '_') === false) { $url .= '_0'; } $url = ++ $url; } } while ($check); return $url; } }<file_sep>/app/controllers/PaymentController.php <?php use Omnipay\Omnipay; class PaymentController extends BaseController { /** * Create payment using credit card * url:stripe * * After user enters payment details, Stripe directs back to '/stripe' (specified in the stripe JS button) * This function will specify the payment amount, and receive the token from Stripe. */ public function processStripePaymentSessions() { $coupon = Session::get('coupon', FALSE); $cart = EverciseCart::getCart($coupon); $token = Input::get('stripeToken'); /* Convert amount to pennies to be sent to Stripe */ $amountInPennies = SessionPayment::poundsToPennies($cart['total']['final_cost']); if ($cart['total']['final_cost'] > 0) { try { $customer = Stripe_Customer::create([ 'email' => $this->user->email, 'card' => $token ]); $charge = Stripe_Charge::create([ 'customer' => $customer->id, 'amount' => $amountInPennies, 'currency' => 'gbp' ]); } catch (Stripe_CardError $e) { return Redirect::route('payment.error'); } } else { $charge = ['id' => Str::random()]; } $wallet = $this->user->getWallet(); if ($cart['total']['from_wallet'] > 0) { $wallet->withdraw($cart['total']['from_wallet'], 'Part payment for classes', 'part_payment'); } $coupon = Coupons::processCoupon($coupon, $this->user); $transactionId = $charge['id']; $transaction = $this->paid($token, $transactionId, 'stripe', $cart, $coupon); $res = [ 'cart' => $cart, 'payment_type' => 'stripe', 'coupon' => $coupon, 'transaction' => $transaction->id, 'track_cart' => TRUE, 'user' => $this->user, 'balance' => ($wallet ? $wallet->balance : 0), ]; return Redirect::route('checkout.confirmation')->with('res', $res); //return View::make('v3.cart.confirmation', $res); } /** * Create payment using paypal * url:paypal * */ public function requestPaypalPaymentSessions() { $coupon = Session::get('coupon', FALSE); $cart = EverciseCart::getCart($coupon); if ($cart['total']['final_cost'] > 0) { try { $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('<PASSWORD>')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); $products = $this->getProductsPaypal($cart); $response = $gateway->purchase( [ 'cancelUrl' => URL::route('payment.cancelled'), 'returnUrl' => URL::route('payment.process.paypal'), 'amount' => round($cart['total']['final_cost'], 2), 'currency' => 'GBP' ] )->send(); //FOR FUCKS SAKE!!! ->setItems($products) if ($response->isRedirect()) { // redirect to offsite payment gateway $response->redirect(); } else { // payment failed: display message to customer echo $response->getMessage(); } } catch (Exception $e) { return Redirect::route('payment.error'); } } else { return Redirect::route('cart.checkout'); } } public function processPaypalPaymentSessions() { $coupon = Session::get('coupon', FALSE); $cart = EverciseCart::getCart($coupon); $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('<PASSWORD>')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); try { $response = $gateway->completePurchase( [ 'amount' => $cart['total']['final_cost'], 'currency' => 'GBP', 'Description' => 'Exercise Classes' ] )->send(); } catch (Exception $e) { Log::error($e->getMessage()); return Redirect::route('payment.error'); } if ($response->isSuccessful()) { $data = $response->getData(); // this is the raw response object $coupon = Coupons::processCoupon($coupon, $this->user); $trans = Transactions::where('transaction', $data['PAYMENTINFO_0_TRANSACTIONID'])->first(); if (!empty($trans->id)) { $res = [ 'cart' => $cart, 'payment_type' => 'paypal', 'coupon' => $coupon, 'transaction' => $trans, 'track_cart' => TRUE, 'user' => $this->user, 'balance' => $this->user->getWallet()->balance, ]; } else { if ($cart['total']['from_wallet'] > 0) { $wallet = $this->user->getWallet(); $wallet->withdraw($cart['total']['from_wallet'], 'Part payment for classes', 'part_payment'); } $transactionId = $data['PAYMENTINFO_0_TRANSACTIONID']; $transaction = $this->paid($data['TOKEN'], $transactionId, 'paypal', $cart, $coupon, $data['PAYMENTINFO_0_SECUREMERCHANTACCOUNTID']); $res = [ 'cart' => $cart, 'payment_type' => 'paypal', 'coupon' => $coupon, 'transaction' => $transaction->id, 'track_cart' => TRUE, 'user' => $this->user, 'balance' => $this->user->getWallet()->balance, ]; } return Redirect::route('checkout.confirmation')->with('res', $res); } else { Log::info($response->getMessage()); return Redirect::route('payment.error')->with('error', $response->getMessage()); } } public function processWalletPaymentSessions() { $coupon = Session::get('coupon', FALSE); $cart = EverciseCart::getCart($coupon); $token = 'w_' . Functions::randomPassword(8); $transactionId = $token; $wallet = $this->user->getWallet(); $wallet->withdraw($cart['total']['from_wallet'], 'Full payment for classes', 'full_payment'); $coupon = Coupons::processCoupon($coupon, $this->user); $transaction = $this->paid($token, $transactionId, 'wallet', $cart, $coupon); $res = [ 'cart' => $cart, 'payment_type' => 'wallet', 'coupon' => $coupon, 'transaction' => $transaction->id, 'track_cart' => TRUE, 'user' => $this->user, 'balance' => $wallet->balance, ]; return Redirect::route('checkout.confirmation')->with('res', $res); //return View::make('v3.cart.confirmation', $res); } public function paymentCancelled() { } public function paymentError() { } public function requestPaypalPaymentTopUp() { $cartRowId = EverciseCart::instance('topup')->search(['id' => 'TOPUP'])[0]; $cartRow = EverciseCart::instance('topup')->get($cartRowId); $amount = $cartRow['price']; if ($amount > 0) { try { $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('PAYPAL_PASS')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); $gateway->setNoShipping(1); $response = $gateway->purchase( [ 'cancelUrl' => URL::route('payment.cancelled'), 'returnUrl' => URL::route('payment.process.paypal.topup'), 'amount' => number_format($amount, 2), 'currency' => 'GBP' ] )->send(); //FOR FUCKS SAKE!!! ->setItems($products) if ($response->isRedirect()) { // redirect to offsite payment gateway $response->redirect(); } else { // payment failed: display message to customer echo $response->getMessage(); } } catch (Exception $e) { return Redirect::route('payment.error'); } } } public function processPaypalPaymentTopUp() { $cartRowId = EverciseCart::instance('topup')->search(['id' => 'TOPUP'])[0]; $cartRow = EverciseCart::instance('topup')->get($cartRowId); $amount = $cartRow['price']; $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('PAYPAL_PASS')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); try { $response = $gateway->completePurchase( [ 'amount' => number_format($amount, 2), 'currency' => 'GBP', 'Description' => 'Wallet TopUp' ] )->send(); } catch (Exception $e) { Log::error($e->getMessage()); return Redirect::route('payment.error'); } //return var_dump($response); if ($response->isSuccessful()) { $data = $response->getData(); // this is the raw response object $transactionId = $data['PAYMENTINFO_0_TRANSACTIONID']; $newBalance = $this->user->wallet->deposit($amount, 'Top up with Paypal', 'deposit', 0, $data['TOKEN'], $transactionId, 'paypal', 0); $transaction = $this->paidTopup($amount, [ 'token' => $data['TOKEN'], 'transaction' => $transactionId, 'payment_method' => 'paypal', ]); event('user.topup.completed', [$this->user, $transaction, $newBalance]); EverciseCart::clearTopup(); $data = [ 'amount' => $amount, 'token' => $data['TOKEN'], 'transactionId' => $transaction->id, ]; return Redirect::to('topup_confirmation') ->with('topup_details', $data); } else { Log::info($response->getMessage()); return Redirect::route('payment.error')->with('error', $response->getMessage()); } } public function paidTopup($amount, $params = []) { $transaction = Transactions::create( [ 'user_id' => $this->user->id, 'total' => round(abs($amount), 2), 'total_after_fees' => round(abs($amount), 2), 'coupon_id' => 0, 'commission' => 0, 'token' => (!empty($params['token']) ? $params['token'] : 0), 'transaction' => (!empty($params['transaction']) ? $params['transaction'] : 0), 'payment_method' => (!empty($params['payment_method']) ? $params['payment_method'] : 0), 'payer_id' => (!empty($params['payer_id']) ? $params['payer_id'] : 0), ]); $item = new TransactionItems([ 'user_id' => $this->user->id, 'type' => 'topup', 'sessionmember_id' => 0, 'amount' => round(abs($amount), 2), 'final_price' => round(abs($amount), 2), 'name' => 'Wallet TopUp', ]); $transaction->items()->save($item); return $transaction; } /** * @return \Illuminate\Http\RedirectResponse * @throws Exception */ public function processStripePaymentTopup() { $cartRowId = EverciseCart::instance('topup')->search(['id' => 'TOPUP'])[0]; $cartRow = EverciseCart::instance('topup')->get($cartRowId); $amount = $cartRow['price']; $token = ''; if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['stripeToken'])) { $token = $_POST['stripeToken']; } else { throw new \Exception('Could not find token'); } } /* Convert amount to pennies to be sent to Stripe */ $amountInPennies = SessionPayment::poundsToPennies($amount); try { $customer = Stripe_Customer::create([ 'email' => $this->user->email, 'card' => $token ]); $charge = Stripe_Charge::create([ 'customer' => $customer->id, 'amount' => $amountInPennies, 'currency' => 'gbp' ]); } catch (Stripe_CardError $e) { return 'card error'; } $transactionId = $charge['id']; $newBalance = $this->user->wallet->deposit($amount, 'top up with Stripe', 'deposit', 0, $token, $transactionId, 'stripe', 0); $transaction = $this->paidTopup($amount, [ 'token' => $token, 'transaction' => $transactionId, 'payment_method' => 'stripe', ]); event('user.topup.completed', [$this->user, $transaction, $newBalance]); EverciseCart::clearTopup(); $data = [ 'amount' => $amount, 'token' => $token, 'transactionId' => $transaction->id, ]; return Redirect::to('topup_confirmation') ->with('topup_details', $data); } /** * Actually add the user to the classes they have purchased, or credit their account with the package/top up. * * @param $token * @param $transactionId * @return \Illuminate\View\View */ public function paid($token, $transactionId, $paymentMethod, $cart = [], $coupon = 0, $payer_id = 0) { $commission = ($this->user->custom_commission > 0 ? $this->user->custom_commission : Config::get('evercise.commission')); $transaction = Transactions::create( [ 'user_id' => $this->user->id, 'total' => $cart['total']['final_cost'], 'total_after_fees' => (($cart['total']['final_cost'] / 100) * (100 - $commission)), 'coupon_id' => $coupon, 'commission' => $commission, 'token' => $token, 'transaction' => $transactionId, 'payment_method' => $paymentMethod, 'payer_id' => $payer_id ]); /** Add Packages to DB */ foreach ($cart['packages'] as $package) { $p = UserPackages::create([ 'status' => 1, 'package_id' => $package['id'], 'user_id' => $this->user->id ]); $item = new TransactionItems([ 'user_id' => $this->user->id, 'type' => 'package', 'package_id' => $p->id, 'amount' => round($p->package()->first()->price, 2), 'final_price' => round($p->package()->first()->price, 2), 'name' => $p->package()->first()->name, ]); $transaction->items()->save($item); } $trainer_notify = []; foreach ($cart['sessions'] as $session) { $free = FALSE; $evercisesession = Evercisesession::find($session['id']); try { $check = UserPackages::check($evercisesession, $this->user); $packageClass = UserPackageClasses::create([ 'user_id' => $this->user->id, 'evercisesession_id' => $session['id'], 'package_id' => $check->id, 'status' => 1 ]); event('activity.user.package.used', [$this->user, $check, $evercisesession]); $free = TRUE; } catch (Exception $e) { /** No package available */ Log::info($e->getMessage()); } $created = Sessionmember::create( [ 'user_id' => $this->user->id, 'evercisesession_id' => $session['id'], 'token' => $transaction->token, 'transaction_id' => $transaction->id, 'payment_method' => $paymentMethod ] ); // Not to be done from here. Happens in Command: CheckSessions the day after the class happens. /* $session_payment = Sessionpayment::create( [ 'user_id' => $this->user->id, 'evercisesession_id' => $session['id'], 'total' => $session['price'], 'total_after_fees' => (($session['price'] / 100) * (100 - $commission)), 'commission' => round($commission, 3), 'processed' => 0 ] );*/ $item = new TransactionItems([ 'user_id' => $this->user->id, 'type' => 'session', 'sessionmember_id' => $created->id, 'amount' => round(abs($session['price']), 2), 'final_price' => round($free ? 0 : abs($session['price']), 2), 'name' => $evercisesession->evercisegroup()->first()->name, ]); $transaction->items()->save($item); $evercisegroup = $evercisesession->evercisegroup()->first(); $trainer = $evercisegroup->user()->first(); $trainer_notify[$trainer->id][] = ['user' => $this->user, 'trainer' => $trainer, 'session' => $evercisesession, 'group' => $evercisegroup, 'transaction' => $transaction]; event('session.joined', [$this->user, $trainer, $evercisesession, $evercisegroup, $transaction]); //event('trainer.session.joined', [$this->user, $trainer, $evercisesession, $evercisegroup, $transaction]); } foreach($trainer_notify as $trainerId => $sessionDetails) { event('trainer.session.joined', [$trainerId, $sessionDetails]); } //$token, $transactionId, $paymentMethod, $cart = [], $coupon = 0, $payer_id = 0 event('user.cart.completed', [$this->user, $cart, $transaction]); EverciseCart::clearCart(); MilestoneRewards::clearUser($this->user->id); Session::forget('coupon'); return $transaction; } public function showConfirmation() { $res = Session::get('res'); if ($res) { return View::make('v3.cart.confirmation', $res); } else { return Redirect::route('home'); } } public function topupConfirmation() { /* Get topup details sent with redirect */ $data = Session::get('topup_details'); if (!$data) { return Redirect::route('home'); } $balance = $this->user->getWallet()->getBalance(); $data['balance'] = $balance; return View::make('v3.cart.topup_confirmation') ->with('data', $data); } /** * @param $cart * @return array */ public function getProductsPaypal($cart) { $products = []; /** Add Packages to DB */ foreach ($cart['packages'] as $package) { $products[] = ['name' => $package['name'], 'quantity' => 1, 'price' => round($package['price'], 2)]; } foreach ($cart['sessions_grouped'] as $id => $session) { $class = Evercisegroup::find($session['evercisegroup_id']); $products[] = [ 'name' => $class->name, 'quantity' => $session['qty'], 'price' => round($session['price'], 2) ]; } return $products; } } <file_sep>/app/models/Geo.php <?php /** * Class Geo */ class Geo { /** * @param $location * @return array */ public static function getLatLng($location) { /* check for searched location, otherwise use the ip address */ if ($location == '') { $location = Request::getClientIp(); } if ($location == '127.0.0.1' || $location == null) { $location = '192.168.127.12'; } try { $geocode = Geocoder::geocode($location); $latitude = $geocode->getLatitude(); $longitude = $geocode->getlongitude(); } catch (Exception $e) { //return $e->getMessage(); $latitude = 0; $longitude = 0; } return (['lat' => $latitude, 'lng' => $longitude]); } }<file_sep>/app/models/Evercoinhistory.php <?php /** * Class Evercoinhistory */ class Evercoinhistory extends \Eloquent { /** * @var array */ protected $fillable = ['user_id', 'transaction_amount', 'new_balance']; /** * @var string */ protected $table = 'evercoinhistory'; }<file_sep>/app/models/SearchModel.php <?php use Carbon\Carbon; class SearchModel { protected $evercisegroup; protected $sentry; protected $link; protected $input; protected $log; protected $session; protected $redirect; protected $paginator; protected $place; protected $elastic; protected $search; public function __construct( Evercisegroup $evercisegroup, Sentry $sentry, Link $link, Illuminate\Http\Request $input, Illuminate\Log\Writer $log, Illuminate\Session\Store $session, Illuminate\Routing\Redirector $redirect, Illuminate\Pagination\Factory $paginator, Illuminate\Config\Repository $config, Es $elasticsearch, Geotools $geotools, Place $place ) { $this->evercisegroup = $evercisegroup; $this->sentry = $sentry; $this->link = $link; $this->input = $input; $this->log = $log; $this->place = $place; $this->session = $session; $this->redirect = $redirect; $this->paginator = $paginator; $this->config = $config; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); $this->search = new Search($this->elastic, $this->evercisegroup, $this->log); } public function search($area = FALSE, $input = [], $user = FALSE, $dates = FALSE) { /** * * search * location * city * per_page or size * page * sort * distance * venue_id * * */ $landing = FALSE; if (!empty($input['landing'])) { $landing = $input['landing']; unset($input['landing']); } /** Clean up empty Arrays */ foreach ($input as $key => $val) { if (empty($val)) { unset($input[$key]); } } unset($input['area_id']); if (!empty($input['per_page']) && in_array($input['per_page'], $this->config->get('evercise.per_page'))) { $this->session->put('PER_PAGE', $input['per_page']); unset($input['per_page']); } if (!empty($input['size']) && in_array($input['size'], $this->config->get('evercise.per_page'))) { $this->session->put('PER_PAGE', $input['size']); unset($input['size']); } $fullLocation = $this->input->get('fullLocation', FALSE); $google_location = []; if ($fullLocation) { $google_location = $this->parseGoogleLocation(json_decode($fullLocation)); } $input = array_except($input, ['fullLocation', 'area']); /** If Area is not a object lets add it to the database so we have it for later use */ if (!$area instanceof Place) { $this->log->info('Not a Place'); if (!isset($input['location']) || empty($input['location'])) { $input['location'] = 'London'; } if (!isset($input['city']) || empty($input['city'])) { $input['city'] = 'London'; } if (!$location = $this->place->getByGoogleLocation($google_location)) { $location = $this->place->getByLocation($input['location'], 'London'); } if (is_null($location)) { $this->log->info('Address ERROR: ' . $input['location'] . '?' . http_build_query($input)); $input['allsegments'] = ''; $input = array_except($input, ['location', 'city']); $input = array_filter($input); if ($dates) { return FALSE; } return [ 'redirect' => $this->redirect->route( 'search.parse', $input, 301 ) ]; } else { $input = array_except($input, ['location', 'city', 'date']); } /** We have save the location to the DB so we can redirect the user to the new URL now */ $this->log->info('Redirect TO: ' . $location->link->permalink . '?' . http_build_query($input)); $input['allsegments'] = $location->link->permalink; if ($dates) { return FALSE; } return [ 'redirect' => $this->redirect->route( 'search.parse', $input, 301 ) ]; } $radius = (!empty($input['radius']) ? $input['radius'] : FALSE); if (!$radius) { $radius = (!empty($input['distance']) ? $input['distance'] : FALSE); } $size = $this->session->get('PER_PAGE', $this->config->get('evercise.default_per_page')); if (!$radius && !empty($area->min_radius)) { $radius = $area->min_radius; } elseif (!$radius && empty($area->min_radius)) { $radius = $this->config->get('evercise.default_radius'); if (!empty($area->link->type)) { switch ($area->link->type) { case 'ZIP': case 'STATION': case 'BOROUGH': case 'AREA': $radius = '3mi'; break; } } } $page = (!empty($input['page']) ? $input['page'] : 1); $sort = $this->getSort($area, (!empty($input['sort']) ? $input['sort'] : 'best')); $search = (!empty($input['search']) ? $input['search'] : ''); $params = [ 'clean' => TRUE, 'size' => $size, 'venue_id' => (!empty($input['venue_id']) ? $input['venue_id'] : FALSE), 'from' => (($page - 1) * $size), 'sort' => $sort, 'radius' => (in_array( $radius, array_values($this->config->get('evercise.radius')) ) ? $radius : $this->config->get( 'evercise.default_radius' )), 'search' => $search ]; if (!empty($input['featured'])) { $params['featured'] = TRUE; } if (!empty($input['ne']) && !empty($input['sw'])) { //Fix Bounds Google does NE and Elastic deos NW $params['bounds'] = [ 'top_right' => $input['ne'], 'bottom_left' => $input['sw'], ]; } if ($dates) { $cache_params = array_except($params, 'date'); $cache_id = md5((!empty($area->id) ? $area->id : '') . '_' . serialize($cache_params)); if (Cache::has($cache_id)) { //return Cache::get($cache_id); } $searchResults = $this->search->getResults($area, $params, $dates); Cache::put($cache_id, $searchResults, 60); return $searchResults; } if (!empty($input['date']) && $input['date']) { $params['date'] = $input['date']; } $searchResults = $this->search->getResults($area, $params); $this->elastic->saveStats((!empty($user->id) ? $user->id : 0), $this->input->ip(), $area, $params, $searchResults->total); $data = [ 'area' => $area, 'results' => $searchResults, 'url' => $area->link->permalink, 'size' => $size, 'sort' => (!empty($input['sort']) ? $input['sort'] : 'best'), 'venue_id' => (!empty($input['venue_id']) ? $input['venue_id'] : ''), 'venue' => (!empty($input['venue_id']) ? Venue::find($input['venue_id'])->toArray() : ''), 'radius' => $radius, 'allowed_radius' => array_flip($this->config->get('evercise.radius')), 'page' => $page, 'search' => $search ]; if ($landing) { foreach ($this->config->get('landing_pages') as $url => $params) { if (str_replace('/uk/london/', '', $url) == $landing) { $item = $params; } } if (!empty($item)) { $data['landing'] = $item; } } return $data; } public function searchMap($area = FALSE, $input = [], $user = FALSE) { /** * * search * location * city * per_page * page * sort * from * distance * venue_id * * map_nw = [lat => '', lon => ''] * map_se = [lat => '', lon => ''] * * */ $landing = FALSE; if (!empty($input['landing'])) { $landing = $input['landing']; unset($input['landing']); } /** Clean up empty Arrays */ foreach ($input as $key => $val) { if (empty($val)) { unset($input[$key]); } } unset($input['area_id']); /** If Area is not a object lets add it to the database so we have it for later use */ if (!$area instanceof Place) { $this->log->info('Not a Place'); if (!isset($input['location']) || empty($input['location'])) { $input['location'] = 'London'; } if (!isset($input['city']) || empty($input['city'])) { $input['city'] = 'London'; } $area = $this->place->getByLocation($input['location'], $input['city']); } $radius = $this->input->get('radius'); if (!$radius) { $radius = $this->input->get('distance', $this->config->get('evercise.default_radius')); } $sort = $this->getSort($area, (!empty($input['sort']) ? $input['sort'] : 'best')); $search = (!empty($input['search']) ? $input['search'] : ''); $params = [ 'size' => $this->config->get('evercise.max_display_map_results'), 'from' => 0, 'sort' => $sort, 'radius' => '25mi', 'search' => $search ]; if (!empty($input['featured'])) { $params['featured'] = TRUE; } if (!empty($input['ne']) && !empty($input['sw'])) { //Fix Bounds Google does NE and Elastic deos NW $params['bounds'] = [ 'top_right' => $input['ne'], 'bottom_left' => $input['sw'], ]; } $searchResults = $this->search->getMapResults($area, $params); return $searchResults; } public function getClasses($params) { /* * * location = 'london'; * */ $location = $this->place->getByLocation((!empty($params['location']) ? $params['location'] : 'London')); $query = [ 'size' => (!empty($params['size']) ? $params['size'] : $this->config->get('evercise.default_per_page')), 'from' => (!empty($params['from']) ? $params['from'] : 0), 'sort' => $this->getSort($location, (!empty($params['sort']) ? $params['sort'] : 'nearme')), 'radius' => (!empty($params['radius']) ? $params['radius'] : $this->config->get('evercise.default_radius')), 'search' => (!empty($params['search']) ? $params['search'] : ''), 'featured' => (isset($params['featured']) ? $params['featured'] : '') ]; $searchResults = $this->search->getResults($location, $query); return $searchResults; } private function getSort($area, $sort = '') { $options = [ 'price_asc' => ['default_price' => 'asc'], 'price_desc' => ['default_price' => 'desc'], 'duration_asc' => ['default_duration' => 'asc'], 'duration_desc' => ['default_duration' => 'desc'], 'viewed_asc' => ['counter' => 'asc'], 'viewed_desc' => ['counter' => 'desc'], 'nearme' => [ "_geo_distance" => [ 'venue.location' => $this->elastic->getLocationHash($area->lat, $area->lng), "order" => "asc", "unit" => "mi" ] ] ]; if (!empty($options[$sort])) { return $options[$sort]; } return FALSE; } public function parseGoogleLocation($location) { $res = []; if (!empty($location->types[0])) { $res['type'] = $location->types[0]; $res['formatted'] = $location->formatted_address; if ($res['type'] == 'postal_code_prefix') { $res['type'] = 'postal_code'; } if ($res['type'] == 'administrative_area_level_3') { $res['type'] = 'neighborhood'; } foreach ($location->address_components as $component) { if (!empty($component->types)) { foreach ($component->types as $type) { switch ($type) { case 'train_station': case 'subway_station': $res['station'] = $component->long_name; break; case 'postal_town': case 'administrative_area_level_2': $res['city'] = ($component->long_name == 'Greater London' ? 'London' : $component->long_name); break; case 'locality': $res['locality'] = $component->long_name; break; case 'postal_code': case 'postal_code_prefix': $res['postcode'] = $component->long_name; break; case 'country': case 'administrative_area_level_1': $res['country'] = $component->long_name; break; case 'route': $res['route'] = $component->long_name; break; case 'point_of_interest': $res['point'] = $component->long_name; break; case 'park': $res['park'] = $component->long_name; break; case 'neighborhood': case 'administrative_area_level_3': $res['neighborhood'] = $component->long_name; break; case 'establishment': $res['establishment'] = $component->long_name; break; } } } } $res['lat'] = ''; $res['lng'] = ''; if (!empty($location->geometry->location)) { $i = 0; foreach ($location->geometry->location as $key => $val) { if ($i == 0) { $res['lat'] = $val; } if ($i == 1) { $res['lng'] = $val; } $i++; } } } return $res; } public function getSearchDate($dates, $input = []) { if (!$dates) { return FALSE; } $search_date_keys = array_keys($dates); $search_date = FALSE; /** Check if we have enough of classes to Show for the next 7 days */ $days = 7; $minimum = 10; $total = 0; $i = 0; foreach ($dates as $date => $amount) { $i++; if ($i > $days) { break; } $total += $amount; } if ($minimum > $total) { // return FALSE; } if (!empty($search_date_keys[0])) { $search_date = $search_date_keys[0]; } if (!empty($input['date']) && !empty($dates[$input['date']])) { return $input['date']; } return $search_date; } }<file_sep>/app/events/Classes.php <?php namespace events; use App; use Illuminate\Log\Writer; class Classes { protected $activity; protected $indexer; /** * @var Stats */ private $stats; private $log; public function __construct(Activity $activity, Indexer $indexer, Mail $mail, Stats $stats, Writer $log) { $this->activity = $activity; $this->indexer = $indexer; $this->mail = $mail; $this->stats = $stats; $this->log = $log; } public function classCreated($class, $trainer) { $this->log->info('Trainer ' . $trainer->id . ' created class ' . $trainer->name); /** Mail And other shit Go here */ if ($trainer->numGroups() == 1) { $this->mail->classCreatedFirstTime($class, $trainer); } $this->activity->createdClass($class, $trainer); $this->indexer->indexSingle($class->id); } public function classPublished($class, $trainer) { $this->log->info('Trainer ' . $trainer->id . ' Published class ' . $class->name); /** Mail And other shit Go here */ $this->activity->publishedClass($class, $trainer); $this->indexer->indexSingle($class->id); } public function classUnPublished($class, $trainer) { $this->log->info('Trainer ' . $trainer->id . ' UnPublished class ' . $class->name); $this->activity->unPublishedClass($class, $trainer); $this->indexer->indexSingle($class->id); } public function classDeleted($class, $user) { $this->log->info('User ' . $user->id . ' Updated class ' . $class->name); $this->activity->deletedClass($class, $user); /** Mail And other shit Go here */ $this->indexer->indexSingle($class->id); } public function classUpdated($class, $user) { $this->log->info('User ' . $user->id . ' Updated class ' . $class->name); $this->activity->updatedClass($class, $user); /** Mail And other shit Go here */ $this->indexer->indexSingle($class->id); } public function classViewed($class, $user = FALSE) { $this->stats->classViewed($class); $this->indexer->indexSingle($class->id); } public function venueCreated($venue, $user) { $this->log->info('User ' . $user->id . ' Created Venue ' . $venue->name); $this->activity->createdVenue($venue, $user); } public function venueUpdated($venue, $user) { $this->log->info('User ' . $user->id . ' Updated Venue ' . $venue->name); $this->activity->updatedVenue($venue, $user); } }<file_sep>/app/database/migrations/2014_07_29_111427_create_foreign_keys_2.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateForeignKeys2 extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('evercoinhistory', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('milestones', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('tokens', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('withdrawalrequests', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('referrals', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); //$table->foreign('referee_id')->references('id')->on('users'); }); Schema::table('evercisegroup_subcategories', function(Blueprint $table) { $table->foreign('evercisegroup_id')->references('id')->on('evercisegroups'); $table->foreign('subcategory_id')->references('id')->on('subcategories'); }); /* Schema::table('subcategory_categories', function(Blueprint $table) { $table->foreign('subcategory_id')->references('id')->on('subcategories'); $table->foreign('category_id')->references('id')->on('categories'); });*/ } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('evercoinhistory', function(Blueprint $table) { $table->dropForeign('evercoinhistory_user_id_foreign'); }); Schema::table('milestones', function(Blueprint $table) { $table->dropForeign('milestones_user_id_foreign'); }); Schema::table('tokens', function(Blueprint $table) { $table->dropForeign('tokens_user_id_foreign'); }); Schema::table('withdrawalrequests', function(Blueprint $table) { $table->dropForeign('withdrawalrequests_user_id_foreign'); }); Schema::table('referrals', function(Blueprint $table) { $table->dropForeign('referrals_user_id_foreign'); }); Schema::table('evercisegroup_subcategories', function(Blueprint $table) { $table->dropForeign('evercisegroup_subcategories_evercisegroup_id_foreign'); $table->dropForeign('evercisegroup_subcategories_subcategory_id_foreign'); }); /* Schema::table('subcategory_categories', function(Blueprint $table) { $table->dropForeign('subcategory_categories_subcategory_id_foreign'); $table->dropForeign('subcategory_categories_category_id_foreign'); });*/ } } <file_sep>/app/controllers/admin/ArticlesController.php <?php use Illuminate\View\Factory as View; use Illuminate\Http\Request as Request; use Illuminate\Config\Repository as Config; /** * Class ArticlesController */ class ArticlesController extends \BaseController { private $articlecategories; private $articles; private $view; private $config; private $request; public function __construct( Articles $articles, ArticleCategories $articlecategories, View $view, Request $request, Config $config ) { $this->articlecategories = $articlecategories; $this->articles = $articles; $this->view = $view; $this->config = $config; $this->request = $request; } public function articles() { $articles = $this->articles->orderBy('created_at', 'desc')->get(); return $this->view->make('admin.cms.articles', compact('articles'))->render(); } /** * Manage Article * * @return Response */ public function manage($id = 0) { //$data = $this->request->except(['_token', 'row_single']); //return $data['published_on']; if (!empty($_POST)) { $save = $this->saveArticle($id); if (!empty($save['validation_failed'])) { return Redirect::back()->withInput()->withErrors( $save['validator'] ); } Session::flash('notification', 'Article Saved'); if(!empty($save['new'])) { if ($save['new']) { return Redirect::route('admin.article.manage', ['id' => $save['article']->id]); } } } $article = $this->articles->find($id); $categories = $this->articlecategories->all(); $cat_drop = []; foreach($categories as $c) { $cat_drop[$c->id] = $c->title; } $templates = $this->getTemplates(); $evercisegroup = Evercisegroup::has('futuresessions') ->has('confirmed') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); $cookie = Cookie::make('allowFinder', true, 60); $view = $this->view->make('admin.cms.manage', compact('article', 'categories', 'evercisegroup', 'templates', 'cat_drop'))->render(); return Response::make($view)->withCookie($cookie); } private function saveArticle($id = 0) { $data = $this->request->except(['_token', 'row_single']); $validator = Validator::make( $data, [ 'title' => 'required|max:160|min:5', 'meta_title' => 'required|max:160|min:5', 'description' => 'required|max:5000|min:100', 'category_id' => 'required|numeric', 'main_image' => 'image|mimes:jpeg,jpg,png,gif', 'intro' => 'required|max:500', 'keywords' => 'required|max:160', 'content' => 'required|min:300', 'permalink' => 'required', 'status' => 'required' ] ); if ($validator->fails()) { return [ 'validation_failed' => 1, 'validator' => $validator, 'errors' => $validator->errors()->toArray() ]; } else { if(!empty($data['id']) && $data['id'] > 0) { $id = $data['id']; unset($data['id']); } if($data['template'] == '0') { $data['template'] = ''; } $dir = public_path() . '/files/pages'; if (!is_dir($dir)) { mkdir($dir); } $dir .= '/' . date('Y'); if (!is_dir($dir)) { mkdir($dir); } $dir .= '/' . date('m'); if (!is_dir($dir)) { mkdir($dir); } if ($this->request->file('main_image')) { $file = $dir . '/' . slugIt($data['title']).'.'.$this->request->file('main_image')->getClientOriginalExtension(); $image = Image::make($this->request->file('main_image')->getRealPath())->fit( $this->config->get('evercise.article_main_image.regular.width'), $this->config->get('evercise.article_main_image.regular.height') )->save($file); $data['main_image'] = str_replace(public_path() . '/', '', $file); $file = $dir . '/thumb_' . slugIt($data['title']).'.'.$this->request->file('main_image')->getClientOriginalExtension(); $image = Image::make($this->request->file('main_image')->getRealPath())->resize( $this->config->get('evercise.article_main_image.thumb.width'), $this->config->get('evercise.article_main_image.thumb.height') )->save($file); $data['thumb_image'] = str_replace(public_path() . '/', '', $file); } if(is_null($data['main_image'])) { unset($data['main_image']); } if (!isset($data['published_on'])) { $data['published_on'] = new \Carbon\Carbon(); } else { $data['published_on'] = \Carbon\Carbon::createFromFormat('d/m/Y', $data['published_on']); } $url = ''; if (!empty($data['page']) && $data['page'] > 0) { $category = $this->articlecategories->find($data['category_id']); $url .= $category->permalink . '/'; } $url .= $data['permalink']; /** Fix Image Path */ $data['content'] = str_replace(getcwd(), '', $data['content']); unset($data['save']); if ($id == 0) { $new = true; $article = $this->articles->create($data); } else { $new = false; $article = $this->articles->find($id); foreach ($data as $key => $val) { $article->{$key} = $val; } $article->save(); } return [ 'new' => $new, 'article' => $article, 'url' => url($url, ['preview' => 'true']) ]; } } protected function getTemplates() { $templates = array(); $templates[] = 'Default'; //Get from the main template directory first: foreach (glob(app_path() . '/views/v3/pages/template_*') as $filename) { $filename = basename($filename); $name = str_replace(array('template_', '_','.blade.php'), array('', ' ', ''), $filename); $templates[str_replace('.blade.php', '', $filename)] = ucfirst($name); } return $templates; } public function deleteArticle($id = 0) { $article = $this->articles->find($id); if($article) { $article->delete(); return Redirect::route('admin.articles')->with('notification', 'Article Deleted'); } } public function categories(){ $categories = $this->articlecategories->all(); return $this->view->make('admin.cms.categories', compact('categories'))->render(); } public function categoriesManage($id = 0){ if (!empty($_POST)) { $save = $this->saveCategory($id); if (!empty($save['validation_failed'])) { return Redirect::back()->withInput()->withErrors( $save['validator'] ); } if(!empty($save['new'])) { if ($save['new']) { return Redirect::route('admin.article.category.manage', ['id' => $save['category']->id]); } } } $category = $this->articlecategories->find($id); return $this->view->make('admin.cms.manage_categories', compact('category'))->render(); } private function saveCategory($id = 0) { $data = $this->request->except('_token'); $validator = Validator::make( $data, [ 'title' => 'required|max:160|min:5', 'description' => 'required|max:5000|min:100', 'main_image' => 'image|mimes:jpeg,jpg,png,gif', 'keywords' => 'required|max:160', 'permalink' => 'required', 'status' => 'required' ] ); if ($validator->fails()) { return [ 'validation_failed' => 1, 'validator' => $validator, 'errors' => $validator->errors()->toArray() ]; } else { if(!empty($data['id']) && $data['id'] > 0) { $id = $data['id']; unset($data['id']); } $dir = public_path() . '/files/pages'; if (!is_dir($dir)) { mkdir($dir); } $dir .= '/' . date('Y'); if (!is_dir($dir)) { mkdir($dir); } $dir .= '/' . date('m'); if (!is_dir($dir)) { mkdir($dir); } if ($this->request->file('main_image')) { $file = $dir . '/' . Str::slug($data['title']).'.'.$this->request->file('main_image')->getClientOriginalExtension(); $image = Image::make($this->request->file('main_image')->getRealPath())->fit( $this->config->get('evercise.article_category_main_image.width'), $this->config->get('evercise.article_category_main_image.height') )->save($file); $data['main_image'] = str_replace(public_path() . '/', '', $file); } if(is_null($data['main_image'])) { unset($data['main_image']); } unset($data['save']); if ($id == 0) { $new = true; $category = $this->articlecategories->create($data); } else { $new = false; $category = $this->articlecategories->find($id); foreach ($data as $key => $val) { $category->{$key} = $val; } $category->save(); } return [ 'new' => $new, 'category' => $category ]; } } }<file_sep>/app/composers/AdminHeaderComposer.php <?php namespace composers; use Trainer; class AdminHeaderComposer { public function compose($view) { $unconfirmedTrainers = Trainer::getUnconfirmedTrainers(); return $view ->with('unconfirmedTrainers', $unconfirmedTrainers); } }<file_sep>/public/assets/jsdev/angular/product-page.js if(typeof angular != 'undefined') { app.controller('calendarController', ["$scope", "$filter" ,function ($scope, $filter) { $scope.sessions = JSON.parse($('input[name="sessions"]').val()); $scope.rows = []; $scope.activeDate; $scope.cartItems = JSON.parse(CART); $('#class-calendar').datepicker({ format: "yyyy-mm-dd", startDate: "-1d", weekStart : 1, todayHighlight : false, multidate: false, setDate: null, beforeShowDay: function(d) { var date = d.getFullYear() + '-' + ('0' + (d.getMonth() +1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); var result = $.grep($scope.sessions, function(e){ if(e.remaining > 0){ var dt = e.date_time; dt = dt.split(/\s+/); return dt[0] == date; } }); if(result.length > 0){ for(var key in result){ if (!checkDuplicate(result[key].id)){ var date = result[key].date_time, values = date.split(/[^0-9]/), year = parseInt(values[0], 10), month = parseInt(values[1], 10) - 1, // Month is zero based, so subtract 1 day = parseInt(values[2], 10), hours = parseInt(values[3], 10), minutes = parseInt(values[4], 10), seconds = parseInt(values[5], 10), dt; dt = new Date(year, month, day, hours, minutes, seconds); var time = $filter('date')(dt, 'hh:mm a'); if(result[key].remaining > 0){ $scope.rows.push({ 'id' : result[key].id, 'date' : dt, 'time' : time, 'price' :result[key].price, 'remaining' :result[key].remaining, 'default_tickets' :result[key].default_tickets, 'selected' : $scope.cartItems[result[key].id], 'show' : false }) } } } return { enabled : true, classes : 'session' }; } else{ return { enabled : false, classes : false }; } } }).on('changeDate', function(e){ $scope.activeDate = e.date; //$scope.activeDate = d.getFullYear() + '-' + ('0' + (d.getMonth() +1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); $scope.$apply(); $(".select-box").selectbox(); }) function checkDuplicate(id){ for ( var i=0; i < $scope.rows.length; i++ ){ if ($scope.rows[i].id == id) return true; } return false; } $scope.activeFilter = function (rows) { if (typeof $scope.activeDate !== 'undefined') { var start = rows.date; start.setHours(0,0,0,0); return start.toString() == $scope.activeDate.toString(); } }; }]) }<file_sep>/app/composers/AdminGroupComposer.php <?php namespace composers; use Evercisegroup; use Input; use Subcategory; class AdminGroupComposer { public function compose($view) { //JavaScript::put(['initSearchByName' => 1 ]); $cats = ( Subcategory::lists( 'name') ); $categories = json_encode($cats); $status = Input::get('status'); $searchTerm = Input::get('search'); $orderBy = Input::get('order') ? Input::get('order') : 'id'; $selectedGroups = []; if ($status == 'active') { if ($searchTerm != "") $futuregroups = Evercisegroup::has('futuresessions')->where('name', 'LIKE', '%'.$searchTerm.'%')->orderBy($orderBy)->get(); else $futuregroups = Evercisegroup::has('futuresessions')->orderBy($orderBy)->get(); foreach($futuregroups as $futuregroup) { array_push($selectedGroups, $futuregroup); } } else if ($status == 'expired') { $pastGroupIds = []; $futureGroupIds = []; $futuregroups = Evercisegroup::has('futuresessions')->orderBy($orderBy)->get(); if ($searchTerm != "") $pastgroups = Evercisegroup::has('pastsessions')->where('name', 'LIKE', '%'.$searchTerm.'%')->orderBy($orderBy)->get(); else $pastgroups = Evercisegroup::has('pastsessions')->orderBy($orderBy)->get(); foreach($pastgroups as $pastgroup) array_push($pastGroupIds, $pastgroup->id); foreach($futuregroups as $futuregroup) array_push($futureGroupIds, $futuregroup->id); foreach($pastgroups as $pastgroup) { if(! in_array($pastgroup->id, $futureGroupIds)) array_push($selectedGroups, $pastgroup); } } else { if ($searchTerm != "") $evercisegroups = Evercisegroup::where('name', 'LIKE', '%'.$searchTerm.'%')->orderBy($orderBy)->get(); else $evercisegroups = Evercisegroup::orderBy($orderBy)->get(); foreach($evercisegroups as $evercisegroup) { array_push($selectedGroups, $evercisegroup); } } return $view ->with('categories', $categories) ->with('selectedGroups', $selectedGroups) ->with('status', $status) ->with('search', $searchTerm); } }<file_sep>/app/database/migrations/2014_06_25_104005_create_foreign_keys.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateForeignKeys extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('trainers', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); //$table->foreign('specialities_id')->references('id')->on('specialities'); }); Schema::table('user_marketingpreferences', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('marketingpreference_id')->references('id')->on('marketingpreferences'); }); Schema::table('ratings', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('sessionmember_id')->references('id')->on('sessionmembers'); $table->foreign('session_id')->references('id')->on('evercisesessions'); $table->foreign('evercisegroup_id')->references('id')->on('evercisegroups'); $table->foreign('user_created_id')->references('id')->on('users'); }); Schema::table('evercisesessions', function(Blueprint $table) { $table->foreign('evercisegroup_id')->references('id')->on('evercisegroups'); }); Schema::table('evercisegroups', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); //$table->foreign('category_id')->references('id')->on('categories'); $table->foreign('venue_id')->references('id')->on('venues'); }); Schema::table('trainerhistory', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('historytype_id')->references('id')->on('historytypes'); }); Schema::table('user_has_categories', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('category_id')->references('id')->on('categories'); }); Schema::table('sessionmembers', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('evercisesession_id')->references('id')->on('evercisesessions'); }); Schema::table('venues', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('venue_facilities', function(Blueprint $table) { $table->foreign('venue_id')->references('id')->on('venues'); $table->foreign('facility_id')->references('id')->on('facilities'); }); Schema::table('wallets', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); Schema::table('wallethistory', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); //$table->foreign('sessionpayment_id')->references('id')->on('sessionpayments'); }); Schema::table('evercoins', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('trainers', function(Blueprint $table) { $table->dropForeign('trainers_user_id_foreign'); }); Schema::table('user_marketingpreferences', function(Blueprint $table) { $table->dropForeign('user_marketingpreferences_user_id_foreign'); $table->dropForeign('user_marketingpreferences_marketingpreference_id_foreign'); }); Schema::table('ratings', function(Blueprint $table) { $table->dropForeign('ratings_user_id_foreign'); $table->dropForeign('ratings_sessionmember_id_foreign'); $table->dropForeign('ratings_session_id_foreign'); $table->dropForeign('ratings_evercisegroup_id_foreign'); $table->dropForeign('ratings_user_created_id_foreign'); }); Schema::table('evercisesessions', function(Blueprint $table) { $table->dropForeign('evercisesessions_evercisegroup_id_foreign'); }); Schema::table('evercisegroups', function(Blueprint $table) { $table->dropForeign('evercisegroups_user_id_foreign'); $table->dropForeign('evercisegroups_venue_id_foreign'); }); Schema::table('trainerhistory', function(Blueprint $table) { $table->dropForeign('trainerhistory_user_id_foreign'); $table->dropForeign('trainerhistory_historytype_id_foreign'); }); Schema::table('user_has_categories', function(Blueprint $table) { $table->dropForeign('user_has_categories_user_id_foreign'); $table->dropForeign('user_has_categories_category_id_foreign'); }); Schema::table('sessionmembers', function(Blueprint $table) { $table->dropForeign('sessionmembers_user_id_foreign'); $table->dropForeign('sessionmembers_evercisesession_id_foreign'); }); Schema::table('venues', function(Blueprint $table) { $table->dropForeign('venues_user_id_foreign'); }); Schema::table('venue_facilities', function(Blueprint $table) { $table->dropForeign('venue_facilities_venue_id_foreign'); $table->dropForeign('venue_facilities_facility_id_foreign'); }); Schema::table('wallets', function(Blueprint $table) { $table->dropForeign('wallets_user_id_foreign'); }); Schema::table('wallethistory', function(Blueprint $table) { $table->dropForeign('wallethistory_user_id_foreign'); }); Schema::table('evercoins', function(Blueprint $table) { $table->dropForeign('evercoins_user_id_foreign'); }); } } <file_sep>/app/lang/en/redirect-messages.php <?php return [ 'facebook_signup' => 'you have successfully signed up with facebook, Your password has been emailed to you', ];<file_sep>/app/events/PardotEmail.php <?php /** * Class PardotEmail */ class PardotEmail { /** * @var */ public $subject; /** * @var */ public $content; /** * @var */ public $from; /** * @var */ public $fromName; /** * @var */ public $plainText; /** * @param array $params */ public function __construct($params = []) { $config = Config::get('mail.from'); $this->from = $config['address']; $this->fromName = $config['name']; foreach ($params as $key => $val) { $this->{$key} = $val; } } }<file_sep>/app/controllers/ajax/SearchController.php <?php namespace ajax; use Es; use Evercisegroup; use Geotools; use Illuminate\Config\Repository; use Illuminate\Http\Request; use Illuminate\Log\Writer; use Illuminate\Pagination\Factory; use Illuminate\Routing\Redirector; use Illuminate\Session\Store; use Link; use Place; use Response; use Sentry; use Search; use SearchModel; use Elastic; class SearchController extends AjaxBaseController { private $evercisegroup; private $sentry; private $link; private $input; private $log; private $session; private $redirect; private $paginator; private $place; private $elastic; private $search; private $searchmodel; public function __construct( Evercisegroup $evercisegroup, Sentry $sentry, Link $link, Request $input, Writer $log, Store $session, Redirector $redirect, Factory $paginator, Repository $config, Es $elasticsearch, Geotools $geotools, Place $place, SearchModel $searchModel ) { parent::__construct(); $this->evercisegroup = $evercisegroup; $this->sentry = $sentry; $this->link = $link; $this->input = $input; $this->log = $log; $this->place = $place; $this->session = $session; $this->redirect = $redirect; $this->paginator = $paginator; $this->config = $config; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); $this->search = new Search($this->elastic, $this->evercisegroup, $this->log); $this->searchmodel = $searchModel; $this->user = Sentry::getUser(); } /** * Parse All Params and forward it to the right function * @param array $all_segments */ public function parseUrl($all_segments = '') { $link = $this->link->checkLink($all_segments, $this->input->get('area_id', FALSE)); if ($link) { return $this->search($link->getArea); } elseif (!$link && !$this->input->get('location', FALSE) && $all_segments != '') { $this->log->info('Somebody tried to access a missing URL ' . $this->input->url()); $input['allsegments'] = ''; return $this->redirect->route( 'search.parse', $input ); } return $this->search(); } public function parseMapUrl($all_segments = '') { $link = $this->link->checkLink($all_segments, $this->input->get('area_id', FALSE)); if ($link) { switch ($link->type) { case 'AREA': case 'STATION': case 'POSTCODE': case 'ZIP': return $this->searchMap($link->getArea); break; } } elseif (!$link && !$this->input->get('location', FALSE) && $all_segments != '') { $this->log->info('Somebody tried to access a missing URL ' . $this->input->url()); $input['allsegments'] = ''; return $this->redirect->route( 'search.parse', $input ); } return $this->searchMap(); } public function search($area = FALSE) { $input = array_filter($this->input->all()); $dates = $this->searchmodel->search($area, $input, $this->user, TRUE); $input['date'] = $this->searchmodel->getSearchDate($dates, $input); $results = $this->searchmodel->search($area, $input, $this->user); $results['selected_date'] = $input['date']; $results['available_dates'] = $dates; if (!empty($results['redirect'])) { return $results['redirect']; } $results['related_categories'] = \Subcategory::getRelatedFromSearch(!empty($input['search']) ? $input['search'] : FALSE); return Response::json($results); } public function searchMap($area = FALSE) { return $this->search($area); } }<file_sep>/app/models/EverciseCart.php <?php class EverciseCart extends Cart { /** * @param $type * @param $id * @return string * * Convert session-id or package-id into a unique product code */ public static function toProductCode($type, $id) { $productCode = ''; switch ($type) { case 'session': $productCode = 'S' . $id; break; case 'package': $productCode = 'P' . $id; break; } return $productCode; } /** * @param $productCode * @return array|bool * * Convert product code back to session-id or package-id */ public static function fromProductCode($productCode) { if (count($chunks = explode('S', $productCode)) > 1) { $type = 'session'; if (count($chunks) < 2) { return FALSE; } $id = $chunks[1]; } else { if (count($chunks = explode('P', $productCode)) > 1) { $type = 'package'; if (count($chunks) < 2) { return FALSE; } $id = $chunks[1]; } else { if (count($chunks = explode('T', $productCode)) > 1) { $type = 'topup'; $id = 'TOPUP'; } else { Log::error('Something is wrong here with product code ' . $productCode); return FALSE; } } } return ['id' => $id, 'type' => $type]; } /** * @return $this * * Return Cart data formatted as an array */ public static function getCartOLD($coupon = FALSE) { $cartRows = parent::instance('main')->content(); $subTotal = parent::total(); $discount = 0; $total = ($subTotal / 100) * (100 - $discount); $data = [ 'discount' => $discount, 'subTotal' => $subTotal, 'total' => $total, 'cartRows' => $cartRows, ]; return $data; } public static function getCart($coupon = FALSE) { $cart = []; //$cart['wallet'] = 0; $cartRows = parent::instance('main')->content(); $subTotal = parent::total(); $user = Sentry::getUser(); $packages = []; if (!empty($user->id)) { foreach ($user->packages as $p) { // && $p->created_at->addMonths(2)->format('Y-m-d') >= date('Y-m-d') if (count($p->package)) { $package = $p->package->toArray(); $package['available'] = ($p->package()->first()->classes - $p->classes()->count()); $package['package_id'] = $package['id']; $package['id'] = $p->id; $packages[] = $package; } }; // $cart['wallet'] = $user->getWallet()->getBalance(); } /** Get all packages that exist in Cart */ $cart_packages = []; $sessions = []; $objects = []; foreach ($cartRows as $row) { $code = EverciseCart::fromProductCode($row['id']); switch ($code['type']) { case 'package': for ($i = 0; $i < $row->qty; $i++) { $package = Packages::find($code['id'])->toArray(); $package['available'] = $package['classes']; $package['cart_id'] = $row['id']; $cart_packages[] = $package; } break; case 'session': for ($i = 0; $i < $row->qty; $i++) { if (!empty($objects['sessions'][$code['id']])) { $session = $objects['sessions'][$code['id']]; } else { $session = Evercisesession::find($code['id']); $objects['sessions'][$code['id']] = $session; } if (!empty($session->id)) { $remaining_tickets = $session->remainingTickets(); $slug = $session->evercisegroup->slug; $session = $session->toArray(); $session['tickets'] = $remaining_tickets; $session['slug'] = $slug; unset($session['sessionmembers']); $sessions[] = $session; } } break; } } /** run All the Classes and Deduct from Package */ $s = 0; $package_deduct = 0; foreach ($sessions as $session) { $sessions[$s]['package'] = 0; $sessions[$s]['cart_id'] = $session['id']; if (!empty($objects['groups'][$session['evercisegroup_id']])) { $evercisegroup = $objects['groups'][$session['evercisegroup_id']]; } else { $evercisegroup = Evercisegroup::find($session['evercisegroup_id']); $objects['groups'][$session['evercisegroup_id']] = $evercisegroup; } $sessions[$s]['name'] = $evercisegroup->name; $package_used = FALSE; /** DB packages First */ $i = 0; foreach ($packages as $package) { if ($package['max_class_price'] >= $session['price'] && $packages[$i]['available'] > 0 && !$package_used) { $sessions[$s]['package'] = $package['id']; $packages[$i]['available']--; $package_deduct += $session['price']; $package_used = TRUE; } $i++; } /** Cart Packages */ $i = 0; foreach ($cart_packages as $package) { if ($package['max_class_price'] >= $session['price'] && $cart_packages[$i]['available'] > 0 && $sessions[$s]['package'] == 0) { $sessions[$s]['package'] = $package['id']; $cart_packages[$i]['available']--; $package_deduct += $session['price']; $package_used = TRUE; } $i++; } $s++; } /** Group Session IDs to display Quantities */ $cart['sessions_grouped'] = []; foreach ($sessions as $s) { if (!empty($cart['sessions_grouped'][$s['id']]['qty'])) { $cart['sessions_grouped'][$s['id']]['qty']++; // $cart['sessions_grouped'][$s['id']]['tickets_left']--; $cart['sessions_grouped'][$s['id']]['grouped_price'] += $s['price']; if ($s['package'] == 0) { $cart['sessions_grouped'][$s['id']]['grouped_price_discount'] += $s['price']; } } else { $cart['sessions_grouped'][$s['id']] = $s; $cart['sessions_grouped'][$s['id']]['qty'] = 1; // $cart['sessions_grouped'][$s['id']]['tickets_left'] = $s['tickets'] - 1; $cart['sessions_grouped'][$s['id']]['tickets_left'] = $s['tickets']; $cart['sessions_grouped'][$s['id']]['grouped_price'] = $s['price']; $cart['sessions_grouped'][$s['id']]['grouped_price_discount'] = 0; if ($s['package'] == 0) { $cart['sessions_grouped'][$s['id']]['grouped_price_discount'] = $s['price']; } } } /** Combine Back the Cart and figure things out */ $cart['packages'] = $cart_packages; $cart['sessions'] = $sessions; $cart['total']['subtotal'] = $subTotal; $cart['total']['package_deduct'] = $package_deduct; // $cart['total']['from_wallet'] = 0; $cart['total']['rewards_deduct'] = 0; $cart['total']['final_cost'] = ($subTotal - $package_deduct); /** DISABLE FROM WALLET if ($cart['wallet'] > 0) { if ($cart['wallet'] > $cart['total']['final_cost']) { $cart['total']['from_wallet'] = $cart['total']['final_cost']; $cart['total']['final_cost'] = 0; } else { $cart['total']['from_wallet'] = $cart['wallet']; $cart['total']['final_cost'] = ($cart['total']['final_cost'] - $cart['wallet']); } } */ $cart['discount'] = []; $cart['discount']['amount'] = 0; /** Check Coupon */ if ($coupon) { $coupon = Coupons::check($coupon); if (!empty($coupon->id)) { $cart['discount'] = [ 'type' => $coupon->type, 'percentage' => $coupon->percentage, 'amount' => $coupon->amount, 'description' => $coupon->description ]; switch ($coupon->type) { case 'percentage': $cart['discount']['new_total'] = round(($cart['total']['final_cost'] / 100) * (100 - $coupon->percentage), 2); $cart['discount']['amount'] = round(($cart['total']['final_cost'] / 100) * $coupon->percentage, 2); break; case 'amount': $cart['discount']['new_total'] = round($cart['total']['final_cost'] - $coupon->amount, 2); $cart['discount']['amount'] = round($coupon->amount, 2); break; } if ($cart['discount']['new_total'] < 0) { $cart['discount']['new_total'] = 0; } if ($cart['discount']['amount'] < 0) { $cart['discount']['amount'] = 0; } $cart['total']['final_cost'] = ($cart['discount']['new_total']); } } $cart['rewards'] = []; $deduct_rewards = 0; if (!empty($user->id)) { foreach ($user->rewards as $reward) { // && $p->created_at->addMonths(2)->format('Y-m-d') >= date('Y-m-d') if ($reward->status == 0) { $cart['rewards'][][$reward->message] = $reward->amount; $cart['total']['rewards_deduct'] += $reward->amount; $deduct_rewards += $reward->amount; } }; if($deduct_rewards > 0) { $cart['total']['final_cost'] -=$deduct_rewards; } } if($cart['total']['final_cost'] < 0) { $cart['total']['final_cost'] = 0; } $cart['total']['from_wallet'] = 0; // If remainder is less than 50p, add discount for the remaining amount, cos we're nice if($cart['total']['final_cost'] > 0 && $cart['total']['final_cost'] < 0.50) { $cart['rewards'][]['Keep the change'] = $cart['total']['final_cost']; $cart['total']['rewards_deduct'] += $cart['total']['final_cost']; $cart['total']['final_cost'] -= $cart['total']['rewards_deduct']; } return $cart; } public static function clearTopup() { $cartRowIds = EverciseCart::instance('topup')->search(['id' => 'TOPUP']); if ($cartRowIds) { foreach ($cartRowIds as $cartRowId) { EverciseCart::instance('topup')->remove($cartRowId); } } } public static function clearCart() { EverciseCart::instance('main')->destroy(); } }<file_sep>/app/composers/SearchClassesComposer.php <?php namespace composers; use JavaScript; class SearchClassesComposer { public function compose($view) { JavaScript::put(array('InitSearchForm' => 1 )); } }<file_sep>/app/models/FakeRating.php <?php /** * Class FakeRating */ class FakeRating extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'evercisegroup_id', 'stars', 'comment']; /** * The database table used by the model. * * @var string */ protected $table = 'fakeratings'; /* the user that rated this class */ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function rator() { return $this->belongsTo('User', 'user_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function evercisegroup() { return $this->belongsTo('evercisegroup', 'evercisegroup_id'); } public static function validateAndCreateRating() { $validator = Validator::make( Input::all(), array( 'rator' => 'required|max:5|min:1', 'evercisegroup_id' => 'required|max:5|min:1', 'stars' => 'required|max:1|min:1|between:0,5', 'comment' => 'required|max:255|min:4', ) ); if ($validator->fails()) { return array( 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ); } else { $stars = Input::get('stars', 1); $comment = Input::get('comment', 1); $evercisegroup_id = Input::get('evercisegroup_id', 1); $rator = Input::get('rator', 0); Static::create([ 'user_id'=>$rator, 'evercisegroup_id'=>$evercisegroup_id, 'stars'=>$stars, 'comment'=>$comment, ]); return array( 'validation_failed' => 0, ); } } }<file_sep>/_ide_helper.php <?php /** * An helper file for Laravel 4, to provide autocomplete information to your IDE * Generated for Laravel 4.2.17 on 2015-02-18. * * @author <NAME> <<EMAIL>> * @see https://github.com/barryvdh/laravel-ide-helper */ namespace { exit("This file should not be included, only analyzed by your IDE"); class App extends \Illuminate\Support\Facades\App{ /** * Bind the installation paths to the application. * * @param array $paths * @return void * @static */ public static function bindInstallPaths($paths){ \Illuminate\Foundation\Application::bindInstallPaths($paths); } /** * Get the application bootstrap file. * * @return string * @static */ public static function getBootstrapFile(){ return \Illuminate\Foundation\Application::getBootstrapFile(); } /** * Start the exception handling for the request. * * @return void * @static */ public static function startExceptionHandling(){ \Illuminate\Foundation\Application::startExceptionHandling(); } /** * Get or check the current application environment. * * @param mixed * @return string * @static */ public static function environment(){ return \Illuminate\Foundation\Application::environment(); } /** * Determine if application is in local environment. * * @return bool * @static */ public static function isLocal(){ return \Illuminate\Foundation\Application::isLocal(); } /** * Detect the application's current environment. * * @param array|string $envs * @return string * @static */ public static function detectEnvironment($envs){ return \Illuminate\Foundation\Application::detectEnvironment($envs); } /** * Determine if we are running in the console. * * @return bool * @static */ public static function runningInConsole(){ return \Illuminate\Foundation\Application::runningInConsole(); } /** * Determine if we are running unit tests. * * @return bool * @static */ public static function runningUnitTests(){ return \Illuminate\Foundation\Application::runningUnitTests(); } /** * Force register a service provider with the application. * * @param \Illuminate\Support\ServiceProvider|string $provider * @param array $options * @return \Illuminate\Support\ServiceProvider * @static */ public static function forceRegister($provider, $options = array()){ return \Illuminate\Foundation\Application::forceRegister($provider, $options); } /** * Register a service provider with the application. * * @param \Illuminate\Support\ServiceProvider|string $provider * @param array $options * @param bool $force * @return \Illuminate\Support\ServiceProvider * @static */ public static function register($provider, $options = array(), $force = false){ return \Illuminate\Foundation\Application::register($provider, $options, $force); } /** * Get the registered service provider instance if it exists. * * @param \Illuminate\Support\ServiceProvider|string $provider * @return \Illuminate\Support\ServiceProvider|null * @static */ public static function getRegistered($provider){ return \Illuminate\Foundation\Application::getRegistered($provider); } /** * Resolve a service provider instance from the class name. * * @param string $provider * @return \Illuminate\Support\ServiceProvider * @static */ public static function resolveProviderClass($provider){ return \Illuminate\Foundation\Application::resolveProviderClass($provider); } /** * Load and boot all of the remaining deferred providers. * * @return void * @static */ public static function loadDeferredProviders(){ \Illuminate\Foundation\Application::loadDeferredProviders(); } /** * Register a deferred provider and service. * * @param string $provider * @param string $service * @return void * @static */ public static function registerDeferredProvider($provider, $service = null){ \Illuminate\Foundation\Application::registerDeferredProvider($provider, $service); } /** * Resolve the given type from the container. * * (Overriding Container::make) * * @param string $abstract * @param array $parameters * @return mixed * @static */ public static function make($abstract, $parameters = array()){ return \Illuminate\Foundation\Application::make($abstract, $parameters); } /** * Determine if the given abstract type has been bound. * * (Overriding Container::bound) * * @param string $abstract * @return bool * @static */ public static function bound($abstract){ return \Illuminate\Foundation\Application::bound($abstract); } /** * "Extend" an abstract type in the container. * * (Overriding Container::extend) * * @param string $abstract * @param \Closure $closure * @return void * @throws \InvalidArgumentException * @static */ public static function extend($abstract, $closure){ \Illuminate\Foundation\Application::extend($abstract, $closure); } /** * Register a "before" application filter. * * @param \Closure|string $callback * @return void * @static */ public static function before($callback){ \Illuminate\Foundation\Application::before($callback); } /** * Register an "after" application filter. * * @param \Closure|string $callback * @return void * @static */ public static function after($callback){ \Illuminate\Foundation\Application::after($callback); } /** * Register a "finish" application filter. * * @param \Closure|string $callback * @return void * @static */ public static function finish($callback){ \Illuminate\Foundation\Application::finish($callback); } /** * Register a "shutdown" callback. * * @param callable $callback * @return void * @static */ public static function shutdown($callback = null){ \Illuminate\Foundation\Application::shutdown($callback); } /** * Register a function for determining when to use array sessions. * * @param \Closure $callback * @return void * @static */ public static function useArraySessions($callback){ \Illuminate\Foundation\Application::useArraySessions($callback); } /** * Determine if the application has booted. * * @return bool * @static */ public static function isBooted(){ return \Illuminate\Foundation\Application::isBooted(); } /** * Boot the application's service providers. * * @return void * @static */ public static function boot(){ \Illuminate\Foundation\Application::boot(); } /** * Register a new boot listener. * * @param mixed $callback * @return void * @static */ public static function booting($callback){ \Illuminate\Foundation\Application::booting($callback); } /** * Register a new "booted" listener. * * @param mixed $callback * @return void * @static */ public static function booted($callback){ \Illuminate\Foundation\Application::booted($callback); } /** * Run the application and send the response. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void * @static */ public static function run($request = null){ \Illuminate\Foundation\Application::run($request); } /** * Add a HttpKernel middleware onto the stack. * * @param string $class * @param array $parameters * @return $this * @static */ public static function middleware($class, $parameters = array()){ return \Illuminate\Foundation\Application::middleware($class, $parameters); } /** * Remove a custom middleware from the application. * * @param string $class * @return void * @static */ public static function forgetMiddleware($class){ \Illuminate\Foundation\Application::forgetMiddleware($class); } /** * Handle the given request and get the response. * * Provides compatibility with BrowserKit functional testing. * * @implements HttpKernelInterface::handle * @param \Symfony\Component\HttpFoundation\Request $request * @param int $type * @param bool $catch * @return \Symfony\Component\HttpFoundation\Response * @throws \Exception * @static */ public static function handle($request, $type = 1, $catch = true){ return \Illuminate\Foundation\Application::handle($request, $type, $catch); } /** * Handle the given request and get the response. * * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response * @static */ public static function dispatch($request){ return \Illuminate\Foundation\Application::dispatch($request); } /** * Call the "finish" and "shutdown" callbacks assigned to the application. * * @param \Symfony\Component\HttpFoundation\Request $request * @param \Symfony\Component\HttpFoundation\Response $response * @return void * @static */ public static function terminate($request, $response){ \Illuminate\Foundation\Application::terminate($request, $response); } /** * Call the "finish" callbacks assigned to the application. * * @param \Symfony\Component\HttpFoundation\Request $request * @param \Symfony\Component\HttpFoundation\Response $response * @return void * @static */ public static function callFinishCallbacks($request, $response){ \Illuminate\Foundation\Application::callFinishCallbacks($request, $response); } /** * Prepare the request by injecting any services. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Request * @static */ public static function prepareRequest($request){ return \Illuminate\Foundation\Application::prepareRequest($request); } /** * Prepare the given value as a Response object. * * @param mixed $value * @return \Symfony\Component\HttpFoundation\Response * @static */ public static function prepareResponse($value){ return \Illuminate\Foundation\Application::prepareResponse($value); } /** * Determine if the application is ready for responses. * * @return bool * @static */ public static function readyForResponses(){ return \Illuminate\Foundation\Application::readyForResponses(); } /** * Determine if the application is currently down for maintenance. * * @return bool * @static */ public static function isDownForMaintenance(){ return \Illuminate\Foundation\Application::isDownForMaintenance(); } /** * Register a maintenance mode event listener. * * @param \Closure $callback * @return void * @static */ public static function down($callback){ \Illuminate\Foundation\Application::down($callback); } /** * Throw an HttpException with the given data. * * @param int $code * @param string $message * @param array $headers * @return void * @throws \Symfony\Component\HttpKernel\Exception\HttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @static */ public static function abort($code, $message = '', $headers = array()){ \Illuminate\Foundation\Application::abort($code, $message, $headers); } /** * Register a 404 error handler. * * @param \Closure $callback * @return void * @static */ public static function missing($callback){ \Illuminate\Foundation\Application::missing($callback); } /** * Register an application error handler. * * @param \Closure $callback * @return void * @static */ public static function error($callback){ \Illuminate\Foundation\Application::error($callback); } /** * Register an error handler at the bottom of the stack. * * @param \Closure $callback * @return void * @static */ public static function pushError($callback){ \Illuminate\Foundation\Application::pushError($callback); } /** * Register an error handler for fatal errors. * * @param \Closure $callback * @return void * @static */ public static function fatal($callback){ \Illuminate\Foundation\Application::fatal($callback); } /** * Get the configuration loader instance. * * @return \Illuminate\Config\LoaderInterface * @static */ public static function getConfigLoader(){ return \Illuminate\Foundation\Application::getConfigLoader(); } /** * Get the environment variables loader instance. * * @return \Illuminate\Config\EnvironmentVariablesLoaderInterface * @static */ public static function getEnvironmentVariablesLoader(){ return \Illuminate\Foundation\Application::getEnvironmentVariablesLoader(); } /** * Get the service provider repository instance. * * @return \Illuminate\Foundation\ProviderRepository * @static */ public static function getProviderRepository(){ return \Illuminate\Foundation\Application::getProviderRepository(); } /** * Get the service providers that have been loaded. * * @return array * @static */ public static function getLoadedProviders(){ return \Illuminate\Foundation\Application::getLoadedProviders(); } /** * Set the application's deferred services. * * @param array $services * @return void * @static */ public static function setDeferredServices($services){ \Illuminate\Foundation\Application::setDeferredServices($services); } /** * Determine if the given service is a deferred service. * * @param string $service * @return bool * @static */ public static function isDeferredService($service){ return \Illuminate\Foundation\Application::isDeferredService($service); } /** * Get or set the request class for the application. * * @param string $class * @return string * @static */ public static function requestClass($class = null){ return \Illuminate\Foundation\Application::requestClass($class); } /** * Set the application request for the console environment. * * @return void * @static */ public static function setRequestForConsoleEnvironment(){ \Illuminate\Foundation\Application::setRequestForConsoleEnvironment(); } /** * Call a method on the default request class. * * @param string $method * @param array $parameters * @return mixed * @static */ public static function onRequest($method, $parameters = array()){ return \Illuminate\Foundation\Application::onRequest($method, $parameters); } /** * Get the current application locale. * * @return string * @static */ public static function getLocale(){ return \Illuminate\Foundation\Application::getLocale(); } /** * Set the current application locale. * * @param string $locale * @return void * @static */ public static function setLocale($locale){ \Illuminate\Foundation\Application::setLocale($locale); } /** * Register the core class aliases in the container. * * @return void * @static */ public static function registerCoreContainerAliases(){ \Illuminate\Foundation\Application::registerCoreContainerAliases(); } /** * Determine if the given abstract type has been resolved. * * @param string $abstract * @return bool * @static */ public static function resolved($abstract){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::resolved($abstract); } /** * Determine if a given string is an alias. * * @param string $name * @return bool * @static */ public static function isAlias($name){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::isAlias($name); } /** * Register a binding with the container. * * @param string|array $abstract * @param \Closure|string|null $concrete * @param bool $shared * @return void * @static */ public static function bind($abstract, $concrete = null, $shared = false){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::bind($abstract, $concrete, $shared); } /** * Register a binding if it hasn't already been registered. * * @param string $abstract * @param \Closure|string|null $concrete * @param bool $shared * @return void * @static */ public static function bindIf($abstract, $concrete = null, $shared = false){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::bindIf($abstract, $concrete, $shared); } /** * Register a shared binding in the container. * * @param string $abstract * @param \Closure|string|null $concrete * @return void * @static */ public static function singleton($abstract, $concrete = null){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::singleton($abstract, $concrete); } /** * Wrap a Closure such that it is shared. * * @param \Closure $closure * @return \Closure * @static */ public static function share($closure){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::share($closure); } /** * Bind a shared Closure into the container. * * @param string $abstract * @param \Closure $closure * @return void * @static */ public static function bindShared($abstract, $closure){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::bindShared($abstract, $closure); } /** * Register an existing instance as shared in the container. * * @param string $abstract * @param mixed $instance * @return void * @static */ public static function instance($abstract, $instance){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::instance($abstract, $instance); } /** * Alias a type to a shorter name. * * @param string $abstract * @param string $alias * @return void * @static */ public static function alias($abstract, $alias){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::alias($abstract, $alias); } /** * Bind a new callback to an abstract's rebind event. * * @param string $abstract * @param \Closure $callback * @return mixed * @static */ public static function rebinding($abstract, $callback){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::rebinding($abstract, $callback); } /** * Refresh an instance on the given target and method. * * @param string $abstract * @param mixed $target * @param string $method * @return mixed * @static */ public static function refresh($abstract, $target, $method){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::refresh($abstract, $target, $method); } /** * Instantiate a concrete instance of the given type. * * @param string $concrete * @param array $parameters * @return mixed * @throws BindingResolutionException * @static */ public static function build($concrete, $parameters = array()){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::build($concrete, $parameters); } /** * Register a new resolving callback. * * @param string $abstract * @param \Closure $callback * @return void * @static */ public static function resolving($abstract, $callback){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::resolving($abstract, $callback); } /** * Register a new resolving callback for all types. * * @param \Closure $callback * @return void * @static */ public static function resolvingAny($callback){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::resolvingAny($callback); } /** * Determine if a given type is shared. * * @param string $abstract * @return bool * @static */ public static function isShared($abstract){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::isShared($abstract); } /** * Get the container's bindings. * * @return array * @static */ public static function getBindings(){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::getBindings(); } /** * Remove a resolved instance from the instance cache. * * @param string $abstract * @return void * @static */ public static function forgetInstance($abstract){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::forgetInstance($abstract); } /** * Clear all of the instances from the container. * * @return void * @static */ public static function forgetInstances(){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::forgetInstances(); } /** * Determine if a given offset exists. * * @param string $key * @return bool * @static */ public static function offsetExists($key){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::offsetExists($key); } /** * Get the value at a given offset. * * @param string $key * @return mixed * @static */ public static function offsetGet($key){ //Method inherited from \Illuminate\Container\Container return \Illuminate\Foundation\Application::offsetGet($key); } /** * Set the value at a given offset. * * @param string $key * @param mixed $value * @return void * @static */ public static function offsetSet($key, $value){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::offsetSet($key, $value); } /** * Unset the value at a given offset. * * @param string $key * @return void * @static */ public static function offsetUnset($key){ //Method inherited from \Illuminate\Container\Container \Illuminate\Foundation\Application::offsetUnset($key); } } class Artisan extends \Illuminate\Support\Facades\Artisan{ /** * Create and boot a new Console application. * * @param \Illuminate\Foundation\Application $app * @return \Illuminate\Console\Application * @static */ public static function start($app){ return \Illuminate\Console\Application::start($app); } /** * Create a new Console application. * * @param \Illuminate\Foundation\Application $app * @return \Illuminate\Console\Application * @static */ public static function make($app){ return \Illuminate\Console\Application::make($app); } /** * Boot the Console application. * * @return $this * @static */ public static function boot(){ return \Illuminate\Console\Application::boot(); } /** * Run an Artisan console command by name. * * @param string $command * @param array $parameters * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void * @static */ public static function call($command, $parameters = array(), $output = null){ \Illuminate\Console\Application::call($command, $parameters, $output); } /** * Add a command to the console. * * @param \Symfony\Component\Console\Command\Command $command * @return \Symfony\Component\Console\Command\Command * @static */ public static function add($command){ return \Illuminate\Console\Application::add($command); } /** * Add a command, resolving through the application. * * @param string $command * @return \Symfony\Component\Console\Command\Command * @static */ public static function resolve($command){ return \Illuminate\Console\Application::resolve($command); } /** * Resolve an array of commands through the application. * * @param array|mixed $commands * @return void * @static */ public static function resolveCommands($commands){ \Illuminate\Console\Application::resolveCommands($commands); } /** * Render the given exception. * * @param \Exception $e * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void * @static */ public static function renderException($e, $output){ \Illuminate\Console\Application::renderException($e, $output); } /** * Set the exception handler instance. * * @param \Illuminate\Exception\Handler $handler * @return $this * @static */ public static function setExceptionHandler($handler){ return \Illuminate\Console\Application::setExceptionHandler($handler); } /** * Set the Laravel application instance. * * @param \Illuminate\Foundation\Application $laravel * @return $this * @static */ public static function setLaravel($laravel){ return \Illuminate\Console\Application::setLaravel($laravel); } /** * Set whether the Console app should auto-exit when done. * * @param bool $boolean * @return $this * @static */ public static function setAutoExit($boolean){ return \Illuminate\Console\Application::setAutoExit($boolean); } /** * * * @static */ public static function setDispatcher($dispatcher){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setDispatcher($dispatcher); } /** * Runs the current application. * * @param \Symfony\Component\Console\InputInterface $input An Input instance * @param \Symfony\Component\Console\OutputInterface $output An Output instance * @return int 0 if everything went fine, or an error code * @throws \Exception When doRun returns Exception * @api * @static */ public static function run($input = null, $output = null){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::run($input, $output); } /** * Runs the current application. * * @param \Symfony\Component\Console\InputInterface $input An Input instance * @param \Symfony\Component\Console\OutputInterface $output An Output instance * @return int 0 if everything went fine, or an error code * @static */ public static function doRun($input, $output){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::doRun($input, $output); } /** * Set a helper set to be used with the command. * * @param \Symfony\Component\Console\HelperSet $helperSet The helper set * @api * @static */ public static function setHelperSet($helperSet){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setHelperSet($helperSet); } /** * Get the helper set associated with the command. * * @return \Symfony\Component\Console\HelperSet The HelperSet instance associated with this command * @api * @static */ public static function getHelperSet(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getHelperSet(); } /** * Set an input definition set to be used with this application. * * @param \Symfony\Component\Console\InputDefinition $definition The input definition * @api * @static */ public static function setDefinition($definition){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setDefinition($definition); } /** * Gets the InputDefinition related to this Application. * * @return \Symfony\Component\Console\InputDefinition The InputDefinition instance * @static */ public static function getDefinition(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getDefinition(); } /** * Gets the help message. * * @return string A help message. * @static */ public static function getHelp(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getHelp(); } /** * Sets whether to catch exceptions or not during commands execution. * * @param bool $boolean Whether to catch exceptions or not during commands execution * @api * @static */ public static function setCatchExceptions($boolean){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setCatchExceptions($boolean); } /** * Gets the name of the application. * * @return string The application name * @api * @static */ public static function getName(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getName(); } /** * Sets the application name. * * @param string $name The application name * @api * @static */ public static function setName($name){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setName($name); } /** * Gets the application version. * * @return string The application version * @api * @static */ public static function getVersion(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getVersion(); } /** * Sets the application version. * * @param string $version The application version * @api * @static */ public static function setVersion($version){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setVersion($version); } /** * Returns the long version of the application. * * @return string The long application version * @api * @static */ public static function getLongVersion(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getLongVersion(); } /** * Registers a new command. * * @param string $name The command name * @return \Symfony\Component\Console\Command The newly created command * @api * @static */ public static function register($name){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::register($name); } /** * Adds an array of command objects. * * @param \Symfony\Component\Console\Command[] $commands An array of commands * @api * @static */ public static function addCommands($commands){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::addCommands($commands); } /** * Returns a registered command by name or alias. * * @param string $name The command name or alias * @return \Symfony\Component\Console\Command A Command object * @throws \InvalidArgumentException When command name given does not exist * @api * @static */ public static function get($name){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::get($name); } /** * Returns true if the command exists, false otherwise. * * @param string $name The command name or alias * @return bool true if the command exists, false otherwise * @api * @static */ public static function has($name){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::has($name); } /** * Returns an array of all unique namespaces used by currently registered commands. * * It does not returns the global namespace which always exists. * * @return array An array of namespaces * @static */ public static function getNamespaces(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getNamespaces(); } /** * Finds a registered namespace by a name or an abbreviation. * * @param string $namespace A namespace or abbreviation to search for * @return string A registered namespace * @throws \InvalidArgumentException When namespace is incorrect or ambiguous * @static */ public static function findNamespace($namespace){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::findNamespace($namespace); } /** * Finds a command by name or alias. * * Contrary to get, this command tries to find the best * match if you give it an abbreviation of a name or alias. * * @param string $name A command name or a command alias * @return \Symfony\Component\Console\Command A Command instance * @throws \InvalidArgumentException When command name is incorrect or ambiguous * @api * @static */ public static function find($name){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::find($name); } /** * Gets the commands (registered in the given namespace if provided). * * The array keys are the full names and the values the command instances. * * @param string $namespace A namespace name * @return \Symfony\Component\Console\Command[] An array of Command instances * @api * @static */ public static function all($namespace = null){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::all($namespace); } /** * Returns an array of possible abbreviations given a set of names. * * @param array $names An array of names * @return array An array of abbreviations * @static */ public static function getAbbreviations($names){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getAbbreviations($names); } /** * Returns a text representation of the Application. * * @param string $namespace An optional namespace name * @param bool $raw Whether to return raw command list * @return string A string representing the Application * @deprecated Deprecated since version 2.3, to be removed in 3.0. * @static */ public static function asText($namespace = null, $raw = false){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::asText($namespace, $raw); } /** * Returns an XML representation of the Application. * * @param string $namespace An optional namespace name * @param bool $asDom Whether to return a DOM or an XML string * @return string|\DOMDocument An XML string representing the Application * @deprecated Deprecated since version 2.3, to be removed in 3.0. * @static */ public static function asXml($namespace = null, $asDom = false){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::asXml($namespace, $asDom); } /** * Tries to figure out the terminal dimensions based on the current environment. * * @return array Array containing width and height * @static */ public static function getTerminalDimensions(){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::getTerminalDimensions(); } /** * Sets terminal dimensions. * * Can be useful to force terminal dimensions for functional tests. * * @param int $width The width * @param int $height The height * @return \Symfony\Component\Console\Application The current application * @static */ public static function setTerminalDimensions($width, $height){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setTerminalDimensions($width, $height); } /** * Returns the namespace part of the command name. * * This method is not part of public API and should not be used directly. * * @param string $name The full name of the command * @param string $limit The maximum number of parts of the namespace * @return string The namespace of the command * @static */ public static function extractNamespace($name, $limit = null){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::extractNamespace($name, $limit); } /** * Sets the default Command name. * * @param string $commandName The Command name * @static */ public static function setDefaultCommand($commandName){ //Method inherited from \Symfony\Component\Console\Application return \Illuminate\Console\Application::setDefaultCommand($commandName); } } class Auth extends \Illuminate\Support\Facades\Auth{ /** * Create an instance of the database driver. * * @return \Illuminate\Auth\Guard * @static */ public static function createDatabaseDriver(){ return \Illuminate\Auth\AuthManager::createDatabaseDriver(); } /** * Create an instance of the Eloquent driver. * * @return \Illuminate\Auth\Guard * @static */ public static function createEloquentDriver(){ return \Illuminate\Auth\AuthManager::createEloquentDriver(); } /** * Get the default authentication driver name. * * @return string * @static */ public static function getDefaultDriver(){ return \Illuminate\Auth\AuthManager::getDefaultDriver(); } /** * Set the default authentication driver name. * * @param string $name * @return void * @static */ public static function setDefaultDriver($name){ \Illuminate\Auth\AuthManager::setDefaultDriver($name); } /** * Get a driver instance. * * @param string $driver * @return mixed * @static */ public static function driver($driver = null){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Auth\AuthManager::driver($driver); } /** * Register a custom driver creator Closure. * * @param string $driver * @param \Closure $callback * @return $this * @static */ public static function extend($driver, $callback){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Auth\AuthManager::extend($driver, $callback); } /** * Get all of the created "drivers". * * @return array * @static */ public static function getDrivers(){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Auth\AuthManager::getDrivers(); } /** * Determine if the current user is authenticated. * * @return bool * @static */ public static function check(){ return \Illuminate\Auth\Guard::check(); } /** * Determine if the current user is a guest. * * @return bool * @static */ public static function guest(){ return \Illuminate\Auth\Guard::guest(); } /** * Get the currently authenticated user. * * @return \User|null * @static */ public static function user(){ return \Illuminate\Auth\Guard::user(); } /** * Get the ID for the currently authenticated user. * * @return int|null * @static */ public static function id(){ return \Illuminate\Auth\Guard::id(); } /** * Log a user into the application without sessions or cookies. * * @param array $credentials * @return bool * @static */ public static function once($credentials = array()){ return \Illuminate\Auth\Guard::once($credentials); } /** * Validate a user's credentials. * * @param array $credentials * @return bool * @static */ public static function validate($credentials = array()){ return \Illuminate\Auth\Guard::validate($credentials); } /** * Attempt to authenticate using HTTP Basic Auth. * * @param string $field * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\Response|null * @static */ public static function basic($field = 'email', $request = null){ return \Illuminate\Auth\Guard::basic($field, $request); } /** * Perform a stateless HTTP Basic login attempt. * * @param string $field * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\Response|null * @static */ public static function onceBasic($field = 'email', $request = null){ return \Illuminate\Auth\Guard::onceBasic($field, $request); } /** * Attempt to authenticate a user using the given credentials. * * @param array $credentials * @param bool $remember * @param bool $login * @return bool * @static */ public static function attempt($credentials = array(), $remember = false, $login = true){ return \Illuminate\Auth\Guard::attempt($credentials, $remember, $login); } /** * Register an authentication attempt event listener. * * @param mixed $callback * @return void * @static */ public static function attempting($callback){ \Illuminate\Auth\Guard::attempting($callback); } /** * Log a user into the application. * * @param \Illuminate\Auth\UserInterface $user * @param bool $remember * @return void * @static */ public static function login($user, $remember = false){ \Illuminate\Auth\Guard::login($user, $remember); } /** * Log the given user ID into the application. * * @param mixed $id * @param bool $remember * @return \User * @static */ public static function loginUsingId($id, $remember = false){ return \Illuminate\Auth\Guard::loginUsingId($id, $remember); } /** * Log the given user ID into the application without sessions or cookies. * * @param mixed $id * @return bool * @static */ public static function onceUsingId($id){ return \Illuminate\Auth\Guard::onceUsingId($id); } /** * Log the user out of the application. * * @return void * @static */ public static function logout(){ \Illuminate\Auth\Guard::logout(); } /** * Get the cookie creator instance used by the guard. * * @return \Illuminate\Cookie\CookieJar * @throws \RuntimeException * @static */ public static function getCookieJar(){ return \Illuminate\Auth\Guard::getCookieJar(); } /** * Set the cookie creator instance used by the guard. * * @param \Illuminate\Cookie\CookieJar $cookie * @return void * @static */ public static function setCookieJar($cookie){ \Illuminate\Auth\Guard::setCookieJar($cookie); } /** * Get the event dispatcher instance. * * @return \Illuminate\Events\Dispatcher * @static */ public static function getDispatcher(){ return \Illuminate\Auth\Guard::getDispatcher(); } /** * Set the event dispatcher instance. * * @param \Illuminate\Events\Dispatcher * @return void * @static */ public static function setDispatcher($events){ \Illuminate\Auth\Guard::setDispatcher($events); } /** * Get the session store used by the guard. * * @return \Illuminate\Session\Store * @static */ public static function getSession(){ return \Illuminate\Auth\Guard::getSession(); } /** * Get the user provider used by the guard. * * @return \Illuminate\Auth\Guard * @static */ public static function getProvider(){ return \Illuminate\Auth\Guard::getProvider(); } /** * Set the user provider used by the guard. * * @param \Illuminate\Auth\UserProviderInterface $provider * @return void * @static */ public static function setProvider($provider){ \Illuminate\Auth\Guard::setProvider($provider); } /** * Return the currently cached user of the application. * * @return \User|null * @static */ public static function getUser(){ return \Illuminate\Auth\Guard::getUser(); } /** * Set the current user of the application. * * @param \Illuminate\Auth\UserInterface $user * @return void * @static */ public static function setUser($user){ \Illuminate\Auth\Guard::setUser($user); } /** * Get the current request instance. * * @return \Symfony\Component\HttpFoundation\Request * @static */ public static function getRequest(){ return \Illuminate\Auth\Guard::getRequest(); } /** * Set the current request instance. * * @param \Symfony\Component\HttpFoundation\Request * @return $this * @static */ public static function setRequest($request){ return \Illuminate\Auth\Guard::setRequest($request); } /** * Get the last user we attempted to authenticate. * * @return \User * @static */ public static function getLastAttempted(){ return \Illuminate\Auth\Guard::getLastAttempted(); } /** * Get a unique identifier for the auth session value. * * @return string * @static */ public static function getName(){ return \Illuminate\Auth\Guard::getName(); } /** * Get the name of the cookie used to store the "recaller". * * @return string * @static */ public static function getRecallerName(){ return \Illuminate\Auth\Guard::getRecallerName(); } /** * Determine if the user was authenticated via "remember me" cookie. * * @return bool * @static */ public static function viaRemember(){ return \Illuminate\Auth\Guard::viaRemember(); } } class Blade extends \Illuminate\Support\Facades\Blade{ /** * Compile the view at the given path. * * @param string $path * @return void * @static */ public static function compile($path = null){ \Illuminate\View\Compilers\BladeCompiler::compile($path); } /** * Get the path currently being compiled. * * @return string * @static */ public static function getPath(){ return \Illuminate\View\Compilers\BladeCompiler::getPath(); } /** * Set the path currently being compiled. * * @param string $path * @return void * @static */ public static function setPath($path){ \Illuminate\View\Compilers\BladeCompiler::setPath($path); } /** * Compile the given Blade template contents. * * @param string $value * @return string * @static */ public static function compileString($value){ return \Illuminate\View\Compilers\BladeCompiler::compileString($value); } /** * Compile the default values for the echo statement. * * @param string $value * @return string * @static */ public static function compileEchoDefaults($value){ return \Illuminate\View\Compilers\BladeCompiler::compileEchoDefaults($value); } /** * Register a custom Blade compiler. * * @param \Closure $compiler * @return void * @static */ public static function extend($compiler){ \Illuminate\View\Compilers\BladeCompiler::extend($compiler); } /** * Get the regular expression for a generic Blade function. * * @param string $function * @return string * @static */ public static function createMatcher($function){ return \Illuminate\View\Compilers\BladeCompiler::createMatcher($function); } /** * Get the regular expression for a generic Blade function. * * @param string $function * @return string * @static */ public static function createOpenMatcher($function){ return \Illuminate\View\Compilers\BladeCompiler::createOpenMatcher($function); } /** * Create a plain Blade matcher. * * @param string $function * @return string * @static */ public static function createPlainMatcher($function){ return \Illuminate\View\Compilers\BladeCompiler::createPlainMatcher($function); } /** * Sets the content tags used for the compiler. * * @param string $openTag * @param string $closeTag * @param bool $escaped * @return void * @static */ public static function setContentTags($openTag, $closeTag, $escaped = false){ \Illuminate\View\Compilers\BladeCompiler::setContentTags($openTag, $closeTag, $escaped); } /** * Sets the escaped content tags used for the compiler. * * @param string $openTag * @param string $closeTag * @return void * @static */ public static function setEscapedContentTags($openTag, $closeTag){ \Illuminate\View\Compilers\BladeCompiler::setEscapedContentTags($openTag, $closeTag); } /** * Gets the content tags used for the compiler. * * @return string * @static */ public static function getContentTags(){ return \Illuminate\View\Compilers\BladeCompiler::getContentTags(); } /** * Gets the escaped content tags used for the compiler. * * @return string * @static */ public static function getEscapedContentTags(){ return \Illuminate\View\Compilers\BladeCompiler::getEscapedContentTags(); } /** * Get the path to the compiled version of a view. * * @param string $path * @return string * @static */ public static function getCompiledPath($path){ //Method inherited from \Illuminate\View\Compilers\Compiler return \Illuminate\View\Compilers\BladeCompiler::getCompiledPath($path); } /** * Determine if the view at the given path is expired. * * @param string $path * @return bool * @static */ public static function isExpired($path){ //Method inherited from \Illuminate\View\Compilers\Compiler return \Illuminate\View\Compilers\BladeCompiler::isExpired($path); } } class Cache extends \Illuminate\Support\Facades\Cache{ /** * Get the cache "prefix" value. * * @return string * @static */ public static function getPrefix(){ return \Illuminate\Cache\CacheManager::getPrefix(); } /** * Set the cache "prefix" value. * * @param string $name * @return void * @static */ public static function setPrefix($name){ \Illuminate\Cache\CacheManager::setPrefix($name); } /** * Get the default cache driver name. * * @return string * @static */ public static function getDefaultDriver(){ return \Illuminate\Cache\CacheManager::getDefaultDriver(); } /** * Set the default cache driver name. * * @param string $name * @return void * @static */ public static function setDefaultDriver($name){ \Illuminate\Cache\CacheManager::setDefaultDriver($name); } /** * Get a driver instance. * * @param string $driver * @return mixed * @static */ public static function driver($driver = null){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Cache\CacheManager::driver($driver); } /** * Register a custom driver creator Closure. * * @param string $driver * @param \Closure $callback * @return $this * @static */ public static function extend($driver, $callback){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Cache\CacheManager::extend($driver, $callback); } /** * Get all of the created "drivers". * * @return array * @static */ public static function getDrivers(){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Cache\CacheManager::getDrivers(); } /** * Determine if an item exists in the cache. * * @param string $key * @return bool * @static */ public static function has($key){ return \Illuminate\Cache\Repository::has($key); } /** * Retrieve an item from the cache by key. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function get($key, $default = null){ return \Illuminate\Cache\Repository::get($key, $default); } /** * Retrieve an item from the cache and delete it. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function pull($key, $default = null){ return \Illuminate\Cache\Repository::pull($key, $default); } /** * Store an item in the cache. * * @param string $key * @param mixed $value * @param \DateTime|int $minutes * @return void * @static */ public static function put($key, $value, $minutes){ \Illuminate\Cache\Repository::put($key, $value, $minutes); } /** * Store an item in the cache if the key does not exist. * * @param string $key * @param mixed $value * @param \DateTime|int $minutes * @return bool * @static */ public static function add($key, $value, $minutes){ return \Illuminate\Cache\Repository::add($key, $value, $minutes); } /** * Get an item from the cache, or store the default value. * * @param string $key * @param \DateTime|int $minutes * @param \Closure $callback * @return mixed * @static */ public static function remember($key, $minutes, $callback){ return \Illuminate\Cache\Repository::remember($key, $minutes, $callback); } /** * Get an item from the cache, or store the default value forever. * * @param string $key * @param \Closure $callback * @return mixed * @static */ public static function sear($key, $callback){ return \Illuminate\Cache\Repository::sear($key, $callback); } /** * Get an item from the cache, or store the default value forever. * * @param string $key * @param \Closure $callback * @return mixed * @static */ public static function rememberForever($key, $callback){ return \Illuminate\Cache\Repository::rememberForever($key, $callback); } /** * Get the default cache time. * * @return int * @static */ public static function getDefaultCacheTime(){ return \Illuminate\Cache\Repository::getDefaultCacheTime(); } /** * Set the default cache time in minutes. * * @param int $minutes * @return void * @static */ public static function setDefaultCacheTime($minutes){ \Illuminate\Cache\Repository::setDefaultCacheTime($minutes); } /** * Get the cache store implementation. * * @return \Illuminate\Cache\FileStore * @static */ public static function getStore(){ return \Illuminate\Cache\Repository::getStore(); } /** * Determine if a cached value exists. * * @param string $key * @return bool * @static */ public static function offsetExists($key){ return \Illuminate\Cache\Repository::offsetExists($key); } /** * Retrieve an item from the cache by key. * * @param string $key * @return mixed * @static */ public static function offsetGet($key){ return \Illuminate\Cache\Repository::offsetGet($key); } /** * Store an item in the cache for the default time. * * @param string $key * @param mixed $value * @return void * @static */ public static function offsetSet($key, $value){ \Illuminate\Cache\Repository::offsetSet($key, $value); } /** * Remove an item from the cache. * * @param string $key * @return void * @static */ public static function offsetUnset($key){ \Illuminate\Cache\Repository::offsetUnset($key); } /** * Register a custom macro. * * @param string $name * @param callable $macro * @return void * @static */ public static function macro($name, $macro){ \Illuminate\Cache\Repository::macro($name, $macro); } /** * Checks if macro is registered * * @param string $name * @return boolean * @static */ public static function hasMacro($name){ return \Illuminate\Cache\Repository::hasMacro($name); } /** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * @return mixed * @throws \BadMethodCallException * @static */ public static function macroCall($method, $parameters){ return \Illuminate\Cache\Repository::macroCall($method, $parameters); } /** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int * @static */ public static function increment($key, $value = 1){ return \Illuminate\Cache\FileStore::increment($key, $value); } /** * Decrement the value of an item in the cache. * * @param string $key * @param mixed $value * @return int * @static */ public static function decrement($key, $value = 1){ return \Illuminate\Cache\FileStore::decrement($key, $value); } /** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return void * @static */ public static function forever($key, $value){ \Illuminate\Cache\FileStore::forever($key, $value); } /** * Remove an item from the cache. * * @param string $key * @return void * @static */ public static function forget($key){ \Illuminate\Cache\FileStore::forget($key); } /** * Remove all items from the cache. * * @return void * @static */ public static function flush(){ \Illuminate\Cache\FileStore::flush(); } /** * Get the Filesystem instance. * * @return \Illuminate\Filesystem\Filesystem * @static */ public static function getFilesystem(){ return \Illuminate\Cache\FileStore::getFilesystem(); } /** * Get the working directory of the cache. * * @return string * @static */ public static function getDirectory(){ return \Illuminate\Cache\FileStore::getDirectory(); } } class ClassLoader extends \Illuminate\Support\ClassLoader{ } class Config extends \Illuminate\Support\Facades\Config{ /** * Determine if the given configuration value exists. * * @param string $key * @return bool * @static */ public static function has($key){ return \Illuminate\Config\Repository::has($key); } /** * Determine if a configuration group exists. * * @param string $key * @return bool * @static */ public static function hasGroup($key){ return \Illuminate\Config\Repository::hasGroup($key); } /** * Get the specified configuration value. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function get($key, $default = null){ return \Illuminate\Config\Repository::get($key, $default); } /** * Set a given configuration value. * * @param string $key * @param mixed $value * @return void * @static */ public static function set($key, $value){ \Illuminate\Config\Repository::set($key, $value); } /** * Register a package for cascading configuration. * * @param string $package * @param string $hint * @param string $namespace * @return void * @static */ public static function package($package, $hint, $namespace = null){ \Illuminate\Config\Repository::package($package, $hint, $namespace); } /** * Register an after load callback for a given namespace. * * @param string $namespace * @param \Closure $callback * @return void * @static */ public static function afterLoading($namespace, $callback){ \Illuminate\Config\Repository::afterLoading($namespace, $callback); } /** * Add a new namespace to the loader. * * @param string $namespace * @param string $hint * @return void * @static */ public static function addNamespace($namespace, $hint){ \Illuminate\Config\Repository::addNamespace($namespace, $hint); } /** * Returns all registered namespaces with the config * loader. * * @return array * @static */ public static function getNamespaces(){ return \Illuminate\Config\Repository::getNamespaces(); } /** * Get the loader implementation. * * @return \Illuminate\Config\LoaderInterface * @static */ public static function getLoader(){ return \Illuminate\Config\Repository::getLoader(); } /** * Set the loader implementation. * * @param \Illuminate\Config\LoaderInterface $loader * @return void * @static */ public static function setLoader($loader){ \Illuminate\Config\Repository::setLoader($loader); } /** * Get the current configuration environment. * * @return string * @static */ public static function getEnvironment(){ return \Illuminate\Config\Repository::getEnvironment(); } /** * Get the after load callback array. * * @return array * @static */ public static function getAfterLoadCallbacks(){ return \Illuminate\Config\Repository::getAfterLoadCallbacks(); } /** * Get all of the configuration items. * * @return array * @static */ public static function getItems(){ return \Illuminate\Config\Repository::getItems(); } /** * Determine if the given configuration option exists. * * @param string $key * @return bool * @static */ public static function offsetExists($key){ return \Illuminate\Config\Repository::offsetExists($key); } /** * Get a configuration option. * * @param string $key * @return mixed * @static */ public static function offsetGet($key){ return \Illuminate\Config\Repository::offsetGet($key); } /** * Set a configuration option. * * @param string $key * @param mixed $value * @return void * @static */ public static function offsetSet($key, $value){ \Illuminate\Config\Repository::offsetSet($key, $value); } /** * Unset a configuration option. * * @param string $key * @return void * @static */ public static function offsetUnset($key){ \Illuminate\Config\Repository::offsetUnset($key); } /** * Parse a key into namespace, group, and item. * * @param string $key * @return array * @static */ public static function parseKey($key){ //Method inherited from \Illuminate\Support\NamespacedItemResolver return \Illuminate\Config\Repository::parseKey($key); } /** * Set the parsed value of a key. * * @param string $key * @param array $parsed * @return void * @static */ public static function setParsedKey($key, $parsed){ //Method inherited from \Illuminate\Support\NamespacedItemResolver \Illuminate\Config\Repository::setParsedKey($key, $parsed); } } class Controller extends \Illuminate\Routing\Controller{ } class Cookie extends \Illuminate\Support\Facades\Cookie{ /** * Create a new cookie instance. * * @param string $name * @param string $value * @param int $minutes * @param string $path * @param string $domain * @param bool $secure * @param bool $httpOnly * @return \Symfony\Component\HttpFoundation\Cookie * @static */ public static function make($name, $value, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = true){ return \Illuminate\Cookie\CookieJar::make($name, $value, $minutes, $path, $domain, $secure, $httpOnly); } /** * Create a cookie that lasts "forever" (five years). * * @param string $name * @param string $value * @param string $path * @param string $domain * @param bool $secure * @param bool $httpOnly * @return \Symfony\Component\HttpFoundation\Cookie * @static */ public static function forever($name, $value, $path = null, $domain = null, $secure = false, $httpOnly = true){ return \Illuminate\Cookie\CookieJar::forever($name, $value, $path, $domain, $secure, $httpOnly); } /** * Expire the given cookie. * * @param string $name * @param string $path * @param string $domain * @return \Symfony\Component\HttpFoundation\Cookie * @static */ public static function forget($name, $path = null, $domain = null){ return \Illuminate\Cookie\CookieJar::forget($name, $path, $domain); } /** * Determine if a cookie has been queued. * * @param string $key * @return bool * @static */ public static function hasQueued($key){ return \Illuminate\Cookie\CookieJar::hasQueued($key); } /** * Get a queued cookie instance. * * @param string $key * @param mixed $default * @return \Symfony\Component\HttpFoundation\Cookie * @static */ public static function queued($key, $default = null){ return \Illuminate\Cookie\CookieJar::queued($key, $default); } /** * Queue a cookie to send with the next response. * * @param mixed * @return void * @static */ public static function queue(){ \Illuminate\Cookie\CookieJar::queue(); } /** * Remove a cookie from the queue. * * @param string $name * @static */ public static function unqueue($name){ return \Illuminate\Cookie\CookieJar::unqueue($name); } /** * Set the default path and domain for the jar. * * @param string $path * @param string $domain * @return $this * @static */ public static function setDefaultPathAndDomain($path, $domain){ return \Illuminate\Cookie\CookieJar::setDefaultPathAndDomain($path, $domain); } /** * Get the cookies which have been queued for the next request * * @return array * @static */ public static function getQueuedCookies(){ return \Illuminate\Cookie\CookieJar::getQueuedCookies(); } } class Crypt extends \Illuminate\Support\Facades\Crypt{ /** * Encrypt the given value. * * @param string $value * @return string * @static */ public static function encrypt($value){ return \Illuminate\Encryption\Encrypter::encrypt($value); } /** * Decrypt the given value. * * @param string $payload * @return string * @static */ public static function decrypt($payload){ return \Illuminate\Encryption\Encrypter::decrypt($payload); } /** * Set the encryption key. * * @param string $key * @return void * @static */ public static function setKey($key){ \Illuminate\Encryption\Encrypter::setKey($key); } /** * Set the encryption cipher. * * @param string $cipher * @return void * @static */ public static function setCipher($cipher){ \Illuminate\Encryption\Encrypter::setCipher($cipher); } /** * Set the encryption mode. * * @param string $mode * @return void * @static */ public static function setMode($mode){ \Illuminate\Encryption\Encrypter::setMode($mode); } } class DB extends \Illuminate\Support\Facades\DB{ /** * Get a database connection instance. * * @param string $name * @return \Illuminate\Database\Connection * @static */ public static function connection($name = null){ return \Illuminate\Database\DatabaseManager::connection($name); } /** * Disconnect from the given database and remove from local cache. * * @param string $name * @return void * @static */ public static function purge($name = null){ \Illuminate\Database\DatabaseManager::purge($name); } /** * Disconnect from the given database. * * @param string $name * @return void * @static */ public static function disconnect($name = null){ \Illuminate\Database\DatabaseManager::disconnect($name); } /** * Reconnect to the given database. * * @param string $name * @return \Illuminate\Database\Connection * @static */ public static function reconnect($name = null){ return \Illuminate\Database\DatabaseManager::reconnect($name); } /** * Get the default connection name. * * @return string * @static */ public static function getDefaultConnection(){ return \Illuminate\Database\DatabaseManager::getDefaultConnection(); } /** * Set the default connection name. * * @param string $name * @return void * @static */ public static function setDefaultConnection($name){ \Illuminate\Database\DatabaseManager::setDefaultConnection($name); } /** * Register an extension connection resolver. * * @param string $name * @param callable $resolver * @return void * @static */ public static function extend($name, $resolver){ \Illuminate\Database\DatabaseManager::extend($name, $resolver); } /** * Return all of the created connections. * * @return array * @static */ public static function getConnections(){ return \Illuminate\Database\DatabaseManager::getConnections(); } /** * Get a schema builder instance for the connection. * * @return \Illuminate\Database\Schema\MySqlBuilder * @static */ public static function getSchemaBuilder(){ return \Illuminate\Database\MySqlConnection::getSchemaBuilder(); } /** * Set the query grammar to the default implementation. * * @return void * @static */ public static function useDefaultQueryGrammar(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::useDefaultQueryGrammar(); } /** * Set the schema grammar to the default implementation. * * @return void * @static */ public static function useDefaultSchemaGrammar(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::useDefaultSchemaGrammar(); } /** * Set the query post processor to the default implementation. * * @return void * @static */ public static function useDefaultPostProcessor(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::useDefaultPostProcessor(); } /** * Begin a fluent query against a database table. * * @param string $table * @return \Illuminate\Database\Query\Builder * @static */ public static function table($table){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::table($table); } /** * Get a new raw query expression. * * @param mixed $value * @return \Illuminate\Database\Query\Expression * @static */ public static function raw($value){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::raw($value); } /** * Run a select statement and return a single result. * * @param string $query * @param array $bindings * @return mixed * @static */ public static function selectOne($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::selectOne($query, $bindings); } /** * Run a select statement against the database. * * @param string $query * @param array $bindings * @return array * @static */ public static function selectFromWriteConnection($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::selectFromWriteConnection($query, $bindings); } /** * Run a select statement against the database. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return array * @static */ public static function select($query, $bindings = array(), $useReadPdo = true){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::select($query, $bindings, $useReadPdo); } /** * Run an insert statement against the database. * * @param string $query * @param array $bindings * @return bool * @static */ public static function insert($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::insert($query, $bindings); } /** * Run an update statement against the database. * * @param string $query * @param array $bindings * @return int * @static */ public static function update($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::update($query, $bindings); } /** * Run a delete statement against the database. * * @param string $query * @param array $bindings * @return int * @static */ public static function delete($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::delete($query, $bindings); } /** * Execute an SQL statement and return the boolean result. * * @param string $query * @param array $bindings * @return bool * @static */ public static function statement($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::statement($query, $bindings); } /** * Run an SQL statement and get the number of rows affected. * * @param string $query * @param array $bindings * @return int * @static */ public static function affectingStatement($query, $bindings = array()){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::affectingStatement($query, $bindings); } /** * Run a raw, unprepared query against the PDO connection. * * @param string $query * @return bool * @static */ public static function unprepared($query){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::unprepared($query); } /** * Prepare the query bindings for execution. * * @param array $bindings * @return array * @static */ public static function prepareBindings($bindings){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::prepareBindings($bindings); } /** * Execute a Closure within a transaction. * * @param \Closure $callback * @return mixed * @throws \Exception * @static */ public static function transaction($callback){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::transaction($callback); } /** * Start a new database transaction. * * @return void * @static */ public static function beginTransaction(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::beginTransaction(); } /** * Commit the active database transaction. * * @return void * @static */ public static function commit(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::commit(); } /** * Rollback the active database transaction. * * @return void * @static */ public static function rollBack(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::rollBack(); } /** * Get the number of active transactions. * * @return int * @static */ public static function transactionLevel(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::transactionLevel(); } /** * Execute the given callback in "dry run" mode. * * @param \Closure $callback * @return array * @static */ public static function pretend($callback){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::pretend($callback); } /** * Log a query in the connection's query log. * * @param string $query * @param array $bindings * @param float|null $time * @return void * @static */ public static function logQuery($query, $bindings, $time = null){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::logQuery($query, $bindings, $time); } /** * Register a database query listener with the connection. * * @param \Closure $callback * @return void * @static */ public static function listen($callback){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::listen($callback); } /** * Get a Doctrine Schema Column instance. * * @param string $table * @param string $column * @return \Doctrine\DBAL\Schema\Column * @static */ public static function getDoctrineColumn($table, $column){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getDoctrineColumn($table, $column); } /** * Get the Doctrine DBAL schema manager for the connection. * * @return \Doctrine\DBAL\Schema\AbstractSchemaManager * @static */ public static function getDoctrineSchemaManager(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getDoctrineSchemaManager(); } /** * Get the Doctrine DBAL database connection instance. * * @return \Doctrine\DBAL\Connection * @static */ public static function getDoctrineConnection(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getDoctrineConnection(); } /** * Get the current PDO connection. * * @return \PDO * @static */ public static function getPdo(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getPdo(); } /** * Get the current PDO connection used for reading. * * @return \PDO * @static */ public static function getReadPdo(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getReadPdo(); } /** * Set the PDO connection. * * @param \PDO|null $pdo * @return $this * @static */ public static function setPdo($pdo){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::setPdo($pdo); } /** * Set the PDO connection used for reading. * * @param \PDO|null $pdo * @return $this * @static */ public static function setReadPdo($pdo){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::setReadPdo($pdo); } /** * Set the reconnect instance on the connection. * * @param callable $reconnector * @return $this * @static */ public static function setReconnector($reconnector){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::setReconnector($reconnector); } /** * Get the database connection name. * * @return string|null * @static */ public static function getName(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getName(); } /** * Get an option from the configuration options. * * @param string $option * @return mixed * @static */ public static function getConfig($option){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getConfig($option); } /** * Get the PDO driver name. * * @return string * @static */ public static function getDriverName(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getDriverName(); } /** * Get the query grammar used by the connection. * * @return \Illuminate\Database\Query\Grammars\Grammar * @static */ public static function getQueryGrammar(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getQueryGrammar(); } /** * Set the query grammar used by the connection. * * @param \Illuminate\Database\Query\Grammars\Grammar * @return void * @static */ public static function setQueryGrammar($grammar){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setQueryGrammar($grammar); } /** * Get the schema grammar used by the connection. * * @return \Illuminate\Database\Query\Grammars\Grammar * @static */ public static function getSchemaGrammar(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getSchemaGrammar(); } /** * Set the schema grammar used by the connection. * * @param \Illuminate\Database\Schema\Grammars\Grammar * @return void * @static */ public static function setSchemaGrammar($grammar){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setSchemaGrammar($grammar); } /** * Get the query post processor used by the connection. * * @return \Illuminate\Database\Query\Processors\Processor * @static */ public static function getPostProcessor(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getPostProcessor(); } /** * Set the query post processor used by the connection. * * @param \Illuminate\Database\Query\Processors\Processor * @return void * @static */ public static function setPostProcessor($processor){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setPostProcessor($processor); } /** * Get the event dispatcher used by the connection. * * @return \Illuminate\Events\Dispatcher * @static */ public static function getEventDispatcher(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getEventDispatcher(); } /** * Set the event dispatcher instance on the connection. * * @param \Illuminate\Events\Dispatcher * @return void * @static */ public static function setEventDispatcher($events){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setEventDispatcher($events); } /** * Get the paginator environment instance. * * @return \Illuminate\Pagination\Factory * @static */ public static function getPaginator(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getPaginator(); } /** * Set the pagination environment instance. * * @param \Illuminate\Pagination\Factory|\Closure $paginator * @return void * @static */ public static function setPaginator($paginator){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setPaginator($paginator); } /** * Get the cache manager instance. * * @return \Illuminate\Cache\CacheManager * @static */ public static function getCacheManager(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getCacheManager(); } /** * Set the cache manager instance on the connection. * * @param \Illuminate\Cache\CacheManager|\Closure $cache * @return void * @static */ public static function setCacheManager($cache){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setCacheManager($cache); } /** * Determine if the connection in a "dry run". * * @return bool * @static */ public static function pretending(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::pretending(); } /** * Get the default fetch mode for the connection. * * @return int * @static */ public static function getFetchMode(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getFetchMode(); } /** * Set the default fetch mode for the connection. * * @param int $fetchMode * @return int * @static */ public static function setFetchMode($fetchMode){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::setFetchMode($fetchMode); } /** * Get the connection query log. * * @return array * @static */ public static function getQueryLog(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getQueryLog(); } /** * Clear the query log. * * @return void * @static */ public static function flushQueryLog(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::flushQueryLog(); } /** * Enable the query log on the connection. * * @return void * @static */ public static function enableQueryLog(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::enableQueryLog(); } /** * Disable the query log on the connection. * * @return void * @static */ public static function disableQueryLog(){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::disableQueryLog(); } /** * Determine whether we're logging queries. * * @return bool * @static */ public static function logging(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::logging(); } /** * Get the name of the connected database. * * @return string * @static */ public static function getDatabaseName(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getDatabaseName(); } /** * Set the name of the connected database. * * @param string $database * @return string * @static */ public static function setDatabaseName($database){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::setDatabaseName($database); } /** * Get the table prefix for the connection. * * @return string * @static */ public static function getTablePrefix(){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::getTablePrefix(); } /** * Set the table prefix in use by the connection. * * @param string $prefix * @return void * @static */ public static function setTablePrefix($prefix){ //Method inherited from \Illuminate\Database\Connection \Illuminate\Database\MySqlConnection::setTablePrefix($prefix); } /** * Set the table prefix and return the grammar. * * @param \Illuminate\Database\Grammar $grammar * @return \Illuminate\Database\Grammar * @static */ public static function withTablePrefix($grammar){ //Method inherited from \Illuminate\Database\Connection return \Illuminate\Database\MySqlConnection::withTablePrefix($grammar); } } class Eloquent extends \Illuminate\Database\Eloquent\Model{ /** * Find a model by its primary key. * * @param array $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static * @static */ public static function findMany($id, $columns = array()){ return \Illuminate\Database\Eloquent\Builder::findMany($id, $columns); } /** * Execute the query and get the first result. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model|static|null * @static */ public static function first($columns = array()){ return \Illuminate\Database\Eloquent\Builder::first($columns); } /** * Execute the query and get the first result or throw an exception. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model|static * @throws \Illuminate\Database\Eloquent\ModelNotFoundException * @static */ public static function firstOrFail($columns = array()){ return \Illuminate\Database\Eloquent\Builder::firstOrFail($columns); } /** * Execute the query as a "select" statement. * * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|static[] * @static */ public static function get($columns = array()){ return \Illuminate\Database\Eloquent\Builder::get($columns); } /** * Pluck a single column from the database. * * @param string $column * @return mixed * @static */ public static function pluck($column){ return \Illuminate\Database\Eloquent\Builder::pluck($column); } /** * Chunk the results of the query. * * @param int $count * @param callable $callback * @return void * @static */ public static function chunk($count, $callback){ \Illuminate\Database\Eloquent\Builder::chunk($count, $callback); } /** * Get an array with the values of a given column. * * @param string $column * @param string $key * @return array * @static */ public static function lists($column, $key = null){ return \Illuminate\Database\Eloquent\Builder::lists($column, $key); } /** * Get a paginator for the "select" statement. * * @param int $perPage * @param array $columns * @return \Illuminate\Pagination\Paginator * @static */ public static function paginate($perPage = null, $columns = array()){ return \Illuminate\Database\Eloquent\Builder::paginate($perPage, $columns); } /** * Get a paginator only supporting simple next and previous links. * * This is more efficient on larger data-sets, etc. * * @param int $perPage * @param array $columns * @return \Illuminate\Pagination\Paginator * @static */ public static function simplePaginate($perPage = null, $columns = array()){ return \Illuminate\Database\Eloquent\Builder::simplePaginate($perPage, $columns); } /** * Register a replacement for the default delete function. * * @param \Closure $callback * @return void * @static */ public static function onDelete($callback){ \Illuminate\Database\Eloquent\Builder::onDelete($callback); } /** * Get the hydrated models without eager loading. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model[] * @static */ public static function getModels($columns = array()){ return \Illuminate\Database\Eloquent\Builder::getModels($columns); } /** * Eager load the relationships for the models. * * @param array $models * @return array * @static */ public static function eagerLoadRelations($models){ return \Illuminate\Database\Eloquent\Builder::eagerLoadRelations($models); } /** * Add a basic where clause to the query. * * @param string $column * @param string $operator * @param mixed $value * @param string $boolean * @return $this * @static */ public static function where($column, $operator = null, $value = null, $boolean = 'and'){ return \Illuminate\Database\Eloquent\Builder::where($column, $operator, $value, $boolean); } /** * Add an "or where" clause to the query. * * @param string $column * @param string $operator * @param mixed $value * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function orWhere($column, $operator = null, $value = null){ return \Illuminate\Database\Eloquent\Builder::orWhere($column, $operator, $value); } /** * Add a relationship count condition to the query. * * @param string $relation * @param string $operator * @param int $count * @param string $boolean * @param \Closure|null $callback * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null){ return \Illuminate\Database\Eloquent\Builder::has($relation, $operator, $count, $boolean, $callback); } /** * Add a relationship count condition to the query. * * @param string $relation * @param string $boolean * @param \Closure|null $callback * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function doesntHave($relation, $boolean = 'and', $callback = null){ return \Illuminate\Database\Eloquent\Builder::doesntHave($relation, $boolean, $callback); } /** * Add a relationship count condition to the query with where clauses. * * @param string $relation * @param \Closure $callback * @param string $operator * @param int $count * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function whereHas($relation, $callback, $operator = '>=', $count = 1){ return \Illuminate\Database\Eloquent\Builder::whereHas($relation, $callback, $operator, $count); } /** * Add a relationship count condition to the query with where clauses. * * @param string $relation * @param \Closure|null $callback * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function whereDoesntHave($relation, $callback = null){ return \Illuminate\Database\Eloquent\Builder::whereDoesntHave($relation, $callback); } /** * Add a relationship count condition to the query with an "or". * * @param string $relation * @param string $operator * @param int $count * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function orHas($relation, $operator = '>=', $count = 1){ return \Illuminate\Database\Eloquent\Builder::orHas($relation, $operator, $count); } /** * Add a relationship count condition to the query with where clauses and an "or". * * @param string $relation * @param \Closure $callback * @param string $operator * @param int $count * @return \Illuminate\Database\Eloquent\Builder|static * @static */ public static function orWhereHas($relation, $callback, $operator = '>=', $count = 1){ return \Illuminate\Database\Eloquent\Builder::orWhereHas($relation, $callback, $operator, $count); } /** * Get the underlying query builder instance. * * @return \Illuminate\Database\Query\Builder|static * @static */ public static function getQuery(){ return \Illuminate\Database\Eloquent\Builder::getQuery(); } /** * Set the underlying query builder instance. * * @param \Illuminate\Database\Query\Builder $query * @return void * @static */ public static function setQuery($query){ \Illuminate\Database\Eloquent\Builder::setQuery($query); } /** * Get the relationships being eagerly loaded. * * @return array * @static */ public static function getEagerLoads(){ return \Illuminate\Database\Eloquent\Builder::getEagerLoads(); } /** * Set the relationships being eagerly loaded. * * @param array $eagerLoad * @return void * @static */ public static function setEagerLoads($eagerLoad){ \Illuminate\Database\Eloquent\Builder::setEagerLoads($eagerLoad); } /** * Get the model instance being queried. * * @return \Illuminate\Database\Eloquent\Model * @static */ public static function getModel(){ return \Illuminate\Database\Eloquent\Builder::getModel(); } /** * Set a model instance for the model being queried. * * @param \Illuminate\Database\Eloquent\Model $model * @return $this * @static */ public static function setModel($model){ return \Illuminate\Database\Eloquent\Builder::setModel($model); } /** * Extend the builder with a given callback. * * @param string $name * @param \Closure $callback * @return void * @static */ public static function macro($name, $callback){ \Illuminate\Database\Eloquent\Builder::macro($name, $callback); } /** * Get the given macro by name. * * @param string $name * @return \Closure * @static */ public static function getMacro($name){ return \Illuminate\Database\Eloquent\Builder::getMacro($name); } /** * Set the columns to be selected. * * @param array $columns * @return $this * @static */ public static function select($columns = array()){ return \Illuminate\Database\Query\Builder::select($columns); } /** * Add a new "raw" select expression to the query. * * @param string $expression * @return \Illuminate\Database\Query\Builder|static * @static */ public static function selectRaw($expression){ return \Illuminate\Database\Query\Builder::selectRaw($expression); } /** * Add a new select column to the query. * * @param mixed $column * @return $this * @static */ public static function addSelect($column){ return \Illuminate\Database\Query\Builder::addSelect($column); } /** * Force the query to only return distinct results. * * @return $this * @static */ public static function distinct(){ return \Illuminate\Database\Query\Builder::distinct(); } /** * Set the table which the query is targeting. * * @param string $table * @return $this * @static */ public static function from($table){ return \Illuminate\Database\Query\Builder::from($table); } /** * Add a join clause to the query. * * @param string $table * @param string $one * @param string $operator * @param string $two * @param string $type * @param bool $where * @return $this * @static */ public static function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false){ return \Illuminate\Database\Query\Builder::join($table, $one, $operator, $two, $type, $where); } /** * Add a "join where" clause to the query. * * @param string $table * @param string $one * @param string $operator * @param string $two * @param string $type * @return \Illuminate\Database\Query\Builder|static * @static */ public static function joinWhere($table, $one, $operator, $two, $type = 'inner'){ return \Illuminate\Database\Query\Builder::joinWhere($table, $one, $operator, $two, $type); } /** * Add a left join to the query. * * @param string $table * @param string $first * @param string $operator * @param string $second * @return \Illuminate\Database\Query\Builder|static * @static */ public static function leftJoin($table, $first, $operator = null, $second = null){ return \Illuminate\Database\Query\Builder::leftJoin($table, $first, $operator, $second); } /** * Add a "join where" clause to the query. * * @param string $table * @param string $one * @param string $operator * @param string $two * @return \Illuminate\Database\Query\Builder|static * @static */ public static function leftJoinWhere($table, $one, $operator, $two){ return \Illuminate\Database\Query\Builder::leftJoinWhere($table, $one, $operator, $two); } /** * Add a right join to the query. * * @param string $table * @param string $first * @param string $operator * @param string $second * @return \Illuminate\Database\Query\Builder|static * @static */ public static function rightJoin($table, $first, $operator = null, $second = null){ return \Illuminate\Database\Query\Builder::rightJoin($table, $first, $operator, $second); } /** * Add a "right join where" clause to the query. * * @param string $table * @param string $one * @param string $operator * @param string $two * @return \Illuminate\Database\Query\Builder|static * @static */ public static function rightJoinWhere($table, $one, $operator, $two){ return \Illuminate\Database\Query\Builder::rightJoinWhere($table, $one, $operator, $two); } /** * Add a raw where clause to the query. * * @param string $sql * @param array $bindings * @param string $boolean * @return $this * @static */ public static function whereRaw($sql, $bindings = array(), $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereRaw($sql, $bindings, $boolean); } /** * Add a raw or where clause to the query. * * @param string $sql * @param array $bindings * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereRaw($sql, $bindings = array()){ return \Illuminate\Database\Query\Builder::orWhereRaw($sql, $bindings); } /** * Add a where between statement to the query. * * @param string $column * @param array $values * @param string $boolean * @param bool $not * @return $this * @static */ public static function whereBetween($column, $values, $boolean = 'and', $not = false){ return \Illuminate\Database\Query\Builder::whereBetween($column, $values, $boolean, $not); } /** * Add an or where between statement to the query. * * @param string $column * @param array $values * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereBetween($column, $values){ return \Illuminate\Database\Query\Builder::orWhereBetween($column, $values); } /** * Add a where not between statement to the query. * * @param string $column * @param array $values * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereNotBetween($column, $values, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereNotBetween($column, $values, $boolean); } /** * Add an or where not between statement to the query. * * @param string $column * @param array $values * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereNotBetween($column, $values){ return \Illuminate\Database\Query\Builder::orWhereNotBetween($column, $values); } /** * Add a nested where statement to the query. * * @param \Closure $callback * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereNested($callback, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereNested($callback, $boolean); } /** * Add another query builder as a nested where to the query builder. * * @param \Illuminate\Database\Query\Builder|static $query * @param string $boolean * @return $this * @static */ public static function addNestedWhereQuery($query, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::addNestedWhereQuery($query, $boolean); } /** * Add an exists clause to the query. * * @param \Closure $callback * @param string $boolean * @param bool $not * @return $this * @static */ public static function whereExists($callback, $boolean = 'and', $not = false){ return \Illuminate\Database\Query\Builder::whereExists($callback, $boolean, $not); } /** * Add an or exists clause to the query. * * @param \Closure $callback * @param bool $not * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereExists($callback, $not = false){ return \Illuminate\Database\Query\Builder::orWhereExists($callback, $not); } /** * Add a where not exists clause to the query. * * @param \Closure $callback * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereNotExists($callback, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereNotExists($callback, $boolean); } /** * Add a where not exists clause to the query. * * @param \Closure $callback * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereNotExists($callback){ return \Illuminate\Database\Query\Builder::orWhereNotExists($callback); } /** * Add a "where in" clause to the query. * * @param string $column * @param mixed $values * @param string $boolean * @param bool $not * @return $this * @static */ public static function whereIn($column, $values, $boolean = 'and', $not = false){ return \Illuminate\Database\Query\Builder::whereIn($column, $values, $boolean, $not); } /** * Add an "or where in" clause to the query. * * @param string $column * @param mixed $values * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereIn($column, $values){ return \Illuminate\Database\Query\Builder::orWhereIn($column, $values); } /** * Add a "where not in" clause to the query. * * @param string $column * @param mixed $values * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereNotIn($column, $values, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereNotIn($column, $values, $boolean); } /** * Add an "or where not in" clause to the query. * * @param string $column * @param mixed $values * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereNotIn($column, $values){ return \Illuminate\Database\Query\Builder::orWhereNotIn($column, $values); } /** * Add a "where null" clause to the query. * * @param string $column * @param string $boolean * @param bool $not * @return $this * @static */ public static function whereNull($column, $boolean = 'and', $not = false){ return \Illuminate\Database\Query\Builder::whereNull($column, $boolean, $not); } /** * Add an "or where null" clause to the query. * * @param string $column * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereNull($column){ return \Illuminate\Database\Query\Builder::orWhereNull($column); } /** * Add a "where not null" clause to the query. * * @param string $column * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereNotNull($column, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereNotNull($column, $boolean); } /** * Add an "or where not null" clause to the query. * * @param string $column * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orWhereNotNull($column){ return \Illuminate\Database\Query\Builder::orWhereNotNull($column); } /** * Add a "where date" statement to the query. * * @param string $column * @param string $operator * @param int $value * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereDate($column, $operator, $value, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereDate($column, $operator, $value, $boolean); } /** * Add a "where day" statement to the query. * * @param string $column * @param string $operator * @param int $value * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereDay($column, $operator, $value, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereDay($column, $operator, $value, $boolean); } /** * Add a "where month" statement to the query. * * @param string $column * @param string $operator * @param int $value * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereMonth($column, $operator, $value, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereMonth($column, $operator, $value, $boolean); } /** * Add a "where year" statement to the query. * * @param string $column * @param string $operator * @param int $value * @param string $boolean * @return \Illuminate\Database\Query\Builder|static * @static */ public static function whereYear($column, $operator, $value, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::whereYear($column, $operator, $value, $boolean); } /** * Handles dynamic "where" clauses to the query. * * @param string $method * @param string $parameters * @return $this * @static */ public static function dynamicWhere($method, $parameters){ return \Illuminate\Database\Query\Builder::dynamicWhere($method, $parameters); } /** * Add a "group by" clause to the query. * * @param array|string $column,... * @return $this * @static */ public static function groupBy(){ return \Illuminate\Database\Query\Builder::groupBy(); } /** * Add a "having" clause to the query. * * @param string $column * @param string $operator * @param string $value * @param string $boolean * @return $this * @static */ public static function having($column, $operator = null, $value = null, $boolean = 'and'){ return \Illuminate\Database\Query\Builder::having($column, $operator, $value, $boolean); } /** * Add a "or having" clause to the query. * * @param string $column * @param string $operator * @param string $value * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orHaving($column, $operator = null, $value = null){ return \Illuminate\Database\Query\Builder::orHaving($column, $operator, $value); } /** * Add a raw having clause to the query. * * @param string $sql * @param array $bindings * @param string $boolean * @return $this * @static */ public static function havingRaw($sql, $bindings = array(), $boolean = 'and'){ return \Illuminate\Database\Query\Builder::havingRaw($sql, $bindings, $boolean); } /** * Add a raw or having clause to the query. * * @param string $sql * @param array $bindings * @return \Illuminate\Database\Query\Builder|static * @static */ public static function orHavingRaw($sql, $bindings = array()){ return \Illuminate\Database\Query\Builder::orHavingRaw($sql, $bindings); } /** * Add an "order by" clause to the query. * * @param string $column * @param string $direction * @return $this * @static */ public static function orderBy($column, $direction = 'asc'){ return \Illuminate\Database\Query\Builder::orderBy($column, $direction); } /** * Add an "order by" clause for a timestamp to the query. * * @param string $column * @return \Illuminate\Database\Query\Builder|static * @static */ public static function latest($column = 'created_at'){ return \Illuminate\Database\Query\Builder::latest($column); } /** * Add an "order by" clause for a timestamp to the query. * * @param string $column * @return \Illuminate\Database\Query\Builder|static * @static */ public static function oldest($column = 'created_at'){ return \Illuminate\Database\Query\Builder::oldest($column); } /** * Add a raw "order by" clause to the query. * * @param string $sql * @param array $bindings * @return $this * @static */ public static function orderByRaw($sql, $bindings = array()){ return \Illuminate\Database\Query\Builder::orderByRaw($sql, $bindings); } /** * Set the "offset" value of the query. * * @param int $value * @return $this * @static */ public static function offset($value){ return \Illuminate\Database\Query\Builder::offset($value); } /** * Alias to set the "offset" value of the query. * * @param int $value * @return \Illuminate\Database\Query\Builder|static * @static */ public static function skip($value){ return \Illuminate\Database\Query\Builder::skip($value); } /** * Set the "limit" value of the query. * * @param int $value * @return $this * @static */ public static function limit($value){ return \Illuminate\Database\Query\Builder::limit($value); } /** * Alias to set the "limit" value of the query. * * @param int $value * @return \Illuminate\Database\Query\Builder|static * @static */ public static function take($value){ return \Illuminate\Database\Query\Builder::take($value); } /** * Set the limit and offset for a given page. * * @param int $page * @param int $perPage * @return \Illuminate\Database\Query\Builder|static * @static */ public static function forPage($page, $perPage = 15){ return \Illuminate\Database\Query\Builder::forPage($page, $perPage); } /** * Add a union statement to the query. * * @param \Illuminate\Database\Query\Builder|\Closure $query * @param bool $all * @return \Illuminate\Database\Query\Builder|static * @static */ public static function union($query, $all = false){ return \Illuminate\Database\Query\Builder::union($query, $all); } /** * Add a union all statement to the query. * * @param \Illuminate\Database\Query\Builder|\Closure $query * @return \Illuminate\Database\Query\Builder|static * @static */ public static function unionAll($query){ return \Illuminate\Database\Query\Builder::unionAll($query); } /** * Lock the selected rows in the table. * * @param bool $value * @return $this * @static */ public static function lock($value = true){ return \Illuminate\Database\Query\Builder::lock($value); } /** * Lock the selected rows in the table for updating. * * @return \Illuminate\Database\Query\Builder * @static */ public static function lockForUpdate(){ return \Illuminate\Database\Query\Builder::lockForUpdate(); } /** * Share lock the selected rows in the table. * * @return \Illuminate\Database\Query\Builder * @static */ public static function sharedLock(){ return \Illuminate\Database\Query\Builder::sharedLock(); } /** * Get the SQL representation of the query. * * @return string * @static */ public static function toSql(){ return \Illuminate\Database\Query\Builder::toSql(); } /** * Indicate that the query results should be cached. * * @param \DateTime|int $minutes * @param string $key * @return $this * @static */ public static function remember($minutes, $key = null){ return \Illuminate\Database\Query\Builder::remember($minutes, $key); } /** * Indicate that the query results should be cached forever. * * @param string $key * @return \Illuminate\Database\Query\Builder|static * @static */ public static function rememberForever($key = null){ return \Illuminate\Database\Query\Builder::rememberForever($key); } /** * Indicate that the results, if cached, should use the given cache tags. * * @param array|mixed $cacheTags * @return $this * @static */ public static function cacheTags($cacheTags){ return \Illuminate\Database\Query\Builder::cacheTags($cacheTags); } /** * Indicate that the results, if cached, should use the given cache driver. * * @param string $cacheDriver * @return $this * @static */ public static function cacheDriver($cacheDriver){ return \Illuminate\Database\Query\Builder::cacheDriver($cacheDriver); } /** * Execute the query as a fresh "select" statement. * * @param array $columns * @return array|static[] * @static */ public static function getFresh($columns = array()){ return \Illuminate\Database\Query\Builder::getFresh($columns); } /** * Execute the query as a cached "select" statement. * * @param array $columns * @return array * @static */ public static function getCached($columns = array()){ return \Illuminate\Database\Query\Builder::getCached($columns); } /** * Get a unique cache key for the complete query. * * @return string * @static */ public static function getCacheKey(){ return \Illuminate\Database\Query\Builder::getCacheKey(); } /** * Generate the unique cache key for the query. * * @return string * @static */ public static function generateCacheKey(){ return \Illuminate\Database\Query\Builder::generateCacheKey(); } /** * Concatenate values of a given column as a string. * * @param string $column * @param string $glue * @return string * @static */ public static function implode($column, $glue = null){ return \Illuminate\Database\Query\Builder::implode($column, $glue); } /** * Build a paginator instance from a raw result array. * * @param \Illuminate\Pagination\Factory $paginator * @param array $results * @param int $perPage * @return \Illuminate\Pagination\Paginator * @static */ public static function buildRawPaginator($paginator, $results, $perPage){ return \Illuminate\Database\Query\Builder::buildRawPaginator($paginator, $results, $perPage); } /** * Get the count of the total records for pagination. * * @return int * @static */ public static function getPaginationCount(){ return \Illuminate\Database\Query\Builder::getPaginationCount(); } /** * Determine if any rows exist for the current query. * * @return bool * @static */ public static function exists(){ return \Illuminate\Database\Query\Builder::exists(); } /** * Retrieve the "count" result of the query. * * @param string $columns * @return int * @static */ public static function count($columns = '*'){ return \Illuminate\Database\Query\Builder::count($columns); } /** * Retrieve the minimum value of a given column. * * @param string $column * @return mixed * @static */ public static function min($column){ return \Illuminate\Database\Query\Builder::min($column); } /** * Retrieve the maximum value of a given column. * * @param string $column * @return mixed * @static */ public static function max($column){ return \Illuminate\Database\Query\Builder::max($column); } /** * Retrieve the sum of the values of a given column. * * @param string $column * @return mixed * @static */ public static function sum($column){ return \Illuminate\Database\Query\Builder::sum($column); } /** * Retrieve the average of the values of a given column. * * @param string $column * @return mixed * @static */ public static function avg($column){ return \Illuminate\Database\Query\Builder::avg($column); } /** * Execute an aggregate function on the database. * * @param string $function * @param array $columns * @return mixed * @static */ public static function aggregate($function, $columns = array()){ return \Illuminate\Database\Query\Builder::aggregate($function, $columns); } /** * Insert a new record into the database. * * @param array $values * @return bool * @static */ public static function insert($values){ return \Illuminate\Database\Query\Builder::insert($values); } /** * Insert a new record and get the value of the primary key. * * @param array $values * @param string $sequence * @return int * @static */ public static function insertGetId($values, $sequence = null){ return \Illuminate\Database\Query\Builder::insertGetId($values, $sequence); } /** * Run a truncate statement on the table. * * @return void * @static */ public static function truncate(){ \Illuminate\Database\Query\Builder::truncate(); } /** * Merge an array of where clauses and bindings. * * @param array $wheres * @param array $bindings * @return void * @static */ public static function mergeWheres($wheres, $bindings){ \Illuminate\Database\Query\Builder::mergeWheres($wheres, $bindings); } /** * Create a raw database expression. * * @param mixed $value * @return \Illuminate\Database\Query\Expression * @static */ public static function raw($value){ return \Illuminate\Database\Query\Builder::raw($value); } /** * Get the current query value bindings in a flattened array. * * @return array * @static */ public static function getBindings(){ return \Illuminate\Database\Query\Builder::getBindings(); } /** * Get the raw array of bindings. * * @return array * @static */ public static function getRawBindings(){ return \Illuminate\Database\Query\Builder::getRawBindings(); } /** * Set the bindings on the query builder. * * @param array $bindings * @param string $type * @return $this * @throws \InvalidArgumentException * @static */ public static function setBindings($bindings, $type = 'where'){ return \Illuminate\Database\Query\Builder::setBindings($bindings, $type); } /** * Add a binding to the query. * * @param mixed $value * @param string $type * @return $this * @throws \InvalidArgumentException * @static */ public static function addBinding($value, $type = 'where'){ return \Illuminate\Database\Query\Builder::addBinding($value, $type); } /** * Merge an array of bindings into our bindings. * * @param \Illuminate\Database\Query\Builder $query * @return $this * @static */ public static function mergeBindings($query){ return \Illuminate\Database\Query\Builder::mergeBindings($query); } /** * Get the database query processor instance. * * @return \Illuminate\Database\Query\Processors\Processor * @static */ public static function getProcessor(){ return \Illuminate\Database\Query\Builder::getProcessor(); } /** * Get the query grammar instance. * * @return \Illuminate\Database\Grammar * @static */ public static function getGrammar(){ return \Illuminate\Database\Query\Builder::getGrammar(); } /** * Use the write pdo for query. * * @return $this * @static */ public static function useWritePdo(){ return \Illuminate\Database\Query\Builder::useWritePdo(); } } class Event extends \Illuminate\Support\Facades\Event{ /** * Register an event listener with the dispatcher. * * @param string|array $events * @param mixed $listener * @param int $priority * @return void * @static */ public static function listen($events, $listener, $priority = 0){ \Illuminate\Events\Dispatcher::listen($events, $listener, $priority); } /** * Determine if a given event has listeners. * * @param string $eventName * @return bool * @static */ public static function hasListeners($eventName){ return \Illuminate\Events\Dispatcher::hasListeners($eventName); } /** * Register a queued event and payload. * * @param string $event * @param array $payload * @return void * @static */ public static function queue($event, $payload = array()){ \Illuminate\Events\Dispatcher::queue($event, $payload); } /** * Register an event subscriber with the dispatcher. * * @param string $subscriber * @return void * @static */ public static function subscribe($subscriber){ \Illuminate\Events\Dispatcher::subscribe($subscriber); } /** * Fire an event until the first non-null response is returned. * * @param string $event * @param array $payload * @return mixed * @static */ public static function until($event, $payload = array()){ return \Illuminate\Events\Dispatcher::until($event, $payload); } /** * Flush a set of queued events. * * @param string $event * @return void * @static */ public static function flush($event){ \Illuminate\Events\Dispatcher::flush($event); } /** * Get the event that is currently firing. * * @return string * @static */ public static function firing(){ return \Illuminate\Events\Dispatcher::firing(); } /** * Fire an event and call the listeners. * * @param string $event * @param mixed $payload * @param bool $halt * @return array|null * @static */ public static function fire($event, $payload = array(), $halt = false){ return \Illuminate\Events\Dispatcher::fire($event, $payload, $halt); } /** * Get all of the listeners for a given event name. * * @param string $eventName * @return array * @static */ public static function getListeners($eventName){ return \Illuminate\Events\Dispatcher::getListeners($eventName); } /** * Register an event listener with the dispatcher. * * @param mixed $listener * @return mixed * @static */ public static function makeListener($listener){ return \Illuminate\Events\Dispatcher::makeListener($listener); } /** * Create a class based listener using the IoC container. * * @param mixed $listener * @return \Closure * @static */ public static function createClassListener($listener){ return \Illuminate\Events\Dispatcher::createClassListener($listener); } /** * Remove a set of listeners from the dispatcher. * * @param string $event * @return void * @static */ public static function forget($event){ \Illuminate\Events\Dispatcher::forget($event); } /** * Forget all of the queued listeners. * * @return void * @static */ public static function forgetQueued(){ \Illuminate\Events\Dispatcher::forgetQueued(); } } class File extends \Illuminate\Support\Facades\File{ /** * Determine if a file exists. * * @param string $path * @return bool * @static */ public static function exists($path){ return \Illuminate\Filesystem\Filesystem::exists($path); } /** * Get the contents of a file. * * @param string $path * @return string * @throws FileNotFoundException * @static */ public static function get($path){ return \Illuminate\Filesystem\Filesystem::get($path); } /** * Get the returned value of a file. * * @param string $path * @return mixed * @throws FileNotFoundException * @static */ public static function getRequire($path){ return \Illuminate\Filesystem\Filesystem::getRequire($path); } /** * Require the given file once. * * @param string $file * @return mixed * @static */ public static function requireOnce($file){ return \Illuminate\Filesystem\Filesystem::requireOnce($file); } /** * Write the contents of a file. * * @param string $path * @param string $contents * @param bool $lock * @return int * @static */ public static function put($path, $contents, $lock = false){ return \Illuminate\Filesystem\Filesystem::put($path, $contents, $lock); } /** * Prepend to a file. * * @param string $path * @param string $data * @return int * @static */ public static function prepend($path, $data){ return \Illuminate\Filesystem\Filesystem::prepend($path, $data); } /** * Append to a file. * * @param string $path * @param string $data * @return int * @static */ public static function append($path, $data){ return \Illuminate\Filesystem\Filesystem::append($path, $data); } /** * Delete the file at a given path. * * @param string|array $paths * @return bool * @static */ public static function delete($paths){ return \Illuminate\Filesystem\Filesystem::delete($paths); } /** * Move a file to a new location. * * @param string $path * @param string $target * @return bool * @static */ public static function move($path, $target){ return \Illuminate\Filesystem\Filesystem::move($path, $target); } /** * Copy a file to a new location. * * @param string $path * @param string $target * @return bool * @static */ public static function copy($path, $target){ return \Illuminate\Filesystem\Filesystem::copy($path, $target); } /** * Extract the file name from a file path. * * @param string $path * @return string * @static */ public static function name($path){ return \Illuminate\Filesystem\Filesystem::name($path); } /** * Extract the file extension from a file path. * * @param string $path * @return string * @static */ public static function extension($path){ return \Illuminate\Filesystem\Filesystem::extension($path); } /** * Get the file type of a given file. * * @param string $path * @return string * @static */ public static function type($path){ return \Illuminate\Filesystem\Filesystem::type($path); } /** * Get the file size of a given file. * * @param string $path * @return int * @static */ public static function size($path){ return \Illuminate\Filesystem\Filesystem::size($path); } /** * Get the file's last modification time. * * @param string $path * @return int * @static */ public static function lastModified($path){ return \Illuminate\Filesystem\Filesystem::lastModified($path); } /** * Determine if the given path is a directory. * * @param string $directory * @return bool * @static */ public static function isDirectory($directory){ return \Illuminate\Filesystem\Filesystem::isDirectory($directory); } /** * Determine if the given path is writable. * * @param string $path * @return bool * @static */ public static function isWritable($path){ return \Illuminate\Filesystem\Filesystem::isWritable($path); } /** * Determine if the given path is a file. * * @param string $file * @return bool * @static */ public static function isFile($file){ return \Illuminate\Filesystem\Filesystem::isFile($file); } /** * Find path names matching a given pattern. * * @param string $pattern * @param int $flags * @return array * @static */ public static function glob($pattern, $flags = 0){ return \Illuminate\Filesystem\Filesystem::glob($pattern, $flags); } /** * Get an array of all files in a directory. * * @param string $directory * @return array * @static */ public static function files($directory){ return \Illuminate\Filesystem\Filesystem::files($directory); } /** * Get all of the files from the given directory (recursive). * * @param string $directory * @return array * @static */ public static function allFiles($directory){ return \Illuminate\Filesystem\Filesystem::allFiles($directory); } /** * Get all of the directories within a given directory. * * @param string $directory * @return array * @static */ public static function directories($directory){ return \Illuminate\Filesystem\Filesystem::directories($directory); } /** * Create a directory. * * @param string $path * @param int $mode * @param bool $recursive * @param bool $force * @return bool * @static */ public static function makeDirectory($path, $mode = 493, $recursive = false, $force = false){ return \Illuminate\Filesystem\Filesystem::makeDirectory($path, $mode, $recursive, $force); } /** * Copy a directory from one location to another. * * @param string $directory * @param string $destination * @param int $options * @return bool * @static */ public static function copyDirectory($directory, $destination, $options = null){ return \Illuminate\Filesystem\Filesystem::copyDirectory($directory, $destination, $options); } /** * Recursively delete a directory. * * The directory itself may be optionally preserved. * * @param string $directory * @param bool $preserve * @return bool * @static */ public static function deleteDirectory($directory, $preserve = false){ return \Illuminate\Filesystem\Filesystem::deleteDirectory($directory, $preserve); } /** * Empty the specified directory of all files and folders. * * @param string $directory * @return bool * @static */ public static function cleanDirectory($directory){ return \Illuminate\Filesystem\Filesystem::cleanDirectory($directory); } } class Form extends \Illuminate\Support\Facades\Form{ /** * Open up a new HTML form. * * @param array $options * @return string * @static */ public static function open($options = array()){ return \Illuminate\Html\FormBuilder::open($options); } /** * Create a new model based form builder. * * @param mixed $model * @param array $options * @return string * @static */ public static function model($model, $options = array()){ return \Illuminate\Html\FormBuilder::model($model, $options); } /** * Set the model instance on the form builder. * * @param mixed $model * @return void * @static */ public static function setModel($model){ \Illuminate\Html\FormBuilder::setModel($model); } /** * Close the current form. * * @return string * @static */ public static function close(){ return \Illuminate\Html\FormBuilder::close(); } /** * Generate a hidden field with the current CSRF token. * * @return string * @static */ public static function token(){ return \Illuminate\Html\FormBuilder::token(); } /** * Create a form label element. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function label($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::label($name, $value, $options); } /** * Create a form input field. * * @param string $type * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function input($type, $name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::input($type, $name, $value, $options); } /** * Create a text input field. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function text($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::text($name, $value, $options); } /** * Create a password input field. * * @param string $name * @param array $options * @return string * @static */ public static function password($name, $options = array()){ return \Illuminate\Html\FormBuilder::password($name, $options); } /** * Create a hidden input field. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function hidden($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::hidden($name, $value, $options); } /** * Create an e-mail input field. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function email($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::email($name, $value, $options); } /** * Create a url input field. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function url($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::url($name, $value, $options); } /** * Create a file input field. * * @param string $name * @param array $options * @return string * @static */ public static function file($name, $options = array()){ return \Illuminate\Html\FormBuilder::file($name, $options); } /** * Create a textarea input field. * * @param string $name * @param string $value * @param array $options * @return string * @static */ public static function textarea($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::textarea($name, $value, $options); } /** * Create a number input field. * * @param string $name * @param string|null $value * @param array $options * @return string * @static */ public static function number($name, $value = null, $options = array()){ return \Illuminate\Html\FormBuilder::number($name, $value, $options); } /** * Create a select box field. * * @param string $name * @param array $list * @param string $selected * @param array $options * @return string * @static */ public static function select($name, $list = array(), $selected = null, $options = array()){ return \Illuminate\Html\FormBuilder::select($name, $list, $selected, $options); } /** * Create a select range field. * * @param string $name * @param string $begin * @param string $end * @param string $selected * @param array $options * @return string * @static */ public static function selectRange($name, $begin, $end, $selected = null, $options = array()){ return \Illuminate\Html\FormBuilder::selectRange($name, $begin, $end, $selected, $options); } /** * Create a select year field. * * @param string $name * @param string $begin * @param string $end * @param string $selected * @param array $options * @return string * @static */ public static function selectYear(){ return \Illuminate\Html\FormBuilder::selectYear(); } /** * Create a select month field. * * @param string $name * @param string $selected * @param array $options * @param string $format * @return string * @static */ public static function selectMonth($name, $selected = null, $options = array(), $format = '%B'){ return \Illuminate\Html\FormBuilder::selectMonth($name, $selected, $options, $format); } /** * Get the select option for the given value. * * @param string $display * @param string $value * @param string $selected * @return string * @static */ public static function getSelectOption($display, $value, $selected){ return \Illuminate\Html\FormBuilder::getSelectOption($display, $value, $selected); } /** * Create a checkbox input field. * * @param string $name * @param mixed $value * @param bool $checked * @param array $options * @return string * @static */ public static function checkbox($name, $value = 1, $checked = null, $options = array()){ return \Illuminate\Html\FormBuilder::checkbox($name, $value, $checked, $options); } /** * Create a radio button input field. * * @param string $name * @param mixed $value * @param bool $checked * @param array $options * @return string * @static */ public static function radio($name, $value = null, $checked = null, $options = array()){ return \Illuminate\Html\FormBuilder::radio($name, $value, $checked, $options); } /** * Create a HTML reset input element. * * @param string $value * @param array $attributes * @return string * @static */ public static function reset($value, $attributes = array()){ return \Illuminate\Html\FormBuilder::reset($value, $attributes); } /** * Create a HTML image input element. * * @param string $url * @param string $name * @param array $attributes * @return string * @static */ public static function image($url, $name = null, $attributes = array()){ return \Illuminate\Html\FormBuilder::image($url, $name, $attributes); } /** * Create a submit button element. * * @param string $value * @param array $options * @return string * @static */ public static function submit($value = null, $options = array()){ return \Illuminate\Html\FormBuilder::submit($value, $options); } /** * Create a button element. * * @param string $value * @param array $options * @return string * @static */ public static function button($value = null, $options = array()){ return \Illuminate\Html\FormBuilder::button($value, $options); } /** * Get the ID attribute for a field name. * * @param string $name * @param array $attributes * @return string * @static */ public static function getIdAttribute($name, $attributes){ return \Illuminate\Html\FormBuilder::getIdAttribute($name, $attributes); } /** * Get the value that should be assigned to the field. * * @param string $name * @param string $value * @return string * @static */ public static function getValueAttribute($name, $value = null){ return \Illuminate\Html\FormBuilder::getValueAttribute($name, $value); } /** * Get a value from the session's old input. * * @param string $name * @return string * @static */ public static function old($name){ return \Illuminate\Html\FormBuilder::old($name); } /** * Determine if the old input is empty. * * @return bool * @static */ public static function oldInputIsEmpty(){ return \Illuminate\Html\FormBuilder::oldInputIsEmpty(); } /** * Get the session store implementation. * * @return \Illuminate\Session\Store $session * @static */ public static function getSessionStore(){ return \Illuminate\Html\FormBuilder::getSessionStore(); } /** * Set the session store implementation. * * @param \Illuminate\Session\Store $session * @return $this * @static */ public static function setSessionStore($session){ return \Illuminate\Html\FormBuilder::setSessionStore($session); } /** * Register a custom macro. * * @param string $name * @param callable $macro * @return void * @static */ public static function macro($name, $macro){ \Illuminate\Html\FormBuilder::macro($name, $macro); } /** * Checks if macro is registered * * @param string $name * @return boolean * @static */ public static function hasMacro($name){ return \Illuminate\Html\FormBuilder::hasMacro($name); } } class Hash extends \Illuminate\Support\Facades\Hash{ /** * Hash the given value. * * @param string $value * @param array $options * @return string * @throws \RuntimeException * @static */ public static function make($value, $options = array()){ return \Illuminate\Hashing\BcryptHasher::make($value, $options); } /** * Check the given plain value against a hash. * * @param string $value * @param string $hashedValue * @param array $options * @return bool * @static */ public static function check($value, $hashedValue, $options = array()){ return \Illuminate\Hashing\BcryptHasher::check($value, $hashedValue, $options); } /** * Check if the given hash has been hashed using the given options. * * @param string $hashedValue * @param array $options * @return bool * @static */ public static function needsRehash($hashedValue, $options = array()){ return \Illuminate\Hashing\BcryptHasher::needsRehash($hashedValue, $options); } /** * Set the default crypt cost factor. * * @param int $rounds * @return void * @static */ public static function setRounds($rounds){ \Illuminate\Hashing\BcryptHasher::setRounds($rounds); } } class HTML extends \Illuminate\Support\Facades\HTML{ /** * Convert an HTML string to entities. * * @param string $value * @return string * @static */ public static function entities($value){ return \Illuminate\Html\HtmlBuilder::entities($value); } /** * Convert entities to HTML characters. * * @param string $value * @return string * @static */ public static function decode($value){ return \Illuminate\Html\HtmlBuilder::decode($value); } /** * Generate a link to a JavaScript file. * * @param string $url * @param array $attributes * @param bool $secure * @return string * @static */ public static function script($url, $attributes = array(), $secure = null){ return \Illuminate\Html\HtmlBuilder::script($url, $attributes, $secure); } /** * Generate a link to a CSS file. * * @param string $url * @param array $attributes * @param bool $secure * @return string * @static */ public static function style($url, $attributes = array(), $secure = null){ return \Illuminate\Html\HtmlBuilder::style($url, $attributes, $secure); } /** * Generate an HTML image element. * * @param string $url * @param string $alt * @param array $attributes * @param bool $secure * @return string * @static */ public static function image($url, $alt = null, $attributes = array(), $secure = null){ return \Illuminate\Html\HtmlBuilder::image($url, $alt, $attributes, $secure); } /** * Generate a HTML link. * * @param string $url * @param string $title * @param array $attributes * @param bool $secure * @return string * @static */ public static function link($url, $title = null, $attributes = array(), $secure = null){ return \Illuminate\Html\HtmlBuilder::link($url, $title, $attributes, $secure); } /** * Generate a HTTPS HTML link. * * @param string $url * @param string $title * @param array $attributes * @return string * @static */ public static function secureLink($url, $title = null, $attributes = array()){ return \Illuminate\Html\HtmlBuilder::secureLink($url, $title, $attributes); } /** * Generate a HTML link to an asset. * * @param string $url * @param string $title * @param array $attributes * @param bool $secure * @return string * @static */ public static function linkAsset($url, $title = null, $attributes = array(), $secure = null){ return \Illuminate\Html\HtmlBuilder::linkAsset($url, $title, $attributes, $secure); } /** * Generate a HTTPS HTML link to an asset. * * @param string $url * @param string $title * @param array $attributes * @return string * @static */ public static function linkSecureAsset($url, $title = null, $attributes = array()){ return \Illuminate\Html\HtmlBuilder::linkSecureAsset($url, $title, $attributes); } /** * Generate a HTML link to a named route. * * @param string $name * @param string $title * @param array $parameters * @param array $attributes * @return string * @static */ public static function linkRoute($name, $title = null, $parameters = array(), $attributes = array()){ return \Illuminate\Html\HtmlBuilder::linkRoute($name, $title, $parameters, $attributes); } /** * Generate a HTML link to a controller action. * * @param string $action * @param string $title * @param array $parameters * @param array $attributes * @return string * @static */ public static function linkAction($action, $title = null, $parameters = array(), $attributes = array()){ return \Illuminate\Html\HtmlBuilder::linkAction($action, $title, $parameters, $attributes); } /** * Generate a HTML link to an email address. * * @param string $email * @param string $title * @param array $attributes * @return string * @static */ public static function mailto($email, $title = null, $attributes = array()){ return \Illuminate\Html\HtmlBuilder::mailto($email, $title, $attributes); } /** * Obfuscate an e-mail address to prevent spam-bots from sniffing it. * * @param string $email * @return string * @static */ public static function email($email){ return \Illuminate\Html\HtmlBuilder::email($email); } /** * Generate an ordered list of items. * * @param array $list * @param array $attributes * @return string * @static */ public static function ol($list, $attributes = array()){ return \Illuminate\Html\HtmlBuilder::ol($list, $attributes); } /** * Generate an un-ordered list of items. * * @param array $list * @param array $attributes * @return string * @static */ public static function ul($list, $attributes = array()){ return \Illuminate\Html\HtmlBuilder::ul($list, $attributes); } /** * Build an HTML attribute string from an array. * * @param array $attributes * @return string * @static */ public static function attributes($attributes){ return \Illuminate\Html\HtmlBuilder::attributes($attributes); } /** * Obfuscate a string to prevent spam-bots from sniffing it. * * @param string $value * @return string * @static */ public static function obfuscate($value){ return \Illuminate\Html\HtmlBuilder::obfuscate($value); } /** * Register a custom macro. * * @param string $name * @param callable $macro * @return void * @static */ public static function macro($name, $macro){ \Illuminate\Html\HtmlBuilder::macro($name, $macro); } /** * Checks if macro is registered * * @param string $name * @return boolean * @static */ public static function hasMacro($name){ return \Illuminate\Html\HtmlBuilder::hasMacro($name); } } class Input extends \Illuminate\Support\Facades\Input{ /** * Return the Request instance. * * @return $this * @static */ public static function instance(){ return \Illuminate\Http\Request::instance(); } /** * Get the request method. * * @return string * @static */ public static function method(){ return \Illuminate\Http\Request::method(); } /** * Get the root URL for the application. * * @return string * @static */ public static function root(){ return \Illuminate\Http\Request::root(); } /** * Get the URL (no query string) for the request. * * @return string * @static */ public static function url(){ return \Illuminate\Http\Request::url(); } /** * Get the full URL for the request. * * @return string * @static */ public static function fullUrl(){ return \Illuminate\Http\Request::fullUrl(); } /** * Get the current path info for the request. * * @return string * @static */ public static function path(){ return \Illuminate\Http\Request::path(); } /** * Get the current encoded path info for the request. * * @return string * @static */ public static function decodedPath(){ return \Illuminate\Http\Request::decodedPath(); } /** * Get a segment from the URI (1 based index). * * @param string $index * @param mixed $default * @return string * @static */ public static function segment($index, $default = null){ return \Illuminate\Http\Request::segment($index, $default); } /** * Get all of the segments for the request path. * * @return array * @static */ public static function segments(){ return \Illuminate\Http\Request::segments(); } /** * Determine if the current request URI matches a pattern. * * @param mixed string * @return bool * @static */ public static function is(){ return \Illuminate\Http\Request::is(); } /** * Determine if the request is the result of an AJAX call. * * @return bool * @static */ public static function ajax(){ return \Illuminate\Http\Request::ajax(); } /** * Determine if the request is over HTTPS. * * @return bool * @static */ public static function secure(){ return \Illuminate\Http\Request::secure(); } /** * Returns the client IP address. * * @return string * @static */ public static function ip(){ return \Illuminate\Http\Request::ip(); } /** * Returns the client IP addresses. * * @return array * @static */ public static function ips(){ return \Illuminate\Http\Request::ips(); } /** * Determine if the request contains a given input item key. * * @param string|array $key * @return bool * @static */ public static function exists($key){ return \Illuminate\Http\Request::exists($key); } /** * Determine if the request contains a non-empty value for an input item. * * @param string|array $key * @return bool * @static */ public static function has($key){ return \Illuminate\Http\Request::has($key); } /** * Get all of the input and files for the request. * * @return array * @static */ public static function all(){ return \Illuminate\Http\Request::all(); } /** * Retrieve an input item from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function input($key = null, $default = null){ return \Illuminate\Http\Request::input($key, $default); } /** * Get a subset of the items from the input data. * * @param array $keys * @return array * @static */ public static function only($keys){ return \Illuminate\Http\Request::only($keys); } /** * Get all of the input except for a specified array of items. * * @param array $keys * @return array * @static */ public static function except($keys){ return \Illuminate\Http\Request::except($keys); } /** * Retrieve a query string item from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function query($key = null, $default = null){ return \Illuminate\Http\Request::query($key, $default); } /** * Determine if a cookie is set on the request. * * @param string $key * @return bool * @static */ public static function hasCookie($key){ return \Illuminate\Http\Request::hasCookie($key); } /** * Retrieve a cookie from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function cookie($key = null, $default = null){ return \Illuminate\Http\Request::cookie($key, $default); } /** * Retrieve a file from the request. * * @param string $key * @param mixed $default * @return \Symfony\Component\HttpFoundation\File\UploadedFile|array * @static */ public static function file($key = null, $default = null){ return \Illuminate\Http\Request::file($key, $default); } /** * Determine if the uploaded data contains a file. * * @param string $key * @return bool * @static */ public static function hasFile($key){ return \Illuminate\Http\Request::hasFile($key); } /** * Retrieve a header from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function header($key = null, $default = null){ return \Illuminate\Http\Request::header($key, $default); } /** * Retrieve a server variable from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function server($key = null, $default = null){ return \Illuminate\Http\Request::server($key, $default); } /** * Retrieve an old input item. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function old($key = null, $default = null){ return \Illuminate\Http\Request::old($key, $default); } /** * Flash the input for the current request to the session. * * @param string $filter * @param array $keys * @return void * @static */ public static function flash($filter = null, $keys = array()){ \Illuminate\Http\Request::flash($filter, $keys); } /** * Flash only some of the input to the session. * * @param mixed string * @return void * @static */ public static function flashOnly($keys){ \Illuminate\Http\Request::flashOnly($keys); } /** * Flash only some of the input to the session. * * @param mixed string * @return void * @static */ public static function flashExcept($keys){ \Illuminate\Http\Request::flashExcept($keys); } /** * Flush all of the old input from the session. * * @return void * @static */ public static function flush(){ \Illuminate\Http\Request::flush(); } /** * Merge new input into the current request's input array. * * @param array $input * @return void * @static */ public static function merge($input){ \Illuminate\Http\Request::merge($input); } /** * Replace the input for the current request. * * @param array $input * @return void * @static */ public static function replace($input){ \Illuminate\Http\Request::replace($input); } /** * Get the JSON payload for the request. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function json($key = null, $default = null){ return \Illuminate\Http\Request::json($key, $default); } /** * Determine if the request is sending JSON. * * @return bool * @static */ public static function isJson(){ return \Illuminate\Http\Request::isJson(); } /** * Determine if the current request is asking for JSON in return. * * @return bool * @static */ public static function wantsJson(){ return \Illuminate\Http\Request::wantsJson(); } /** * Get the data format expected in the response. * * @param string $default * @return string * @static */ public static function format($default = 'html'){ return \Illuminate\Http\Request::format($default); } /** * Create an Illuminate request from a Symfony instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return \Illuminate\Http\Request * @static */ public static function createFromBase($request){ return \Illuminate\Http\Request::createFromBase($request); } /** * Get the session associated with the request. * * @return \Illuminate\Session\Store * @throws \RuntimeException * @static */ public static function session(){ return \Illuminate\Http\Request::session(); } /** * Sets the parameters for this request. * * This method also re-initializes all properties. * * @param array $query The GET parameters * @param array $request The POST parameters * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) * @param array $cookies The COOKIE parameters * @param array $files The FILES parameters * @param array $server The SERVER parameters * @param string $content The raw body data * @api * @static */ public static function initialize($query = array(), $request = array(), $attributes = array(), $cookies = array(), $files = array(), $server = array(), $content = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::initialize($query, $request, $attributes, $cookies, $files, $server, $content); } /** * Creates a new request with values from PHP's super globals. * * @return \Symfony\Component\HttpFoundation\Request A new request * @api * @static */ public static function createFromGlobals(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::createFromGlobals(); } /** * Creates a Request based on a given URI and configuration. * * The information contained in the URI always take precedence * over the other information (server and parameters). * * @param string $uri The URI * @param string $method The HTTP method * @param array $parameters The query (GET) or request (POST) parameters * @param array $cookies The request cookies ($_COOKIE) * @param array $files The request files ($_FILES) * @param array $server The server parameters ($_SERVER) * @param string $content The raw body data * @return \Symfony\Component\HttpFoundation\Request A Request instance * @api * @static */ public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::create($uri, $method, $parameters, $cookies, $files, $server, $content); } /** * Sets a callable able to create a Request instance. * * This is mainly useful when you need to override the Request class * to keep BC with an existing system. It should not be used for any * other purpose. * * @param callable|null $callable A PHP callable * @static */ public static function setFactory($callable){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setFactory($callable); } /** * Clones a request and overrides some of its parameters. * * @param array $query The GET parameters * @param array $request The POST parameters * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) * @param array $cookies The COOKIE parameters * @param array $files The FILES parameters * @param array $server The SERVER parameters * @return \Symfony\Component\HttpFoundation\Request The duplicated request * @api * @static */ public static function duplicate($query = null, $request = null, $attributes = null, $cookies = null, $files = null, $server = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::duplicate($query, $request, $attributes, $cookies, $files, $server); } /** * Overrides the PHP global variables according to this request instance. * * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. * $_FILES is never overridden, see rfc1867 * * @api * @static */ public static function overrideGlobals(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::overrideGlobals(); } /** * Sets a list of trusted proxies. * * You should only list the reverse proxies that you manage directly. * * @param array $proxies A list of trusted proxies * @api * @static */ public static function setTrustedProxies($proxies){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedProxies($proxies); } /** * Gets the list of trusted proxies. * * @return array An array of trusted proxies. * @static */ public static function getTrustedProxies(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedProxies(); } /** * Sets a list of trusted host patterns. * * You should only list the hosts you manage using regexs. * * @param array $hostPatterns A list of trusted host patterns * @static */ public static function setTrustedHosts($hostPatterns){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedHosts($hostPatterns); } /** * Gets the list of trusted host patterns. * * @return array An array of trusted host patterns. * @static */ public static function getTrustedHosts(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedHosts(); } /** * Sets the name for trusted headers. * * The following header keys are supported: * * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp()) * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getClientHost()) * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getClientPort()) * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure()) * * Setting an empty value allows to disable the trusted header for the given key. * * @param string $key The header key * @param string $value The header name * @throws \InvalidArgumentException * @static */ public static function setTrustedHeaderName($key, $value){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedHeaderName($key, $value); } /** * Gets the trusted proxy header name. * * @param string $key The header key * @return string The header name * @throws \InvalidArgumentException * @static */ public static function getTrustedHeaderName($key){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedHeaderName($key); } /** * Normalizes a query string. * * It builds a normalized query string, where keys/value pairs are alphabetized, * have consistent escaping and unneeded delimiters are removed. * * @param string $qs Query string * @return string A normalized query string for the Request * @static */ public static function normalizeQueryString($qs){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::normalizeQueryString($qs); } /** * Enables support for the _method request parameter to determine the intended HTTP method. * * Be warned that enabling this feature might lead to CSRF issues in your code. * Check that you are using CSRF tokens when required. * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered * and used to send a "PUT" or "DELETE" request via the _method request parameter. * If these methods are not protected against CSRF, this presents a possible vulnerability. * * The HTTP method can only be overridden when the real HTTP method is POST. * * @static */ public static function enableHttpMethodParameterOverride(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::enableHttpMethodParameterOverride(); } /** * Checks whether support for the _method request parameter is enabled. * * @return bool True when the _method request parameter is enabled, false otherwise * @static */ public static function getHttpMethodParameterOverride(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHttpMethodParameterOverride(); } /** * Gets a "parameter" value. * * This method is mainly useful for libraries that want to provide some flexibility. * * Order of precedence: GET, PATH, POST * * Avoid using this method in controllers: * * * slow * * prefer to get from a "named" source * * It is better to explicitly get request parameters from the appropriate * public property instead (query, attributes, request). * * @param string $key the key * @param mixed $default the default value * @param bool $deep is parameter deep in multidimensional array * @return mixed * @static */ public static function get($key, $default = null, $deep = false){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::get($key, $default, $deep); } /** * Gets the Session. * * @return \Symfony\Component\HttpFoundation\SessionInterface|null The session * @api * @static */ public static function getSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getSession(); } /** * Whether the request contains a Session which was started in one of the * previous requests. * * @return bool * @api * @static */ public static function hasPreviousSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::hasPreviousSession(); } /** * Whether the request contains a Session object. * * This method does not give any information about the state of the session object, * like whether the session is started or not. It is just a way to check if this Request * is associated with a Session instance. * * @return bool true when the Request contains a Session object, false otherwise * @api * @static */ public static function hasSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::hasSession(); } /** * Sets the Session. * * @param \Symfony\Component\HttpFoundation\SessionInterface $session The Session * @api * @static */ public static function setSession($session){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setSession($session); } /** * Returns the client IP addresses. * * In the returned array the most trusted IP address is first, and the * least trusted one last. The "real" client IP address is the last one, * but this is also the least trusted one. Trusted proxies are stripped. * * Use this method carefully; you should use getClientIp() instead. * * @return array The client IP addresses * @see getClientIp() * @static */ public static function getClientIps(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getClientIps(); } /** * Returns the client IP address. * * This method can read the client IP address from the "X-Forwarded-For" header * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" * header value is a comma+space separated list of IP addresses, the left-most * being the original client, and each successive proxy that passed the request * adding the IP address where it received the request from. * * If your reverse proxy uses a different header name than "X-Forwarded-For", * ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with * the "client-ip" key. * * @return string The client IP address * @see getClientIps() * @see http://en.wikipedia.org/wiki/X-Forwarded-For * @api * @static */ public static function getClientIp(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getClientIp(); } /** * Returns current script name. * * @return string * @api * @static */ public static function getScriptName(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getScriptName(); } /** * Returns the path being requested relative to the executed script. * * The path info always starts with a /. * * Suppose this request is instantiated from /mysite on localhost: * * * http://localhost/mysite returns an empty string * * http://localhost/mysite/about returns '/about' * * http://localhost/mysite/enco%20ded returns '/enco%20ded' * * http://localhost/mysite/about?var=1 returns '/about' * * @return string The raw path (i.e. not urldecoded) * @api * @static */ public static function getPathInfo(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPathInfo(); } /** * Returns the root path from which this request is executed. * * Suppose that an index.php file instantiates this request object: * * * http://localhost/index.php returns an empty string * * http://localhost/index.php/page returns an empty string * * http://localhost/web/index.php returns '/web' * * http://localhost/we%20b/index.php returns '/we%20b' * * @return string The raw path (i.e. not urldecoded) * @api * @static */ public static function getBasePath(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getBasePath(); } /** * Returns the root URL from which this request is executed. * * The base URL never ends with a /. * * This is similar to getBasePath(), except that it also includes the * script filename (e.g. index.php) if one exists. * * @return string The raw URL (i.e. not urldecoded) * @api * @static */ public static function getBaseUrl(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getBaseUrl(); } /** * Gets the request's scheme. * * @return string * @api * @static */ public static function getScheme(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getScheme(); } /** * Returns the port on which the request is made. * * This method can read the client port from the "X-Forwarded-Port" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Port" header must contain the client port. * * If your reverse proxy uses a different header name than "X-Forwarded-Port", * configure it via "setTrustedHeaderName()" with the "client-port" key. * * @return string * @api * @static */ public static function getPort(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPort(); } /** * Returns the user. * * @return string|null * @static */ public static function getUser(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUser(); } /** * Returns the password. * * @return string|null * @static */ public static function getPassword(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPassword(); } /** * Gets the user info. * * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server * @static */ public static function getUserInfo(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUserInfo(); } /** * Returns the HTTP host being requested. * * The port name will be appended to the host if it's non-standard. * * @return string * @api * @static */ public static function getHttpHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHttpHost(); } /** * Returns the requested URI (path and query string). * * @return string The raw URI (i.e. not URI decoded) * @api * @static */ public static function getRequestUri(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRequestUri(); } /** * Gets the scheme and HTTP host. * * If the URL was called with basic authentication, the user * and the password are not added to the generated string. * * @return string The scheme and HTTP host * @static */ public static function getSchemeAndHttpHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getSchemeAndHttpHost(); } /** * Generates a normalized URI (URL) for the Request. * * @return string A normalized URI (URL) for the Request * @see getQueryString() * @api * @static */ public static function getUri(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUri(); } /** * Generates a normalized URI for the given path. * * @param string $path A path to use instead of the current one * @return string The normalized URI for the path * @api * @static */ public static function getUriForPath($path){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUriForPath($path); } /** * Generates the normalized query string for the Request. * * It builds a normalized query string, where keys/value pairs are alphabetized * and have consistent escaping. * * @return string|null A normalized query string for the Request * @api * @static */ public static function getQueryString(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getQueryString(); } /** * Checks whether the request is secure or not. * * This method can read the client port from the "X-Forwarded-Proto" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". * * If your reverse proxy uses a different header name than "X-Forwarded-Proto" * ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with * the "client-proto" key. * * @return bool * @api * @static */ public static function isSecure(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isSecure(); } /** * Returns the host name. * * This method can read the client port from the "X-Forwarded-Host" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Host" header must contain the client host name. * * If your reverse proxy uses a different header name than "X-Forwarded-Host", * configure it via "setTrustedHeaderName()" with the "client-host" key. * * @return string * @throws \UnexpectedValueException when the host name is invalid * @api * @static */ public static function getHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHost(); } /** * Sets the request method. * * @param string $method * @api * @static */ public static function setMethod($method){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setMethod($method); } /** * Gets the request "intended" method. * * If the X-HTTP-Method-Override header is set, and if the method is a POST, * then it is used to determine the "real" intended HTTP method. * * The _method request parameter can also be used to determine the HTTP method, * but only if enableHttpMethodParameterOverride() has been called. * * The method is always an uppercased string. * * @return string The request method * @api * @see getRealMethod() * @static */ public static function getMethod(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getMethod(); } /** * Gets the "real" request method. * * @return string The request method * @see getMethod() * @static */ public static function getRealMethod(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRealMethod(); } /** * Gets the mime type associated with the format. * * @param string $format The format * @return string The associated mime type (null if not found) * @api * @static */ public static function getMimeType($format){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getMimeType($format); } /** * Gets the format associated with the mime type. * * @param string $mimeType The associated mime type * @return string|null The format (null if not found) * @api * @static */ public static function getFormat($mimeType){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getFormat($mimeType); } /** * Associates a format with mime types. * * @param string $format The format * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) * @api * @static */ public static function setFormat($format, $mimeTypes){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setFormat($format, $mimeTypes); } /** * Gets the request format. * * Here is the process to determine the format: * * * format defined by the user (with setRequestFormat()) * * _format request parameter * * $default * * @param string $default The default format * @return string The request format * @api * @static */ public static function getRequestFormat($default = 'html'){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRequestFormat($default); } /** * Sets the request format. * * @param string $format The request format. * @api * @static */ public static function setRequestFormat($format){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setRequestFormat($format); } /** * Gets the format associated with the request. * * @return string|null The format (null if no content type is present) * @api * @static */ public static function getContentType(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getContentType(); } /** * Sets the default locale. * * @param string $locale * @api * @static */ public static function setDefaultLocale($locale){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setDefaultLocale($locale); } /** * Get the default locale. * * @return string * @static */ public static function getDefaultLocale(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getDefaultLocale(); } /** * Sets the locale. * * @param string $locale * @api * @static */ public static function setLocale($locale){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setLocale($locale); } /** * Get the locale. * * @return string * @static */ public static function getLocale(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getLocale(); } /** * Checks if the request method is of specified type. * * @param string $method Uppercase request method (GET, POST etc). * @return bool * @static */ public static function isMethod($method){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isMethod($method); } /** * Checks whether the method is safe or not. * * @return bool * @api * @static */ public static function isMethodSafe(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isMethodSafe(); } /** * Returns the request body content. * * @param bool $asResource If true, a resource will be returned * @return string|resource The request body content or a resource to read the body stream. * @throws \LogicException * @static */ public static function getContent($asResource = false){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getContent($asResource); } /** * Gets the Etags. * * @return array The entity tags * @static */ public static function getETags(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getETags(); } /** * * * @return bool * @static */ public static function isNoCache(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isNoCache(); } /** * Returns the preferred language. * * @param array $locales An array of ordered available locales * @return string|null The preferred locale * @api * @static */ public static function getPreferredLanguage($locales = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPreferredLanguage($locales); } /** * Gets a list of languages acceptable by the client browser. * * @return array Languages ordered in the user browser preferences * @api * @static */ public static function getLanguages(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getLanguages(); } /** * Gets a list of charsets acceptable by the client browser. * * @return array List of charsets in preferable order * @api * @static */ public static function getCharsets(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getCharsets(); } /** * Gets a list of encodings acceptable by the client browser. * * @return array List of encodings in preferable order * @static */ public static function getEncodings(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getEncodings(); } /** * Gets a list of content types acceptable by the client browser. * * @return array List of content types in preferable order * @api * @static */ public static function getAcceptableContentTypes(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getAcceptableContentTypes(); } /** * Returns true if the request is a XMLHttpRequest. * * It works if your JavaScript library sets an X-Requested-With HTTP header. * It is known to work with common JavaScript frameworks: * * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript * @return bool true if the request is an XMLHttpRequest, false otherwise * @api * @static */ public static function isXmlHttpRequest(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isXmlHttpRequest(); } } class Lang extends \Illuminate\Support\Facades\Lang{ /** * Determine if a translation exists. * * @param string $key * @param string $locale * @return bool * @static */ public static function has($key, $locale = null){ return \Illuminate\Translation\Translator::has($key, $locale); } /** * Get the translation for the given key. * * @param string $key * @param array $replace * @param string $locale * @return string * @static */ public static function get($key, $replace = array(), $locale = null){ return \Illuminate\Translation\Translator::get($key, $replace, $locale); } /** * Get a translation according to an integer value. * * @param string $key * @param int $number * @param array $replace * @param string $locale * @return string * @static */ public static function choice($key, $number, $replace = array(), $locale = null){ return \Illuminate\Translation\Translator::choice($key, $number, $replace, $locale); } /** * Get the translation for a given key. * * @param string $id * @param array $parameters * @param string $domain * @param string $locale * @return string * @static */ public static function trans($id, $parameters = array(), $domain = 'messages', $locale = null){ return \Illuminate\Translation\Translator::trans($id, $parameters, $domain, $locale); } /** * Get a translation according to an integer value. * * @param string $id * @param int $number * @param array $parameters * @param string $domain * @param string $locale * @return string * @static */ public static function transChoice($id, $number, $parameters = array(), $domain = 'messages', $locale = null){ return \Illuminate\Translation\Translator::transChoice($id, $number, $parameters, $domain, $locale); } /** * Load the specified language group. * * @param string $namespace * @param string $group * @param string $locale * @return void * @static */ public static function load($namespace, $group, $locale){ \Illuminate\Translation\Translator::load($namespace, $group, $locale); } /** * Add a new namespace to the loader. * * @param string $namespace * @param string $hint * @return void * @static */ public static function addNamespace($namespace, $hint){ \Illuminate\Translation\Translator::addNamespace($namespace, $hint); } /** * Parse a key into namespace, group, and item. * * @param string $key * @return array * @static */ public static function parseKey($key){ return \Illuminate\Translation\Translator::parseKey($key); } /** * Get the message selector instance. * * @return \Symfony\Component\Translation\MessageSelector * @static */ public static function getSelector(){ return \Illuminate\Translation\Translator::getSelector(); } /** * Set the message selector instance. * * @param \Symfony\Component\Translation\MessageSelector $selector * @return void * @static */ public static function setSelector($selector){ \Illuminate\Translation\Translator::setSelector($selector); } /** * Get the language line loader implementation. * * @return \Illuminate\Translation\LoaderInterface * @static */ public static function getLoader(){ return \Illuminate\Translation\Translator::getLoader(); } /** * Get the default locale being used. * * @return string * @static */ public static function locale(){ return \Illuminate\Translation\Translator::locale(); } /** * Get the default locale being used. * * @return string * @static */ public static function getLocale(){ return \Illuminate\Translation\Translator::getLocale(); } /** * Set the default locale. * * @param string $locale * @return void * @static */ public static function setLocale($locale){ \Illuminate\Translation\Translator::setLocale($locale); } /** * Get the fallback locale being used. * * @return string * @static */ public static function getFallback(){ return \Illuminate\Translation\Translator::getFallback(); } /** * Set the fallback locale being used. * * @param string $fallback * @return void * @static */ public static function setFallback($fallback){ \Illuminate\Translation\Translator::setFallback($fallback); } /** * Set the parsed value of a key. * * @param string $key * @param array $parsed * @return void * @static */ public static function setParsedKey($key, $parsed){ //Method inherited from \Illuminate\Support\NamespacedItemResolver \Illuminate\Translation\Translator::setParsedKey($key, $parsed); } } class Mail extends \Illuminate\Support\Facades\Mail{ /** * Set the global from address and name. * * @param string $address * @param string $name * @return void * @static */ public static function alwaysFrom($address, $name = null){ \Illuminate\Mail\Mailer::alwaysFrom($address, $name); } /** * Send a new message when only a plain part. * * @param string $view * @param array $data * @param mixed $callback * @return int * @static */ public static function plain($view, $data, $callback){ return \Illuminate\Mail\Mailer::plain($view, $data, $callback); } /** * Send a new message using a view. * * @param string|array $view * @param array $data * @param \Closure|string $callback * @return void * @static */ public static function send($view, $data, $callback){ \Illuminate\Mail\Mailer::send($view, $data, $callback); } /** * Queue a new e-mail message for sending. * * @param string|array $view * @param array $data * @param \Closure|string $callback * @param string $queue * @return mixed * @static */ public static function queue($view, $data, $callback, $queue = null){ return \Illuminate\Mail\Mailer::queue($view, $data, $callback, $queue); } /** * Queue a new e-mail message for sending on the given queue. * * @param string $queue * @param string|array $view * @param array $data * @param \Closure|string $callback * @return mixed * @static */ public static function queueOn($queue, $view, $data, $callback){ return \Illuminate\Mail\Mailer::queueOn($queue, $view, $data, $callback); } /** * Queue a new e-mail message for sending after (n) seconds. * * @param int $delay * @param string|array $view * @param array $data * @param \Closure|string $callback * @param string $queue * @return mixed * @static */ public static function later($delay, $view, $data, $callback, $queue = null){ return \Illuminate\Mail\Mailer::later($delay, $view, $data, $callback, $queue); } /** * Queue a new e-mail message for sending after (n) seconds on the given queue. * * @param string $queue * @param int $delay * @param string|array $view * @param array $data * @param \Closure|string $callback * @return mixed * @static */ public static function laterOn($queue, $delay, $view, $data, $callback){ return \Illuminate\Mail\Mailer::laterOn($queue, $delay, $view, $data, $callback); } /** * Handle a queued e-mail message job. * * @param \Illuminate\Queue\Jobs\Job $job * @param array $data * @return void * @static */ public static function handleQueuedMessage($job, $data){ \Illuminate\Mail\Mailer::handleQueuedMessage($job, $data); } /** * Tell the mailer to not really send messages. * * @param bool $value * @return void * @static */ public static function pretend($value = true){ \Illuminate\Mail\Mailer::pretend($value); } /** * Check if the mailer is pretending to send messages. * * @return bool * @static */ public static function isPretending(){ return \Illuminate\Mail\Mailer::isPretending(); } /** * Get the view factory instance. * * @return \Illuminate\View\Factory * @static */ public static function getViewFactory(){ return \Illuminate\Mail\Mailer::getViewFactory(); } /** * Get the Swift Mailer instance. * * @return \Swift_Mailer * @static */ public static function getSwiftMailer(){ return \Illuminate\Mail\Mailer::getSwiftMailer(); } /** * Get the array of failed recipients. * * @return array * @static */ public static function failures(){ return \Illuminate\Mail\Mailer::failures(); } /** * Set the Swift Mailer instance. * * @param \Swift_Mailer $swift * @return void * @static */ public static function setSwiftMailer($swift){ \Illuminate\Mail\Mailer::setSwiftMailer($swift); } /** * Set the log writer instance. * * @param \Illuminate\Log\Writer $logger * @return $this * @static */ public static function setLogger($logger){ return \Illuminate\Mail\Mailer::setLogger($logger); } /** * Set the queue manager instance. * * @param \Illuminate\Queue\QueueManager $queue * @return $this * @static */ public static function setQueue($queue){ return \Illuminate\Mail\Mailer::setQueue($queue); } /** * Set the IoC container instance. * * @param \Illuminate\Container\Container $container * @return void * @static */ public static function setContainer($container){ \Illuminate\Mail\Mailer::setContainer($container); } } class Paginator extends \Illuminate\Support\Facades\Paginator{ /** * Get a new paginator instance. * * @param array $items * @param int $total * @param int|null $perPage * @return \Illuminate\Pagination\Paginator * @static */ public static function make($items, $total, $perPage = null){ return \Illuminate\Pagination\Factory::make($items, $total, $perPage); } /** * Get the pagination view. * * @param \Illuminate\Pagination\Paginator $paginator * @param string $view * @return \Illuminate\View\View * @static */ public static function getPaginationView($paginator, $view = null){ return \Illuminate\Pagination\Factory::getPaginationView($paginator, $view); } /** * Get the number of the current page. * * @return int * @static */ public static function getCurrentPage(){ return \Illuminate\Pagination\Factory::getCurrentPage(); } /** * Set the number of the current page. * * @param int $number * @return void * @static */ public static function setCurrentPage($number){ \Illuminate\Pagination\Factory::setCurrentPage($number); } /** * Get the root URL for the request. * * @return string * @static */ public static function getCurrentUrl(){ return \Illuminate\Pagination\Factory::getCurrentUrl(); } /** * Set the base URL in use by the paginator. * * @param string $baseUrl * @return void * @static */ public static function setBaseUrl($baseUrl){ \Illuminate\Pagination\Factory::setBaseUrl($baseUrl); } /** * Set the input page parameter name used by the paginator. * * @param string $pageName * @return void * @static */ public static function setPageName($pageName){ \Illuminate\Pagination\Factory::setPageName($pageName); } /** * Get the input page parameter name used by the paginator. * * @return string * @static */ public static function getPageName(){ return \Illuminate\Pagination\Factory::getPageName(); } /** * Get the name of the pagination view. * * @param string $view * @return string * @static */ public static function getViewName($view = null){ return \Illuminate\Pagination\Factory::getViewName($view); } /** * Set the name of the pagination view. * * @param string $viewName * @return void * @static */ public static function setViewName($viewName){ \Illuminate\Pagination\Factory::setViewName($viewName); } /** * Get the locale of the paginator. * * @return string * @static */ public static function getLocale(){ return \Illuminate\Pagination\Factory::getLocale(); } /** * Set the locale of the paginator. * * @param string $locale * @return void * @static */ public static function setLocale($locale){ \Illuminate\Pagination\Factory::setLocale($locale); } /** * Get the active request instance. * * @return \Symfony\Component\HttpFoundation\Request * @static */ public static function getRequest(){ return \Illuminate\Pagination\Factory::getRequest(); } /** * Set the active request instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void * @static */ public static function setRequest($request){ \Illuminate\Pagination\Factory::setRequest($request); } /** * Get the current view factory. * * @return \Illuminate\View\Factory * @static */ public static function getViewFactory(){ return \Illuminate\Pagination\Factory::getViewFactory(); } /** * Set the current view factory. * * @param \Illuminate\View\Factory $view * @return void * @static */ public static function setViewFactory($view){ \Illuminate\Pagination\Factory::setViewFactory($view); } /** * Get the translator instance. * * @return \Symfony\Component\Translation\TranslatorInterface * @static */ public static function getTranslator(){ return \Illuminate\Pagination\Factory::getTranslator(); } } class Password extends \Illuminate\Support\Facades\Password{ /** * Send a password reminder to a user. * * @param array $credentials * @param \Closure $callback * @return string * @static */ public static function remind($credentials, $callback = null){ return \Illuminate\Auth\Reminders\PasswordBroker::remind($credentials, $callback); } /** * Send the password reminder e-mail. * * @param \Illuminate\Auth\Reminders\RemindableInterface $user * @param string $token * @param \Closure $callback * @return int * @static */ public static function sendReminder($user, $token, $callback = null){ return \Illuminate\Auth\Reminders\PasswordBroker::sendReminder($user, $token, $callback); } /** * Reset the password for the given token. * * @param array $credentials * @param \Closure $callback * @return mixed * @static */ public static function reset($credentials, $callback){ return \Illuminate\Auth\Reminders\PasswordBroker::reset($credentials, $callback); } /** * Set a custom password validator. * * @param \Closure $callback * @return void * @static */ public static function validator($callback){ \Illuminate\Auth\Reminders\PasswordBroker::validator($callback); } /** * Get the user for the given credentials. * * @param array $credentials * @return \Illuminate\Auth\Reminders\RemindableInterface * @throws \UnexpectedValueException * @static */ public static function getUser($credentials){ return \Illuminate\Auth\Reminders\PasswordBroker::getUser($credentials); } } class Queue extends \Illuminate\Support\Facades\Queue{ /** * Register an event listener for the daemon queue loop. * * @param mixed $callback * @return void * @static */ public static function looping($callback){ \Illuminate\Queue\QueueManager::looping($callback); } /** * Register an event listener for the failed job event. * * @param mixed $callback * @return void * @static */ public static function failing($callback){ \Illuminate\Queue\QueueManager::failing($callback); } /** * Register an event listener for the daemon queue stopping. * * @param mixed $callback * @return void * @static */ public static function stopping($callback){ \Illuminate\Queue\QueueManager::stopping($callback); } /** * Determine if the driver is connected. * * @param string $name * @return bool * @static */ public static function connected($name = null){ return \Illuminate\Queue\QueueManager::connected($name); } /** * Resolve a queue connection instance. * * @param string $name * @return \Illuminate\Queue\SyncQueue * @static */ public static function connection($name = null){ return \Illuminate\Queue\QueueManager::connection($name); } /** * Add a queue connection resolver. * * @param string $driver * @param \Closure $resolver * @return void * @static */ public static function extend($driver, $resolver){ \Illuminate\Queue\QueueManager::extend($driver, $resolver); } /** * Add a queue connection resolver. * * @param string $driver * @param \Closure $resolver * @return void * @static */ public static function addConnector($driver, $resolver){ \Illuminate\Queue\QueueManager::addConnector($driver, $resolver); } /** * Get the name of the default queue connection. * * @return string * @static */ public static function getDefaultDriver(){ return \Illuminate\Queue\QueueManager::getDefaultDriver(); } /** * Set the name of the default queue connection. * * @param string $name * @return void * @static */ public static function setDefaultDriver($name){ \Illuminate\Queue\QueueManager::setDefaultDriver($name); } /** * Get the full name for the given connection. * * @param string $connection * @return string * @static */ public static function getName($connection = null){ return \Illuminate\Queue\QueueManager::getName($connection); } /** * Determine if the application is in maintenance mode. * * @return bool * @static */ public static function isDownForMaintenance(){ return \Illuminate\Queue\QueueManager::isDownForMaintenance(); } /** * Push a new job onto the queue. * * @param string $job * @param mixed $data * @param string $queue * @return mixed * @static */ public static function push($job, $data = '', $queue = null){ return \Illuminate\Queue\SyncQueue::push($job, $data, $queue); } /** * Push a raw payload onto the queue. * * @param string $payload * @param string $queue * @param array $options * @return mixed * @static */ public static function pushRaw($payload, $queue = null, $options = array()){ return \Illuminate\Queue\SyncQueue::pushRaw($payload, $queue, $options); } /** * Push a new job onto the queue after a delay. * * @param \DateTime|int $delay * @param string $job * @param mixed $data * @param string $queue * @return mixed * @static */ public static function later($delay, $job, $data = '', $queue = null){ return \Illuminate\Queue\SyncQueue::later($delay, $job, $data, $queue); } /** * Pop the next job off of the queue. * * @param string $queue * @return \Illuminate\Queue\Jobs\Job|null * @static */ public static function pop($queue = null){ return \Illuminate\Queue\SyncQueue::pop($queue); } /** * Marshal a push queue request and fire the job. * * @throws \RuntimeException * @static */ public static function marshal(){ //Method inherited from \Illuminate\Queue\Queue return \Illuminate\Queue\SyncQueue::marshal(); } /** * Push an array of jobs onto the queue. * * @param array $jobs * @param mixed $data * @param string $queue * @return mixed * @static */ public static function bulk($jobs, $data = '', $queue = null){ //Method inherited from \Illuminate\Queue\Queue return \Illuminate\Queue\SyncQueue::bulk($jobs, $data, $queue); } /** * Get the current UNIX timestamp. * * @return int * @static */ public static function getTime(){ //Method inherited from \Illuminate\Queue\Queue return \Illuminate\Queue\SyncQueue::getTime(); } /** * Set the IoC container instance. * * @param \Illuminate\Container\Container $container * @return void * @static */ public static function setContainer($container){ //Method inherited from \Illuminate\Queue\Queue \Illuminate\Queue\SyncQueue::setContainer($container); } /** * Set the encrypter instance. * * @param \Illuminate\Encryption\Encrypter $crypt * @return void * @static */ public static function setEncrypter($crypt){ //Method inherited from \Illuminate\Queue\Queue \Illuminate\Queue\SyncQueue::setEncrypter($crypt); } } class Redirect extends \Illuminate\Support\Facades\Redirect{ /** * Create a new redirect response to the "home" route. * * @param int $status * @return \Illuminate\Http\RedirectResponse * @static */ public static function home($status = 302){ return \Illuminate\Routing\Redirector::home($status); } /** * Create a new redirect response to the previous location. * * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function back($status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::back($status, $headers); } /** * Create a new redirect response to the current URI. * * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function refresh($status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::refresh($status, $headers); } /** * Create a new redirect response, while putting the current URL in the session. * * @param string $path * @param int $status * @param array $headers * @param bool $secure * @return \Illuminate\Http\RedirectResponse * @static */ public static function guest($path, $status = 302, $headers = array(), $secure = null){ return \Illuminate\Routing\Redirector::guest($path, $status, $headers, $secure); } /** * Create a new redirect response to the previously intended location. * * @param string $default * @param int $status * @param array $headers * @param bool $secure * @return \Illuminate\Http\RedirectResponse * @static */ public static function intended($default = '/', $status = 302, $headers = array(), $secure = null){ return \Illuminate\Routing\Redirector::intended($default, $status, $headers, $secure); } /** * Create a new redirect response to the given path. * * @param string $path * @param int $status * @param array $headers * @param bool $secure * @return \Illuminate\Http\RedirectResponse * @static */ public static function to($path, $status = 302, $headers = array(), $secure = null){ return \Illuminate\Routing\Redirector::to($path, $status, $headers, $secure); } /** * Create a new redirect response to an external URL (no validation). * * @param string $path * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function away($path, $status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::away($path, $status, $headers); } /** * Create a new redirect response to the given HTTPS path. * * @param string $path * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function secure($path, $status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::secure($path, $status, $headers); } /** * Create a new redirect response to a named route. * * @param string $route * @param array $parameters * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function route($route, $parameters = array(), $status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::route($route, $parameters, $status, $headers); } /** * Create a new redirect response to a controller action. * * @param string $action * @param array $parameters * @param int $status * @param array $headers * @return \Illuminate\Http\RedirectResponse * @static */ public static function action($action, $parameters = array(), $status = 302, $headers = array()){ return \Illuminate\Routing\Redirector::action($action, $parameters, $status, $headers); } /** * Get the URL generator instance. * * @return \Illuminate\Routing\UrlGenerator * @static */ public static function getUrlGenerator(){ return \Illuminate\Routing\Redirector::getUrlGenerator(); } /** * Set the active session store. * * @param \Illuminate\Session\Store $session * @return void * @static */ public static function setSession($session){ \Illuminate\Routing\Redirector::setSession($session); } } class Redis extends \Illuminate\Support\Facades\Redis{ /** * Get a specific Redis connection instance. * * @param string $name * @return \Predis\ClientInterface * @static */ public static function connection($name = 'default'){ return \Illuminate\Redis\Database::connection($name); } /** * Run a command against the Redis database. * * @param string $method * @param array $parameters * @return mixed * @static */ public static function command($method, $parameters = array()){ return \Illuminate\Redis\Database::command($method, $parameters); } } class Request extends \Illuminate\Support\Facades\Request{ /** * Return the Request instance. * * @return $this * @static */ public static function instance(){ return \Illuminate\Http\Request::instance(); } /** * Get the request method. * * @return string * @static */ public static function method(){ return \Illuminate\Http\Request::method(); } /** * Get the root URL for the application. * * @return string * @static */ public static function root(){ return \Illuminate\Http\Request::root(); } /** * Get the URL (no query string) for the request. * * @return string * @static */ public static function url(){ return \Illuminate\Http\Request::url(); } /** * Get the full URL for the request. * * @return string * @static */ public static function fullUrl(){ return \Illuminate\Http\Request::fullUrl(); } /** * Get the current path info for the request. * * @return string * @static */ public static function path(){ return \Illuminate\Http\Request::path(); } /** * Get the current encoded path info for the request. * * @return string * @static */ public static function decodedPath(){ return \Illuminate\Http\Request::decodedPath(); } /** * Get a segment from the URI (1 based index). * * @param string $index * @param mixed $default * @return string * @static */ public static function segment($index, $default = null){ return \Illuminate\Http\Request::segment($index, $default); } /** * Get all of the segments for the request path. * * @return array * @static */ public static function segments(){ return \Illuminate\Http\Request::segments(); } /** * Determine if the current request URI matches a pattern. * * @param mixed string * @return bool * @static */ public static function is(){ return \Illuminate\Http\Request::is(); } /** * Determine if the request is the result of an AJAX call. * * @return bool * @static */ public static function ajax(){ return \Illuminate\Http\Request::ajax(); } /** * Determine if the request is over HTTPS. * * @return bool * @static */ public static function secure(){ return \Illuminate\Http\Request::secure(); } /** * Returns the client IP address. * * @return string * @static */ public static function ip(){ return \Illuminate\Http\Request::ip(); } /** * Returns the client IP addresses. * * @return array * @static */ public static function ips(){ return \Illuminate\Http\Request::ips(); } /** * Determine if the request contains a given input item key. * * @param string|array $key * @return bool * @static */ public static function exists($key){ return \Illuminate\Http\Request::exists($key); } /** * Determine if the request contains a non-empty value for an input item. * * @param string|array $key * @return bool * @static */ public static function has($key){ return \Illuminate\Http\Request::has($key); } /** * Get all of the input and files for the request. * * @return array * @static */ public static function all(){ return \Illuminate\Http\Request::all(); } /** * Retrieve an input item from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function input($key = null, $default = null){ return \Illuminate\Http\Request::input($key, $default); } /** * Get a subset of the items from the input data. * * @param array $keys * @return array * @static */ public static function only($keys){ return \Illuminate\Http\Request::only($keys); } /** * Get all of the input except for a specified array of items. * * @param array $keys * @return array * @static */ public static function except($keys){ return \Illuminate\Http\Request::except($keys); } /** * Retrieve a query string item from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function query($key = null, $default = null){ return \Illuminate\Http\Request::query($key, $default); } /** * Determine if a cookie is set on the request. * * @param string $key * @return bool * @static */ public static function hasCookie($key){ return \Illuminate\Http\Request::hasCookie($key); } /** * Retrieve a cookie from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function cookie($key = null, $default = null){ return \Illuminate\Http\Request::cookie($key, $default); } /** * Retrieve a file from the request. * * @param string $key * @param mixed $default * @return \Symfony\Component\HttpFoundation\File\UploadedFile|array * @static */ public static function file($key = null, $default = null){ return \Illuminate\Http\Request::file($key, $default); } /** * Determine if the uploaded data contains a file. * * @param string $key * @return bool * @static */ public static function hasFile($key){ return \Illuminate\Http\Request::hasFile($key); } /** * Retrieve a header from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function header($key = null, $default = null){ return \Illuminate\Http\Request::header($key, $default); } /** * Retrieve a server variable from the request. * * @param string $key * @param mixed $default * @return string * @static */ public static function server($key = null, $default = null){ return \Illuminate\Http\Request::server($key, $default); } /** * Retrieve an old input item. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function old($key = null, $default = null){ return \Illuminate\Http\Request::old($key, $default); } /** * Flash the input for the current request to the session. * * @param string $filter * @param array $keys * @return void * @static */ public static function flash($filter = null, $keys = array()){ \Illuminate\Http\Request::flash($filter, $keys); } /** * Flash only some of the input to the session. * * @param mixed string * @return void * @static */ public static function flashOnly($keys){ \Illuminate\Http\Request::flashOnly($keys); } /** * Flash only some of the input to the session. * * @param mixed string * @return void * @static */ public static function flashExcept($keys){ \Illuminate\Http\Request::flashExcept($keys); } /** * Flush all of the old input from the session. * * @return void * @static */ public static function flush(){ \Illuminate\Http\Request::flush(); } /** * Merge new input into the current request's input array. * * @param array $input * @return void * @static */ public static function merge($input){ \Illuminate\Http\Request::merge($input); } /** * Replace the input for the current request. * * @param array $input * @return void * @static */ public static function replace($input){ \Illuminate\Http\Request::replace($input); } /** * Get the JSON payload for the request. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function json($key = null, $default = null){ return \Illuminate\Http\Request::json($key, $default); } /** * Determine if the request is sending JSON. * * @return bool * @static */ public static function isJson(){ return \Illuminate\Http\Request::isJson(); } /** * Determine if the current request is asking for JSON in return. * * @return bool * @static */ public static function wantsJson(){ return \Illuminate\Http\Request::wantsJson(); } /** * Get the data format expected in the response. * * @param string $default * @return string * @static */ public static function format($default = 'html'){ return \Illuminate\Http\Request::format($default); } /** * Create an Illuminate request from a Symfony instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return \Illuminate\Http\Request * @static */ public static function createFromBase($request){ return \Illuminate\Http\Request::createFromBase($request); } /** * Get the session associated with the request. * * @return \Illuminate\Session\Store * @throws \RuntimeException * @static */ public static function session(){ return \Illuminate\Http\Request::session(); } /** * Sets the parameters for this request. * * This method also re-initializes all properties. * * @param array $query The GET parameters * @param array $request The POST parameters * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) * @param array $cookies The COOKIE parameters * @param array $files The FILES parameters * @param array $server The SERVER parameters * @param string $content The raw body data * @api * @static */ public static function initialize($query = array(), $request = array(), $attributes = array(), $cookies = array(), $files = array(), $server = array(), $content = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::initialize($query, $request, $attributes, $cookies, $files, $server, $content); } /** * Creates a new request with values from PHP's super globals. * * @return \Symfony\Component\HttpFoundation\Request A new request * @api * @static */ public static function createFromGlobals(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::createFromGlobals(); } /** * Creates a Request based on a given URI and configuration. * * The information contained in the URI always take precedence * over the other information (server and parameters). * * @param string $uri The URI * @param string $method The HTTP method * @param array $parameters The query (GET) or request (POST) parameters * @param array $cookies The request cookies ($_COOKIE) * @param array $files The request files ($_FILES) * @param array $server The server parameters ($_SERVER) * @param string $content The raw body data * @return \Symfony\Component\HttpFoundation\Request A Request instance * @api * @static */ public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::create($uri, $method, $parameters, $cookies, $files, $server, $content); } /** * Sets a callable able to create a Request instance. * * This is mainly useful when you need to override the Request class * to keep BC with an existing system. It should not be used for any * other purpose. * * @param callable|null $callable A PHP callable * @static */ public static function setFactory($callable){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setFactory($callable); } /** * Clones a request and overrides some of its parameters. * * @param array $query The GET parameters * @param array $request The POST parameters * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) * @param array $cookies The COOKIE parameters * @param array $files The FILES parameters * @param array $server The SERVER parameters * @return \Symfony\Component\HttpFoundation\Request The duplicated request * @api * @static */ public static function duplicate($query = null, $request = null, $attributes = null, $cookies = null, $files = null, $server = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::duplicate($query, $request, $attributes, $cookies, $files, $server); } /** * Overrides the PHP global variables according to this request instance. * * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. * $_FILES is never overridden, see rfc1867 * * @api * @static */ public static function overrideGlobals(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::overrideGlobals(); } /** * Sets a list of trusted proxies. * * You should only list the reverse proxies that you manage directly. * * @param array $proxies A list of trusted proxies * @api * @static */ public static function setTrustedProxies($proxies){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedProxies($proxies); } /** * Gets the list of trusted proxies. * * @return array An array of trusted proxies. * @static */ public static function getTrustedProxies(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedProxies(); } /** * Sets a list of trusted host patterns. * * You should only list the hosts you manage using regexs. * * @param array $hostPatterns A list of trusted host patterns * @static */ public static function setTrustedHosts($hostPatterns){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedHosts($hostPatterns); } /** * Gets the list of trusted host patterns. * * @return array An array of trusted host patterns. * @static */ public static function getTrustedHosts(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedHosts(); } /** * Sets the name for trusted headers. * * The following header keys are supported: * * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp()) * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getClientHost()) * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getClientPort()) * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure()) * * Setting an empty value allows to disable the trusted header for the given key. * * @param string $key The header key * @param string $value The header name * @throws \InvalidArgumentException * @static */ public static function setTrustedHeaderName($key, $value){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setTrustedHeaderName($key, $value); } /** * Gets the trusted proxy header name. * * @param string $key The header key * @return string The header name * @throws \InvalidArgumentException * @static */ public static function getTrustedHeaderName($key){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getTrustedHeaderName($key); } /** * Normalizes a query string. * * It builds a normalized query string, where keys/value pairs are alphabetized, * have consistent escaping and unneeded delimiters are removed. * * @param string $qs Query string * @return string A normalized query string for the Request * @static */ public static function normalizeQueryString($qs){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::normalizeQueryString($qs); } /** * Enables support for the _method request parameter to determine the intended HTTP method. * * Be warned that enabling this feature might lead to CSRF issues in your code. * Check that you are using CSRF tokens when required. * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered * and used to send a "PUT" or "DELETE" request via the _method request parameter. * If these methods are not protected against CSRF, this presents a possible vulnerability. * * The HTTP method can only be overridden when the real HTTP method is POST. * * @static */ public static function enableHttpMethodParameterOverride(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::enableHttpMethodParameterOverride(); } /** * Checks whether support for the _method request parameter is enabled. * * @return bool True when the _method request parameter is enabled, false otherwise * @static */ public static function getHttpMethodParameterOverride(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHttpMethodParameterOverride(); } /** * Gets a "parameter" value. * * This method is mainly useful for libraries that want to provide some flexibility. * * Order of precedence: GET, PATH, POST * * Avoid using this method in controllers: * * * slow * * prefer to get from a "named" source * * It is better to explicitly get request parameters from the appropriate * public property instead (query, attributes, request). * * @param string $key the key * @param mixed $default the default value * @param bool $deep is parameter deep in multidimensional array * @return mixed * @static */ public static function get($key, $default = null, $deep = false){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::get($key, $default, $deep); } /** * Gets the Session. * * @return \Symfony\Component\HttpFoundation\SessionInterface|null The session * @api * @static */ public static function getSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getSession(); } /** * Whether the request contains a Session which was started in one of the * previous requests. * * @return bool * @api * @static */ public static function hasPreviousSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::hasPreviousSession(); } /** * Whether the request contains a Session object. * * This method does not give any information about the state of the session object, * like whether the session is started or not. It is just a way to check if this Request * is associated with a Session instance. * * @return bool true when the Request contains a Session object, false otherwise * @api * @static */ public static function hasSession(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::hasSession(); } /** * Sets the Session. * * @param \Symfony\Component\HttpFoundation\SessionInterface $session The Session * @api * @static */ public static function setSession($session){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setSession($session); } /** * Returns the client IP addresses. * * In the returned array the most trusted IP address is first, and the * least trusted one last. The "real" client IP address is the last one, * but this is also the least trusted one. Trusted proxies are stripped. * * Use this method carefully; you should use getClientIp() instead. * * @return array The client IP addresses * @see getClientIp() * @static */ public static function getClientIps(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getClientIps(); } /** * Returns the client IP address. * * This method can read the client IP address from the "X-Forwarded-For" header * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" * header value is a comma+space separated list of IP addresses, the left-most * being the original client, and each successive proxy that passed the request * adding the IP address where it received the request from. * * If your reverse proxy uses a different header name than "X-Forwarded-For", * ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with * the "client-ip" key. * * @return string The client IP address * @see getClientIps() * @see http://en.wikipedia.org/wiki/X-Forwarded-For * @api * @static */ public static function getClientIp(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getClientIp(); } /** * Returns current script name. * * @return string * @api * @static */ public static function getScriptName(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getScriptName(); } /** * Returns the path being requested relative to the executed script. * * The path info always starts with a /. * * Suppose this request is instantiated from /mysite on localhost: * * * http://localhost/mysite returns an empty string * * http://localhost/mysite/about returns '/about' * * http://localhost/mysite/enco%20ded returns '/enco%20ded' * * http://localhost/mysite/about?var=1 returns '/about' * * @return string The raw path (i.e. not urldecoded) * @api * @static */ public static function getPathInfo(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPathInfo(); } /** * Returns the root path from which this request is executed. * * Suppose that an index.php file instantiates this request object: * * * http://localhost/index.php returns an empty string * * http://localhost/index.php/page returns an empty string * * http://localhost/web/index.php returns '/web' * * http://localhost/we%20b/index.php returns '/we%20b' * * @return string The raw path (i.e. not urldecoded) * @api * @static */ public static function getBasePath(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getBasePath(); } /** * Returns the root URL from which this request is executed. * * The base URL never ends with a /. * * This is similar to getBasePath(), except that it also includes the * script filename (e.g. index.php) if one exists. * * @return string The raw URL (i.e. not urldecoded) * @api * @static */ public static function getBaseUrl(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getBaseUrl(); } /** * Gets the request's scheme. * * @return string * @api * @static */ public static function getScheme(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getScheme(); } /** * Returns the port on which the request is made. * * This method can read the client port from the "X-Forwarded-Port" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Port" header must contain the client port. * * If your reverse proxy uses a different header name than "X-Forwarded-Port", * configure it via "setTrustedHeaderName()" with the "client-port" key. * * @return string * @api * @static */ public static function getPort(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPort(); } /** * Returns the user. * * @return string|null * @static */ public static function getUser(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUser(); } /** * Returns the password. * * @return string|null * @static */ public static function getPassword(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPassword(); } /** * Gets the user info. * * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server * @static */ public static function getUserInfo(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUserInfo(); } /** * Returns the HTTP host being requested. * * The port name will be appended to the host if it's non-standard. * * @return string * @api * @static */ public static function getHttpHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHttpHost(); } /** * Returns the requested URI (path and query string). * * @return string The raw URI (i.e. not URI decoded) * @api * @static */ public static function getRequestUri(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRequestUri(); } /** * Gets the scheme and HTTP host. * * If the URL was called with basic authentication, the user * and the password are not added to the generated string. * * @return string The scheme and HTTP host * @static */ public static function getSchemeAndHttpHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getSchemeAndHttpHost(); } /** * Generates a normalized URI (URL) for the Request. * * @return string A normalized URI (URL) for the Request * @see getQueryString() * @api * @static */ public static function getUri(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUri(); } /** * Generates a normalized URI for the given path. * * @param string $path A path to use instead of the current one * @return string The normalized URI for the path * @api * @static */ public static function getUriForPath($path){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getUriForPath($path); } /** * Generates the normalized query string for the Request. * * It builds a normalized query string, where keys/value pairs are alphabetized * and have consistent escaping. * * @return string|null A normalized query string for the Request * @api * @static */ public static function getQueryString(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getQueryString(); } /** * Checks whether the request is secure or not. * * This method can read the client port from the "X-Forwarded-Proto" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". * * If your reverse proxy uses a different header name than "X-Forwarded-Proto" * ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with * the "client-proto" key. * * @return bool * @api * @static */ public static function isSecure(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isSecure(); } /** * Returns the host name. * * This method can read the client port from the "X-Forwarded-Host" header * when trusted proxies were set via "setTrustedProxies()". * * The "X-Forwarded-Host" header must contain the client host name. * * If your reverse proxy uses a different header name than "X-Forwarded-Host", * configure it via "setTrustedHeaderName()" with the "client-host" key. * * @return string * @throws \UnexpectedValueException when the host name is invalid * @api * @static */ public static function getHost(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getHost(); } /** * Sets the request method. * * @param string $method * @api * @static */ public static function setMethod($method){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setMethod($method); } /** * Gets the request "intended" method. * * If the X-HTTP-Method-Override header is set, and if the method is a POST, * then it is used to determine the "real" intended HTTP method. * * The _method request parameter can also be used to determine the HTTP method, * but only if enableHttpMethodParameterOverride() has been called. * * The method is always an uppercased string. * * @return string The request method * @api * @see getRealMethod() * @static */ public static function getMethod(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getMethod(); } /** * Gets the "real" request method. * * @return string The request method * @see getMethod() * @static */ public static function getRealMethod(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRealMethod(); } /** * Gets the mime type associated with the format. * * @param string $format The format * @return string The associated mime type (null if not found) * @api * @static */ public static function getMimeType($format){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getMimeType($format); } /** * Gets the format associated with the mime type. * * @param string $mimeType The associated mime type * @return string|null The format (null if not found) * @api * @static */ public static function getFormat($mimeType){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getFormat($mimeType); } /** * Associates a format with mime types. * * @param string $format The format * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) * @api * @static */ public static function setFormat($format, $mimeTypes){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setFormat($format, $mimeTypes); } /** * Gets the request format. * * Here is the process to determine the format: * * * format defined by the user (with setRequestFormat()) * * _format request parameter * * $default * * @param string $default The default format * @return string The request format * @api * @static */ public static function getRequestFormat($default = 'html'){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getRequestFormat($default); } /** * Sets the request format. * * @param string $format The request format. * @api * @static */ public static function setRequestFormat($format){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setRequestFormat($format); } /** * Gets the format associated with the request. * * @return string|null The format (null if no content type is present) * @api * @static */ public static function getContentType(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getContentType(); } /** * Sets the default locale. * * @param string $locale * @api * @static */ public static function setDefaultLocale($locale){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setDefaultLocale($locale); } /** * Get the default locale. * * @return string * @static */ public static function getDefaultLocale(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getDefaultLocale(); } /** * Sets the locale. * * @param string $locale * @api * @static */ public static function setLocale($locale){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::setLocale($locale); } /** * Get the locale. * * @return string * @static */ public static function getLocale(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getLocale(); } /** * Checks if the request method is of specified type. * * @param string $method Uppercase request method (GET, POST etc). * @return bool * @static */ public static function isMethod($method){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isMethod($method); } /** * Checks whether the method is safe or not. * * @return bool * @api * @static */ public static function isMethodSafe(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isMethodSafe(); } /** * Returns the request body content. * * @param bool $asResource If true, a resource will be returned * @return string|resource The request body content or a resource to read the body stream. * @throws \LogicException * @static */ public static function getContent($asResource = false){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getContent($asResource); } /** * Gets the Etags. * * @return array The entity tags * @static */ public static function getETags(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getETags(); } /** * * * @return bool * @static */ public static function isNoCache(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isNoCache(); } /** * Returns the preferred language. * * @param array $locales An array of ordered available locales * @return string|null The preferred locale * @api * @static */ public static function getPreferredLanguage($locales = null){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getPreferredLanguage($locales); } /** * Gets a list of languages acceptable by the client browser. * * @return array Languages ordered in the user browser preferences * @api * @static */ public static function getLanguages(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getLanguages(); } /** * Gets a list of charsets acceptable by the client browser. * * @return array List of charsets in preferable order * @api * @static */ public static function getCharsets(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getCharsets(); } /** * Gets a list of encodings acceptable by the client browser. * * @return array List of encodings in preferable order * @static */ public static function getEncodings(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getEncodings(); } /** * Gets a list of content types acceptable by the client browser. * * @return array List of content types in preferable order * @api * @static */ public static function getAcceptableContentTypes(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::getAcceptableContentTypes(); } /** * Returns true if the request is a XMLHttpRequest. * * It works if your JavaScript library sets an X-Requested-With HTTP header. * It is known to work with common JavaScript frameworks: * * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript * @return bool true if the request is an XMLHttpRequest, false otherwise * @api * @static */ public static function isXmlHttpRequest(){ //Method inherited from \Symfony\Component\HttpFoundation\Request return \Illuminate\Http\Request::isXmlHttpRequest(); } } class Response extends \Illuminate\Support\Facades\Response{ } class Route extends \Illuminate\Support\Facades\Route{ /** * Register a new GET route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function get($uri, $action){ return \Illuminate\Routing\Router::get($uri, $action); } /** * Register a new POST route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function post($uri, $action){ return \Illuminate\Routing\Router::post($uri, $action); } /** * Register a new PUT route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function put($uri, $action){ return \Illuminate\Routing\Router::put($uri, $action); } /** * Register a new PATCH route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function patch($uri, $action){ return \Illuminate\Routing\Router::patch($uri, $action); } /** * Register a new DELETE route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function delete($uri, $action){ return \Illuminate\Routing\Router::delete($uri, $action); } /** * Register a new OPTIONS route with the router. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function options($uri, $action){ return \Illuminate\Routing\Router::options($uri, $action); } /** * Register a new route responding to all verbs. * * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function any($uri, $action){ return \Illuminate\Routing\Router::any($uri, $action); } /** * Register a new route with the given verbs. * * @param array|string $methods * @param string $uri * @param \Closure|array|string $action * @return \Illuminate\Routing\Route * @static */ public static function match($methods, $uri, $action){ return \Illuminate\Routing\Router::match($methods, $uri, $action); } /** * Register an array of controllers with wildcard routing. * * @param array $controllers * @return void * @static */ public static function controllers($controllers){ \Illuminate\Routing\Router::controllers($controllers); } /** * Route a controller to a URI with wildcard routing. * * @param string $uri * @param string $controller * @param array $names * @return void * @static */ public static function controller($uri, $controller, $names = array()){ \Illuminate\Routing\Router::controller($uri, $controller, $names); } /** * Route a resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return void * @static */ public static function resource($name, $controller, $options = array()){ \Illuminate\Routing\Router::resource($name, $controller, $options); } /** * Get the base resource URI for a given resource. * * @param string $resource * @return string * @static */ public static function getResourceUri($resource){ return \Illuminate\Routing\Router::getResourceUri($resource); } /** * Format a resource wildcard for usage. * * @param string $value * @return string * @static */ public static function getResourceWildcard($value){ return \Illuminate\Routing\Router::getResourceWildcard($value); } /** * Create a route group with shared attributes. * * @param array $attributes * @param \Closure $callback * @return void * @static */ public static function group($attributes, $callback){ \Illuminate\Routing\Router::group($attributes, $callback); } /** * Merge the given array with the last group stack. * * @param array $new * @return array * @static */ public static function mergeWithLastGroup($new){ return \Illuminate\Routing\Router::mergeWithLastGroup($new); } /** * Merge the given group attributes. * * @param array $new * @param array $old * @return array * @static */ public static function mergeGroup($new, $old){ return \Illuminate\Routing\Router::mergeGroup($new, $old); } /** * Dispatch the request to the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response * @static */ public static function dispatch($request){ return \Illuminate\Routing\Router::dispatch($request); } /** * Dispatch the request to a route and return the response. * * @param \Illuminate\Http\Request $request * @return mixed * @static */ public static function dispatchToRoute($request){ return \Illuminate\Routing\Router::dispatchToRoute($request); } /** * Register a route matched event listener. * * @param string|callable $callback * @return void * @static */ public static function matched($callback){ \Illuminate\Routing\Router::matched($callback); } /** * Register a new "before" filter with the router. * * @param string|callable $callback * @return void * @static */ public static function before($callback){ \Illuminate\Routing\Router::before($callback); } /** * Register a new "after" filter with the router. * * @param string|callable $callback * @return void * @static */ public static function after($callback){ \Illuminate\Routing\Router::after($callback); } /** * Register a new filter with the router. * * @param string $name * @param string|callable $callback * @return void * @static */ public static function filter($name, $callback){ \Illuminate\Routing\Router::filter($name, $callback); } /** * Register a pattern-based filter with the router. * * @param string $pattern * @param string $name * @param array|null $methods * @return void * @static */ public static function when($pattern, $name, $methods = null){ \Illuminate\Routing\Router::when($pattern, $name, $methods); } /** * Register a regular expression based filter with the router. * * @param string $pattern * @param string $name * @param array|null $methods * @return void * @static */ public static function whenRegex($pattern, $name, $methods = null){ \Illuminate\Routing\Router::whenRegex($pattern, $name, $methods); } /** * Register a model binder for a wildcard. * * @param string $key * @param string $class * @param \Closure $callback * @return void * @throws NotFoundHttpException * @static */ public static function model($key, $class, $callback = null){ \Illuminate\Routing\Router::model($key, $class, $callback); } /** * Add a new route parameter binder. * * @param string $key * @param string|callable $binder * @return void * @static */ public static function bind($key, $binder){ \Illuminate\Routing\Router::bind($key, $binder); } /** * Create a class based binding using the IoC container. * * @param string $binding * @return \Closure * @static */ public static function createClassBinding($binding){ return \Illuminate\Routing\Router::createClassBinding($binding); } /** * Set a global where pattern on all routes * * @param string $key * @param string $pattern * @return void * @static */ public static function pattern($key, $pattern){ \Illuminate\Routing\Router::pattern($key, $pattern); } /** * Set a group of global where patterns on all routes * * @param array $patterns * @return void * @static */ public static function patterns($patterns){ \Illuminate\Routing\Router::patterns($patterns); } /** * Call the given route's before filters. * * @param \Illuminate\Routing\Route $route * @param \Illuminate\Http\Request $request * @return mixed * @static */ public static function callRouteBefore($route, $request){ return \Illuminate\Routing\Router::callRouteBefore($route, $request); } /** * Find the patterned filters matching a request. * * @param \Illuminate\Http\Request $request * @return array * @static */ public static function findPatternFilters($request){ return \Illuminate\Routing\Router::findPatternFilters($request); } /** * Call the given route's before filters. * * @param \Illuminate\Routing\Route $route * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * @return mixed * @static */ public static function callRouteAfter($route, $request, $response){ return \Illuminate\Routing\Router::callRouteAfter($route, $request, $response); } /** * Call the given route filter. * * @param string $filter * @param array $parameters * @param \Illuminate\Routing\Route $route * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response|null $response * @return mixed * @static */ public static function callRouteFilter($filter, $parameters, $route, $request, $response = null){ return \Illuminate\Routing\Router::callRouteFilter($filter, $parameters, $route, $request, $response); } /** * Run a callback with filters disable on the router. * * @param callable $callback * @return void * @static */ public static function withoutFilters($callback){ \Illuminate\Routing\Router::withoutFilters($callback); } /** * Enable route filtering on the router. * * @return void * @static */ public static function enableFilters(){ \Illuminate\Routing\Router::enableFilters(); } /** * Disable route filtering on the router. * * @return void * @static */ public static function disableFilters(){ \Illuminate\Routing\Router::disableFilters(); } /** * Get a route parameter for the current route. * * @param string $key * @param string $default * @return mixed * @static */ public static function input($key, $default = null){ return \Illuminate\Routing\Router::input($key, $default); } /** * Get the currently dispatched route instance. * * @return \Illuminate\Routing\Route * @static */ public static function getCurrentRoute(){ return \Illuminate\Routing\Router::getCurrentRoute(); } /** * Get the currently dispatched route instance. * * @return \Illuminate\Routing\Route * @static */ public static function current(){ return \Illuminate\Routing\Router::current(); } /** * Check if a route with the given name exists. * * @param string $name * @return bool * @static */ public static function has($name){ return \Illuminate\Routing\Router::has($name); } /** * Get the current route name. * * @return string|null * @static */ public static function currentRouteName(){ return \Illuminate\Routing\Router::currentRouteName(); } /** * Alias for the "currentRouteNamed" method. * * @param mixed string * @return bool * @static */ public static function is(){ return \Illuminate\Routing\Router::is(); } /** * Determine if the current route matches a given name. * * @param string $name * @return bool * @static */ public static function currentRouteNamed($name){ return \Illuminate\Routing\Router::currentRouteNamed($name); } /** * Get the current route action. * * @return string|null * @static */ public static function currentRouteAction(){ return \Illuminate\Routing\Router::currentRouteAction(); } /** * Alias for the "currentRouteUses" method. * * @param mixed string * @return bool * @static */ public static function uses(){ return \Illuminate\Routing\Router::uses(); } /** * Determine if the current route action matches a given action. * * @param string $action * @return bool * @static */ public static function currentRouteUses($action){ return \Illuminate\Routing\Router::currentRouteUses($action); } /** * Get the request currently being dispatched. * * @return \Illuminate\Http\Request * @static */ public static function getCurrentRequest(){ return \Illuminate\Routing\Router::getCurrentRequest(); } /** * Get the underlying route collection. * * @return \Illuminate\Routing\RouteCollection * @static */ public static function getRoutes(){ return \Illuminate\Routing\Router::getRoutes(); } /** * Get the controller dispatcher instance. * * @return \Illuminate\Routing\ControllerDispatcher * @static */ public static function getControllerDispatcher(){ return \Illuminate\Routing\Router::getControllerDispatcher(); } /** * Set the controller dispatcher instance. * * @param \Illuminate\Routing\ControllerDispatcher $dispatcher * @return void * @static */ public static function setControllerDispatcher($dispatcher){ \Illuminate\Routing\Router::setControllerDispatcher($dispatcher); } /** * Get a controller inspector instance. * * @return \Illuminate\Routing\ControllerInspector * @static */ public static function getInspector(){ return \Illuminate\Routing\Router::getInspector(); } /** * Get the global "where" patterns. * * @return array * @static */ public static function getPatterns(){ return \Illuminate\Routing\Router::getPatterns(); } /** * Get the response for a given request. * * @param \Symfony\Component\HttpFoundation\Request $request * @param int $type * @param bool $catch * @return \Illuminate\Http\Response * @static */ public static function handle($request, $type = 1, $catch = true){ return \Illuminate\Routing\Router::handle($request, $type, $catch); } } class Schema extends \Illuminate\Support\Facades\Schema{ /** * Determine if the given table exists. * * @param string $table * @return bool * @static */ public static function hasTable($table){ return \Illuminate\Database\Schema\MySqlBuilder::hasTable($table); } /** * Get the column listing for a given table. * * @param string $table * @return array * @static */ public static function getColumnListing($table){ return \Illuminate\Database\Schema\MySqlBuilder::getColumnListing($table); } /** * Determine if the given table has a given column. * * @param string $table * @param string $column * @return bool * @static */ public static function hasColumn($table, $column){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::hasColumn($table, $column); } /** * Modify a table on the schema. * * @param string $table * @param \Closure $callback * @return \Illuminate\Database\Schema\Blueprint * @static */ public static function table($table, $callback){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::table($table, $callback); } /** * Create a new table on the schema. * * @param string $table * @param \Closure $callback * @return \Illuminate\Database\Schema\Blueprint * @static */ public static function create($table, $callback){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::create($table, $callback); } /** * Drop a table from the schema. * * @param string $table * @return \Illuminate\Database\Schema\Blueprint * @static */ public static function drop($table){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::drop($table); } /** * Drop a table from the schema if it exists. * * @param string $table * @return \Illuminate\Database\Schema\Blueprint * @static */ public static function dropIfExists($table){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::dropIfExists($table); } /** * Rename a table on the schema. * * @param string $from * @param string $to * @return \Illuminate\Database\Schema\Blueprint * @static */ public static function rename($from, $to){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::rename($from, $to); } /** * Get the database connection instance. * * @return \Illuminate\Database\Connection * @static */ public static function getConnection(){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::getConnection(); } /** * Set the database connection instance. * * @param \Illuminate\Database\Connection * @return $this * @static */ public static function setConnection($connection){ //Method inherited from \Illuminate\Database\Schema\Builder return \Illuminate\Database\Schema\MySqlBuilder::setConnection($connection); } /** * Set the Schema Blueprint resolver callback. * * @param \Closure $resolver * @return void * @static */ public static function blueprintResolver($resolver){ //Method inherited from \Illuminate\Database\Schema\Builder \Illuminate\Database\Schema\MySqlBuilder::blueprintResolver($resolver); } } class Seeder extends \Illuminate\Database\Seeder{ } class Session extends \Illuminate\Support\Facades\Session{ /** * Get the session configuration. * * @return array * @static */ public static function getSessionConfig(){ return \Illuminate\Session\SessionManager::getSessionConfig(); } /** * Get the default session driver name. * * @return string * @static */ public static function getDefaultDriver(){ return \Illuminate\Session\SessionManager::getDefaultDriver(); } /** * Set the default session driver name. * * @param string $name * @return void * @static */ public static function setDefaultDriver($name){ \Illuminate\Session\SessionManager::setDefaultDriver($name); } /** * Get a driver instance. * * @param string $driver * @return mixed * @static */ public static function driver($driver = null){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Session\SessionManager::driver($driver); } /** * Register a custom driver creator Closure. * * @param string $driver * @param \Closure $callback * @return $this * @static */ public static function extend($driver, $callback){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Session\SessionManager::extend($driver, $callback); } /** * Get all of the created "drivers". * * @return array * @static */ public static function getDrivers(){ //Method inherited from \Illuminate\Support\Manager return \Illuminate\Session\SessionManager::getDrivers(); } /** * Starts the session storage. * * @return bool True if session started. * @throws \RuntimeException If session fails to start. * @api * @static */ public static function start(){ return \Illuminate\Session\Store::start(); } /** * Returns the session ID. * * @return string The session ID. * @api * @static */ public static function getId(){ return \Illuminate\Session\Store::getId(); } /** * Sets the session ID. * * @param string $id * @api * @static */ public static function setId($id){ return \Illuminate\Session\Store::setId($id); } /** * Determine if this is a valid session ID. * * @param string $id * @return bool * @static */ public static function isValidId($id){ return \Illuminate\Session\Store::isValidId($id); } /** * Returns the session name. * * @return mixed The session name. * @api * @static */ public static function getName(){ return \Illuminate\Session\Store::getName(); } /** * Sets the session name. * * @param string $name * @api * @static */ public static function setName($name){ return \Illuminate\Session\Store::setName($name); } /** * Invalidates the current session. * * Clears all session attributes and flashes and regenerates the * session and deletes the old session from persistence. * * @param int $lifetime Sets the cookie lifetime for the session cookie. A null value * will leave the system settings unchanged, 0 sets the cookie * to expire with browser session. Time is in seconds, and is * not a Unix timestamp. * @return bool True if session invalidated, false if error. * @api * @static */ public static function invalidate($lifetime = null){ return \Illuminate\Session\Store::invalidate($lifetime); } /** * Migrates the current session to a new session id while maintaining all * session attributes. * * @param bool $destroy Whether to delete the old session or leave it to garbage collection. * @param int $lifetime Sets the cookie lifetime for the session cookie. A null value * will leave the system settings unchanged, 0 sets the cookie * to expire with browser session. Time is in seconds, and is * not a Unix timestamp. * @return bool True if session migrated, false if error. * @api * @static */ public static function migrate($destroy = false, $lifetime = null){ return \Illuminate\Session\Store::migrate($destroy, $lifetime); } /** * Generate a new session identifier. * * @param bool $destroy * @return bool * @static */ public static function regenerate($destroy = false){ return \Illuminate\Session\Store::regenerate($destroy); } /** * Force the session to be saved and closed. * * This method is generally not required for real sessions as * the session will be automatically saved at the end of * code execution. * * @static */ public static function save(){ return \Illuminate\Session\Store::save(); } /** * Age the flash data for the session. * * @return void * @static */ public static function ageFlashData(){ \Illuminate\Session\Store::ageFlashData(); } /** * Checks if an attribute is defined. * * @param string $name The attribute name * @return bool true if the attribute is defined, false otherwise * @api * @static */ public static function has($name){ return \Illuminate\Session\Store::has($name); } /** * Returns an attribute. * * @param string $name The attribute name * @param mixed $default The default value if not found. * @return mixed * @api * @static */ public static function get($name, $default = null){ return \Illuminate\Session\Store::get($name, $default); } /** * Get the value of a given key and then forget it. * * @param string $key * @param string $default * @return mixed * @static */ public static function pull($key, $default = null){ return \Illuminate\Session\Store::pull($key, $default); } /** * Determine if the session contains old input. * * @param string $key * @return bool * @static */ public static function hasOldInput($key = null){ return \Illuminate\Session\Store::hasOldInput($key); } /** * Get the requested item from the flashed input array. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function getOldInput($key = null, $default = null){ return \Illuminate\Session\Store::getOldInput($key, $default); } /** * Sets an attribute. * * @param string $name * @param mixed $value * @api * @static */ public static function set($name, $value){ return \Illuminate\Session\Store::set($name, $value); } /** * Put a key / value pair or array of key / value pairs in the session. * * @param string|array $key * @param mixed|null $value * @return void * @static */ public static function put($key, $value = null){ \Illuminate\Session\Store::put($key, $value); } /** * Push a value onto a session array. * * @param string $key * @param mixed $value * @return void * @static */ public static function push($key, $value){ \Illuminate\Session\Store::push($key, $value); } /** * Flash a key / value pair to the session. * * @param string $key * @param mixed $value * @return void * @static */ public static function flash($key, $value){ \Illuminate\Session\Store::flash($key, $value); } /** * Flash an input array to the session. * * @param array $value * @return void * @static */ public static function flashInput($value){ \Illuminate\Session\Store::flashInput($value); } /** * Reflash all of the session flash data. * * @return void * @static */ public static function reflash(){ \Illuminate\Session\Store::reflash(); } /** * Reflash a subset of the current flash data. * * @param array|mixed $keys * @return void * @static */ public static function keep($keys = null){ \Illuminate\Session\Store::keep($keys); } /** * Returns attributes. * * @return array Attributes * @api * @static */ public static function all(){ return \Illuminate\Session\Store::all(); } /** * Sets attributes. * * @param array $attributes Attributes * @static */ public static function replace($attributes){ return \Illuminate\Session\Store::replace($attributes); } /** * Removes an attribute. * * @param string $name * @return mixed The removed value or null when it does not exist * @api * @static */ public static function remove($name){ return \Illuminate\Session\Store::remove($name); } /** * Remove an item from the session. * * @param string $key * @return void * @static */ public static function forget($key){ \Illuminate\Session\Store::forget($key); } /** * Clears all attributes. * * @api * @static */ public static function clear(){ return \Illuminate\Session\Store::clear(); } /** * Remove all of the items from the session. * * @return void * @static */ public static function flush(){ \Illuminate\Session\Store::flush(); } /** * Checks if the session was started. * * @return bool * @static */ public static function isStarted(){ return \Illuminate\Session\Store::isStarted(); } /** * Registers a SessionBagInterface with the session. * * @param \Symfony\Component\HttpFoundation\Session\SessionBagInterface $bag * @static */ public static function registerBag($bag){ return \Illuminate\Session\Store::registerBag($bag); } /** * Gets a bag instance by name. * * @param string $name * @return \Symfony\Component\HttpFoundation\Session\SessionBagInterface * @static */ public static function getBag($name){ return \Illuminate\Session\Store::getBag($name); } /** * Gets session meta. * * @return \Symfony\Component\HttpFoundation\Session\MetadataBag * @static */ public static function getMetadataBag(){ return \Illuminate\Session\Store::getMetadataBag(); } /** * Get the raw bag data array for a given bag. * * @param string $name * @return array * @static */ public static function getBagData($name){ return \Illuminate\Session\Store::getBagData($name); } /** * Get the CSRF token value. * * @return string * @static */ public static function token(){ return \Illuminate\Session\Store::token(); } /** * Get the CSRF token value. * * @return string * @static */ public static function getToken(){ return \Illuminate\Session\Store::getToken(); } /** * Regenerate the CSRF token value. * * @return void * @static */ public static function regenerateToken(){ \Illuminate\Session\Store::regenerateToken(); } /** * Set the existence of the session on the handler if applicable. * * @param bool $value * @return void * @static */ public static function setExists($value){ \Illuminate\Session\Store::setExists($value); } /** * Get the underlying session handler implementation. * * @return \SessionHandlerInterface * @static */ public static function getHandler(){ return \Illuminate\Session\Store::getHandler(); } /** * Determine if the session handler needs a request. * * @return bool * @static */ public static function handlerNeedsRequest(){ return \Illuminate\Session\Store::handlerNeedsRequest(); } /** * Set the request on the handler instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void * @static */ public static function setRequestOnHandler($request){ \Illuminate\Session\Store::setRequestOnHandler($request); } } class SSH extends \Illuminate\Support\Facades\SSH{ /** * Get a remote connection instance. * * @param string|array|mixed $name * @return \Illuminate\Remote\Connection * @static */ public static function into($name){ return \Illuminate\Remote\RemoteManager::into($name); } /** * Get a remote connection instance. * * @param string|array $name * @return \Illuminate\Remote\Connection * @static */ public static function connection($name = null){ return \Illuminate\Remote\RemoteManager::connection($name); } /** * Get a connection group instance by name. * * @param string $name * @return \Illuminate\Remote\Connection * @static */ public static function group($name){ return \Illuminate\Remote\RemoteManager::group($name); } /** * Resolve a multiple connection instance. * * @param array $names * @return \Illuminate\Remote\MultiConnection * @static */ public static function multiple($names){ return \Illuminate\Remote\RemoteManager::multiple($names); } /** * Resolve a remote connection instance. * * @param string $name * @return \Illuminate\Remote\Connection * @static */ public static function resolve($name){ return \Illuminate\Remote\RemoteManager::resolve($name); } /** * Get the default connection name. * * @return string * @static */ public static function getDefaultConnection(){ return \Illuminate\Remote\RemoteManager::getDefaultConnection(); } /** * Set the default connection name. * * @param string $name * @return void * @static */ public static function setDefaultConnection($name){ \Illuminate\Remote\RemoteManager::setDefaultConnection($name); } /** * Define a set of commands as a task. * * @param string $task * @param string|array $commands * @return void * @static */ public static function define($task, $commands){ \Illuminate\Remote\Connection::define($task, $commands); } /** * Run a task against the connection. * * @param string $task * @param \Closure $callback * @return void * @static */ public static function task($task, $callback = null){ \Illuminate\Remote\Connection::task($task, $callback); } /** * Run a set of commands against the connection. * * @param string|array $commands * @param \Closure $callback * @return void * @static */ public static function run($commands, $callback = null){ \Illuminate\Remote\Connection::run($commands, $callback); } /** * Download the contents of a remote file. * * @param string $remote * @param string $local * @return void * @static */ public static function get($remote, $local){ \Illuminate\Remote\Connection::get($remote, $local); } /** * Get the contents of a remote file. * * @param string $remote * @return string * @static */ public static function getString($remote){ return \Illuminate\Remote\Connection::getString($remote); } /** * Upload a local file to the server. * * @param string $local * @param string $remote * @return void * @static */ public static function put($local, $remote){ \Illuminate\Remote\Connection::put($local, $remote); } /** * Upload a string to to the given file on the server. * * @param string $remote * @param string $contents * @return void * @static */ public static function putString($remote, $contents){ \Illuminate\Remote\Connection::putString($remote, $contents); } /** * Display the given line using the default output. * * @param string $line * @return void * @static */ public static function display($line){ \Illuminate\Remote\Connection::display($line); } /** * Get the exit status of the last command. * * @return int|bool * @static */ public static function status(){ return \Illuminate\Remote\Connection::status(); } /** * Get the gateway implementation. * * @return \Illuminate\Remote\GatewayInterface * @throws \RuntimeException * @static */ public static function getGateway(){ return \Illuminate\Remote\Connection::getGateway(); } /** * Get the output implementation for the connection. * * @return \Symfony\Component\Console\Output\OutputInterface * @static */ public static function getOutput(){ return \Illuminate\Remote\Connection::getOutput(); } /** * Set the output implementation. * * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void * @static */ public static function setOutput($output){ \Illuminate\Remote\Connection::setOutput($output); } } class Str extends \Illuminate\Support\Str{ } class URL extends \Illuminate\Support\Facades\URL{ /** * Get the full URL for the current request. * * @return string * @static */ public static function full(){ return \Illuminate\Routing\UrlGenerator::full(); } /** * Get the current URL for the request. * * @return string * @static */ public static function current(){ return \Illuminate\Routing\UrlGenerator::current(); } /** * Get the URL for the previous request. * * @return string * @static */ public static function previous(){ return \Illuminate\Routing\UrlGenerator::previous(); } /** * Generate a absolute URL to the given path. * * @param string $path * @param mixed $extra * @param bool|null $secure * @return string * @static */ public static function to($path, $extra = array(), $secure = null){ return \Illuminate\Routing\UrlGenerator::to($path, $extra, $secure); } /** * Generate a secure, absolute URL to the given path. * * @param string $path * @param array $parameters * @return string * @static */ public static function secure($path, $parameters = array()){ return \Illuminate\Routing\UrlGenerator::secure($path, $parameters); } /** * Generate a URL to an application asset. * * @param string $path * @param bool|null $secure * @return string * @static */ public static function asset($path, $secure = null){ return \Illuminate\Routing\UrlGenerator::asset($path, $secure); } /** * Generate a URL to a secure asset. * * @param string $path * @return string * @static */ public static function secureAsset($path){ return \Illuminate\Routing\UrlGenerator::secureAsset($path); } /** * Force the schema for URLs. * * @param string $schema * @return void * @static */ public static function forceSchema($schema){ \Illuminate\Routing\UrlGenerator::forceSchema($schema); } /** * Get the URL to a named route. * * @param string $name * @param mixed $parameters * @param bool $absolute * @param \Illuminate\Routing\Route $route * @return string * @throws \InvalidArgumentException * @static */ public static function route($name, $parameters = array(), $absolute = true, $route = null){ return \Illuminate\Routing\UrlGenerator::route($name, $parameters, $absolute, $route); } /** * Get the URL to a controller action. * * @param string $action * @param mixed $parameters * @param bool $absolute * @return string * @static */ public static function action($action, $parameters = array(), $absolute = true){ return \Illuminate\Routing\UrlGenerator::action($action, $parameters, $absolute); } /** * Set the forced root URL. * * @param string $root * @return void * @static */ public static function forceRootUrl($root){ \Illuminate\Routing\UrlGenerator::forceRootUrl($root); } /** * Determine if the given path is a valid URL. * * @param string $path * @return bool * @static */ public static function isValidUrl($path){ return \Illuminate\Routing\UrlGenerator::isValidUrl($path); } /** * Get the request instance. * * @return \Symfony\Component\HttpFoundation\Request * @static */ public static function getRequest(){ return \Illuminate\Routing\UrlGenerator::getRequest(); } /** * Set the current request instance. * * @param \Illuminate\Http\Request $request * @return void * @static */ public static function setRequest($request){ \Illuminate\Routing\UrlGenerator::setRequest($request); } } class Validator extends \Illuminate\Support\Facades\Validator{ /** * Create a new Validator instance. * * @param array $data * @param array $rules * @param array $messages * @param array $customAttributes * @return \Illuminate\Validation\Validator * @static */ public static function make($data, $rules, $messages = array(), $customAttributes = array()){ return \Illuminate\Validation\Factory::make($data, $rules, $messages, $customAttributes); } /** * Register a custom validator extension. * * @param string $rule * @param \Closure|string $extension * @param string $message * @return void * @static */ public static function extend($rule, $extension, $message = null){ \Illuminate\Validation\Factory::extend($rule, $extension, $message); } /** * Register a custom implicit validator extension. * * @param string $rule * @param \Closure|string $extension * @param string $message * @return void * @static */ public static function extendImplicit($rule, $extension, $message = null){ \Illuminate\Validation\Factory::extendImplicit($rule, $extension, $message); } /** * Register a custom implicit validator message replacer. * * @param string $rule * @param \Closure|string $replacer * @return void * @static */ public static function replacer($rule, $replacer){ \Illuminate\Validation\Factory::replacer($rule, $replacer); } /** * Set the Validator instance resolver. * * @param \Closure $resolver * @return void * @static */ public static function resolver($resolver){ \Illuminate\Validation\Factory::resolver($resolver); } /** * Get the Translator implementation. * * @return \Symfony\Component\Translation\TranslatorInterface * @static */ public static function getTranslator(){ return \Illuminate\Validation\Factory::getTranslator(); } /** * Get the Presence Verifier implementation. * * @return \Illuminate\Validation\PresenceVerifierInterface * @static */ public static function getPresenceVerifier(){ return \Illuminate\Validation\Factory::getPresenceVerifier(); } /** * Set the Presence Verifier implementation. * * @param \Illuminate\Validation\PresenceVerifierInterface $presenceVerifier * @return void * @static */ public static function setPresenceVerifier($presenceVerifier){ \Illuminate\Validation\Factory::setPresenceVerifier($presenceVerifier); } } class View extends \Illuminate\Support\Facades\View{ /** * Get the evaluated view contents for the given view. * * @param string $view * @param array $data * @param array $mergeData * @return \Illuminate\View\View * @static */ public static function make($view, $data = array(), $mergeData = array()){ return \Illuminate\View\Factory::make($view, $data, $mergeData); } /** * Get the evaluated view contents for a named view. * * @param string $view * @param mixed $data * @return \Illuminate\View\View * @static */ public static function of($view, $data = array()){ return \Illuminate\View\Factory::of($view, $data); } /** * Register a named view. * * @param string $view * @param string $name * @return void * @static */ public static function name($view, $name){ \Illuminate\View\Factory::name($view, $name); } /** * Add an alias for a view. * * @param string $view * @param string $alias * @return void * @static */ public static function alias($view, $alias){ \Illuminate\View\Factory::alias($view, $alias); } /** * Determine if a given view exists. * * @param string $view * @return bool * @static */ public static function exists($view){ return \Illuminate\View\Factory::exists($view); } /** * Get the rendered contents of a partial from a loop. * * @param string $view * @param array $data * @param string $iterator * @param string $empty * @return string * @static */ public static function renderEach($view, $data, $iterator, $empty = 'raw|'){ return \Illuminate\View\Factory::renderEach($view, $data, $iterator, $empty); } /** * Get the appropriate view engine for the given path. * * @param string $path * @return \Illuminate\View\Engines\EngineInterface * @throws \InvalidArgumentException * @static */ public static function getEngineFromPath($path){ return \Illuminate\View\Factory::getEngineFromPath($path); } /** * Add a piece of shared data to the environment. * * @param string $key * @param mixed $value * @return void * @static */ public static function share($key, $value = null){ \Illuminate\View\Factory::share($key, $value); } /** * Register a view creator event. * * @param array|string $views * @param \Closure|string $callback * @return array * @static */ public static function creator($views, $callback){ return \Illuminate\View\Factory::creator($views, $callback); } /** * Register multiple view composers via an array. * * @param array $composers * @return array * @static */ public static function composers($composers){ return \Illuminate\View\Factory::composers($composers); } /** * Register a view composer event. * * @param array|string $views * @param \Closure|string $callback * @param int|null $priority * @return array * @static */ public static function composer($views, $callback, $priority = null){ return \Illuminate\View\Factory::composer($views, $callback, $priority); } /** * Call the composer for a given view. * * @param \Illuminate\View\View $view * @return void * @static */ public static function callComposer($view){ \Illuminate\View\Factory::callComposer($view); } /** * Call the creator for a given view. * * @param \Illuminate\View\View $view * @return void * @static */ public static function callCreator($view){ \Illuminate\View\Factory::callCreator($view); } /** * Start injecting content into a section. * * @param string $section * @param string $content * @return void * @static */ public static function startSection($section, $content = ''){ \Illuminate\View\Factory::startSection($section, $content); } /** * Inject inline content into a section. * * @param string $section * @param string $content * @return void * @static */ public static function inject($section, $content){ \Illuminate\View\Factory::inject($section, $content); } /** * Stop injecting content into a section and return its contents. * * @return string * @static */ public static function yieldSection(){ return \Illuminate\View\Factory::yieldSection(); } /** * Stop injecting content into a section. * * @param bool $overwrite * @return string * @static */ public static function stopSection($overwrite = false){ return \Illuminate\View\Factory::stopSection($overwrite); } /** * Stop injecting content into a section and append it. * * @return string * @static */ public static function appendSection(){ return \Illuminate\View\Factory::appendSection(); } /** * Get the string contents of a section. * * @param string $section * @param string $default * @return string * @static */ public static function yieldContent($section, $default = ''){ return \Illuminate\View\Factory::yieldContent($section, $default); } /** * Flush all of the section contents. * * @return void * @static */ public static function flushSections(){ \Illuminate\View\Factory::flushSections(); } /** * Flush all of the section contents if done rendering. * * @return void * @static */ public static function flushSectionsIfDoneRendering(){ \Illuminate\View\Factory::flushSectionsIfDoneRendering(); } /** * Increment the rendering counter. * * @return void * @static */ public static function incrementRender(){ \Illuminate\View\Factory::incrementRender(); } /** * Decrement the rendering counter. * * @return void * @static */ public static function decrementRender(){ \Illuminate\View\Factory::decrementRender(); } /** * Check if there are no active render operations. * * @return bool * @static */ public static function doneRendering(){ return \Illuminate\View\Factory::doneRendering(); } /** * Add a location to the array of view locations. * * @param string $location * @return void * @static */ public static function addLocation($location){ \Illuminate\View\Factory::addLocation($location); } /** * Add a new namespace to the loader. * * @param string $namespace * @param string|array $hints * @return void * @static */ public static function addNamespace($namespace, $hints){ \Illuminate\View\Factory::addNamespace($namespace, $hints); } /** * Prepend a new namespace to the loader. * * @param string $namespace * @param string|array $hints * @return void * @static */ public static function prependNamespace($namespace, $hints){ \Illuminate\View\Factory::prependNamespace($namespace, $hints); } /** * Register a valid view extension and its engine. * * @param string $extension * @param string $engine * @param \Closure $resolver * @return void * @static */ public static function addExtension($extension, $engine, $resolver = null){ \Illuminate\View\Factory::addExtension($extension, $engine, $resolver); } /** * Get the extension to engine bindings. * * @return array * @static */ public static function getExtensions(){ return \Illuminate\View\Factory::getExtensions(); } /** * Get the engine resolver instance. * * @return \Illuminate\View\Engines\EngineResolver * @static */ public static function getEngineResolver(){ return \Illuminate\View\Factory::getEngineResolver(); } /** * Get the view finder instance. * * @return \Illuminate\View\ViewFinderInterface * @static */ public static function getFinder(){ return \Illuminate\View\Factory::getFinder(); } /** * Set the view finder instance. * * @param \Illuminate\View\ViewFinderInterface $finder * @return void * @static */ public static function setFinder($finder){ \Illuminate\View\Factory::setFinder($finder); } /** * Get the event dispatcher instance. * * @return \Illuminate\Events\Dispatcher * @static */ public static function getDispatcher(){ return \Illuminate\View\Factory::getDispatcher(); } /** * Set the event dispatcher instance. * * @param \Illuminate\Events\Dispatcher * @return void * @static */ public static function setDispatcher($events){ \Illuminate\View\Factory::setDispatcher($events); } /** * Get the IoC container instance. * * @return \Illuminate\Container\Container * @static */ public static function getContainer(){ return \Illuminate\View\Factory::getContainer(); } /** * Set the IoC container instance. * * @param \Illuminate\Container\Container $container * @return void * @static */ public static function setContainer($container){ \Illuminate\View\Factory::setContainer($container); } /** * Get an item from the shared data. * * @param string $key * @param mixed $default * @return mixed * @static */ public static function shared($key, $default = null){ return \Illuminate\View\Factory::shared($key, $default); } /** * Get all of the shared data for the environment. * * @return array * @static */ public static function getShared(){ return \Illuminate\View\Factory::getShared(); } /** * Get the entire array of sections. * * @return array * @static */ public static function getSections(){ return \Illuminate\View\Factory::getSections(); } /** * Get all of the registered named views in environment. * * @return array * @static */ public static function getNames(){ return \Illuminate\View\Factory::getNames(); } } class Sentry extends \Cartalyst\Sentry\Facades\Laravel\Sentry{ /** * Registers a user by giving the required credentials * and an optional flag for whether to activate the user. * * @param array $credentials * @param bool $activate * @return \Cartalyst\Sentry\Users\UserInterface * @static */ public static function register($credentials, $activate = false){ return \Cartalyst\Sentry\Sentry::register($credentials, $activate); } /** * Attempts to authenticate the given user * according to the passed credentials. * * @param array $credentials * @param bool $remember * @return \Cartalyst\Sentry\Users\UserInterface * @throws \Cartalyst\Sentry\Throttling\UserBannedException * @throws \Cartalyst\Sentry\Throttling\UserSuspendedException * @throws \Cartalyst\Sentry\Users\LoginRequiredException * @throws \Cartalyst\Sentry\Users\PasswordRequiredException * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function authenticate($credentials, $remember = false){ return \Cartalyst\Sentry\Sentry::authenticate($credentials, $remember); } /** * Alias for authenticating with the remember flag checked. * * @param array $credentials * @return \Cartalyst\Sentry\Users\UserInterface * @static */ public static function authenticateAndRemember($credentials){ return \Cartalyst\Sentry\Sentry::authenticateAndRemember($credentials); } /** * Check to see if the user is logged in and activated, and hasn't been banned or suspended. * * @return bool * @static */ public static function check(){ return \Cartalyst\Sentry\Sentry::check(); } /** * Logs in the given user and sets properties * in the session. * * @param \Cartalyst\Sentry\Users\UserInterface $user * @param bool $remember * @return void * @throws \Cartalyst\Sentry\Users\UserNotActivatedException * @static */ public static function login($user, $remember = false){ \Cartalyst\Sentry\Sentry::login($user, $remember); } /** * Alias for logging in and remembering. * * @param \Cartalyst\Sentry\Users\UserInterface $user * @static */ public static function loginAndRemember($user){ return \Cartalyst\Sentry\Sentry::loginAndRemember($user); } /** * Logs the current user out. * * @return void * @static */ public static function logout(){ \Cartalyst\Sentry\Sentry::logout(); } /** * Sets the user to be used by Sentry. * * @param \Cartalyst\Sentry\Users\UserInterface * @return void * @static */ public static function setUser($user){ \Cartalyst\Sentry\Sentry::setUser($user); } /** * Returns the current user being used by Sentry, if any. * * @return \Cartalyst\Sentry\Users\UserInterface * @static */ public static function getUser(){ return \Cartalyst\Sentry\Sentry::getUser(); } /** * Sets the session driver for Sentry. * * @param \Cartalyst\Sentry\Sessions\SessionInterface $session * @return void * @static */ public static function setSession($session){ \Cartalyst\Sentry\Sentry::setSession($session); } /** * Gets the session driver for Sentry. * * @return \Cartalyst\Sentry\Sessions\SessionInterface * @static */ public static function getSession(){ return \Cartalyst\Sentry\Sentry::getSession(); } /** * Sets the cookie driver for Sentry. * * @param \Cartalyst\Sentry\Cookies\CookieInterface $cookie * @return void * @static */ public static function setCookie($cookie){ \Cartalyst\Sentry\Sentry::setCookie($cookie); } /** * Gets the cookie driver for Sentry. * * @return \Cartalyst\Sentry\Cookies\CookieInterface * @static */ public static function getCookie(){ return \Cartalyst\Sentry\Sentry::getCookie(); } /** * Sets the group provider for Sentry. * * @param \Cartalyst\Sentry\Groups\ProviderInterface * @return void * @static */ public static function setGroupProvider($groupProvider){ \Cartalyst\Sentry\Sentry::setGroupProvider($groupProvider); } /** * Gets the group provider for Sentry. * * @return \Cartalyst\Sentry\Groups\ProviderInterface * @static */ public static function getGroupProvider(){ return \Cartalyst\Sentry\Sentry::getGroupProvider(); } /** * Sets the user provider for Sentry. * * @param \Cartalyst\Sentry\Users\ProviderInterface * @return void * @static */ public static function setUserProvider($userProvider){ \Cartalyst\Sentry\Sentry::setUserProvider($userProvider); } /** * Gets the user provider for Sentry. * * @return \Cartalyst\Sentry\Users\ProviderInterface * @static */ public static function getUserProvider(){ return \Cartalyst\Sentry\Sentry::getUserProvider(); } /** * Sets the throttle provider for Sentry. * * @param \Cartalyst\Sentry\Throttling\ProviderInterface * @return void * @static */ public static function setThrottleProvider($throttleProvider){ \Cartalyst\Sentry\Sentry::setThrottleProvider($throttleProvider); } /** * Gets the throttle provider for Sentry. * * @return \Cartalyst\Sentry\Throttling\ProviderInterface * @static */ public static function getThrottleProvider(){ return \Cartalyst\Sentry\Sentry::getThrottleProvider(); } /** * Sets the IP address Sentry is bound to. * * @param string $ipAddress * @return void * @static */ public static function setIpAddress($ipAddress){ \Cartalyst\Sentry\Sentry::setIpAddress($ipAddress); } /** * Gets the IP address Sentry is bound to. * * @return string * @static */ public static function getIpAddress(){ return \Cartalyst\Sentry\Sentry::getIpAddress(); } /** * Find the group by ID. * * @param int $id * @return \Cartalyst\Sentry\Groups\GroupInterface $group * @throws \Cartalyst\Sentry\Groups\GroupNotFoundException * @static */ public static function findGroupById($id){ return \Cartalyst\Sentry\Sentry::findGroupById($id); } /** * Find the group by name. * * @param string $name * @return \Cartalyst\Sentry\Groups\GroupInterface $group * @throws \Cartalyst\Sentry\Groups\GroupNotFoundException * @static */ public static function findGroupByName($name){ return \Cartalyst\Sentry\Sentry::findGroupByName($name); } /** * Returns all groups. * * @return array $groups * @static */ public static function findAllGroups(){ return \Cartalyst\Sentry\Sentry::findAllGroups(); } /** * Creates a group. * * @param array $attributes * @return \Cartalyst\Sentry\Groups\GroupInterface * @static */ public static function createGroup($attributes){ return \Cartalyst\Sentry\Sentry::createGroup($attributes); } /** * Finds a user by the given user ID. * * @param mixed $id * @return \Cartalyst\Sentry\Users\UserInterface * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function findUserById($id){ return \Cartalyst\Sentry\Sentry::findUserById($id); } /** * Finds a user by the login value. * * @param string $login * @return \Cartalyst\Sentry\Users\UserInterface * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function findUserByLogin($login){ return \Cartalyst\Sentry\Sentry::findUserByLogin($login); } /** * Finds a user by the given credentials. * * @param array $credentials * @return \Cartalyst\Sentry\Users\UserInterface * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function findUserByCredentials($credentials){ return \Cartalyst\Sentry\Sentry::findUserByCredentials($credentials); } /** * Finds a user by the given activation code. * * @param string $code * @return \Cartalyst\Sentry\Users\UserInterface * @throws \RuntimeException * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function findUserByActivationCode($code){ return \Cartalyst\Sentry\Sentry::findUserByActivationCode($code); } /** * Finds a user by the given reset password code. * * @param string $code * @return \Cartalyst\Sentry\Users\UserInterface * @throws \RuntimeException * @throws \Cartalyst\Sentry\Users\UserNotFoundException * @static */ public static function findUserByResetPasswordCode($code){ return \Cartalyst\Sentry\Sentry::findUserByResetPasswordCode($code); } /** * Returns an all users. * * @return array * @static */ public static function findAllUsers(){ return \Cartalyst\Sentry\Sentry::findAllUsers(); } /** * Returns all users who belong to * a group. * * @param \Cartalyst\Sentry\Groups\GroupInterface $group * @return array * @static */ public static function findAllUsersInGroup($group){ return \Cartalyst\Sentry\Sentry::findAllUsersInGroup($group); } /** * Returns all users with access to * a permission(s). * * @param string|array $permissions * @return array * @static */ public static function findAllUsersWithAccess($permissions){ return \Cartalyst\Sentry\Sentry::findAllUsersWithAccess($permissions); } /** * Returns all users with access to * any given permission(s). * * @param array $permissions * @return array * @static */ public static function findAllUsersWithAnyAccess($permissions){ return \Cartalyst\Sentry\Sentry::findAllUsersWithAnyAccess($permissions); } /** * Creates a user. * * @param array $credentials * @return \Cartalyst\Sentry\Users\UserInterface * @static */ public static function createUser($credentials){ return \Cartalyst\Sentry\Sentry::createUser($credentials); } /** * Returns an empty user object. * * @return \Cartalyst\Sentry\Users\UserInterface * @static */ public static function getEmptyUser(){ return \Cartalyst\Sentry\Sentry::getEmptyUser(); } /** * Finds a throttler by the given user ID. * * @param mixed $id * @param string $ipAddress * @return \Cartalyst\Sentry\Throttling\ThrottleInterface * @static */ public static function findThrottlerByUserId($id, $ipAddress = null){ return \Cartalyst\Sentry\Sentry::findThrottlerByUserId($id, $ipAddress); } /** * Finds a throttling interface by the given user login. * * @param string $login * @param string $ipAddress * @return \Cartalyst\Sentry\Throttling\ThrottleInterface * @static */ public static function findThrottlerByUserLogin($login, $ipAddress = null){ return \Cartalyst\Sentry\Sentry::findThrottlerByUserLogin($login, $ipAddress); } } class Image extends \Intervention\Image\Facades\Image{ /** * Overrides configuration settings * * @param array $config * @static */ public static function configure($config = array()){ return \Intervention\Image\ImageManager::configure($config); } /** * Initiates an Image instance from different input types * * @param mixed $data * @return \Intervention\Image\Image * @static */ public static function make($data){ return \Intervention\Image\ImageManager::make($data); } /** * Creates an empty image canvas * * @param integer $width * @param integer $height * @param mixed $background * @return \Intervention\Image\Image * @static */ public static function canvas($width, $height, $background = null){ return \Intervention\Image\ImageManager::canvas($width, $height, $background); } /** * Create new cached image and run callback * (requires additional package intervention/imagecache) * * @param \Closure $callback * @param integer $lifetime * @param boolean $returnObj * @return \Intervention\Image\Image * @static */ public static function cache($callback, $lifetime = null, $returnObj = false){ return \Intervention\Image\ImageManager::cache($callback, $lifetime, $returnObj); } } class Geocoder extends \Toin0u\Geocoder\GeocoderFacade{ /** * * * @param \Geocoder\ResultFactoryInterface $resultFactory * @static */ public static function setResultFactory($resultFactory = null){ return \Geocoder\Geocoder::setResultFactory($resultFactory); } /** * * * @param integer $maxResults * @return \Geocoder\GeocoderInterface * @static */ public static function limit($maxResults){ return \Geocoder\Geocoder::limit($maxResults); } /** * * * @return integer $maxResults * @static */ public static function getMaxResults(){ return \Geocoder\Geocoder::getMaxResults(); } /** * {@inheritDoc} * * @static */ public static function geocode($value){ return \Geocoder\Geocoder::geocode($value); } /** * {@inheritDoc} * * @static */ public static function reverse($latitude, $longitude){ return \Geocoder\Geocoder::reverse($latitude, $longitude); } /** * Registers a provider. * * @param \Geocoder\ProviderInterface $provider * @return \Geocoder\GeocoderInterface * @static */ public static function registerProvider($provider){ return \Geocoder\Geocoder::registerProvider($provider); } /** * Registers a set of providers. * * @param \Geocoder\ProviderInterface[] $providers * @return \Geocoder\GeocoderInterface * @static */ public static function registerProviders($providers = array()){ return \Geocoder\Geocoder::registerProviders($providers); } /** * Sets the provider to use. * * @param string $name A provider's name * @return \Geocoder\GeocoderInterface * @static */ public static function using($name){ return \Geocoder\Geocoder::using($name); } /** * Returns registered providers indexed by name. * * @return \Geocoder\ProviderInterface[] * @static */ public static function getProviders(){ return \Geocoder\Geocoder::getProviders(); } } class Calendar extends \Gloudemans\Calendar\Facades\Calendar{ /** * Initialize the user preferences * * Accepts an associative array as input, containing display preferences * * @access public * @param array config preferences * @return void * @static */ public static function initialize($config = array()){ \Gloudemans\Calendar\CalendarGenerator::initialize($config); } /** * Generate the calendar * * @access public * @param integer the year * @param integer the month * @param array the data to be shown in the calendar cells * @return string * @static */ public static function generate($year = '', $month = '', $data = array()){ return \Gloudemans\Calendar\CalendarGenerator::generate($year, $month, $data); } } class Geotools extends \Toin0u\Geotools\GeotoolsFacade{ /** * Set the latitude and the longitude of the coordinates into an selected ellipsoid. * * @param \Toin0u\Geotools\ResultInterface|array|string $coordinates The coordinates. * @param \Toin0u\Geotools\Ellipsoid $ellipsoid The selected ellipsoid (WGS84 by default). * @return \Toin0u\Geotools\Coordinate * @static */ public static function coordinate($coordinates, $ellipsoid = null){ return \Toin0u\Geotools\Geotools::coordinate($coordinates, $ellipsoid); } /** * {@inheritDoc} * * @static */ public static function distance(){ //Method inherited from \League\Geotools\Geotools return \Toin0u\Geotools\Geotools::distance(); } /** * {@inheritDoc} * * @static */ public static function point(){ //Method inherited from \League\Geotools\Geotools return \Toin0u\Geotools\Geotools::point(); } /** * {@inheritDoc} * * @static */ public static function batch($geocoder){ //Method inherited from \League\Geotools\Geotools return \Toin0u\Geotools\Geotools::batch($geocoder); } /** * {@inheritDoc} * * @static */ public static function geohash(){ //Method inherited from \League\Geotools\Geotools return \Toin0u\Geotools\Geotools::geohash(); } /** * {@inheritDoc} * * @static */ public static function convert($coordinates){ //Method inherited from \League\Geotools\Geotools return \Toin0u\Geotools\Geotools::convert($coordinates); } } class Share extends \Thujohn\Share\ShareFacade{ /** * * * @static */ public static function load($link, $text = '', $media = ''){ return \Thujohn\Share\Share::load($link, $text, $media); } /** * * * @static */ public static function services(){ return \Thujohn\Share\Share::services(); } /** * * * @static */ public static function delicious(){ return \Thujohn\Share\Share::delicious(); } /** * * * @static */ public static function digg(){ return \Thujohn\Share\Share::digg(); } /** * * * @static */ public static function evernote(){ return \Thujohn\Share\Share::evernote(); } /** * * * @static */ public static function facebook(){ return \Thujohn\Share\Share::facebook(); } /** * * * @static */ public static function gmail(){ return \Thujohn\Share\Share::gmail(); } /** * * * @static */ public static function gplus(){ return \Thujohn\Share\Share::gplus(); } /** * * * @static */ public static function linkedin(){ return \Thujohn\Share\Share::linkedin(); } /** * * * @static */ public static function pinterest(){ return \Thujohn\Share\Share::pinterest(); } /** * * * @static */ public static function reddit(){ return \Thujohn\Share\Share::reddit(); } /** * * * @static */ public static function scoopit(){ return \Thujohn\Share\Share::scoopit(); } /** * * * @static */ public static function springpad(){ return \Thujohn\Share\Share::springpad(); } /** * * * @static */ public static function tumblr(){ return \Thujohn\Share\Share::tumblr(); } /** * * * @static */ public static function twitter(){ return \Thujohn\Share\Share::twitter(); } /** * * * @static */ public static function viadeo(){ return \Thujohn\Share\Share::viadeo(); } /** * * * @static */ public static function vk(){ return \Thujohn\Share\Share::vk(); } } class Omnipay extends \Ignited\LaravelOmnipay\Facades\OmnipayFacade{ /** * Get an instance of the specified gateway * * @param \Ignited\LaravelOmnipay\index of config array to use * @return \Ignited\LaravelOmnipay\Omnipay\Common\AbstractGateway * @static */ public static function gateway($name = null){ return \Ignited\LaravelOmnipay\LaravelOmnipayManager::gateway($name); } /** * * * @static */ public static function creditCard($cardInput){ return \Ignited\LaravelOmnipay\LaravelOmnipayManager::creditCard($cardInput); } /** * * * @static */ public static function getGateway(){ return \Ignited\LaravelOmnipay\LaravelOmnipayManager::getGateway(); } /** * * * @static */ public static function setGateway($name){ return \Ignited\LaravelOmnipay\LaravelOmnipayManager::setGateway($name); } } class Twitter extends \Philo\Twitter\Facades\Twitter{ /** * Get the timeout * * @return int * @static */ public static function getTimeOut(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::getTimeOut(); } /** * Get the useragent that will be used. Our version will be prepended to yours. * * It will look like: "PHP Twitter/<version> <your-user-agent>" * * @return string * @static */ public static function getUserAgent(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::getUserAgent(); } /** * Set the oAuth-token * * @param string $token The token to use. * @static */ public static function setOAuthToken($token){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::setOAuthToken($token); } /** * Set the oAuth-secret * * @param string $secret The secret to use. * @static */ public static function setOAuthTokenSecret($secret){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::setOAuthTokenSecret($secret); } /** * Set the timeout * * @param int $seconds The timeout in seconds. * @static */ public static function setTimeOut($seconds){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::setTimeOut($seconds); } /** * Get the useragent that will be used. Our version will be prepended to yours. * * It will look like: "PHP Twitter/<version> <your-user-agent>" * * @param string $userAgent Your user-agent, it should look like <app-name>/<app-version>. * @static */ public static function setUserAgent($userAgent){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::setUserAgent($userAgent); } /** * Returns the 20 most recent mentions (tweets containing a users's @screen_name) for the authenticating user. * * The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com. * This method can only return up to 800 tweets. * * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied. * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param \TijsVerkoyen\Twitter\bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be disincluded when set to false. * @return array * @static */ public static function statusesMentionsTimeline($count = null, $sinceId = null, $maxId = null, $trimUser = null, $contributorDetails = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesMentionsTimeline($count, $sinceId, $maxId, $trimUser, $contributorDetails, $includeEntities); } /** * Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters. * * User timelines belonging to protected users may only be requested when the authenticated user either "owns" the timeline or is an approved follower of the owner. * The timeline returned is the equivalent of the one seen when you view a user's profile on twitter.com. * This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID. * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of tweets to try and retrieve, up to a maximum of 200 per distinct request. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param \TijsVerkoyen\Twitter\bool[optional] $excludeReplies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets — this is because the count parameter retrieves that many tweets before filtering out retweets and replies. * @param \TijsVerkoyen\Twitter\bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. * @param \TijsVerkoyen\Twitter\bool[optional] $includeRts When set to false, the timeline will strip any native retweets (though they will still count toward both the maximal length of the timeline and the slice selected by the count parameter). Note: If you're using the trim_user parameter in conjunction with include_rts, the retweets will still contain a full user object. * @return array * @static */ public static function statusesUserTimeline($userId = null, $screenName = null, $sinceId = null, $count = null, $maxId = null, $trimUser = null, $excludeReplies = null, $contributorDetails = null, $includeRts = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesUserTimeline($userId, $screenName, $sinceId, $count, $maxId, $trimUser, $excludeReplies, $contributorDetails, $includeRts); } /** * Returns the 20 most recent statuses, including retweets if they exist, posted by the authenticating user and the user's they follow. This is the same timeline seen by a user when they login to twitter.com. * * This method is identical to statusesFriendsTimeline, except that this method always includes retweets. * * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 200. Defaults to 20. * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param \TijsVerkoyen\Twitter\bool[optional] $excludeReplies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets — this is because the count parameter retrieves that many tweets before filtering out retweets and replies. * @param \TijsVerkoyen\Twitter\bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be disincluded when set to false. * @return array * @static */ public static function statusesHomeTimeline($count = null, $sinceId = null, $maxId = null, $trimUser = null, $excludeReplies = null, $contributorDetails = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesHomeTimeline($count, $sinceId, $maxId, $trimUser, $excludeReplies, $contributorDetails, $includeEntities); } /** * Returns the most recent tweets authored by the authenticating user that have recently been retweeted by others. This timeline is a subset of the user's GET statuses/user_timeline. * * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 100. If omitted, 20 will be assumed. * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The tweet entities node will be disincluded when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $includeUserEntities The user entities node will be disincluded when set to false. * @return array * @static */ public static function statusesRetweetsOfMe($count = null, $sinceId = null, $maxId = null, $trimUser = null, $includeEntities = null, $includeUserEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesRetweetsOfMe($count, $sinceId, $maxId, $trimUser, $includeEntities, $includeUserEntities); } /** * Returns up to 100 of the first retweets of a given tweet. * * @param string $id The numerical ID of the desired status. * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 100. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @return array * @static */ public static function statusesRetweets($id, $count = null, $trimUser = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesRetweets($id, $count, $trimUser); } /** * Returns a single Tweet, specified by the id parameter. The Tweet's author will also be embedded within the tweet. * * @param string $id The numerical ID of the desired Tweet. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param \TijsVerkoyen\Twitter\bool[optional] $includeMyRetweet When set to true, any Tweets returned that have been retweeted by the authenticating user will include an additional current_user_retweet node, containing the ID of the source status for the retweet. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be disincluded when set to false. * @return array * @static */ public static function statusesShow($id, $trimUser = null, $includeMyRetweet = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesShow($id, $trimUser, $includeMyRetweet, $includeEntities); } /** * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful. * * @param string $id The numerical ID of the desired status. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @return array * @static */ public static function statusesDestroy($id, $trimUser = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesDestroy($id, $trimUser); } /** * Updates the authenticating user's status. A status update with text identical to the authenticating user's text identical to the authenticating user's current status will be ignored to prevent duplicates. * * @param string $status The text of your status update, typically up to 140 characters. URL encode as necessary. t.co link wrapping may effect character counts. There are some special commands in this field to be aware of. For instance, preceding a message with "D " or "M " and following it with a screen name can create a direct message to that user if the relationship allows for it. * @param \TijsVerkoyen\Twitter\string[optional] $inReplyToStatusId The ID of an existing status that the update is in reply to. Note: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include @username, where username is the author of the referenced tweet, within the update. * @param \TijsVerkoyen\Twitter\float[optional] $lat The latitude of the location this tweet refers to. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param \TijsVerkoyen\Twitter\float[optional] $long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param \TijsVerkoyen\Twitter\string[optional] $placeId A place in the world. These IDs can be retrieved from GET geo/reverse_geocode. * @param \TijsVerkoyen\Twitter\bool[optional] $displayCoordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @return array * @static */ public static function statusesUpdate($status, $inReplyToStatusId = null, $lat = null, $long = null, $placeId = null, $displayCoordinates = null, $trimUser = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesUpdate($status, $inReplyToStatusId, $lat, $long, $placeId, $displayCoordinates, $trimUser); } /** * Retweets a tweet. Returns the original tweet with retweet details embedded. * * @param string $id The numerical ID of the desired status. * @param \TijsVerkoyen\Twitter\bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @return array * @static */ public static function statusesRetweet($id, $trimUser = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesRetweet($id, $trimUser); } /** * Not implemented yet * * @static */ public static function statusesUpdateWithMedia(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesUpdateWithMedia(); } /** * * * @param \TijsVerkoyen\Twitter\string[optional] $id The Tweet/status ID to return embed code for. * @param \TijsVerkoyen\Twitter\string[optional] $url The URL of the Tweet/status to be embedded. * @param \TijsVerkoyen\Twitter\int[optional] $maxwidth The maximum width in pixels that the embed should be rendered at. This value is constrained to be between 250 and 550 pixels. Note that Twitter does not support the oEmbed maxheight parameter. Tweets are fundamentally text, and are therefore of unpredictable height that cannot be scaled like an image or video. Relatedly, the oEmbed response will not provide a value for height. Implementations that need consistent heights for Tweets should refer to the hide_thread and hide_media parameters below. * @param \TijsVerkoyen\Twitter\bool[optional] $hideMedia Specifies whether the embedded Tweet should automatically expand images which were uploaded via POST statuses/update_with_media. When set to true images will not be expanded. Defaults to false. * @param \TijsVerkoyen\Twitter\bool[optional] $hideThread Specifies whether the embedded Tweet should automatically show the original message in the case that the embedded Tweet is a reply. When set to true the original Tweet will not be shown. Defaults to false. * @param \TijsVerkoyen\Twitter\bool[optional] $omitScript Specifies whether the embedded Tweet HTML should include a <script> element pointing to widgets.js. In cases where a page already includes widgets.js, setting this value to true will prevent a redundant script element from being included. When set to true the <script> element will not be included in the embed HTML, meaning that pages must include a reference to widgets.js manually. Defaults to false. * @param \TijsVerkoyen\Twitter\string[optional] $align Specifies whether the embedded Tweet should be left aligned, right aligned, or centered in the page. Valid values are left, right, center, and none. Defaults to none, meaning no alignment styles are specified for the Tweet. * @param \TijsVerkoyen\Twitter\string[optional] $related A value for the TWT related parameter, as described in Web Intents. This value will be forwarded to all Web Intents calls. * @param \TijsVerkoyen\Twitter\string[optional] $lang Language code for the rendered embed. This will affect the text and localization of the rendered HTML. * @return array * @static */ public static function statusesOEmbed($id = null, $url = null, $maxwidth = null, $hideMedia = null, $hideThread = null, $omitScript = null, $align = null, $related = null, $lang = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesOEmbed($id, $url, $maxwidth, $hideMedia, $hideThread, $omitScript, $align, $related, $lang); } /** * Returns tweets that match a specified query. * * @param string $q A UTF-8, URL-encoded search query of 1,000 characters maximum, including operators. Queries may additionally be limited by complexity. * @param \TijsVerkoyen\Twitter\string[optional] $geocode Returns tweets by users located within a given radius of the given latitude/longitude. The location is preferentially taking from the Geotagging API, but will fall back to their Twitter profile. The parameter value is specified by "latitude,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly. A maximum of 1,000 distinct "sub-regions" will be considered when using the radius modifier. * @param \TijsVerkoyen\Twitter\string[optional] $lang Restricts tweets to the given language, given by an ISO 639-1 code. Language detection is best-effort. * @param \TijsVerkoyen\Twitter\string[optional] $locale Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific consumers and the default should work in the majority of cases. * @param \TijsVerkoyen\Twitter\string[optional] $resultType Specifies what type of search results you would prefer to receive. The current default is "mixed." Valid values include: mixed: Include both popular and real time results in the response, recent: return only the most recent results in the response, popular: return only the most popular results in the response. * @param \TijsVerkoyen\Twitter\int[optional] $count The number of tweets to return per page, up to a maximum of 100. Defaults to 15. This was formerly the "rpp" parameter in the old Search API. * @param \TijsVerkoyen\Twitter\string[optional] $until Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD. Keep in mind that the search index may not go back as far as the date you specify here. * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be disincluded when set to false. * @return array * @static */ public static function searchTweets($q, $geocode = null, $lang = null, $locale = null, $resultType = null, $count = null, $until = null, $sinceId = null, $maxId = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::searchTweets($q, $geocode, $lang, $locale, $resultType, $count, $until, $sinceId, $maxId, $includeEntities); } /** * Not implemented yet * * @static */ public static function statusesFilter(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesFilter(); } /** * Not implemented yet * * @static */ public static function statusesSample(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesSample(); } /** * Not implemented yet * * @static */ public static function statusesFirehose(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::statusesFirehose(); } /** * Not implemented yet * * @static */ public static function user(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::user(); } /** * Not implemented yet * * @static */ public static function site(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::site(); } /** * Returns the 20 most recent direct messages sent to the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 incoming DMs. * * Important: This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. * * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of direct messages to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of Tweets to return because suspended or deleted content is removed after the count has been applied. * @param \TijsVerkoyen\Twitter\int[optional] $page Specifies the page of results to retrieve. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function directMessages($sinceId = null, $maxId = null, $count = null, $page = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::directMessages($sinceId, $maxId, $count, $page, $includeEntities, $skipStatus); } /** * Returns the 20 most recent direct messages sent by the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 outgoing DMs. * * Important: This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. * * @param \TijsVerkoyen\Twitter\string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 200. * @param \TijsVerkoyen\Twitter\int[optional] $page Specifies the page of results to retrieve. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @return array * @static */ public static function directMessagesSent($sinceId = null, $maxId = null, $count = null, $page = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::directMessagesSent($sinceId, $maxId, $count, $page, $includeEntities); } /** * * * @param string $id The ID of the direct message. * @return array * @static */ public static function directMessagesShow($id){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::directMessagesShow($id); } /** * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message. * * Important: This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. * * @param string $id The ID of the direct message to delete. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @return array * @static */ public static function directMessagesDestroy($id, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::directMessagesDestroy($id, $includeEntities); } /** * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters and must be a POST. Returns the sent message in the requested format if successful. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user who should receive the direct message. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user who should receive the direct message. Helpful for disambiguating when a valid screen name is also a user ID. * @param string $text The text of your direct message. Be sure to URL encode as necessary, and keep the message under 140 characters. * @return array * @static */ public static function directMessagesNew($userId, $screenName, $text){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::directMessagesNew($userId, $screenName, $text); } /** * Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their "friends"). * * At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. * This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth * @param \TijsVerkoyen\Twitter\bool[optional] $stringifyIds Many programming environments will not consume our Tweet ids due to their size. Provide this option to have ids returned as strings instead. * @return array * @static */ public static function friendsIds($userId = null, $screenName = null, $cursor = null, $stringifyIds = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendsIds($userId, $screenName, $cursor, $stringifyIds); } /** * Returns a cursored collection of user IDs for every user following the specified user. * * At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. * This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth * @param \TijsVerkoyen\Twitter\bool[optional] $stringifyIds Many programming environments will not consume our Tweet ids due to their size. Provide this option to have ids returned as strings instead. * @return array * @static */ public static function followersIds($userId = null, $screenName = null, $cursor = null, $stringifyIds = true){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::followersIds($userId, $screenName, $cursor, $stringifyIds); } /** * Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. * * Values for connections can be: following, following_requested, followed_by, none. * * @param \TijsVerkoyen\Twitter\mixed[optional] $userIds An array of user IDs, up to 100 are allowed in a single request. * @param \TijsVerkoyen\Twitter\mixed[optional] $screenNames An array of screen names, up to 100 are allowed in a single request. * @return array * @static */ public static function friendshipsLookup($userIds = null, $screenNames = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsLookup($userIds, $screenNames); } /** * Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user. * * @param \TijsVerkoyen\Twitter\string[optional] $cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $stringifyIds Many programming environments will not consume our Tweet ids due to their size. Provide this option to have ids returned as strings instead. * @return array * @static */ public static function friendshipsIncoming($cursor = null, $stringifyIds = true){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsIncoming($cursor, $stringifyIds); } /** * Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request. * * @param \TijsVerkoyen\Twitter\string[optional] $cursor Causes the list of connections to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $stringifyIds Many programming environments will not consume our Tweet ids due to their size. Provide this option to have ids returned as strings instead. * @return array * @static */ public static function friendshipsOutgoing($cursor = null, $stringifyIds = true){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsOutgoing($cursor, $stringifyIds); } /** * Allows the authenticating users to follow the user specified in the ID parameter. * * Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. If you are already friends with the user a HTTP 403 may be returned, though for performance reasons you may get a 200 OK message even if the friendship already exists. * Actions taken in this method are asynchronous and changes will be eventually consistent. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to befriend. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to befriend. * @param \TijsVerkoyen\Twitter\bool[optional] $follow Enable notifications for the target user. * @return array * @static */ public static function friendshipsCreate($userId = null, $screenName = null, $follow = false){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsCreate($userId, $screenName, $follow); } /** * Allows the authenticating user to unfollow the user specified in the ID parameter. * * Returns the unfollowed user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * Actions taken in this method are asynchronous and changes will be eventually consistent. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to unfollow. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to unfollow. * @return array * @static */ public static function friendshipsDestroy($userId = null, $screenName = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsDestroy($userId, $screenName); } /** * Allows one to enable or disable retweets and device notifications from the specified user. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to befriend. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to befriend. * @param \TijsVerkoyen\Twitter\bool[optional] $device Enable/disable device notifications from the target user. * @param \TijsVerkoyen\Twitter\bool[optional] $retweets Enable/disable retweets from the target user. * @return array * @static */ public static function friendshipsUpdate($userId = null, $screenName = null, $device = null, $retweets = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsUpdate($userId, $screenName, $device, $retweets); } /** * Returns detailed information about the relationship between two arbitrary users. * * @param \TijsVerkoyen\Twitter\string[optional] $sourceId The user_id of the subject user. * @param \TijsVerkoyen\Twitter\string[optional] $sourceScreenName The screen_name of the subject user. * @param \TijsVerkoyen\Twitter\string[optional] $targetId The screen_name of the subject user. * @param \TijsVerkoyen\Twitter\string[optional] $targetScreenName The screen_name of the target user. * @return array * @static */ public static function friendshipsShow($sourceId = null, $sourceScreenName = null, $targetId = null, $targetScreenName = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendshipsShow($sourceId, $sourceScreenName, $targetId, $targetScreenName); } /** * Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends"). * * At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\int[optional] $cursor Causes the results to be broken into pages of no more than 20 records at a time. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The user object entities node will be disincluded when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function friendsList($userId = null, $screenName = null, $cursor = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::friendsList($userId, $screenName, $cursor, $includeEntities, $skipStatus); } /** * Returns a cursored collection of user objects for users following the specified user. * * At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\int[optional] $cursor Causes the results to be broken into pages of no more than 20 records at a time. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The user object entities node will be disincluded when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function followersList($userId = null, $screenName = null, $cursor = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::followersList($userId, $screenName, $cursor, $includeEntities, $skipStatus); } /** * Returns settings (including current trend, geo and sleep time information) for the authenticating user. * * @return array * @static */ public static function accountSettings(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountSettings(); } /** * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid. * * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to true, statuses will not be included in the returned user objects. * @return array * @static */ public static function accountVerifyCredentials($includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountVerifyCredentials($includeEntities, $skipStatus); } /** * Updates the authenticating user's settings. * * @param \TijsVerkoyen\Twitter\string[optional] $trendLocationWoeId The Yahoo! Where On Earth ID to use as the user's default trend location. Global information is available by using 1 as the WOEID. The woeid must be one of the locations returned by trendsAvailable. * @param \TijsVerkoyen\Twitter\bool[optional] $sleepTimeEnabled When set to true, will enable sleep time for the user. Sleep time is the time when push or SMS notifications should not be sent to the user. * @param \TijsVerkoyen\Twitter\string[optional] $startSleepTime The hour that sleep time should begin if it is enabled. The value for this parameter should be provided in ISO8601 format (i.e. 00-23). The time is considered to be in the same timezone as the user's time_zone setting. * @param \TijsVerkoyen\Twitter\string[optional] $endSleepTime The hour that sleep time should end if it is enabled. The value for this parameter should be provided in ISO8601 format (i.e. 00-23). The time is considered to be in the same timezone as the user's time_zone setting. * @param \TijsVerkoyen\Twitter\string[optional] $timeZone The timezone dates and times should be displayed in for the user. The timezone must be one of the Rails TimeZone names. * @param \TijsVerkoyen\Twitter\string[optional] $lang The language which Twitter should render in for this user. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by helpLanguages. * @return array * @static */ public static function accountSettingsUpdate($trendLocationWoeId = null, $sleepTimeEnabled = null, $startSleepTime = null, $endSleepTime = null, $timeZone = null, $lang = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountSettingsUpdate($trendLocationWoeId, $sleepTimeEnabled, $startSleepTime, $endSleepTime, $timeZone, $lang); } /** * Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable SMS updates. * * @return array * @param string $device Must be one of: sms, none. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities When set to true, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See Tweet Entities for more detail on entities. * @static */ public static function accountUpdateDeliveryDevice($device, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateDeliveryDevice($device, $includeEntities); } /** * Sets values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated. * * @return array * @param \TijsVerkoyen\Twitter\string[optional] $name Full name associated with the profile. Maximum of 20 characters. * @param \TijsVerkoyen\Twitter\string[optional] $url URL associated with the profile. Will be prepended with "http://" if not present. Maximum of 100 characters. * @param \TijsVerkoyen\Twitter\string[optional] $location The city or country describing where the user of the account is located. The contents are not normalized or geocoded in any way. Maximum of 30 characters. * @param \TijsVerkoyen\Twitter\string[optional] $description A description of the user owning the account. Maximum of 160 characters. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to true, statuses will not be included in the returned user objects. * @static */ public static function accountUpdateProfile($name = null, $url = null, $location = null, $description = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateProfile($name, $url, $location, $description, $includeEntities, $skipStatus); } /** * Updates the authenticating user's profile background image. * * @return array * @param string $image The path to the background image for the profile. Must be a valid GIF, JPG, or PNG image of less than 800 kilobytes in size. Images with width larger than 2048 pixels will be forceably scaled down. * @param \TijsVerkoyen\Twitter\bool[optional] $tile Whether or not to tile the background image. If set to true the background image will be displayed tiled. The image will not be tiled otherwise. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities When set to true each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. * @static */ public static function accountUpdateProfileBackgroundImage($image, $tile = false, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateProfileBackgroundImage($image, $tile, $includeEntities); } /** * Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. * * Each parameter's value must be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff). * * @return array * @param \TijsVerkoyen\Twitter\string[optional] $profileBackgroundColor Profile background color. * @param \TijsVerkoyen\Twitter\string[optional] $profileTextColor Profile text color. * @param \TijsVerkoyen\Twitter\string[optional] $profileLinkColor Profile link color. * @param \TijsVerkoyen\Twitter\string[optional] $profileSidebarFillColor Profile sidebar's background color. * @param \TijsVerkoyen\Twitter\string[optional] $profileSidebarBorderColor Profile sidebar's border color. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities When set to true each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. * @static */ public static function accountUpdateProfileColors($profileBackgroundColor = null, $profileTextColor = null, $profileLinkColor = null, $profileSidebarFillColor = null, $profileSidebarBorderColor = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateProfileColors($profileBackgroundColor, $profileTextColor, $profileLinkColor, $profileSidebarFillColor, $profileSidebarBorderColor, $includeEntities); } /** * Updates the authenticating user's profile image. * * @return array * @param string $image The path to the avatar image for the profile. Must be a valid GIF, JPG, or PNG image of less than 700 kilobytes in size. Images with width larger than 500 pixels will be scaled down. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities When set to true each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. * @static */ public static function accountUpdateProfileImage($image, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateProfileImage($image, $includeEntities); } /** * Not implemented yet * * @param \TijsVerkoyen\Twitter\int[optional] $cursor Causes the results to be broken into pages of no more than 20 records at a time. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The user object entities node will be disincluded when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function blocksList($cursor = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::blocksList($cursor, $includeEntities, $skipStatus); } /** * Returns an array of numeric user ids the authenticating user is blocking. * * @param \TijsVerkoyen\Twitter\string[optional] $cursor Causes the list of IDs to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." * @param \TijsVerkoyen\Twitter\bool[optional] $stringifyIds Many programming environments will not consume our ids due to their size. Provide this option to have ids returned as strings instead. * @return array * @static */ public static function blocksIds($cursor = null, $stringifyIds = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::blocksIds($cursor, $stringifyIds); } /** * Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the potentially blocked user. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the potentially blocked user. Helpful for disambiguating when a valid screen name is also a user ID. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function blocksCreate($userId = null, $screenName = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::blocksCreate($userId, $screenName, $includeEntities, $skipStatus); } /** * Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the potentially blocked user. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the potentially blocked user. Helpful for disambiguating when a valid screen name is also a user ID. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function blocksDestroy($userId = null, $screenName = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::blocksDestroy($userId, $screenName, $includeEntities, $skipStatus); } /** * Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters. * * @param \TijsVerkoyen\Twitter\mixed[optional] $userIds An array of user IDs, up to 100 are allowed in a single request. * @param \TijsVerkoyen\Twitter\mixed[optional] $screenNames An array of screen names, up to 100 are allowed in a single request. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node that may appear within embedded statuses will be disincluded when set to false. * @return array * @static */ public static function usersLookup($userIds = null, $screenNames = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersLookup($userIds, $screenNames, $includeEntities); } /** * Returns a variety of information about the user specified by the required user_id or screen_name parameter. * * The author's most recent Tweet will be returned inline when possible. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The screen name of the user for whom to return results for. Either a id or screen_name is required for this method. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The ID of the user for whom to return results for. Either an id or screen_name is required for this method. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @return array * @static */ public static function usersShow($userId = null, $screenName = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersShow($userId, $screenName, $includeEntities); } /** * Run a search for users similar to the Find People button on Twitter.com; the same results returned by people search on Twitter.com will be returned by using this API. * * Usage note: It is only possible to retrieve the first 1000 matches from this API. * * @param string $q The search query to run against people search. * @param \TijsVerkoyen\Twitter\int[optional] $page Specifies the page of results to retrieve. * @param \TijsVerkoyen\Twitter\int[optional] $count The number of potential user results to retrieve per page. This value has a maximum of 20. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be disincluded from embedded tweet objects when set to false. * @return array * @static */ public static function usersSearch($q, $page = null, $count = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersSearch($q, $page, $count, $includeEntities); } /** * Returns a collection of users that the specified user can "contribute" to. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function usersContributees($userId = null, $screenName = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersContributees($userId, $screenName, $includeEntities, $skipStatus); } /** * Returns a collection of users who can contribute to the specified account. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will not be included when set to false. * @param \TijsVerkoyen\Twitter\bool[optional] $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @return array * @static */ public static function usersContributors($userId = null, $screenName = null, $includeEntities = null, $skipStatus = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersContributors($userId, $screenName, $includeEntities, $skipStatus); } /** * Removes the uploaded profile banner for the authenticating user. * * @return bool * @static */ public static function accountRemoveProfileBanner(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountRemoveProfileBanner(); } /** * Not implemented yet * * @static */ public static function accountUpdateProfileBanner(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::accountUpdateProfileBanner(); } /** * Returns a map of the available size variations of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. * * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param \TijsVerkoyen\Twitter\string[optional] $screenName The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID. * @return array * @static */ public static function usersProfileBanner($userId = null, $screenName = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersProfileBanner($userId, $screenName); } /** * Access the users in a given category of the Twitter suggested user list. * * It is recommended that applications cache this data for no more than one hour. * * @param string $slug The short name of list or a category. * @param \TijsVerkoyen\Twitter\string[optional] $lang Restricts the suggested categories to the requested language. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by the helpLanguages API request. Unsupported language codes will receive English (en) results. * @return array * @static */ public static function usersSuggestionsSlug($slug, $lang = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersSuggestionsSlug($slug, $lang); } /** * Access to Twitter's suggested user list. This returns the list of suggested user categories. The category can be used in usersSuggestionsSlug to get the users in that category. * * @param \TijsVerkoyen\Twitter\string[optional] $lang Restricts the suggested categories to the requested language. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by the helpLanguages API request. Unsupported language codes will receive English (en) results. * @return array * @static */ public static function usersSuggestions($lang = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersSuggestions($lang); } /** * Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user. * * @param string $slug The short name of list or a category * @return array * @static */ public static function usersSuggestionsSlugMembers($slug){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::usersSuggestionsSlugMembers($slug); } /** * Returns the 20 most recent Tweets favorited by the authenticating or specified user. * * @param \TijsVerkoyen\Twitter\string[otpional] $userId The ID of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\string[otpional] $screenName The screen name of the user for whom to return results for. * @param \TijsVerkoyen\Twitter\int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 200. Defaults to 20. * @param \TijsVerkoyen\Twitter\string[otpional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. * @param \TijsVerkoyen\Twitter\string[otpional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be omitted when set to false. * @return array * @static */ public static function favoritesList($userId = null, $screenName = null, $count = 20, $sinceId = null, $maxId = null, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::favoritesList($userId, $screenName, $count, $sinceId, $maxId, $includeEntities); } /** * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. * * This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. * * @return array * @param string $id The numerical ID of the desired status. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be omitted when set to false. * @static */ public static function favoritesDestroy($id, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::favoritesDestroy($id, $includeEntities); } /** * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. * * This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. * * @param string $id The numerical ID of the desired status. * @param \TijsVerkoyen\Twitter\bool[optional] $includeEntities The entities node will be omitted when set to false. * @return array * @static */ public static function favoritesCreate($id, $includeEntities = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::favoritesCreate($id, $includeEntities); } /** * Not implemented yet * * @static */ public static function listsList(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsList(); } /** * Not implemented yet * * @static */ public static function listsStatuses(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsStatuses(); } /** * Not implemented yet * * @static */ public static function listsMembersDestroy(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembersDestroy(); } /** * Not implemented yet * * @static */ public static function listsMemberships(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMemberships(); } /** * Not implemented yet * * @static */ public static function listsSubscribers(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsSubscribers(); } /** * Not implemented yet * * @static */ public static function listsSubscribersCreate(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsSubscribersCreate(); } /** * Not implemented yet * * @static */ public static function listsSubscribersShow(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsSubscribersShow(); } /** * Not implemented yet * * @static */ public static function listsSubscribersDestroy(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsSubscribersDestroy(); } /** * Not implemented yet * * @static */ public static function listsMembersCreateAll(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembersCreateAll(); } /** * Not implemented yet * * @static */ public static function listsMembersShow(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembersShow(); } /** * Not implemented yet * * @static */ public static function listsMembers(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembers(); } /** * Not implemented yet * * @static */ public static function listsMembersCreate(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembersCreate(); } /** * Not implemented yet * * @static */ public static function listsDestroy(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsDestroy(); } /** * Not implemented yet * * @static */ public static function listsUpdate(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsUpdate(); } /** * Not implemented yet * * @static */ public static function listsCreate(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsCreate(); } /** * Not implemented yet * * @static */ public static function listsShow(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsShow(); } /** * Not implemented yet * * @static */ public static function listSubscriptions(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listSubscriptions(); } /** * Not implemented yet * * @static */ public static function listsMembersDestroyAll(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::listsMembersDestroyAll(); } /** * Returns the authenticated user's saved search queries. * * @return array * @static */ public static function savedSearchesList(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::savedSearchesList(); } /** * Retrieve the information for the saved search represented by the given id. The authenticating user must be the owner of saved search ID being requested. * * @return array * @param string $id The ID of the saved search. * @static */ public static function savedSearchesShow($id){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::savedSearchesShow($id); } /** * Create a new saved search for the authenticated user. A user may only have 25 saved searches. * * @return array * @param string $query The query of the search the user would like to save. * @static */ public static function savedSearchesCreate($query){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::savedSearchesCreate($query); } /** * Destroys a saved search for the authenticating user. The authenticating user must be the owner of saved search id being destroyed. * * @return array * @param string $id The ID of the saved search. * @static */ public static function savedSearchesDestroy($id){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::savedSearchesDestroy($id); } /** * Returns all the information about a known place. * * @param string $id A place in the world. These IDs can be retrieved from geo/reverse_geocode. * @return array * @static */ public static function geoId($id){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::geoId($id); } /** * Given a latitude and a longitude, searches for up to 20 places that can be used as a place_id when updating a status. * * This request is an informative call and will deliver generalized results about geography. * * @param float $lat The latitude to search around. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param float $long The longitude to search around. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param \TijsVerkoyen\Twitter\string[optional] $accuracy A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If this is not passed in, then it is assumed to be 0m. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). * @param \TijsVerkoyen\Twitter\string[optional] $granularity This is the minimal granularity of place types to return and must be one of: poi, neighborhood, city, admin or country. If no granularity is provided for the request neighborhood is assumed. Setting this to city, for example, will find places which have a type of city, admin or country. * @param \TijsVerkoyen\Twitter\int[optional] $maxResults A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. * @return array * @static */ public static function geoReverseGeoCode($lat, $long, $accuracy = null, $granularity = null, $maxResults = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::geoReverseGeoCode($lat, $long, $accuracy, $granularity, $maxResults); } /** * Search for places that can be attached to a statuses/update. Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status. * * Conceptually, a query can be made from the user's location, retrieve a list of places, have the user validate the location he or she is at, and then send the ID of this location with a call to POST statuses/update. * This is the recommended method to use find places that can be attached to statuses/update. Unlike GET geo/reverse_geocode which provides raw data access, this endpoint can potentially re-order places with regards to the user who is authenticated. This approach is also preferred for interactive place matching with the user. * * @param \TijsVerkoyen\Twitter\float[optional] $lat The latitude to search around. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param \TijsVerkoyen\Twitter\float[optional] $long The longitude to search around. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param \TijsVerkoyen\Twitter\string[optional] $query Free-form text to match against while executing a geo-based query, best suited for finding nearby locations by name. Remember to URL encode the query. * @param \TijsVerkoyen\Twitter\string[optional] $ip An IP address. Used when attempting to fix geolocation based off of the user's IP address. * @param \TijsVerkoyen\Twitter\string[optional] $granularity This is the minimal granularity of place types to return and must be one of: poi, neighborhood, city, admin or country. If no granularity is provided for the request neighborhood is assumed. Setting this to city, for example, will find places which have a type of city, admin or country. * @param \TijsVerkoyen\Twitter\string[optional] $accuracy A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If this is not passed in, then it is assumed to be 0m. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). * @param \TijsVerkoyen\Twitter\int[optional] $maxResults A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. * @param \TijsVerkoyen\Twitter\string[optional] $containedWithin This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. Specify a place_id. For example, to scope all results to places within "San Francisco, CA USA", you would specify a place_id of "5a110d312052166f" * @param \TijsVerkoyen\Twitter\array[optional] $attributes This parameter searches for places which have this given street address. There are other well-known, and application specific attributes available. Custom attributes are also permitted. This should be an key-value-pair-array. * @return array * @static */ public static function geoSearch($lat = null, $long = null, $query = null, $ip = null, $granularity = null, $accuracy = null, $maxResults = null, $containedWithin = null, $attributes = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::geoSearch($lat, $long, $query, $ip, $granularity, $accuracy, $maxResults, $containedWithin, $attributes); } /** * Locates places near the given coordinates which are similar in name. * * Conceptually you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one. * The token contained in the response is the token needed to be able to create a new place. * * @param float $lat The latitude to search around. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param float $long The longitude to search around. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param string $name The name a place is known as. * @param \TijsVerkoyen\Twitter\string[optional] $containedWithin This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. Specify a place_id. For example, to scope all results to places within "San Francisco, CA USA", you would specify a place_id of "5a110d312052166f" * @param \TijsVerkoyen\Twitter\array[optional] $attributes This parameter searches for places which have this given street address. There are other well-known, and application specific attributes available. Custom attributes are also permitted. * @return array * @static */ public static function geoSimilarPlaces($lat, $long, $name, $containedWithin = null, $attributes = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::geoSimilarPlaces($lat, $long, $name, $containedWithin, $attributes); } /** * Creates a new place at the given latitude and longitude. * * @param string $name The name a place is known as. * @param string $containedWithin The place_id within which the new place can be found. Try and be as close as possible with the containing place. For example, for a room in a building, set the contained_within as the building place_id. * @param string $token The token found in the response from geo/similar_places. * @param float $lat The latitude the place is located at. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param float $long The longitude the place is located at. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param \TijsVerkoyen\Twitter\array[optional] $attributes This parameter searches for places which have this given street address. There are other well-known, and application specific attributes available. Custom attributes are also permitted. This should be an key-value-pair-array. * @return array * @static */ public static function geoPlace($name, $containedWithin, $token, $lat, $long, $attributes = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::geoPlace($name, $containedWithin, $token, $lat, $long, $attributes); } /** * Returns the top 10 trending topics for a specific WOEID, if trending information is available for it. * * The response is an array of "trend" objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on Twitter Search, and the Twitter Search URL. * This information is cached for 5 minutes. Requesting more frequently than that will not return any more data, and will count against your rate limit usage. * * @param string $id The Yahoo! Where On Earth ID of the location to return trending information for. Global information is available by using 1 as the WOEID. * @param \TijsVerkoyen\Twitter\string[optional] $exclude Setting this equal to hashtags will remove all hashtags from the trends list. * @return array * @static */ public static function trendsPlace($id, $exclude = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::trendsPlace($id, $exclude); } /** * Returns the locations that Twitter has trending topic information for. * * The response is an array of "locations" that encode the location's WOEID (a Yahoo! Where On Earth ID) and some other human-readable information such as a canonical name and country the location belongs in. * The WOEID that is returned in the location object is to be used when querying for a specific trend. * * @param \TijsVerkoyen\Twitter\float[optional] $lat If passed in conjunction with long, then the available trend locations will be sorted by distance to the lat and long passed in. The sort is nearest to furthest. * @param \TijsVerkoyen\Twitter\float[optional] $long If passed in conjunction with lat, then the available trend locations will be sorted by distance to the lat and long passed in. The sort is nearest to furthest. * @return array * @static */ public static function trendsAvailable($lat = null, $long = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::trendsAvailable($lat, $long); } /** * Returns the locations that Twitter has trending topic information for, closest to a specified location. * * The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in. * * @param \TijsVerkoyen\Twitter\float[optional] $lat If provided with a long parameter the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive. * @param \TijsVerkoyen\Twitter\float[optional] $long If provided with a lat parameter the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive. * @return array * @static */ public static function trendsClosest($lat = null, $long = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::trendsClosest($lat, $long); } /** * The user specified in the id is blocked by the authenticated user and reported as a spammer. * * @param \TijsVerkoyen\Twitter\string[optional] $screenName The ID or screen_name of the user you want to report as a spammer. Helpful for disambiguating when a valid screen name is also a user ID. * @param \TijsVerkoyen\Twitter\string[optional] $userId The ID of the user you want to report as a spammer. Helpful for disambiguating when a valid user ID is also a valid screen name. * @return array * @static */ public static function reportSpam($screenName = null, $userId = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::reportSpam($screenName, $userId); } /** * Allows a Consumer application to use an OAuth request_token to request user authorization. * * This method is a replacement fulfills Secion 6.2 of the OAuth 1.0 authentication flow for * applications using the Sign in with Twitter authentication flow. The method will use the * currently logged in user as the account to for access authorization unless the force_login * parameter is set to true * * @param string $token The token. * @param \TijsVerkoyen\Twitter\bool[optional] $force Force the authentication. * @param \TijsVerkoyen\Twitter\string[optional] $screen_name Prefill the username input box of the OAuth login. * @static */ public static function oAuthAuthenticate($token, $force = false, $screen_name = false){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::oAuthAuthenticate($token, $force, $screen_name); } /** * Will redirect to the page to authorize the applicatione * * @param string $token The token. * @static */ public static function oAuthAuthorize($token){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::oAuthAuthorize($token); } /** * Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. * * This method fulfills Secion 6.3 of the OAuth 1.0 authentication flow. * * @param string $token The token to use. * @param string $verifier The verifier. * @return array * @static */ public static function oAuthAccessToken($token, $verifier){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::oAuthAccessToken($token, $verifier); } /** * Allows a Consumer application to obtain an OAuth Request Token to request user authorization. * * This method fulfills Secion 6.1 of the OAuth 1.0 authentication flow. * * @param \TijsVerkoyen\Twitter\string[optional] $callbackURL The callback URL. * @return array An array containg the token and the secret * @static */ public static function oAuthRequestToken($callbackURL = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::oAuthRequestToken($callbackURL); } /** * Returns the current configuration used by Twitter including twitter.com slugs which are not usernames, maximum photo resolutions, and t.co URL lengths. * * It is recommended applications request this endpoint when they are loaded, but no more than once a day. * * @return array * @static */ public static function helpConfiguration(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::helpConfiguration(); } /** * Returns the list of languages supported by Twitter along with their ISO 639-1 code. The ISO 639-1 code is the two letter value to use if you include lang with any of your requests. * * @return array * @static */ public static function helpLanguages(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::helpLanguages(); } /** * Returns Twitter's Privacy Policy * * @return array * @static */ public static function helpPrivacy(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::helpPrivacy(); } /** * Returns the Twitter Terms of Service in the requested format. These are not the same as the Developer Rules of the Road. * * @return array * @static */ public static function helpTos(){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::helpTos(); } /** * Returns the current rate limits for methods belonging to the specified resource families. * * Each 1.1 API resource belongs to a "resource family" which is indicated in its method documentation. You can typically determine a method's resource family from the first component of the path after the resource version. * This method responds with a map of methods belonging to the families specified by the resources parameter, the current remaining uses for each of those resources within the current rate limiting window, and its expiration time in epoch time. It also includes a rate_limit_context field that indicates the current access token context. * You may also issue requests to this method without any parameters to receive a map of all rate limited GET methods. If your application only uses a few of methods, please explicitly provide a resources parameter with the specified resource families you work with. * * @param array $resources A comma-separated list of resource families you want to know the current rate limit disposition for. For best performance, only specify the resource families pertinent to your application. * @return string * @static */ public static function applicationRateLimitStatus($resources = null){ //Method inherited from \TijsVerkoyen\Twitter\Twitter return \Philo\Twitter\Twitter::applicationRateLimitStatus($resources); } } class PDF extends \Thujohn\Pdf\PdfFacade{ /** * * * @static */ public static function load($html, $size = 'A4', $orientation = 'portrait'){ return \Thujohn\Pdf\Pdf::load($html, $size, $orientation); } /** * * * @static */ public static function show($filename = 'dompdf_out', $options = array()){ return \Thujohn\Pdf\Pdf::show($filename, $options); } /** * * * @static */ public static function download($filename = 'dompdf_out', $options = array()){ return \Thujohn\Pdf\Pdf::download($filename, $options); } /** * * * @static */ public static function output($options = array()){ return \Thujohn\Pdf\Pdf::output($options); } /** * * * @static */ public static function clear(){ return \Thujohn\Pdf\Pdf::clear(); } } class OpenGraph extends \ChrisKonnertz\OpenGraph\OpenGraph{ } class MailchimpWrapper extends \Hugofirth\Mailchimp\Facades\MailchimpWrapper{ /** * Get Mailchimp_Folders object * * @return \Hugofirth\Mailchimp\Mailchimp_Folders * @static */ public static function folders(){ return \Hugofirth\Mailchimp\MailchimpWrapper::folders(); } /** * Get Mailchimp_Templates object * * @return \Hugofirth\Mailchimp\Mailchimp_Templates * @static */ public static function templates(){ return \Hugofirth\Mailchimp\MailchimpWrapper::templates(); } /** * Get Mailchimp_Users object * * @return \Hugofirth\Mailchimp\Mailchimp_Users * @static */ public static function users(){ return \Hugofirth\Mailchimp\MailchimpWrapper::users(); } /** * Get Mailchimp_Helper object * * @return \Hugofirth\Mailchimp\Mailchimp_Helper * @static */ public static function helper(){ return \Hugofirth\Mailchimp\MailchimpWrapper::helper(); } /** * Get Mailchimp_Mobile object * * @return \Hugofirth\Mailchimp\Mailchimp_Mobile * @static */ public static function mobile(){ return \Hugofirth\Mailchimp\MailchimpWrapper::mobile(); } /** * Get Mailchimp_Ecomm object * * @return \Hugofirth\Mailchimp\Mailchimp_Ecomm * @static */ public static function ecomm(){ return \Hugofirth\Mailchimp\MailchimpWrapper::ecomm(); } /** * Get Mailchimp_Neapolitan object * * @return \Hugofirth\Mailchimp\Mailchimp_Neapolitan * @static */ public static function neapolitan(){ return \Hugofirth\Mailchimp\MailchimpWrapper::neapolitan(); } /** * Get Mailchimp_Lists object * * @return \Hugofirth\Mailchimp\Mailchimp_Lists * @static */ public static function lists(){ return \Hugofirth\Mailchimp\MailchimpWrapper::lists(); } /** * Get Mailchimp_Campaigns object * * @return \Hugofirth\Mailchimp\Mailchimp_Campaigns * @static */ public static function campaigns(){ return \Hugofirth\Mailchimp\MailchimpWrapper::campaigns(); } /** * Get Mailchimp_Vip object * * @return \Hugofirth\Mailchimp\Mailchimp_Vip * @static */ public static function vip(){ return \Hugofirth\Mailchimp\MailchimpWrapper::vip(); } /** * Get Mailchimp_Reports object * * @return \Hugofirth\Mailchimp\Mailchimp_Reports * @static */ public static function reports(){ return \Hugofirth\Mailchimp\MailchimpWrapper::reports(); } /** * Get Mailchimp_Gallery object * * @return \Hugofirth\Mailchimp\Mailchimp_Gallery * @static */ public static function gallery(){ return \Hugofirth\Mailchimp\MailchimpWrapper::gallery(); } } class UniversalAnalytics extends \TagPlanet\UniversalAnalytics\UniversalAnalyticsFacade{ /** * Returns the Laravel application * * @return \TagPlanet\UniversalAnalytics\Illuminate\Foundation\Application * @static */ public static function app(){ return \TagPlanet\UniversalAnalytics\UniversalAnalytics::app(); } /** * Find a single tracker instance * * @return \TagPlanet\UniversalAnalytics\TagPlanet\UniversalAnalytics\UniversalAnalyticsInstance * @static */ public static function get($name){ return \TagPlanet\UniversalAnalytics\UniversalAnalytics::get($name); } /** * Render the Universal Analytics code * * @return string * @static */ public static function render($renderedCodeBlock = true, $renderScriptTag = true){ return \TagPlanet\UniversalAnalytics\UniversalAnalytics::render($renderedCodeBlock, $renderScriptTag); } /** * * * @static */ public static function ga(){ return \TagPlanet\UniversalAnalytics\UniversalAnalytics::ga(); } } class ES extends \Elasticsearch\Client{ } class Shortcode extends \Pingpong\Shortcode\Facades\Shortcode{ /** * Get the container instance. * * @return \Illuminate\Container\Container * @static */ public static function getContainer(){ return \Pingpong\Shortcode\Shortcode::getContainer(); } /** * Set the laravel container instance. * * @param \Illuminate\Container\Container $container * @return self * @static */ public static function setContainer($container){ return \Pingpong\Shortcode\Shortcode::setContainer($container); } /** * Get all shortcodes. * * @return array * @static */ public static function all(){ return \Pingpong\Shortcode\Shortcode::all(); } /** * Register new shortcode. * * @param string $name * @param mixed $callback * @return void * @static */ public static function register($name, $callback){ \Pingpong\Shortcode\Shortcode::register($name, $callback); } /** * Unregister the specified shortcode by given name. * * @param string $name * @return void * @static */ public static function unregister($name){ \Pingpong\Shortcode\Shortcode::unregister($name); } /** * Unregister all shortcodes. * * @return self * @static */ public static function destroy(){ return \Pingpong\Shortcode\Shortcode::destroy(); } /** * Strip any shortcodes. * * @param string $content * @return string * @static */ public static function strip($content){ return \Pingpong\Shortcode\Shortcode::strip($content); } /** * Get count from all shortcodes. * * @return integer * @static */ public static function count(){ return \Pingpong\Shortcode\Shortcode::count(); } /** * Return true is the given name exist in shortcodes array. * * @param string $name * @return boolean * @static */ public static function exists($name){ return \Pingpong\Shortcode\Shortcode::exists($name); } /** * Return true is the given content contain the given name shortcode. * * @param string $content * @param string $name * @return boolean * @static */ public static function contains($content, $name){ return \Pingpong\Shortcode\Shortcode::contains($content, $name); } /** * Compile the gived content. * * @param string $content * @return void * @static */ public static function compile($content){ \Pingpong\Shortcode\Shortcode::compile($content); } /** * Render the current calld shortcode. * * @param array $matches * @return void * @static */ public static function render($matches){ \Pingpong\Shortcode\Shortcode::render($matches); } } class Cart extends \Gloudemans\Shoppingcart\Facades\Cart{ /** * Set the current cart instance * * @param string $instance Cart instance name * @return \Gloudemans\Shoppingcart\Gloudemans\Shoppingcart\Cart * @static */ public static function instance($instance = null){ return \Gloudemans\Shoppingcart\Cart::instance($instance); } /** * Set the associated model * * @param string $modelName The name of the model * @param string $modelNamespace The namespace of the model * @return void * @static */ public static function associate($modelName, $modelNamespace = null){ \Gloudemans\Shoppingcart\Cart::associate($modelName, $modelNamespace); } /** * Add a row to the cart * * @param string|array $id Unique ID of the item|Item formated as array|Array of items * @param string $name Name of the item * @param int $qty Item qty to add to the cart * @param float $price Price of one item * @param array $options Array of additional options, such as 'size' or 'color' * @static */ public static function add($id, $name = null, $qty = null, $price = null, $options = array()){ return \Gloudemans\Shoppingcart\Cart::add($id, $name, $qty, $price, $options); } /** * Update the quantity of one row of the cart * * @param string $rowId The rowid of the item you want to update * @param integer|array $attribute New quantity of the item|Array of attributes to update * @return boolean * @static */ public static function update($rowId, $attribute){ return \Gloudemans\Shoppingcart\Cart::update($rowId, $attribute); } /** * Remove a row from the cart * * @param string $rowId The rowid of the item * @return boolean * @static */ public static function remove($rowId){ return \Gloudemans\Shoppingcart\Cart::remove($rowId); } /** * Get a row of the cart by its ID * * @param string $rowId The ID of the row to fetch * @return \Gloudemans\Shoppingcart\Gloudemans\Shoppingcart\CartCollection * @static */ public static function get($rowId){ return \Gloudemans\Shoppingcart\Cart::get($rowId); } /** * Get the cart content * * @return \Gloudemans\Shoppingcart\Gloudemans\Shoppingcart\CartRowCollection * @static */ public static function content(){ return \Gloudemans\Shoppingcart\Cart::content(); } /** * Empty the cart * * @return boolean * @static */ public static function destroy(){ return \Gloudemans\Shoppingcart\Cart::destroy(); } /** * Get the price total * * @return float * @static */ public static function total(){ return \Gloudemans\Shoppingcart\Cart::total(); } /** * Get the number of items in the cart * * @param boolean $totalItems Get all the items (when false, will return the number of rows) * @return int * @static */ public static function count($totalItems = true){ return \Gloudemans\Shoppingcart\Cart::count($totalItems); } /** * Search if the cart has a item * * @param array $search An array with the item ID and optional options * @return array|boolean * @static */ public static function search($search){ return \Gloudemans\Shoppingcart\Cart::search($search); } } class Log extends \Igormatkovic\Livelogger\Facades\Livelogger{ /** * Adds a log record at the DEBUG level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function debug($message, $context = array()){ return \Monolog\Logger::debug($message, $context); } /** * Adds a log record at the INFO level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function info($message, $context = array()){ return \Monolog\Logger::info($message, $context); } /** * Adds a log record at the NOTICE level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function notice($message, $context = array()){ return \Monolog\Logger::notice($message, $context); } /** * Adds a log record at the WARNING level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function warning($message, $context = array()){ return \Monolog\Logger::warning($message, $context); } /** * Adds a log record at the ERROR level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function error($message, $context = array()){ return \Monolog\Logger::error($message, $context); } /** * Adds a log record at the CRITICAL level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function critical($message, $context = array()){ return \Monolog\Logger::critical($message, $context); } /** * Adds a log record at the ALERT level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function alert($message, $context = array()){ return \Monolog\Logger::alert($message, $context); } /** * Adds a log record at the EMERGENCY level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function emergency($message, $context = array()){ return \Monolog\Logger::emergency($message, $context); } /** * Register a file log handler. * * @param string $path * @param string $level * @return void * @static */ public static function useFiles($path, $level = 'debug'){ //Method inherited from \Illuminate\Log\Writer \Igormatkovic\Livelogger\Livelogger::useFiles($path, $level); } /** * Register a daily file log handler. * * @param string $path * @param int $days * @param string $level * @return void * @static */ public static function useDailyFiles($path, $days = 0, $level = 'debug'){ //Method inherited from \Illuminate\Log\Writer \Igormatkovic\Livelogger\Livelogger::useDailyFiles($path, $days, $level); } /** * Register an error_log handler. * * @param string $level * @param int $messageType * @return void * @static */ public static function useErrorLog($level = 'debug', $messageType = 0){ //Method inherited from \Illuminate\Log\Writer \Igormatkovic\Livelogger\Livelogger::useErrorLog($level, $messageType); } /** * Register a new callback handler for when * a log event is triggered. * * @param \Closure $callback * @return void * @throws \RuntimeException * @static */ public static function listen($callback){ //Method inherited from \Illuminate\Log\Writer \Igormatkovic\Livelogger\Livelogger::listen($callback); } /** * Get the underlying Monolog instance. * * @return \Monolog\Logger * @static */ public static function getMonolog(){ //Method inherited from \Illuminate\Log\Writer return \Igormatkovic\Livelogger\Livelogger::getMonolog(); } /** * Get the event dispatcher instance. * * @return \Illuminate\Events\Dispatcher * @static */ public static function getEventDispatcher(){ //Method inherited from \Illuminate\Log\Writer return \Igormatkovic\Livelogger\Livelogger::getEventDispatcher(); } /** * Set the event dispatcher instance. * * @param \Illuminate\Events\Dispatcher * @return void * @static */ public static function setEventDispatcher($dispatcher){ //Method inherited from \Illuminate\Log\Writer \Igormatkovic\Livelogger\Livelogger::setEventDispatcher($dispatcher); } /** * Dynamically pass log calls into the writer. * * @param mixed (level, param, param) * @return mixed * @static */ public static function write(){ //Method inherited from \Illuminate\Log\Writer return \Igormatkovic\Livelogger\Livelogger::write(); } } class TBMsg extends \Tzookb\TBMsg\Facade\TBMsg{ /** * * * @static */ public static function markMessageAs($msgId, $userId, $status){ return \Tzookb\TBMsg\TBMsg::markMessageAs($msgId, $userId, $status); } /** * * * @static */ public static function markMessageAsRead($msgId, $userId){ return \Tzookb\TBMsg\TBMsg::markMessageAsRead($msgId, $userId); } /** * * * @static */ public static function markMessageAsUnread($msgId, $userId){ return \Tzookb\TBMsg\TBMsg::markMessageAsUnread($msgId, $userId); } /** * * * @static */ public static function markMessageAsDeleted($msgId, $userId){ return \Tzookb\TBMsg\TBMsg::markMessageAsDeleted($msgId, $userId); } /** * * * @static */ public static function markMessageAsArchived($msgId, $userId){ return \Tzookb\TBMsg\TBMsg::markMessageAsArchived($msgId, $userId); } /** * * * @static */ public static function getUserConversations($user_id){ return \Tzookb\TBMsg\TBMsg::getUserConversations($user_id); } /** * * * @param $conv_id * @param $user_id * @param bool $newToOld * @return \Tzookb\TBMsg\Conversation * @static */ public static function getConversationMessages($conv_id, $user_id, $newToOld = true){ return \Tzookb\TBMsg\TBMsg::getConversationMessages($conv_id, $user_id, $newToOld); } /** * * * @param $userA_id * @param $userB_id * @throws ConversationNotFoundException * @return mixed -> id of conversation or false on not found * @static */ public static function getConversationByTwoUsers($userA_id, $userB_id){ return \Tzookb\TBMsg\TBMsg::getConversationByTwoUsers($userA_id, $userB_id); } /** * * * @static */ public static function addMessageToConversation($conv_id, $user_id, $content){ return \Tzookb\TBMsg\TBMsg::addMessageToConversation($conv_id, $user_id, $content); } /** * * * @param array $users_ids * @throws Exceptions\NotEnoughUsersInConvException * @return \Tzookb\TBMsg\ConversationEloquent * @static */ public static function createConversation($users_ids){ return \Tzookb\TBMsg\TBMsg::createConversation($users_ids); } /** * * * @static */ public static function sendMessageBetweenTwoUsers($senderId, $receiverId, $content){ return \Tzookb\TBMsg\TBMsg::sendMessageBetweenTwoUsers($senderId, $receiverId, $content); } /** * * * @static */ public static function markReadAllMessagesInConversation($conv_id, $user_id){ return \Tzookb\TBMsg\TBMsg::markReadAllMessagesInConversation($conv_id, $user_id); } /** * * * @static */ public static function markUnreadAllMessagesInConversation($conv_id, $user_id){ return \Tzookb\TBMsg\TBMsg::markUnreadAllMessagesInConversation($conv_id, $user_id); } /** * * * @static */ public static function deleteConversation($conv_id, $user_id){ return \Tzookb\TBMsg\TBMsg::deleteConversation($conv_id, $user_id); } /** * * * @static */ public static function isUserInConversation($conv_id, $user_id){ return \Tzookb\TBMsg\TBMsg::isUserInConversation($conv_id, $user_id); } /** * * * @static */ public static function getUsersInConversation($conv_id){ return \Tzookb\TBMsg\TBMsg::getUsersInConversation($conv_id); } /** * * * @static */ public static function getNumOfUnreadMsgs($user_id){ return \Tzookb\TBMsg\TBMsg::getNumOfUnreadMsgs($user_id); } } class JavaScript extends \Laracasts\Utilities\JavaScript\Facades\JavaScript{ /** * Bind given array of variables to view * * @param array $vars * @static */ public static function put($vars){ return \Laracasts\Utilities\JavaScript\PHPToJavaScriptTransformer::put($vars); } /** * Translate the array of PHP vars * to JavaScript syntax. * * @param array $vars * @internal param $js * @return array * @static */ public static function buildJavaScriptSyntax($vars){ return \Laracasts\Utilities\JavaScript\PHPToJavaScriptTransformer::buildJavaScriptSyntax($vars); } } class FacebookConnect extends \Pitchanon\FacebookConnect\Facades\FacebookConnect{ /** * getInstance. * * @param array $application Example: array('appId' => YOUR_APP_ID, 'secret' => YOUR_APP_SECRET); * @return object new Facebook($application) * @author <NAME>. <<EMAIL>> * @static */ public static function getFacebook($application = array()){ return \Pitchanon\FacebookConnect\Provider\FacebookConnect::getFacebook($application); } /** * Authenticated. * * @param array $permissions List permissions * @param string $url_app Canvas URL * @return array User data facebook * @author <NAME>. <<EMAIL>> * @static */ public static function getUser($permissions, $url_app){ return \Pitchanon\FacebookConnect\Provider\FacebookConnect::getUser($permissions, $url_app); } /** * Check user likes the page in Facebook. * * @param integer $page_id Facebook fan page id * @param integer $user_id Facebook User id * @return \Pitchanon\FacebookConnect\Provider\[type] [description] * @author <NAME>. <<EMAIL>> * @static */ public static function getUserLikePage($page_id, $user_id){ return \Pitchanon\FacebookConnect\Provider\FacebookConnect::getUserLikePage($page_id, $user_id); } /** * post links, feed to user facebook wall. * * @param array $message Example: $message = array('link' => '', 'message' => '','picture' => '', 'name' => '','description' => '', 'access_token' => ''); * @param string $type Type of message (links,feed) * @return string Id of message * @author <NAME>. <<EMAIL>> * @static */ public static function postToFacebook($message, $type = null){ return \Pitchanon\FacebookConnect\Provider\FacebookConnect::postToFacebook($message, $type); } } class Es extends \Shift31\LaravelElasticsearch\Facades\Es{ /** * * * @return array * @static */ public static function info(){ return \Elasticsearch\Client::info(); } /** * * * @static */ public static function ping(){ return \Elasticsearch\Client::ping(); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required) * ['ignore_missing'] = ?? * ['fields'] = (list) A comma-separated list of fields to return in the response * ['parent'] = (string) The ID of the parent document * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['realtime'] = (boolean) Specify whether to perform the operation in realtime or search mode * ['refresh'] = (boolean) Refresh the shard containing the document before performing the operation * ['routing'] = (string) Specific routing value * ['_source'] = (list) True or false to return the _source field or not, or a list of fields to return * ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field * ['_source_include'] = (list) A list of fields to extract and return from the _source field * * @param $params array Associative array of parameters * @return array * @static */ public static function get($params){ return \Elasticsearch\Client::get($params); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required) * ['ignore_missing'] = ?? * ['parent'] = (string) The ID of the parent document * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['realtime'] = (boolean) Specify whether to perform the operation in realtime or search mode * ['refresh'] = (boolean) Refresh the shard containing the document before performing the operation * ['routing'] = (string) Specific routing value * * @param $params array Associative array of parameters * @return array * @static */ public static function getSource($params){ return \Elasticsearch\Client::getSource($params); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (Required) * ['consistency'] = (enum) Specific write consistency setting for the operation * ['parent'] = (string) ID of parent document * ['refresh'] = (boolean) Refresh the index after performing the operation * ['replication'] = (enum) Specific replication type * ['routing'] = (string) Specific routing value * ['timeout'] = (time) Explicit operation timeout * ['version_type'] = (enum) Specific version type * * @param $params array Associative array of parameters * @return array * @static */ public static function delete($params){ return \Elasticsearch\Client::delete($params); } /** * $params[''] @todo finish the rest of these params * ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. * * @param array $params * @return array * @static */ public static function deleteByQuery($params = array()){ return \Elasticsearch\Client::deleteByQuery($params); } /** * $params['index'] = (list) A comma-separated list of indices to restrict the results * ['type'] = (list) A comma-separated list of types to restrict the results * ['min_score'] = (number) Include only documents with a specific `_score` value in the result * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['routing'] = (string) Specific routing value * ['source'] = (string) The URL-encoded query definition (instead of using the request body) * ['body'] = (array) A query to restrict the results (optional) * ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. * * @param $params array Associative array of parameters * @return array * @static */ public static function count($params = array()){ return \Elasticsearch\Client::count($params); } /** * $params['index'] = (list) A comma-separated list of indices to restrict the results * ['type'] = (list) A comma-separated list of types to restrict the results * ['id'] = (string) ID of document * ['ignore_unavailable'] = (boolean) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['routing'] = (string) Specific routing value * ['allow_no_indices'] = (boolean) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * ['body'] = (array) A query to restrict the results (optional) * ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['percolate_index'] = (string) The index to count percolate the document into. Defaults to index. * * ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. * ['version'] = (number) Explicit version number for concurrency control * ['version_type'] = (enum) Specific version type * * @param $params array Associative array of parameters * @return array * @static */ public static function countPercolate($params = array()){ return \Elasticsearch\Client::countPercolate($params); } /** * $params['index'] = (string) The name of the index with a registered percolator query (Required) * ['type'] = (string) The document type (Required) * ['prefer_local'] = (boolean) With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true) * ['body'] = (array) The document (`doc`) to percolate against registered queries; optionally also a `query` to limit the percolation to specific registered queries * * @param $params array Associative array of parameters * @return array * @static */ public static function percolate($params){ return \Elasticsearch\Client::percolate($params); } /** * $params['index'] = (string) Default index for items which don't provide one * ['type'] = (string) Default document type for items which don't provide one * ['ignore_unavailable'] = (boolean) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['allow_no_indices'] = (boolean) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. * * @param $params array Associative array of parameters * @return array * @static */ public static function mpercolate($params = array()){ return \Elasticsearch\Client::mpercolate($params); } /** * $params['index'] = (string) Default index for items which don't provide one * ['type'] = (string) Default document type for items which don't provide one * ['term_statistics'] = (boolean) Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['field_statistics'] = (boolean) Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['fields'] = (list) A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['offsets'] = (boolean) Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['positions'] = (boolean) Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['payloads'] = (boolean) Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['routing'] = (string) Specific routing value. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['parent'] = (string) Parent id of documents. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['realtime'] = (boolean) Specifies if request is real-time as opposed to near-real-time (default: true). * * @param $params array Associative array of parameters * @return array * @static */ public static function termvector($params = array()){ return \Elasticsearch\Client::termvector($params); } /** * $params['index'] = (string) Default index for items which don't provide one * ['type'] = (string) Default document type for items which don't provide one * ['ids'] = (list) A comma-separated list of documents ids. You must define ids as parameter or set \"ids\" or \"docs\" in the request body * ['term_statistics'] = (boolean) Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['field_statistics'] = (boolean) Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['fields'] = (list) A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['offsets'] = (boolean) Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['positions'] = (boolean) Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\"." * ['payloads'] = (boolean) Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['routing'] = (string) Specific routing value. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['parent'] = (string) Parent id of documents. Applies to all returned documents unless otherwise specified in body \"params\" or \"docs\". * ['realtime'] = (boolean) Specifies if request is real-time as opposed to near-real-time (default: true). * * @param $params array Associative array of parameters * @return array * @static */ public static function mtermvectors($params = array()){ return \Elasticsearch\Client::mtermvectors($params); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required) * ['parent'] = (string) The ID of the parent document * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['realtime'] = (boolean) Specify whether to perform the operation in realtime or search mode * ['refresh'] = (boolean) Refresh the shard containing the document before performing the operation * ['routing'] = (string) Specific routing value * * @param $params array Associative array of parameters * @return array * @static */ public static function exists($params){ return \Elasticsearch\Client::exists($params); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (use `_all` to fetch the first document matching the ID across all types) (Required) * ['boost_terms'] = (number) The boost factor * ['max_doc_freq'] = (number) The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored * ['max_query_terms'] = (number) The maximum query terms to be included in the generated query * ['max_word_len'] = (number) The minimum length of the word: longer words will be ignored * ['min_doc_freq'] = (number) The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored * ['min_term_freq'] = (number) The term frequency as percent: terms with lower occurrence in the source document will be ignored * ['min_word_len'] = (number) The minimum length of the word: shorter words will be ignored * ['mlt_fields'] = (list) Specific fields to perform the query against * ['percent_terms_to_match'] = (number) How many terms have to match in order to consider the document a match (default: 0.3) * ['routing'] = (string) Specific routing value * ['search_from'] = (number) The offset from which to return results * ['search_indices'] = (list) A comma-separated list of indices to perform the query against (default: the index containing the document) * ['search_query_hint'] = (string) The search query hint * ['search_scroll'] = (string) A scroll search request definition * ['search_size'] = (number) The number of documents to return (default: 10) * ['search_source'] = (string) A specific search request definition (instead of using the request body) * ['search_type'] = (string) Specific search type (eg. `dfs_then_fetch`, `count`, etc) * ['search_types'] = (list) A comma-separated list of types to perform the query against (default: the same type as the document) * ['stop_words'] = (list) A list of stop words to be ignored * ['body'] = (array) A specific search request definition * * @param $params array Associative array of parameters * @return array * @static */ public static function mlt($params){ return \Elasticsearch\Client::mlt($params); } /** * $params['index'] = (string) The name of the index * ['type'] = (string) The type of the document * ['fields'] = (list) A comma-separated list of fields to return in the response * ['parent'] = (string) The ID of the parent document * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['realtime'] = (boolean) Specify whether to perform the operation in realtime or search mode * ['refresh'] = (boolean) Refresh the shard containing the document before performing the operation * ['routing'] = (string) Specific routing value * ['body'] = (array) Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL. * * ['_source'] = (list) True or false to return the _source field or not, or a list of fields to return * ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field * ['_source_include'] = (list) A list of fields to extract and return from the _source field * * @param $params array Associative array of parameters * @return array * @static */ public static function mget($params = array()){ return \Elasticsearch\Client::mget($params); } /** * $params['index'] = (list) A comma-separated list of index names to use as default * ['type'] = (list) A comma-separated list of document types to use as default * ['search_type'] = (enum) Search operation type * ['body'] = (array|string) The request definitions (metadata-search request definition pairs), separated by newlines * * @param $params array Associative array of parameters * @return array * @static */ public static function msearch($params = array()){ return \Elasticsearch\Client::msearch($params); } /** * $params['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (Required) * ['id'] = (string) Specific document ID (when the POST method is used) * ['consistency'] = (enum) Explicit write consistency setting for the operation * ['parent'] = (string) ID of the parent document * ['percolate'] = (string) Percolator queries to execute while indexing the document * ['refresh'] = (boolean) Refresh the index after performing the operation * ['replication'] = (enum) Specific replication type * ['routing'] = (string) Specific routing value * ['timeout'] = (time) Explicit operation timeout * ['timestamp'] = (time) Explicit timestamp for the document * ['ttl'] = (duration) Expiration time for the document * ['version'] = (number) Explicit version number for concurrency control * ['version_type'] = (enum) Specific version type * ['body'] = (array) The document * * @param $params array Associative array of parameters * @return array * @static */ public static function create($params){ return \Elasticsearch\Client::create($params); } /** * $params['index'] = (string) Default index for items which don't provide one * ['type'] = (string) Default document type for items which don't provide one * ['consistency'] = (enum) Explicit write consistency setting for the operation * ['refresh'] = (boolean) Refresh the index after performing the operation * ['replication'] = (enum) Explicitly set the replication type * ['body'] = (string) Default document type for items which don't provide one * * @param $params array Associative array of parameters * @return array * @static */ public static function bulk($params = array()){ return \Elasticsearch\Client::bulk($params); } /** * $params['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (Required) * ['id'] = (string) Specific document ID (when the POST method is used) * ['consistency'] = (enum) Explicit write consistency setting for the operation * ['op_type'] = (enum) Explicit operation type * ['parent'] = (string) ID of the parent document * ['percolate'] = (string) Percolator queries to execute while indexing the document * ['refresh'] = (boolean) Refresh the index after performing the operation * ['replication'] = (enum) Specific replication type * ['routing'] = (string) Specific routing value * ['timeout'] = (time) Explicit operation timeout * ['timestamp'] = (time) Explicit timestamp for the document * ['ttl'] = (duration) Expiration time for the document * ['version'] = (number) Explicit version number for concurrency control * ['version_type'] = (enum) Specific version type * ['body'] = (array) The document * * @param $params array Associative array of parameters * @return array * @static */ public static function index($params){ return \Elasticsearch\Client::index($params); } /** * $params['index'] = (list) A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices * ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['routing'] = (string) Specific routing value * ['source'] = (string) The URL-encoded request definition (instead of using request body) * ['body'] = (array) The request definition * * @param $params array Associative array of parameters * @return array * @static */ public static function suggest($params = array()){ return \Elasticsearch\Client::suggest($params); } /** * $params['id'] = (string) The document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (Required) * ['analyze_wildcard'] = (boolean) Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false) * ['analyzer'] = (string) The analyzer for the query string query * ['default_operator'] = (enum) The default operator for query string query (AND or OR) * ['df'] = (string) The default field for query string query (default: _all) * ['fields'] = (list) A comma-separated list of fields to return in the response * ['lenient'] = (boolean) Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * ['lowercase_expanded_terms'] = (boolean) Specify whether query terms should be lowercased * ['parent'] = (string) The ID of the parent document * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['q'] = (string) Query in the Lucene query string syntax * ['routing'] = (string) Specific routing value * ['source'] = (string) The URL-encoded query definition (instead of using the request body) * ['_source'] = (list) True or false to return the _source field or not, or a list of fields to return * ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field * ['_source_include'] = (list) A list of fields to extract and return from the _source field * ['body'] = (string) The URL-encoded query definition (instead of using the request body) * * @param $params array Associative array of parameters * @return array * @static */ public static function explain($params){ return \Elasticsearch\Client::explain($params); } /** * $params['index'] = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * ['type'] = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types * ['analyzer'] = (string) The analyzer to use for the query string * ['analyze_wildcard'] = (boolean) Specify whether wildcard and prefix queries should be analyzed (default: false) * ['default_operator'] = (enum) The default operator for query string query (AND or OR) * ['df'] = (string) The field to use as default where no field prefix is given in the query string * ['explain'] = (boolean) Specify whether to return detailed information about score computation as part of a hit * ['fields'] = (list) A comma-separated list of fields to return as part of a hit * ['from'] = (number) Starting offset (default: 0) * ['ignore_indices'] = (enum) When performed on multiple indices, allows to ignore `missing` ones * ['indices_boost'] = (list) Comma-separated list of index boosts * ['lenient'] = (boolean) Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * ['lowercase_expanded_terms'] = (boolean) Specify whether query terms should be lowercased * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['q'] = (string) Query in the Lucene query string syntax * ['routing'] = (list) A comma-separated list of specific routing values * ['scroll'] = (duration) Specify how long a consistent view of the index should be maintained for scrolled search * ['search_type'] = (enum) Search operation type * ['size'] = (number) Number of hits to return (default: 10) * ['sort'] = (list) A comma-separated list of <field>:<direction> pairs * ['source'] = (string) The URL-encoded request definition using the Query DSL (instead of using request body) * ['_source'] = (list) True or false to return the _source field or not, or a list of fields to return * ['_source_exclude'] = (list) A list of fields to exclude from the returned _source field * ['_source_include'] = (list) A list of fields to extract and return from the _source field * ['stats'] = (list) Specific 'tag' of the request for logging and statistical purposes * ['suggest_field'] = (string) Specify which field to use for suggestions * ['suggest_mode'] = (enum) Specify suggest mode * ['suggest_size'] = (number) How many suggestions to return in response * ['suggest_text'] = (text) The source text for which the suggestions should be returned * ['timeout'] = (time) Explicit operation timeout * ['version'] = (boolean) Specify whether to return document version as part of a hit * ['body'] = (array|string) The search definition using the Query DSL * * @param $params array Associative array of parameters * @return array * @static */ public static function search($params = array()){ return \Elasticsearch\Client::search($params); } /** * $params['index'] = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * ['type'] = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types * ['preference'] = (string) Specify the node or shard the operation should be performed on (default: random) * ['routing'] = (string) Specific routing value * ['local'] = (bool) Return local information, do not retrieve the state from master node (default: false) * ['ignore_unavailable'] = (bool) Whether specified concrete indices should be ignored when unavailable (missing or closed) * ['allow_no_indices'] = (bool) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * ['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. * * @param $params array Associative array of parameters * @return array * @static */ public static function searchShards($params = array()){ return \Elasticsearch\Client::searchShards($params); } /** * $params['index'] = (list) A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * ['type'] = (list) A comma-separated list of document types to search; leave empty to perform the operation on all types * * @param $params array Associative array of parameters * @return array * @static */ public static function searchTemplate($params = array()){ return \Elasticsearch\Client::searchTemplate($params); } /** * $params['scroll_id'] = (string) The scroll ID for scrolled search * ['scroll'] = (duration) Specify how long a consistent view of the index should be maintained for scrolled search * ['body'] = (string) The scroll ID for scrolled search * * @param $params array Associative array of parameters * @return array * @static */ public static function scroll($params = array()){ return \Elasticsearch\Client::scroll($params); } /** * $params['scroll_id'] = (string) The scroll ID for scrolled search * ['scroll'] = (duration) Specify how long a consistent view of the index should be maintained for scrolled search * ['body'] = (string) The scroll ID for scrolled search * * @param $params array Associative array of parameters * @return array * @static */ public static function clearScroll($params = array()){ return \Elasticsearch\Client::clearScroll($params); } /** * $params['id'] = (string) Document ID (Required) * ['index'] = (string) The name of the index (Required) * ['type'] = (string) The type of the document (Required) * ['consistency'] = (enum) Explicit write consistency setting for the operation * ['fields'] = (list) A comma-separated list of fields to return in the response * ['lang'] = (string) The script language (default: mvel) * ['parent'] = (string) ID of the parent document * ['percolate'] = (string) Perform percolation during the operation; use specific registered query name, attribute, or wildcard * ['refresh'] = (boolean) Refresh the index after performing the operation * ['replication'] = (enum) Specific replication type * ['retry_on_conflict'] = (number) Specify how many times should the operation be retried when a conflict occurs (default: 0) * ['routing'] = (string) Specific routing value * ['script'] = () The URL-encoded script definition (instead of using request body) * ['timeout'] = (time) Explicit operation timeout * ['timestamp'] = (time) Explicit timestamp for the document * ['ttl'] = (duration) Expiration time for the document * ['version_type'] = (number) Explicit version number for concurrency control * ['body'] = (array) The request definition using either `script` or partial `doc` * * @param $params array Associative array of parameters * @return array * @static */ public static function update($params){ return \Elasticsearch\Client::update($params); } /** * $params['id'] = (string) The script ID (Required) * ['lang'] = (string) The script language (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function getScript($params){ return \Elasticsearch\Client::getScript($params); } /** * $params['id'] = (string) The script ID (Required) * ['lang'] = (string) The script language (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function deleteScript($params){ return \Elasticsearch\Client::deleteScript($params); } /** * $params['id'] = (string) The script ID (Required) * ['lang'] = (string) The script language (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function putScript($params){ return \Elasticsearch\Client::putScript($params); } /** * $params['id'] = (string) The search template ID (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function getTemplate($params){ return \Elasticsearch\Client::getTemplate($params); } /** * $params['id'] = (string) The search template ID (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function deleteTemplate($params){ return \Elasticsearch\Client::deleteTemplate($params); } /** * $params['id'] = (string) The search template ID (Required) * * @param $params array Associative array of parameters * @return array * @static */ public static function putTemplate($params){ return \Elasticsearch\Client::putTemplate($params); } /** * Operate on the Indices Namespace of commands * * @return \Elasticsearch\IndicesNamespace * @static */ public static function indices(){ return \Elasticsearch\Client::indices(); } /** * Operate on the Cluster namespace of commands * * @return \Elasticsearch\ClusterNamespace * @static */ public static function cluster(){ return \Elasticsearch\Client::cluster(); } /** * Operate on the Nodes namespace of commands * * @return \Elasticsearch\NodesNamespace * @static */ public static function nodes(){ return \Elasticsearch\Client::nodes(); } /** * Operate on the Snapshot namespace of commands * * @return \Elasticsearch\SnapshotNamespace * @static */ public static function snapshot(){ return \Elasticsearch\Client::snapshot(); } /** * Operate on the Cat namespace of commands * * @return \Elasticsearch\CatNamespace * @static */ public static function cat(){ return \Elasticsearch\Client::cat(); } /** * * * @param array $params * @param string $arg * @return null|mixed * @static */ public static function extractArgument($params, $arg){ return \Elasticsearch\Client::extractArgument($params, $arg); } } class Salesforce extends \Davispeixoto\LaravelSalesforce\Facades\Salesforce{ /** * * * @static */ public static function create($sObjects, $type){ return \Davispeixoto\LaravelSalesforce\Salesforce::create($sObjects, $type); } /** * * * @static */ public static function update($sObjects, $type, $assignment_header = null, $mru_header = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::update($sObjects, $type, $assignment_header, $mru_header); } /** * * * @static */ public static function upsert($ext_Id, $sObjects, $type = 'Contact'){ return \Davispeixoto\LaravelSalesforce\Salesforce::upsert($ext_Id, $sObjects, $type); } /** * * * @static */ public static function merge($mergeRequest, $type){ return \Davispeixoto\LaravelSalesforce\Salesforce::merge($mergeRequest, $type); } /** * * * @static */ public static function getNamespace(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getNamespace(); } /** * * * @static */ public static function printDebugInfo(){ return \Davispeixoto\LaravelSalesforce\Salesforce::printDebugInfo(); } /** * * * @static */ public static function createConnection($wsdl, $proxy = null, $soap_options = array()){ return \Davispeixoto\LaravelSalesforce\Salesforce::createConnection($wsdl, $proxy, $soap_options); } /** * * * @static */ public static function setCallOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setCallOptions($header); } /** * * * @static */ public static function login($username, $password){ return \Davispeixoto\LaravelSalesforce\Salesforce::login($username, $password); } /** * * * @static */ public static function logout(){ return \Davispeixoto\LaravelSalesforce\Salesforce::logout(); } /** * * * @static */ public static function invalidateSessions(){ return \Davispeixoto\LaravelSalesforce\Salesforce::invalidateSessions(); } /** * * * @static */ public static function setEndpoint($location){ return \Davispeixoto\LaravelSalesforce\Salesforce::setEndpoint($location); } /** * * * @static */ public static function setAssignmentRuleHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setAssignmentRuleHeader($header); } /** * * * @static */ public static function setEmailHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setEmailHeader($header); } /** * * * @static */ public static function setLoginScopeHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setLoginScopeHeader($header); } /** * * * @static */ public static function setMruHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setMruHeader($header); } /** * * * @static */ public static function setSessionHeader($id){ return \Davispeixoto\LaravelSalesforce\Salesforce::setSessionHeader($id); } /** * * * @static */ public static function setUserTerritoryDeleteHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setUserTerritoryDeleteHeader($header); } /** * * * @static */ public static function setQueryOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setQueryOptions($header); } /** * * * @static */ public static function setAllowFieldTruncationHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setAllowFieldTruncationHeader($header); } /** * * * @static */ public static function setLocaleOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setLocaleOptions($header); } /** * * * @static */ public static function setPackageVersionHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setPackageVersionHeader($header); } /** * * * @static */ public static function getSessionId(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getSessionId(); } /** * * * @static */ public static function getLocation(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLocation(); } /** * * * @static */ public static function getConnection(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getConnection(); } /** * * * @static */ public static function getFunctions(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getFunctions(); } /** * * * @static */ public static function getTypes(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getTypes(); } /** * * * @static */ public static function getLastRequest(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastRequest(); } /** * * * @static */ public static function getLastRequestHeaders(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastRequestHeaders(); } /** * * * @static */ public static function getLastResponse(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastResponse(); } /** * * * @static */ public static function getLastResponseHeaders(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastResponseHeaders(); } /** * * * @static */ public static function sendSingleEmail($request){ return \Davispeixoto\LaravelSalesforce\Salesforce::sendSingleEmail($request); } /** * * * @static */ public static function sendMassEmail($request){ return \Davispeixoto\LaravelSalesforce\Salesforce::sendMassEmail($request); } /** * * * @static */ public static function convertLead($leadConverts){ return \Davispeixoto\LaravelSalesforce\Salesforce::convertLead($leadConverts); } /** * * * @static */ public static function delete($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::delete($ids); } /** * * * @static */ public static function undelete($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::undelete($ids); } /** * * * @static */ public static function emptyRecycleBin($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::emptyRecycleBin($ids); } /** * * * @static */ public static function processSubmitRequest($processRequestArray){ return \Davispeixoto\LaravelSalesforce\Salesforce::processSubmitRequest($processRequestArray); } /** * * * @static */ public static function processWorkitemRequest($processRequestArray){ return \Davispeixoto\LaravelSalesforce\Salesforce::processWorkitemRequest($processRequestArray); } /** * * * @static */ public static function describeGlobal(){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeGlobal(); } /** * * * @static */ public static function describeLayout($type, $recordTypeIds = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeLayout($type, $recordTypeIds); } /** * * * @static */ public static function describeSObject($type){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeSObject($type); } /** * * * @static */ public static function describeSObjects($arrayOfTypes){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeSObjects($arrayOfTypes); } /** * * * @static */ public static function describeTabs(){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeTabs(); } /** * * * @static */ public static function describeDataCategoryGroups($sObjectType){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeDataCategoryGroups($sObjectType); } /** * * * @static */ public static function describeDataCategoryGroupStructures($pairs, $topCategoriesOnly){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeDataCategoryGroupStructures($pairs, $topCategoriesOnly); } /** * * * @static */ public static function getDeleted($type, $startDate, $endDate){ return \Davispeixoto\LaravelSalesforce\Salesforce::getDeleted($type, $startDate, $endDate); } /** * * * @static */ public static function getUpdated($type, $startDate, $endDate){ return \Davispeixoto\LaravelSalesforce\Salesforce::getUpdated($type, $startDate, $endDate); } /** * * * @static */ public static function query($query){ return \Davispeixoto\LaravelSalesforce\Salesforce::query($query); } /** * * * @static */ public static function queryMore($queryLocator){ return \Davispeixoto\LaravelSalesforce\Salesforce::queryMore($queryLocator); } /** * * * @static */ public static function queryAll($query, $queryOptions = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::queryAll($query, $queryOptions); } /** * * * @static */ public static function retrieve($fieldList, $sObjectType, $ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::retrieve($fieldList, $sObjectType, $ids); } /** * * * @static */ public static function search($searchString){ return \Davispeixoto\LaravelSalesforce\Salesforce::search($searchString); } /** * * * @static */ public static function getServerTimestamp(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getServerTimestamp(); } /** * * * @static */ public static function getUserInfo(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getUserInfo(); } /** * * * @static */ public static function setPassword($userId, $password){ return \Davispeixoto\LaravelSalesforce\Salesforce::setPassword($userId, $password); } /** * * * @static */ public static function resetPassword($userId){ return \Davispeixoto\LaravelSalesforce\Salesforce::resetPassword($userId); } /** * * * @static */ public static function dump(){ return \Davispeixoto\LaravelSalesforce\Salesforce::dump(); } } class SF extends \Davispeixoto\LaravelSalesforce\Facades\Salesforce{ /** * * * @static */ public static function create($sObjects, $type){ return \Davispeixoto\LaravelSalesforce\Salesforce::create($sObjects, $type); } /** * * * @static */ public static function update($sObjects, $type, $assignment_header = null, $mru_header = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::update($sObjects, $type, $assignment_header, $mru_header); } /** * * * @static */ public static function upsert($ext_Id, $sObjects, $type = 'Contact'){ return \Davispeixoto\LaravelSalesforce\Salesforce::upsert($ext_Id, $sObjects, $type); } /** * * * @static */ public static function merge($mergeRequest, $type){ return \Davispeixoto\LaravelSalesforce\Salesforce::merge($mergeRequest, $type); } /** * * * @static */ public static function getNamespace(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getNamespace(); } /** * * * @static */ public static function printDebugInfo(){ return \Davispeixoto\LaravelSalesforce\Salesforce::printDebugInfo(); } /** * * * @static */ public static function createConnection($wsdl, $proxy = null, $soap_options = array()){ return \Davispeixoto\LaravelSalesforce\Salesforce::createConnection($wsdl, $proxy, $soap_options); } /** * * * @static */ public static function setCallOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setCallOptions($header); } /** * * * @static */ public static function login($username, $password){ return \Davispeixoto\LaravelSalesforce\Salesforce::login($username, $password); } /** * * * @static */ public static function logout(){ return \Davispeixoto\LaravelSalesforce\Salesforce::logout(); } /** * * * @static */ public static function invalidateSessions(){ return \Davispeixoto\LaravelSalesforce\Salesforce::invalidateSessions(); } /** * * * @static */ public static function setEndpoint($location){ return \Davispeixoto\LaravelSalesforce\Salesforce::setEndpoint($location); } /** * * * @static */ public static function setAssignmentRuleHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setAssignmentRuleHeader($header); } /** * * * @static */ public static function setEmailHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setEmailHeader($header); } /** * * * @static */ public static function setLoginScopeHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setLoginScopeHeader($header); } /** * * * @static */ public static function setMruHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setMruHeader($header); } /** * * * @static */ public static function setSessionHeader($id){ return \Davispeixoto\LaravelSalesforce\Salesforce::setSessionHeader($id); } /** * * * @static */ public static function setUserTerritoryDeleteHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setUserTerritoryDeleteHeader($header); } /** * * * @static */ public static function setQueryOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setQueryOptions($header); } /** * * * @static */ public static function setAllowFieldTruncationHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setAllowFieldTruncationHeader($header); } /** * * * @static */ public static function setLocaleOptions($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setLocaleOptions($header); } /** * * * @static */ public static function setPackageVersionHeader($header){ return \Davispeixoto\LaravelSalesforce\Salesforce::setPackageVersionHeader($header); } /** * * * @static */ public static function getSessionId(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getSessionId(); } /** * * * @static */ public static function getLocation(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLocation(); } /** * * * @static */ public static function getConnection(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getConnection(); } /** * * * @static */ public static function getFunctions(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getFunctions(); } /** * * * @static */ public static function getTypes(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getTypes(); } /** * * * @static */ public static function getLastRequest(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastRequest(); } /** * * * @static */ public static function getLastRequestHeaders(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastRequestHeaders(); } /** * * * @static */ public static function getLastResponse(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastResponse(); } /** * * * @static */ public static function getLastResponseHeaders(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getLastResponseHeaders(); } /** * * * @static */ public static function sendSingleEmail($request){ return \Davispeixoto\LaravelSalesforce\Salesforce::sendSingleEmail($request); } /** * * * @static */ public static function sendMassEmail($request){ return \Davispeixoto\LaravelSalesforce\Salesforce::sendMassEmail($request); } /** * * * @static */ public static function convertLead($leadConverts){ return \Davispeixoto\LaravelSalesforce\Salesforce::convertLead($leadConverts); } /** * * * @static */ public static function delete($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::delete($ids); } /** * * * @static */ public static function undelete($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::undelete($ids); } /** * * * @static */ public static function emptyRecycleBin($ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::emptyRecycleBin($ids); } /** * * * @static */ public static function processSubmitRequest($processRequestArray){ return \Davispeixoto\LaravelSalesforce\Salesforce::processSubmitRequest($processRequestArray); } /** * * * @static */ public static function processWorkitemRequest($processRequestArray){ return \Davispeixoto\LaravelSalesforce\Salesforce::processWorkitemRequest($processRequestArray); } /** * * * @static */ public static function describeGlobal(){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeGlobal(); } /** * * * @static */ public static function describeLayout($type, $recordTypeIds = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeLayout($type, $recordTypeIds); } /** * * * @static */ public static function describeSObject($type){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeSObject($type); } /** * * * @static */ public static function describeSObjects($arrayOfTypes){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeSObjects($arrayOfTypes); } /** * * * @static */ public static function describeTabs(){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeTabs(); } /** * * * @static */ public static function describeDataCategoryGroups($sObjectType){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeDataCategoryGroups($sObjectType); } /** * * * @static */ public static function describeDataCategoryGroupStructures($pairs, $topCategoriesOnly){ return \Davispeixoto\LaravelSalesforce\Salesforce::describeDataCategoryGroupStructures($pairs, $topCategoriesOnly); } /** * * * @static */ public static function getDeleted($type, $startDate, $endDate){ return \Davispeixoto\LaravelSalesforce\Salesforce::getDeleted($type, $startDate, $endDate); } /** * * * @static */ public static function getUpdated($type, $startDate, $endDate){ return \Davispeixoto\LaravelSalesforce\Salesforce::getUpdated($type, $startDate, $endDate); } /** * * * @static */ public static function query($query){ return \Davispeixoto\LaravelSalesforce\Salesforce::query($query); } /** * * * @static */ public static function queryMore($queryLocator){ return \Davispeixoto\LaravelSalesforce\Salesforce::queryMore($queryLocator); } /** * * * @static */ public static function queryAll($query, $queryOptions = null){ return \Davispeixoto\LaravelSalesforce\Salesforce::queryAll($query, $queryOptions); } /** * * * @static */ public static function retrieve($fieldList, $sObjectType, $ids){ return \Davispeixoto\LaravelSalesforce\Salesforce::retrieve($fieldList, $sObjectType, $ids); } /** * * * @static */ public static function search($searchString){ return \Davispeixoto\LaravelSalesforce\Salesforce::search($searchString); } /** * * * @static */ public static function getServerTimestamp(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getServerTimestamp(); } /** * * * @static */ public static function getUserInfo(){ return \Davispeixoto\LaravelSalesforce\Salesforce::getUserInfo(); } /** * * * @static */ public static function setPassword($userId, $password){ return \Davispeixoto\LaravelSalesforce\Salesforce::setPassword($userId, $password); } /** * * * @static */ public static function resetPassword($userId){ return \Davispeixoto\LaravelSalesforce\Salesforce::resetPassword($userId); } /** * * * @static */ public static function dump(){ return \Davispeixoto\LaravelSalesforce\Salesforce::dump(); } } class Cron extends \Liebig\Cron\Facades\Cron{ /** * Add a cron job * * Expression definition: * * * * * * * * * - - - - - - * | | | | | | * | | | | | + year [optional] * | | | | +----- day of week (0 - 7) (Sunday=0 or 7) * | | | +---------- month (1 - 12) * | | +--------------- day of month (1 - 31) * | +-------------------- hour (0 - 23) * +------------------------- min (0 - 59) * * @static * @param string $name The name for the cron job - has to be unique * @param string $expression The cron job expression (e.g. for every minute: '* * * * *') * @param callable $function The anonymous function which will be executed * @param bool $isEnabled optional If the cron job should be enabled or disabled - the standard configuration is enabled * @throws \InvalidArgumentException if one of the parameters has the wrong data type, is incorrect or is not set * @static */ public static function add($name, $expression, $function, $isEnabled = true){ return \Liebig\Cron\Cron::add($name, $expression, $function, $isEnabled); } /** * Remove a cron job by name * * @static * @param string $name The name of the cron job which should be removed from execution * @return bool Return true if a cron job with the given name was found and was successfully removed or return false if no job with the given name was found * @static */ public static function remove($name){ return \Liebig\Cron\Cron::remove($name); } /** * Run the cron jobs * This method checks and runs all the defined cron jobs at the right time * This method (route) should be called automatically by a server or service * * @static * @param bool $checkRundateOnce optional When we check if a cronjob is due do we take into account the time when the run function was called ($checkRundateOnce = true) or do we take into account the time when each individual cronjob is executed ($checkRundateOnce = false) - default value is true * @return array Return an array with the rundate, runtime, errors and a result cron job array (with name, function return value, runtime in seconds) * @static */ public static function run($checkRundateOnce = true){ return \Liebig\Cron\Cron::run($checkRundateOnce); } /** * Add a custom Monolog logger object * * @static * @param \Monolog\Logger $logger optional The Monolog logger object which will be used for cron logging, if this parameter is null the logger will be removed - default value is null * @static */ public static function setLogger($logger = null){ return \Liebig\Cron\Cron::setLogger($logger); } /** * Get the Monolog logger object * * @static * @return \Monolog\Logger|null Return the set logger object or null if no logger is set * @static */ public static function getLogger(){ return \Liebig\Cron\Cron::getLogger(); } /** * Enable or disable Laravels build in logging * * @static * @param bool $bool Set to enable or disable Laravels logging * @throws \InvalidArgumentException if the $bool function paramter is not a boolean * @static */ public static function setLaravelLogging($bool){ return \Liebig\Cron\Cron::setLaravelLogging($bool); } /** * Is Laravels build in logging enabled or disabled * * @static * @return bool Return boolean which indicates if Laravels logging is enabled or disabled * @throws \UnexpectedValueException if the cron::laravelLogging config value is not a boolean or NULL * @static */ public static function isLaravelLogging(){ return \Liebig\Cron\Cron::isLaravelLogging(); } /** * Enable or disable database logging * * @static * @param bool $bool Set to enable or disable database logging * @throws \InvalidArgumentException if the $bool function paramter is not a boolean * @static */ public static function setDatabaseLogging($bool){ return \Liebig\Cron\Cron::setDatabaseLogging($bool); } /** * Is logging to database enabled or disabled * * @static * @return boolean Return boolean which indicates if database logging is enabled or disabled * @throws \UnexpectedValueException if the cron::databaseLogging config value is not a boolean * @static */ public static function isDatabaseLogging(){ return \Liebig\Cron\Cron::isDatabaseLogging(); } /** * Enable or disable logging error jobs only to database * NOTE: This works only if database logging is enabled * * @static * @param bool $bool Set to enable or disable logging error jobs only * @throws \InvalidArgumentException if the $bool function paramter is not a boolean * @static */ public static function setLogOnlyErrorJobsToDatabase($bool){ return \Liebig\Cron\Cron::setLogOnlyErrorJobsToDatabase($bool); } /** * Check if log error jobs to database only is enabled or disabled * * @return bool Return boolean which indicates if logging only error jobs to database is enabled or disabled * @throws \UnexpectedValueException if the cron::logOnlyErrorJobsToDatabase config value is not a boolean * @static */ public static function isLogOnlyErrorJobsToDatabase(){ return \Liebig\Cron\Cron::isLogOnlyErrorJobsToDatabase(); } /** * Reset the Cron class * Remove the cron jobs array and the logger object * * @static * @static */ public static function reset(){ return \Liebig\Cron\Cron::reset(); } /** * Set the run interval - the run interval is the time between two cron job route calls * * @static * @param int $minutes Set the interval in minutes * @throws \InvalidArgumentException if the $minutes function paramter is not an integer * @static */ public static function setRunInterval($minutes){ return \Liebig\Cron\Cron::setRunInterval($minutes); } /** * Get the current run interval value * * @return int|null Return the current interval value in minutes or NULL if there is no value set * @throws \UnexpectedValueException if the cron::runInterval config value is not an integer or NULL * @static */ public static function getRunInterval(){ return \Liebig\Cron\Cron::getRunInterval(); } /** * Set the delete time of old database entries in hours * * @static * @param int $hours optional Set the delete time in hours, if this value is 0 the delete old database entries function will be disabled - default value is 0 * @throws \InvalidArgumentException if the $hours function paramter is not an integer * @static */ public static function setDeleteDatabaseEntriesAfter($hours = 0){ return \Liebig\Cron\Cron::setDeleteDatabaseEntriesAfter($hours); } /** * Get the current delete time value in hours for old database entries * * @return int|null Return the current delete time value in hours or NULL if no value was set * @throws \UnexpectedValueException if the cron::deleteDatabaseEntriesAfter config value is not an integer or NULL * @static */ public static function getDeleteDatabaseEntriesAfter(){ return \Liebig\Cron\Cron::getDeleteDatabaseEntriesAfter(); } /** * Enable a job by job name * * @static * @param string $jobname The name of the job which should be enabled * @param bool $enable The trigger for enable (true) or disable (false) the job with the given name * @return bool Return true if job was enabled successfully or false if no job with the $jobname parameter was found * @throws \InvalidArgumentException if the $enable function paramter is not a boolean * @static */ public static function setEnableJob($jobname, $enable = true){ return \Liebig\Cron\Cron::setEnableJob($jobname, $enable); } /** * Disable a job by job name * * @static * @param String $jobname The name of the job which should be disabled * @return bool Return true if job was disabled successfully or false if no job with the $jobname parameter was found * @static */ public static function setDisableJob($jobname){ return \Liebig\Cron\Cron::setDisableJob($jobname); } /** * Is the given job by name enabled or disabled * * @static * @param String $jobname The name of the job which should be checked * @return bool|null Return boolean if job is enabled (true) or disabled (false) or null if no job with the given name is found * @static */ public static function isJobEnabled($jobname){ return \Liebig\Cron\Cron::isJobEnabled($jobname); } /** * Enable prevent job overlapping * * @static * @static */ public static function setEnablePreventOverlapping(){ return \Liebig\Cron\Cron::setEnablePreventOverlapping(); } /** * Disable prevent job overlapping * * @static * @static */ public static function setDisablePreventOverlapping(){ return \Liebig\Cron\Cron::setDisablePreventOverlapping(); } /** * Is prevent job overlapping enabled or disabled * * @static * @return bool Return boolean if prevent job overlapping is enabled (true) or disabled (false) * @static */ public static function isPreventOverlapping(){ return \Liebig\Cron\Cron::isPreventOverlapping(); } /** * Enable the Cron run in time check * * @static * @static */ public static function setEnableInTimeCheck(){ return \Liebig\Cron\Cron::setEnableInTimeCheck(); } /** * Disable the Cron run in time check * * @static * @static */ public static function setDisableInTimeCheck(){ return \Liebig\Cron\Cron::setDisableInTimeCheck(); } /** * Is the Cron run in time check enabled or disabled * * @static * @return bool Return boolean if the Cron run in time check is enabled (true) or disabled (false) * @static */ public static function isInTimeCheck(){ return \Liebig\Cron\Cron::isInTimeCheck(); } /** * Get added Cron jobs as array * * @static * @return array Return array of the added Cron jobs * @static */ public static function getCronJobs(){ return \Liebig\Cron\Cron::getCronJobs(); } } } <file_sep>/app/events/User.php <?php namespace events; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Events\Dispatcher; use Illuminate\Routing\UrlGenerator; /** * Class User * @package events */ class User { /** * @var Repository */ protected $config; /** * @var Writer */ protected $log; /** * @var Dispatcher */ protected $event; /** * @var Activity */ protected $activity; /** * @var Indexer */ protected $indexer; /** * @var Mail */ protected $mail; /** * @var Tracking */ protected $track; /** * @var UrlGenerator */ private $url; /** * @param Activity $activity * @param Indexer $indexer * @param Mail $mail * @param Writer $log * @param Repository $config * @param Dispatcher $event * @param Tracking $track * @param UrlGenerator $url */ public function __construct( Activity $activity, Indexer $indexer, Mail $mail, Writer $log, Repository $config, Dispatcher $event, Tracking $track, UrlGenerator $url ) { $this->config = $config; $this->log = $log; $this->event = $event; $this->track = $track; $this->activity = $activity; $this->indexer = $indexer; $this->mail = $mail; $this->url = $url; } /** * @param $user */ public function login($user) { $this->log->info('User ' . $user->id . ' has Logged In'); $this->track->userLogin($user); } /** * @param $user */ public function facebookLogin($user) { $this->log->info('User ' . $user->id . ' has Logged In with Facebook'); $this->track->userFacebookLogin($user); } /** * @param $user */ public function logout($user) { $this->log->info('User ' . $user->id . ' has Logged Out'); $this->track->userLogout($user); } /** * @param $user */ public function edit($user) { $this->log->info('User ' . $user->id . ' has edited his account'); $this->track->userEdit($user); } /** * @param $user */ public function hasRegistered($user) { $this->log->info('User ' . $user->id . ' has registered'); $this->track->userRegistered($user); } /** * @param $user */ public function facebookRegistered($user) { $this->log->info('User ' . $user->id . ' has registered with Facebook'); $this->track->userFacebookRegistered($user); } /** * @param $user * @param $cart * @param $transaction */ public function cartCompleted($user, $cart, $transaction) { $this->log->info('User ' . $user->id . ' cart completed'); $this->mail->userCartCompleted($user, $cart, $transaction); $this->activity->userCartCompleted($user, $cart, $transaction); } /** * @param $user * @param $transaction */ public function topupCompleted($user, $transaction, $balance) { $this->log->info('User ' . $user->id . ' topup completed'); $this->mail->topupCompleted($user, $transaction, $balance); $this->activity->userTopupCompleted($user, $transaction, 'topupcompleted'); } /** * @param $user * @param $transaction */ public function referralCompleted($user, $amount, $type) { $this->log->info('User ' . $user->id . ' referral completed'); $this->activity->userReferralCompleted($user, $amount, $type); } /** * @param $user * @param $transaction */ public function referralSignup($user, $amount, $type) { $this->log->info('User ' . $user->id . ' signup through referral'); $this->activity->userReferralSignup($user, $amount, $type); } /** * @param $user * @param $transaction * @param $type * @param $description */ public function ppcSignup($user, $amount, $type, $description = 0) { $this->log->info('User ' . $user->id . ' signup through '.$type.' ppc code'); $this->activity->ppcSignup($user, $amount, $type, $description); } /** * @param $user * @param $transaction */ public function withdrawCompleted($user, $transaction, $balance) { $this->log->info('User ' . $user->id . ' topup completed'); $this->mail->withdrawCompleted($user, $transaction, $balance); $this->activity->userWithdrawCompleted($user, $transaction); } /** * @param $user */ public function connectedFacebook($user) { $this->log->info('User ' . $user->id . ' Connected his facebook account'); $this->activity->linkFacebook($user); } /** * @param $user */ public function connectedTwitter($user) { $this->log->info('User ' . $user->id . ' Connected his twitter account'); $this->activity->linkTwitter($user); } /** MOVED FROM UserMailer */ public function welcome($user) { $this->log->info('Sending welcome email to ' . $user->id); $this->mail->welcome($user); $this->activity->userRegistered($user); } /** * @param $user */ public function welcomeGuest($user) { $this->log->info('Sending welcome email with reset password to ' . $user->id); /** @var Forgotten Password Code Generate $resetCode */ $resetCode = $user->getResetPasswordCode(); $link = $this->url->to('users/' . $user->display_name . '/resetpassword/' . urlencode($resetCode)); $this->mail->welcomeGuest($user, $link); } /** * @param $user */ public function facebookWelcome($user) { $this->log->info('Sending welcome email to FB ' . $user->id); /** @var Forgotten Password Code Generate $resetCode */ $resetCode = $user->getResetPasswordCode(); $link = $this->url->to('users/' . $user->display_name . '/resetpassword/' . urlencode($resetCode)); $this->mail->welcomeFacebook($user, $link); } /** * @param $user */ public function forgotPassword($user) { $this->log->info('Sending forgoten password ' . $user->id); /** @var Forgotten Password Code Generate $resetCode */ $resetCode = urlencode($user->getResetPasswordCode()); //$link = $this->url->to('users/' . $user->display_name . '/resetpassword/' . $resetCode); $this->mail->userForgotPassword($user, $resetCode); } /** * @param $user */ public function userChangedPassword($user) { $this->log->info('User changed password ' . $user->id); $this->mail->userChangedPassword($user); $this->track->userChangedPassword($user); } /** * @param $user */ public function userUpgrade($user) { $this->log->info('User upgraded to Trainer ' . $user->id); $this->mail->userUpgrade($user); } /** * @param $email * @param $referralCode * @param $referrerName */ public function invite($email, $referralCode, $referrerName, $referrerEmail, $balanceWithBonus) { $this->log->info('User Invite ' . $email); $this->mail->invite($email, $referralCode, $referrerName); $this->mail->thanksForInviting($referrerEmail, $referrerName, $email, $balanceWithBonus); } /** * @param $email * @param $categoryId * @param $ppcCode */ public function ppc($email, $categoryId, $ppcCode) { $this->log->info('PPC ' . $email); $this->mail->ppc($email, $categoryId, $ppcCode); } public function userLanding($email, $categoryId, $ppcCode, $location) { $this->log->info('landing user ' . $email); $this->mail->userLanding($email, $categoryId, $ppcCode, $location); } public function generateStaticLandingEmail($ppcCode, $categoryId) { $this->log->info('static landing email generated ' . $ppcCode); $this->mail->generateStaticLandingEmail($ppcCode, $categoryId); } public function newYear($user) { $this->log->info('new year message sent ' . $user->id); $this->mail->newYear($user); } public function notReturned($user, $everciseGroups) { $this->log->info('why not returned message sent ' . $user->id); $this->mail->notReturned($user, $everciseGroups); } public function whyNotRefer($user) { $this->log->info('why not refer a friend sent ' . $user->id); $this->mail->whyNotRefer($user); } public function rateClass($user) { $this->log->info('hey rate this class email sent ' . $user->id); $this->mail->rateClass($user); } public function rateClassHasPackage($user) { $this->log->info('hey rate this class email NOT SENT AS USER HAS PACKAGES ' . $user->id); $this->mail->rateClassHasPackage($user); } public function messageReply($sender, $recipient, $body) { $this->log->info('Message sent by ' . $sender->id . ' to ' . $recipient->id); $this->mail->messageReply($sender, $recipient, $body); /** NOT SENDING!!?? */ } } <file_sep>/app/lang/en/the_team.php <?php return [ [ 'name' => '<NAME>', 'title' => 'Managing Director', 'image' => '/img/Fan.jpg', 'food' => 'Mooncake', 'hobby' => 'Basketball, Billiards', 'quote' => 'Why not Evercise?', ], [ 'name' => '<NAME>', 'title' => 'CTO', 'image' => '/img/Jie-Sun.jpg', 'food' => 'Dumplings', 'hobby' => 'Football, Climbing', 'quote' => 'Proficient, Professional, Perfect', ], [ 'name' => '<NAME>', 'title' => 'Development Manager', 'image' => '/img/lewis.jpg', 'food' => 'Steak and ale pie (from shefield)', 'hobby' => 'Motorbiking & playing bass guitar', 'quote' => 'Smoke me a kipper, I&apos;ll be back for breakfast', ], [ 'name' => '<NAME>', 'title' => 'Marketing and Sales Specialist', 'image' => '/img/nas.jpg', 'food' => 'Spaghetti Bolognese. Can&apos;t beat a bit of Spag Bol!', 'hobby' => 'Road trips & playing the violin', 'quote' => 'There is no such thing as a hopeless situation. Every single circumstance of your life can change!', ], [ 'name' => '<NAME>', 'title' => 'Marketing Specialist', 'image' => '/img/tanais.jpg', 'food' => 'Fruits :)', 'hobby' => 'Singing with Lewis Bayfield', 'quote' => 'Positive mind, positive life', ], [ 'name' => '<NAME>', 'title' => 'Developer', 'image' => '/img/tristan.jpg', 'food' => 'Steak', 'hobby' => 'Climbing and mountain biking', 'quote' => 'I caught you a delicious bass', ], ];<file_sep>/app/events/Mail.php <?php namespace events; use App; use Cartalyst\Sentry\Sentry; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Events\Dispatcher; use Illuminate\Mail\Mailer; use Illuminate\View\Factory as View; use Illuminate\Routing\UrlGenerator; use Exception; use EmailOut; use Evercisegroup; use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; /** * Class Mail * @package events */ class Mail { /** * @var Mailer */ private $email; /** * @var Writer */ private $log; /** * @var Repository */ private $config; /** * @var Dispatcher */ private $event; /** * @var array */ private $data; /** * @var View */ private $view; /** * @param Writer $log * @param Repository $config * @param Dispatcher $event * @param Mailer $email * @param View $view */ public function __construct( Writer $log, Repository $config, Dispatcher $event, Mailer $email, View $view, UrlGenerator $url ) { $this->log = $log; $this->config = $config; $this->event = $event; $this->email = $email; $this->view = $view; $this->url = $url; $this->banner_types = [ 'upsell_signup' => [ 'image' => $this->url->to('assets/img/email/user_upsell_signup_today.png'), 'url' => $this->url->to('/'), 'title' => 'Sign Up Today and Receive £5' ], 'welcome' => [ 'image' => $this->url->to('assets/img/email/user_upsell_signup_today.png'), 'url' => $this->url->to('/'), 'title' => 'Sign Up Today and Receive £5' ], 'refer_someone' => [ 'image' => $this->url->to('assets/img/email/referal_banner_blue.png'), 'url' => $this->url->to('/uk/london'), 'title' => 'refer someone Today and Receive £5' ], 'packages' => [ 'image' => $this->url->to('assets/img/email/user_upsell_package.png'), 'url' => $this->url->to('/packages'), 'title' => 'save money by purchasing a 5 or 10 class package' ] ]; if (file_exists('./public/assets/css/mail.css')) { $cssFile = file_get_contents('./public/assets/css/mail.css'); } else { $cssFile = file_get_contents('http://evercise.com/assets/css/mail.css'); } $this->data = [ 'config' => $this->config->get('evercise'), 'subject' => 'Evercise', 'title' => FALSE, 'view' => 'v3.emails.default', 'attachments' => [], 'unsubscribe' => '%%unsubscribe%%', 'link_url' => $this->url->to('/'), 'image' => image('assets/img/email/user_default.jpg', 'Evercise'), 'banner' => FALSE, 'banner_types' => $this->banner_types, 'style' => 'pink', 'css' => $cssFile ]; } /* * ######################################################################################## * ##### USER EMAIL's ################################################# * ######################################################################################## */ /** * @param $user * @param $cart * @param $transaction * * Event user.cart.completed */ public function userCartCompleted($user, $cart, $transaction) { $params = [ 'subject' => 'Confirmation of booking', 'user' => $user, 'cart' => $cart, 'transaction' => $transaction, 'banner' => NULL, 'image' => image('/assets/img/email/user_booking_confirmation.jpg', 'booking confirmation'), 'link_url' => $this->url->to('/uk/london') ]; $params['search'] = App::make('SearchController'); if ($cart['packages']) { /** Pick 3 classes which are priced appropriately for the package purchased. NEEDS WORK!!! */ $upperPrice = round($cart['packages'][0]['max_class_price'], 2) + 0.01; $searchController = App::make('SearchController'); $everciseGroups = $searchController->getClasses([ 'sort' => 'price_desc', 'price' => ['under' => round($upperPrice, 2), 'over' => round(($upperPrice - 10))], 'size' => '3' ]); $params['everciseGroups'] = $everciseGroups->hits; if ($cart['sessions']) { $params['view'] = 'v3.emails.user.cart_completed_both'; } else { $params['view'] = 'v3.emails.user.cart_completed_package'; } } else { $params['view'] = 'v3.emails.user.cart_completed_class'; } $this->send($user->email, $params); } /** * @param $user * @param $transaction * @param $balance * * Event user.topup.completed */ public function topupCompleted($user, $transaction, $balance) { $params = [ 'subject' => 'Funds have been added to your wallet', 'view' => 'v3.emails.user.topup_completed', 'user' => $user, 'transaction' => $transaction, 'balance' => $balance, 'banner' => NULL, 'image' => image('/assets/img/email/user_default.jpg', 'Topup Confirmation'), 'link_url' => $this->url->to('/uk/london') ]; $this->send($user->email, $params); } /** * @param $user * @param $transaction * @param $balance * * Event user.topup.completed */ public function withdrawCompleted($user, $transaction, $balance) { $params = [ 'subject' => 'Confirmation of Withdrawal', 'view' => 'v3.emails.user.withdraw_completed', 'user' => $user, 'transaction' => $transaction, 'balance' => $balance, 'banner' => NULL, 'image' => image('/assets/img/email/user_default.jpg', 'topup confirmation'), 'link_url' => $this->url->to('/uk/london') ]; $this->send($user->email, $params); } /** * @param $user */ public function welcome($user) { $params = [ 'subject' => 'Welcome to Evercise', 'title' => 'Welcome to Evercise!', 'view' => 'v3.emails.user.welcome', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/uk/london') ]; $this->send($user->email, $params); } /** * @param $user * @param string $link */ public function welcomeGuest($user, $link = '') { $params = [ 'subject' => 'Welcome to Evercise', 'title' => 'Welcome to Evercise!', 'view' => 'v3.emails.user.welcome_guest', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/uk/'), 'link' => $link ]; $this->send($user->email, $params); } /** * @param $user * @param string $link */ public function welcomeFacebook($user, $link = '') { $params = [ 'subject' => 'Welcome to Evercise', 'title' => 'Welcome to Evercise!', 'view' => 'v3.emails.user.welcome_facebook', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/uk/'), 'link' => $link ]; $this->send($user->email, $params); } /** * @param $user * @param string $resetCode */ public function userForgotPassword($user, $resetCode = '') { $params = [ 'subject' => 'Reset Password', 'title' => 'Evercise password reset', 'view' => 'v3.emails.user.forgot_password', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/user_default.jpg', 'reset your password'), 'resetCode' => $resetCode ]; $this->send($user->email, $params); } /** * @param $user */ public function userChangedPassword($user) { $params = [ 'subject' => 'Evercise password reset confirmation', 'view' => 'v3.emails.user.changed_password', 'user' => $user ]; $this->send($user->email, $params); } /** * @param $user */ public function userUpgrade($user) { $params = [ 'subject' => 'Welcome! Start selling classes on Evercise.', 'view' => 'v3.emails.user.upgrade', 'user' => $user ]; $this->send($user->email, $params); } /** * @param $userList * @param $group * @param $location * @param $dateTime * @param $trainerName * @param $trainerEmail * @param $classId * * Event session.upcoming_session * Single event fires emails to all users and the trainer involved in the session. */ public function usersSessionRemind( $userList, $group, $location, $dateTime, $trainerName, $trainerEmail, $classId, $sessionId ) { foreach ($userList as $name => $details) { $email = $details['email']; $transaction = \Transactions::find($details['transactionId']); $bookingCodes = $transaction->makeBookingHashBySession($sessionId); $params = [ 'subject' => 'Evercise class reminder', 'view' => 'v3.emails.user.session_remind', 'userList' => $userList, 'group' => $group, 'location' => $location, 'name' => $name, 'email' => $email, 'dateTime' => $dateTime, 'trainerName' => $trainerName, 'trainerEmail' => $trainerEmail, 'classId' => $classId, 'style' => 'blue', 'transactionId' => $details['transactionId'], 'bookingCodes' => $bookingCodes, 'image' => image('/assets/img/email/user_class_reminder.jpg', 'reminder of upcoming class'), 'link_url' => $this->url->to('/profile/' . $group->slug) ]; $this->send($email, $params); } } /** * @param $user * @param $trainer * @param $everciseGroup * @param $sessionDate */ public function userLeaveSession($user, $trainer, $everciseGroup, $sessionDate) { $params = [ 'subject' => 'Sorry to see you leave', 'view' => 'v3.emails.user.session_left', 'user' => $user, 'trainer' => $trainer, 'everciseGroup' => $everciseGroup, 'sessionDate' => $sessionDate, ]; $this->send($user->email, $params); } /** * @param $email * @param $referralCode * @param $referrerName */ public function invite($email, $referralCode, $referrerName) { $params = [ 'subject' => 'Join your friends on Evercise', 'view' => 'v3.emails.user.invite', 'email' => $email, 'referralCode' => $referralCode, 'referrerName' => $referrerName, 'image' => image('/assets/img/email/welcome_from_referral.png', 'Join your friends on Evercise'), 'link_url' => $this->url->to('/refer_a_friend/' . $referralCode), 'banner' => [ 'image' => $this->url->to('assets/img/email/user_upsell_signup_today.png'), 'url' => $this->url->to('/refer_a_friend/' . $referralCode), 'title' => 'SignUp Today and Receive £5' ], ]; $this->send($email, $params); } /** * @param $email * @param $referralCode * @param $referrerName */ public function thanksForInviting($email, $referrerName, $referreeEmail, $balanceWithBonus) { $params = [ 'subject' => 'Thanks for sharing!', 'title' => 'Thanks for sharing!', 'view' => 'v3.emails.user.thanks_inviting', 'email' => $email, 'refereeEmail' => $referreeEmail, 'referrerName' => $referrerName, 'balanceWithBonus' => $balanceWithBonus, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'Thanks for sharing!'), 'link_url' => $this->url->to('/uk/'), 'banner' => FALSE ]; $this->send($email, $params); } /** * @param $email * @param $categoryId * @param $ppcCode */ public function ppc($email, $categoryId, $ppcCode) { $params = [ 'subject' => 'Pay as you go fitness!', 'view' => 'v3.emails.user.ppc', 'email' => $email, 'categoryId' => $categoryId, 'ppcCode' => $ppcCode ]; $this->send($email, $params); } public function userLanding($email, $categoryId, $ppcCode, $location) { $params = [ 'subject' => 'GET ACTIVE, GET SOCIAL, GET FIT', 'title' => 'GET ACTIVE, GET SOCIAL, GET FIT!', 'view' => 'v3.emails.user.landing_email', 'email' => $email, 'categoryId' => $categoryId, 'ppcCode' => $ppcCode, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/uk/'), 'banner' => FALSE ]; $this->send($email, $params); } /** * @param $email * @param $userName * @param $userEmail * @param $group * @param $messageSubject * @param $messageBody */ public function userRequestRefund($email, $userName, $userEmail, $group, $messageSubject, $messageBody) { $params = [ 'subject' => 'Evercise refund request', 'view' => 'v3.emails.user.request_refund', 'email' => $email, 'userName' => $userName, 'userEmail' => $userEmail, 'group' => $group, 'messageSubject' => $messageSubject, 'messageBody' => $messageBody ]; $this->send($email, $params); } public function notReturned($user, $everciseGroups) { $params = [ 'subject' => 'You have not used your £5 Evercise Balance', 'title' => 'You haven&apos;t used your £5 Evercise Balance', 'view' => 'v3.emails.user.why_not_coming_back', 'user' => $user, 'everciseGroups' => $everciseGroups, 'banner' => FALSE, 'image' => image('/assets/img/email/user_default.jpg', 'You have not used your £5 Evercise Balance'), 'link_url' => $this->url->to('/uk/london') ]; $this->send($user->email, $params); } public function whyNotRefer($user) { $params = [ 'subject' => 'Share Evercise with your friends and get £5', 'title' => 'Share Evercise with your friends and get £5', 'view' => 'v3.emails.user.why_not_refer', 'user' => $user, 'banner' => $this->banner_types['refer_someone'], 'image' => image('/assets/img/email/user_reffer_friend.jpg', 'Why not refer a friend'), 'link_url' => $this->url->to('/uk/london'), 'style' => 'blue', ]; $this->send($user->email, $params); } public function rateClass($user) { $params = [ 'subject' => 'How was the class?', 'title' => 'How was the class?', 'view' => 'v3.emails.user.rate_class', 'user' => $user, 'image' => image('/assets/img/email/user_how_was_the_class.jpg', 'rate class'), 'link_url' => $this->url->to('/profile/' . $user->display_name . '/attended'), 'style' => 'pink', 'banner' => $this->banner_types['packages'], ]; $this->send($user->email, $params); } public function rateClassHasPackage($user) { // Send the rate class email, for users that have already have an active package // (the standard email recommends buying a package) $params = [ 'subject' => 'How was the class?', 'title' => 'How was the class?', 'view' => 'v3.emails.user.rate_class', 'user' => $user, 'image' => image('/assets/img/email/user_how_was_the_class.jpg', 'rate class'), 'link_url' => $this->url->to('/profile/' . $user->display_name . '/attended'), 'style' => 'pink', ]; $this->send($user->email, $params); } public function messageReply($sender, $recipient, $body) { $params = [ 'subject' => 'You have a new message', 'view' => 'v3.emails.user.mail_reply', 'sender' => $sender, 'recipient' => $recipient, 'messageBody' => $body ]; $this->send($recipient->email, $params); } /** * ######################################################################################## * ##### TRAINER EMAIL's ################################################# * ######################################################################################## */ /** * @param $trainer */ public function trainerRegisteredPpc($trainer) { $params = [ 'subject' => 'Welcome to Evercise!', 'title' => 'Welcome to Evercise!', 'view' => 'v3.emails.trainer.registered_ppc', 'trainer' => $trainer, 'banner' => NULL, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/profile/' . $trainer->display_name) ]; $this->send($trainer->email, $params); } /** * @param $trainer */ public function trainerRegistered($trainer) { $params = [ 'subject' => 'Welcome to Evercise!', 'title' => 'Welcome to Evercise!', 'view' => 'v3.emails.trainer.registered', 'trainer' => $trainer, 'banner' => NULL, 'image' => image('/assets/img/email/evercise-welcome.jpg', 'welcome to evercise'), 'link_url' => $this->url->to('/profile/' . $trainer->display_name) ]; $this->send($trainer->email, $params); } /** * @param $trainer * * Event: trainer.complete_profile */ public function trainerWhyNotCompleteProfile($trainer) { $params = [ 'subject' => 'BOOST YOUR EVERCISE SALES BY 50%', 'title' => 'BOOST YOUR EVERCISE SALES BY 50%', 'view' => 'v3.emails.trainer.complete_profile', 'trainer' => $trainer, 'banner' => NULL, 'image' => image('/assets/img/email/trainer_finish_profile.png', 'finish profile'), 'link_url' => $this->url->to('/profile/' . $trainer->display_name) ]; $this->send($trainer->email, $params); } public function trainerWhyNotCreateFirstClass($trainer) { $params = [ 'subject' => 'Why not create your first class', 'title' => 'Why not create your first class', 'view' => 'v3.emails.trainer.create_first_class', 'trainer' => $trainer, 'banner' => NULL, 'image' => image('/assets/img/email/trainer_create_first.png', 'why not create your first class'), 'link_url' => $this->url->to('/evercisegroups/create') ]; $this->send($trainer->email, $params); } /** * @param $class * @param $trainer */ public function classCreatedFirstTime($class, $trainer) { $params = [ 'subject' => 'Class created', 'title' => 'Class created', 'view' => 'v3.emails.trainer.class_created', 'trainer' => $trainer, 'class' => $class ]; $this->send($trainer->email, $params); } /** * @param $class * @param $trainer */ public function sendEmailAgain() { die('LETS NOT TRIGGER THIS AGAIN'); $users = [ '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>' ]; foreach($users as $email) { $params = [ 'subject' => 'Evercise Invitation', 'title' => 'Invitation', 'view' => 'v3.emails.user.testers' ]; $this->send($email, $params); } } /** * @param $userList * @param $group * @param $location * @param $dateTime * @param $trainerName * @param $trainerEmail * @param $classId * * Event: session.upcoming_session * Single event fires emails to all users and the trainer involved in the session. */ public function trainerSessionRemind( $userList, $group, $location, $dateTime, $trainerName, $trainerEmail, $classId, $sessionId ) { $params = [ 'subject' => 'Class reminder & participant list', 'view' => 'v3.emails.trainer.session_remind', 'userList' => $userList, 'group' => $group, 'location' => $location, 'dateTime' => $dateTime, 'trainerName' => $trainerName, 'trainerEmail' => $trainerEmail, 'classId' => $classId, 'sessionId' => $sessionId, 'style' => 'blue', 'image' => image('/assets/img/email/user_class_reminder.jpg', 'reminder of upcoming class'), 'link_url' => $this->url->to('/download_user_list/' . $sessionId) ]; $this->send($trainerEmail, $params); } /** * @param $userList * @param $evercisegroup * @param $session * @param $messageSubject * @param $messageBody * @internal param $group */ public function trainerMailAll($userList, $evercisegroup, $session, $messageSubject, $messageBody) { foreach ($userList as $id => $user) { $params = [ 'subject' => 'You have a new message', 'view' => 'v3.emails.trainer.mail_all', 'user' => $user, 'evercisegroup' => $evercisegroup, 'session' => $session, 'messageSubject' => $messageSubject, 'messageBody' => $messageBody ]; $this->send($user->email, $params); } } /** * @param $user * @param $trainer * @param $evercisegroup * @param $sessionDate */ public function trainerLeaveSession($user, $trainer, $evercisegroup, $sessionDate) { $params = [ 'subject' => 'Someone has left your class', 'view' => 'v3.emails.trainer.session_left', 'user' => $user, 'trainer' => $trainer, 'everciseGroup' => $evercisegroup, 'sessionDate' => $sessionDate, ]; $this->send($user->email, $params); } /** * @param $user * @param $trainer * @param $session * @param $evercisegroup * @param $transactionId * * Event: trainer.session.joined */ public function userJoinedTrainersSession($trainerId, $sessionDetails) { // This is fired once for each batch of classes belonging to a single trainer, so the Trainer only gets a single email per booking. $classes = []; foreach ($sessionDetails as $sd) { $this->log->info('SESSION BOOKED: ' . $sd['session']->id); $trainer = $sd['trainer']; $user = $sd['user']; if (!isset($classes[$sd['group']->id])) { $classes[$sd['group']->id] = [ 'transaction' => $sd['transaction'], 'session' => $sd['session'], 'codes' => $sd['transaction']->makeBookingHashBySession($sd['session']->id) ]; } } $params = [ 'subject' => 'A User just Joined your Class', 'view' => 'v3.emails.trainer.user_joined_classes', 'trainer' => $trainer, 'user' => $user, 'classes' => $classes, 'link_url' => $this->url->to('/'), 'image' => image('assets/img/email/user_booking_confirmation.jpg', 'someone has joined your classs'), ]; $this->send($trainer->email, $params); } /** * @param $user * @param $trainer * @param $session * @param $evercisegroup * @param $transactionId * * Event: session.joined */ public function trainerJoinSession($user, $trainer, $session, $evercisegroup, $transaction) { // This is fired for every sessionmember that is created. } public function userReviewedClass($user, $trainer, $rating, $session, $evercisegroup) { $params = [ 'subject' => 'A User Has Reviewed Your Class', 'view' => 'v3.emails.trainer.user_reviewed_class', 'user' => $user, 'trainer' => $trainer, 'rating' => $rating, 'session' => $session, 'evercisegroup' => $evercisegroup, 'link_url' => $this->url->to('/'), ]; $this->send($trainer->email, $params); } public function thanksForReview($user, $trainer, $rating, $session, $evercisegroup) { $params = [ 'subject' => 'Thanks for the review!', 'view' => 'v3.emails.user.thanks_review', 'user' => $user, 'trainer' => $trainer, 'review' => $rating, 'session' => $session, 'group' => $evercisegroup, 'link_url' => $this->url->to('/'), ]; $this->send($user->email, $params); } /** * @param $trainer * @param $user * @param $group * @param $dateTime * @param $messageSubject * @param $messageBody */ public function mailTrainer($trainer, $user, $evercisegroup, $session, $subject, $body) { $params = [ 'subject' => 'You have a new message', 'view' => 'v3.emails.trainer.mail_trainer', 'trainer' => $trainer, 'user' => $user, 'evercisegroup' => $evercisegroup, 'session' => $session, 'messageSubject' => $subject, 'messageBody' => $body ]; $this->send($trainer->email, $params); } public function generateStaticLandingEmail($ppcCode, $categoryId = 0) { $params = [ 'subject' => 'Static Landing Email', 'view' => 'v3.emails.user.static_landing_email', 'ppcCode' => $ppcCode, 'categoryId' => $categoryId, ]; $this->send('<EMAIL>', $params); } public function newYear($user) { $params = [ 'subject' => 'Discover a new fitness challenge', 'title' => 'Discover a new fitness challenge', 'view' => 'v3.emails.user.new_year', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/new_year.jpg', 'Warm up for the new year'), 'link_url' => $this->url->to('/') ]; $this->send($user->email, $params); } public function relaunch($user) { $params = [ 'subject' => 'Evercise Relaunch', 'title' => 'Evercise Relaunch!', 'view' => 'v3.emails.trainer.relaunch', 'user' => $user, 'banner' => FALSE, 'image' => image('/assets/img/email/relaunch.png', 'Check out the all new evercise'), 'link_url' => $this->url->to('/') ]; $this->send($user->email, $params); } public function notReturnedTrainer($trainer) { $params = [ 'subject' => 'Don’t be a stranger!', 'title' => 'Don’t be a stranger!', 'view' => 'v3.emails.trainer.why_not_coming_back', 'user' => $trainer, 'banner' => FALSE, 'image' => image('/assets/img/email/user_default.jpg', 'Don’t be a stranger!'), 'link_url' => $this->url->to('/uk/london') ]; $this->send($trainer->email, $params); } /** * ######################################################################################## * ##### ADMIN STUFF ################################################# * ######################################################################################## */ public function adminSendReminderForPayments($total) { $emails = $this->config->get('evercise.pending_emails'); foreach ($emails as $email) { $params = [ 'subject' => 'You have ' . $total . ' pending payments', 'view' => 'v3.emails.admin.payments_reminder', 'total' => $total, 'link_url' => $this->url->route('admin.pending_withdrawal'), 'image' => image('assets/img/email/admin.jpg', 'Evercise'), ]; $this->send($email, $params); } } /** * ######################################################################################## * ##### DEFAULT STUFF ################################################# * ######################################################################################## */ /** * @param $email * @param array $params */ public function send($email, $params = []) { /** This part will be needed when we assign Functions to Pardot API * example config would be: * * return [ * 'campayns' = [ * 'mail.mailwelcome' =>3598 * ] * ] * * **/ $this->data = array_merge($this->data, $params); if (is_string($this->data['banner']) && !empty($this->data['banner_types'][$this->data['banner']])) { $this->data['banner'] = $this->data['banner_types'][$this->data['banner']]; } $this->data['email'] = $email; $subject = $this->data['subject']; $attachments = $this->data['attachments']; $view = $this->view->make($this->data['view'], $this->data)->render(); // Parse it all Inline $parse = new CssToInlineStyles($view, $this->data['css']); $content = $parse->convert(); $plain_text = $this->plainText($content); $trace = debug_backtrace(); $name = $this->formatName(get_called_class(), next($trace)['function']); // If params contain user or user_id, take user ID from there. Otherwise query the email address to find user ID if (isset($params['user'])) { if ($params['user'] instanceof User || $params['user'] instanceof Sentry) { $user_id = $params['user']->id; } } if (isset($params['user_id'])) { $user_id = $params['user_id']; } if (!isset($user_id)) { $user_id = \User::where('email', $email)->pluck('id'); } if ($this->config->get('pardot.active')) { $campayn_id = $this->config->get('pardot.campayns.' . $name); } $sent = FALSE; if (!empty($campayn_id)) { $pardotEmail = new \PardotEmail([ 'subject' => $subject, 'content' => $content, 'plainText' => $plain_text ]); $pardot = new \Pardot(); try { $pardot->send($email, $campayn_id, $pardotEmail); $sent = TRUE; } catch (Exception $e) { $this->log->error('Pardot Email could not be sent ' . $e->getMessage()); /** ADD HERE SOME SORT OF NOTIFICATION TO ADMINS !!!*/ } } $message_id = ''; if (!$sent) { try { /** Remove Unsubscribe for now! */ $content = str_replace('%%unsubscribe%%', '', $content); $content = str_replace('dev.evercise.com', 'evercise.com', $content); $plain_text = str_replace('%%unsubscribe%%', '', $plain_text); $plain_text = str_replace('dev.evercise.com', 'evercise.com', $plain_text); $this->email->send(['v3.emails.blank', 'v3.emails.plain_blank'], ['content' => $content, 'plain_text' => $plain_text], function ($message) use ($email, $subject, $attachments, &$message_id) { $message_id = $message->getId(); $message->to($email)->subject($subject); if (count($attachments) > 0) { foreach ($attachments as $attachment) { $message->attach($attachment); } } }); $this->log->info('Email sent with basic sending'); } catch (Exception $e) { $this->log->error('Email could not be sent ' . $e->getMessage()); /** ADD HERE SOME SORT OF NOTIFICATION TO ADMINS !!!*/ } if ($user_id) { EmailOut::addRecord($user_id, $name, $message_id); } else { EmailOut::addRecord($email, $name, $message_id); } } /** Output email to file so we can check it out */ if (!empty($_ENV['SAVE_EMAILS']) && $_ENV['SAVE_EMAILS']) { if (!is_dir(storage_path() . '/emails')) { mkdir(storage_path() . '/emails'); } file_put_contents(storage_path() . '/emails/' . $name . '.html', $content); } } /** * Format from: events\Mail, classCreated * To: mail.classcreated * @param $class * @param $function * @return string */ private function formatName($class, $function) { return strtolower(str_replace('\\', '.', implode('.', [str_replace('events\\', '', $class), $function]))); } /** * @param $content * @return string */ private function plainText($content) { /** Strip Styles */ $content = preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $content); $content = strip_tags(str_replace(["\r\n", "\r"], "\n", $content)); $lines = explode("\n", $content); $new_lines = []; foreach ($lines as $i => $line) { if (!empty(trim($line))) { $new_lines[] = trim($line); } } $content = "\n" . implode($new_lines, "\n"); $remove = [ '&copy; Copyright 2014 Evercise', 'Follow us on', 'Unsubscribe' ]; $content = str_replace($remove, '', $content); $content .= $this->view->make('v3.emails.plain_footer', $this->data); return $content; } } <file_sep>/app/database/migrations/2014_09_01_083835_create_foreign_keys_4.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateForeignKeys4 extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('featured_evercisegroups', function(Blueprint $table) { $table->foreign('evercisegroup_id')->references('id')->on('evercisegroups'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('featured_evercisegroups', function(Blueprint $table) { $table->dropForeign('featured_evercisegroups_evercisegroup_id_foreign'); }); } } <file_sep>/app/database/migrations/2014_09_04_100544_create_evercise_permalinks_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEvercisePermalinksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('evercise_links')) { Schema::create('evercise_links', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('link_id'); $table->integer('parent_id')->unsigned(); $table->string ('permalink', 50); $table->enum('type', array('AREA', 'STATION', 'CLASS', 'ZIP'))->default('CLASS'); $table->timestamps(); //Indexes $table->unique('permalink'); $table->index('type'); $table->index('parent_id'); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('evercise_links'); } } <file_sep>/app/config/pardot.php <?php return [ 'active' => getenv('PARDOT_ACTIVE') ?: FALSE, 'campayns' => [ 'mail' => [ // 'welcome' => 3598, // 'welcomefacebook' => 4130, // 'welcomeguest' => 4132, // 'withdrawcompleted' => 4134, // 'userupgrade' => 4136, //Upgrade to Trainer 'userssessionremind' => 4138, 'userreviewedclass' => 4140, // User Reviewed Trainer Class 'userrequestrefund' => 4142, // 'userleavesession' => 4144, // 'userlanding' => 4146, // 'userjoinedtrainerssession' => 4148, // 'userforgotpassword' => 4150, // 'userchangedpassword' => <PASSWORD>, // 'usercartcompleted' => 4154, // 'trainerwhynotcreatefirstclass' => 4156, // 'trainerwhynotcompleteprofile' => 4158, // 'trainersessionremind' => 4160, // // 'trainerregistered' => 4162, // 'trainermailall' => 4164, // 'trainerleavesession' => 4166, // 'trainerjoinsession' => 4168, // 'topupcompleted' => 4170, // 'thanksforreview' => 4172, // 'thanksforinviting' => 4186, // 'ppc' => 4174, // 'mailtrainer' => 4176, // 'invite' => 4178, // 'generatestaticlandingemail' => 4180, // 'classCreatedFirstTime' => 4182, // 'adminSendReminderForPayments' => 4184, // ] ], 'reminders' => [ 'whynotusefreecredit' => ['daysinactive' => 10], 'whynotreferafriend' => ['dayssinceclass' => 4], 'whynotreview' => ['hourssinceclass' => 4], 'usercutoff' => ['year'=>2014, 'month'=>12, 'day'=>01], ] ];<file_sep>/app/models/UserPackages.php <?php /** * Class UserPackages */ class UserPackages extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'package_id', 'user_id']; /** * @var string */ protected $table = 'user_packages'; public function user() { return $this->belongsTo('User', 'user_id'); } public function package() { return $this->belongsTo('Packages'); } public function classes() { return $this->hasMany('UserPackageClasses', 'package_id'); } public static function addTemp($package_id, $user_id) { return static::create(['package_id' => $package_id, 'user_id' => $user_id]); } public function amountUsed($userpackage_id = 0) { return static::where('package_id', $userpackage_id)->where('status', 1)->count(); } /** * Check if there is a User Package that can be used for the $session * @param $class * @param $user */ public static function check(Evercisesession $session, $user) { $res = DB::table('packages') ->select(DB::raw('*, count(user_packages.id) as classes_count, user_packages.id as up_id')) ->join('user_packages', 'packages.id', '=', 'user_packages.package_id') ->leftJoin('user_package_classes', 'user_packages.id', '=', 'user_package_classes.package_id') ->where('user_packages.user_id', '=', $user->id) ->where('packages.max_class_price', '>=', $session->price) ->groupBy('user_packages.id') ->orderBy('packages.max_class_price', 'asc') ->get(); foreach($res as $row) { if($row->classes > $row->classes_count) { $package = static::find($row->up_id); return $package; } } throw new \Exception('No Packages Found for User '); } public static function hasActivePackage($user) { $res = DB::table('packages') ->select(DB::raw('*, count(user_packages.id) as classes_count, user_packages.id as up_id')) ->join('user_packages', 'packages.id', '=', 'user_packages.package_id') ->leftJoin('user_package_classes', 'user_packages.id', '=', 'user_package_classes.package_id') ->where('user_packages.user_id', '=', $user->id) ->get(); foreach($res as $row) { if($row->classes > $row->classes_count) { $package = static::find($row->up_id); return $package; } } return 0; } }<file_sep>/app/models/Trainerhistory.php <?php /** * Class Trainerhistory */ class Trainerhistory extends \Eloquent { /** * @var array */ protected $fillable = ['user_id', 'historytype_id', 'message']; /** * The database table used by the model. * * @var string */ protected $table = 'trainerhistory'; /** * @param array $params */ public static function create(array $params) { switch ($params['type']) { case 'deleted_evercisegroup': $message = $params['display_name'] . ' has deleted ' . $params['name']; $typeId = 3; // these need changing so they are picked up from the database break; case 'deleted_session': $message = $params['display_name'] . ' has deleted ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date']; $typeId = 4; // these need changing so they are picked up from the database break; case 'created_evercisegroup': $message = $params['display_name'] . ' created Class ' . $params['name']; $typeId = 1; // these need changing so they are picked up from the database break; case 'created_session': $message = $params['display_name'] . ' added a new date to ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date']; $typeId = 2; // these need changing so they are picked up from the database break; case 'joined_session': $message = $params['display_name'] . ' has joined ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date']; $typeId = 5; // these need changing so they are picked up from the database break; case 'rated_session': $message = $params['display_name'] . ' has left a review of ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date']; $typeId = 6; // these need changing so they are picked up from the database break; case 'left_session_full': $message = $params['display_name'] . ' has left ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date'] . ' with a full refund'; $typeId = 7; // these need changing so they are picked up from the database break; case 'left_session_half': $message = $params['display_name'] . ' has left ' . $params['name'] . ' at ' . $params['time'] . ' on the ' . $params['date'] . ' with a 50% refund'; $typeId = 8; // these need changing so they are picked up from the database break; } if (isset($message)) { $data = array('user_id' => $params['user_id'], 'historytype_id' => $typeId, 'message' => $message); parent::create($data); } } }<file_sep>/app/assets/javascripts/general.js // Use registerInitFunction() instead of document ready, either; // 1) Specify the second parameter as true to run every time // 2) flag which JS functions to run on each view from PHP as below: // // JavaScript::put(array('initSlider_price' => json_encode(array('name'=>'price', 'min'=>0, 'max'=>99, 'step'=>0.50, 'value'=>1)))); // // The first paramenter should match the name of your // Javascript function. If a '_' is found, anything // after this will be discarded. // The second parameter should be a JSON encoded string // of any parameters to pass to the JS function. // Add functions to 'initFunctions' array, to be run on document ready function registerInitFunction(functionName, always) { //trace("register: "+always+' : '+f) //functionName = /\W*function\s+([\w\$]+)\(/.exec( f.toString() )[ 1 ]; always = always || false; initFunctions.push({'name' : functionName, 'always' : always}); } // Loop through Laracasts, and run the ones that match a registered function jQuery( document ).ready( function( $ ) { var initLog = []; if(typeof laracasts !== 'undefined') { for(var l in laracasts){ //trace('LARACASTS: '+l + ': ' + laracasts[l] + ': ' + initFunctions[l]); var name = l.split('_')[0]; initFunctions.forEach(function(f) { if (f.name == name) { initLog.push('RUNNING: '+name+' : '+laracasts[l]); //f.run(laracasts[l]); window[f.name](laracasts[l]); } }); } } // Loop through all registered init functions, and run the ones flagged 'always' initFunctions.forEach(function(f) { if(f.always) { //trace('ALWAYS: '+f.name); initLog.push("ALWAYS: "+f.name); //f.run(f.name); window[f.name](); } }); trace(initLog, true); /* $('select').each(function(){ var title = $(this).attr('title'); if( $('option:selected', this).val() != '' ) title = $('option:selected',this).text(); w = $(this).width(); $(this) .css({'z-index':10,'opacity':0,'-khtml-appearance':'none'}) .after('<span class="drop_down" style="width:'+w+'px;">' + title + '</span>') .change(function(){ val = $('option:selected',this).text(); $(this).next().text(val); }) }); */ }); function getView(url, callback) { $.ajax({ url: url, type: 'GET', dataType: 'html' }) .done( function(data) { callback(data); } ); return false; } function trace(message, debug) { if (DEBUG_APP) { console.log(arguments.callee.caller.name + ' => ' + message); //window.console && console.log(message); } } function initLoginBox() { $(document).on('click','#cancel_login',function(){ $('.mask').hide(); $('.login_wrap, .modal').remove(); }) // remove error message when user types in box $(document).on('keyup','input, textarea', function(e){ // check for which key has been pressed var code = e.keyCode || e.which; if(code == 13) { //Enter keycode return; // if enter key is pressed return } $(this).closest('div').find('.error-msg').fadeOut(200,function(){ $(this).removeClass('error'); $(this).closest('div').find('.error_msg').remove(); }); }); $(document).on('click','.nav-admin', function(){ $('#displayName-dropdown').toggle(100,function(){ $(document).mouseup(function (e) { //trace('displayName click'); var container = $('#displayName-dropdown'); var link = $('.nav-admin'); if (!container.is(e.target) && !link.is(e.target) && container.has(e.target).length === 0) { container.hide(100); } }); }) }) setTimeout(function() { $('.top-msg').fadeOut(500); }, 5000); } registerInitFunction('initLoginBox', true); // jquery ui's tool tip for input fields function initToolTip() { $('.tooltip').each(function(){ var info = $(this); info.tooltip({ items: "[data-tooltip]", content: function () { return info.data("tooltip"); }, position: { my: "left top-15", at: "right top" } }) .off( "mouseover" ) .on( "click", function(){ $( this ).tooltip( "open" ); return false; }) //.attr( "title", "" ).css({ cursor: "pointer" }); //$(this).tooltip('option', {disabled: false}).tooltip('open'); // uncomment for testing }) } registerInitFunction('initToolTip'); // params: name, min, max, step, value, // callback - a selector of a field to update with the value function initSlider(params) { sliderParams = JSON.parse(params); var sliderName = sliderParams.name; //trace("initSlider("+sliderName+") - callback:"+sliderParams.callback); $( "#"+sliderName+"-slider" ).slider({ range: "min", min: sliderParams.min, max: sliderParams.max, step: sliderParams.step, value: sliderParams.value, format: sliderParams.format, slide: function( event, ui ) { if (ui.value % 1 != 0) { $( "#"+sliderName+"" ).val( ui.value .toFixed(2) ); }else{ $( "#"+sliderName+"" ).val( ui.value ); }; if (sliderParams.callback){ window[sliderParams.callback](); } //if (sliderParams.callback) $(sliderParams.callback).html(ui.value .toFixed(2) ); } }); // end General slider $("#"+sliderName).keyup(function(){ updateSlider(sliderName); }); updateSlider(sliderName); } registerInitFunction('initSlider'); function updateSlider(sliderName) { //trace("sliderName: "+sliderName +', value: '+ $("#"+sliderName).val()); $( "#"+sliderName+"-slider" ).slider({ value: $("#"+sliderName).val() }); } /* used for read more buttons */ function initReadMore() { $(document).on('click', '.expand-wrapper', function(){ $('.expand').toggle(300); }) } registerInitFunction('initReadMore'); /* use for creating charts */ function initChart(params) { try { params = JSON.parse(params); id = params.id; trace(params.id); } catch(error) { id = params; } var chart = $('#'+id); var total = parseInt(chart.data('total')); var fill = parseInt(chart.data('filled')); result = Math.ceil((fill*100)/ total); left = 100 - result; var data = [ { value: result, color:"#ffd21e" }, { value : left, color : "#ebebeb" } ]; var options = { percentageInnerCutout : 87, animationEasing : 'easeInOutQuart', onAnimationComplete : function(){ $(chart).closest('div').find('.canvas-overlay').fadeIn(300); } }; var myDoughnut = new Chart(chart.get(0).getContext("2d")).Doughnut(data, options); } registerInitFunction('initChart'); // edit form // NOW gets the method from the form and sends via that method function initPut (params) { if (params == null || params == 1) { selector = '.create-form, .update-form' ; }else{ params = JSON.parse(params); selector = params.selector; } $( document ).on( 'submit', selector , function() { var form = $(this); form.find('.btn').addClass('disabled'); loading(); var method = ($(this).find('input').val() == 'PUT') ? 'PUT' : $(this).attr('method'); var url = $(this).attr('action'); $('.error-msg').remove(); $('input').removeClass('error'); // post to controller $.ajax({ url: url, type: method, data: $( this ).serialize(), dataType: 'json' }) .done( function(data) { loaded(); if (data.validation_failed == 1) { if (!$('.modal').length) { $('.mask').hide(); }; form.find('.btn').removeClass('disabled'); // show validation errors var arr = data.errors; var scroll = false; $.each(arr, function(index, value) { if (scroll == false) { if (form.find("#" + index).length) { $('html, body').animate({ scrollTop: form.find("#" + index).offset().top -85 }, 400); form.find("#" + index).focus(); }else{ $('html, body').animate({ scrollTop: form.find('input[name="'+index+'"]').offset().top -85 }, 400); form.find('input[name="'+index+'"]').focus(); } scroll = true; }; if (value.length != 0) { form.find("#" + index).addClass('error'); // add a error to input field returned by validation check // check for a slider if (form.find("#" + index+'-slider').length) { if (!form.find("#" + index+'-error').length) { form.find("#" + index+'-slider').after('<span id="'+index+'-error" class="error-msg">' + value + '</span>'); }; }else{ if (!form.find("#" + index+'-error').length) { if (form.find("#" + index).length) { form.find("#" + index).after('<span id="'+index+'-error" class="error-msg">' + value + '</span>'); }else{ form.find('input[name="'+index+'"]').after('<span id="'+index+'-error" class="error-msg">' + value + '</span>'); } } }; } }); form.find('.btn').removeClass('disabled'); }else{ // call back var callback = data.callback; window[callback](data, form); } } ); return false; }); trace('selector: '+ selector); } function gotoUrl(data) { trace('gotourl'); window.location.href = data.url; } function successAndRefresh(data, form) { form.find('.success_msg').show(); window.location.href = ''; } function fail(data, form) { window.location.href = './'; } registerInitFunction('initPut'); function initSwitchView(){ $(document).on('click','.icon-btn', function(){ $('.icon-btn').removeClass('selected'); $(this).addClass('selected'); var view = $(this).data('view'); $('.tab-view').removeClass('selected'); $('#'+view).addClass('selected'); // add view to hidden field $('#view-select').val(view); $( '.view-pag').toggleClass('hidden'); }) } registerInitFunction('initSwitchView'); function InitAccordian(){ $(document).on('click', '.tab-header', function(){ var tab = $(this).data('tab'); if ($(this).hasClass('selected') ) { $(this).removeClass('selected'); $('#'+tab).slideUp(500); $('#'+tab).removeClass('selected'); }else{ $('.tab-header').removeClass('selected'); $(this).addClass('selected'); $('.tab-body.selected').slideUp(500); $('#'+tab).slideDown(500); $('.tab-body').removeClass('selected'); $('#'+tab).addClass('selected'); }; }) } registerInitFunction('InitAccordian'); function initScrollAnchor(string) { var locationPath = filterPath(location.pathname); var sticky_header = 0; var navigation = 0; if ($('.navigation')) { navigation = $('.navigation').height(); }; $('a[href*=#]').each(function() { var thisPath = filterPath(this.pathname) || locationPath; if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) { var $target = $(this.hash), target = this.hash; if (target) { var targetOffset = $target.offset().top - navigation ; $(this).click(function(event) { event.preventDefault(); $('html, body').animate({scrollTop: targetOffset}, 300, function() { trace(targetOffset); // location.hash = target; }); }); } } }); } registerInitFunction('initScrollAnchor'); function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace(/\/$/,''); } function initStickHeader(){ var target = $('.sticky-header'); var targetOffset = target.offset().top; var width = target.width(); $(window).scroll(function(){ trace('y: '+ $(window).scrollTop()); if ($(window).scrollTop() >= targetOffset) { $('.sticky-header').addClass('fixed').css({ 'width': width+'px' }); } else { $('.sticky-header').removeClass('fixed'); } }); } registerInitFunction('initStickHeader'); function refreshpage(){ window.location.href = ''; } function sendhome(data){ trace(data.message); window.location.href = '/'; } function openPopup(data) { $('.mask').show(); trace('openPopup', true); $('body').append(data.popup); // initPut(); } function loading(){ $('.mask').show(); $('html').append('<img src="/img/e-circle-loading-yellow-on-black.gif" class="loading_circle">'); } function loaded(){ if (!$('.modal').length) { $('.mask').hide(); }; $('.loading_circle').remove(); } function overrideGaPageview(params){ params = JSON.parse(params); pageview = params.pageview; ga('send', 'pageview', pageview); } registerInitFunction('overrideGaPageview'); function initSearchByName() { $('input[name="findByName"]').keyup( function(e){ if(this.value.length >= 3 || e.keyCode == 13) { $('.selectors').addClass('hidden'); $("[id*="+this.value.toLowerCase()+"]").removeClass('hidden'); }else{ $('.selectors').removeClass('hidden'); } }) } registerInitFunction('initSearchByName'); function adminPopupMessage(data) { trace(data.message); //alert(data.message); }<file_sep>/app/composers/UserClassesComposer.php <?php namespace composers; use DateTime; use Evercisesession; use Sentry; use Rating; use Evercisegroup; use JavaScript; class UserClassesComposer { public function compose($view) { $user = Sentry::getUser(); $userId = $user->id; $sessions = Evercisesession::whereHas( 'users', function ($query) use (&$userId) { $query->where('user_id', $userId); } )->orderBy('date_time', 'asc')->get(); $pastFutureCount = []; $groupsWithKeys = []; $members = []; $sessionmember_ids = []; // For rating $ratingsWithKeys = []; $pastSessionCount = 0; $currentDate = new DateTime(); if ($sessions->count()) { $group_ids = []; foreach ($sessions as $session_id => $session) { if (!in_array($session->evercisegroup_id, $group_ids)) { $group_ids[] = $session->evercisegroup_id; } $members[$session->id] = count($session->sessionmembers); // Count those members foreach ($session->sessionmembers as $sessionmember) { if ($sessionmember->user_id == $user->id) { $sessionmember_ids[$session->id] = $sessionmember->id; } } if (new DateTime($session->date_time) < $currentDate) { $pastSessionCount ++; } } $pastFutureCount = ['past' => $pastSessionCount, 'future' => ($sessions->count() - $pastSessionCount), 'total' => $sessions->count() ]; $ratings = Rating::whereIn('sessionmember_id', $sessionmember_ids)->get(); foreach ($ratings as $rating) { $ratingsWithKeys[$rating->session_id] = ['comment' => $rating->comment, 'stars' => $rating->stars]; } $groups = Evercisegroup::whereIn('id', $group_ids)->get(); foreach ($groups as $key => $group) { $groupsWithKeys[$group->id] = $group; } } // get current tab $viewdata = $view->getData(); $tab = isset($viewdata['tab']) ? $viewdata['tab'] : 0; // initialise js functions for trainer edit JavaScript::put( [ 'initPut_user_edit' => json_encode(['selector' => '#user_edit']), 'initPut_send_invite' => json_encode(['selector' => '#send_invite']), 'initPut_password_change' => json_encode(['selector' => '#password_change']), 'initPut_feedback' => json_encode(['selector' => '#feedback']), 'initUsers' => 1, 'initToolTip' => 1, //Initialise tooltip JS. 'initDashboardPanel' => 1, // Initialise title swap Trainer JS. 'selectTab' => ['tab' => $tab], 'initAddRating' => 1 ] ); $view->with('groups', $groupsWithKeys) ->with('sessions', $sessions) ->with('members', $members) ->with('sessionmember_ids', $sessionmember_ids) ->with('ratings', $ratingsWithKeys) ->with('pastFutureCount', $pastFutureCount); } }<file_sep>/app/models/User_marketingpreference.php <?php class User_marketingpreference extends \Eloquent { protected $fillable = array('user_id', 'marketingpreference_id'); /** * The database table used by the model. * * @var string */ protected $table = 'user_marketingpreferences'; }<file_sep>/app/database/migrations/2014_07_02_093239_create_withdrawalrequests_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateWithdrawalrequestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('withdrawalrequests')) { Schema::create('withdrawalrequests', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key $table->decimal('transaction_amount', 19, 4); $table->string('account'); $table->string('acc_type'); $table->integer('processed'); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('withdrawalrequests'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/models/Mindbody/MindbodyClient.php <?php namespace MindbodyAPI; use MindbodyAPI\structures\SourceCredentials; use MindbodyAPI\structures\UserCredentials; use UnexpectedValueException; class MindbodyClient extends \SoapClient { public static $classmap = []; public static function service($name) { $class = "MindbodyAPI\\services\\{$name}"; return new $class; } public static function request( $type, SourceCredentials $sourceCredentials = NULL, UserCredentials $userCredentials = NULL, $params = [], $unset = [] ) { $requestName = "MindbodyAPI\\structures\\{$type}"; $requestRequestName = "{$requestName}Request"; if (!class_exists($requestName) || !class_exists($requestRequestName)) { return FALSE; } $request = new $requestName; $request->Request = new $requestRequestName; if ($sourceCredentials) { $request->Request->SourceCredentials = $sourceCredentials; } else { $request->Request->SourceCredentials = new SourceCredentials(); } if ($userCredentials) { $request->Request->UserCredentials = $userCredentials; } foreach ($params as $key => $val) { $request->Request->{$key} = $val; } foreach ($unset as $key) { unset($request->Request->$key); } return $request; } public static function credentials($sourcename = null, $password = null, Array $siteids = null) { $credentials = new structures\SourceCredentials; $credentials->SourceName = $sourcename; $credentials->Password = $<PASSWORD>; $credentials->SiteIDs = $siteids; return $credentials; } public static function userCredentials($username, $password, Array $siteids = null) { $credentials = new structures\UserCredentials; $credentials->Username = $username; $credentials->Password = $<PASSWORD>; $credentials->SiteIDs = $siteids; return $credentials; } public static function structure($type, $propMap = null) { if($propMap && !(is_array($propMap) || is_object($propMap))) throw new UnexpectedValueException("\$propMap must be an array or an object"); if(isset(static::$classmap[$type])) { $structure = new static::$classmap[$type](); if(!empty($propMap)) foreach($propMap as $name => $value) { if(property_exists($structure, $name)) $structure->$name = $value; } return $structure; } else throw new UnexpectedValueException("{$type} is not a valid type associated with ".get_called_class()); } public function __soapCall($function_name, $arguments, $options = [], $input_headers = [], &$output_headers = []) { $result = parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers); $expectedResultType = "{$function_name}Result"; if(isset($result->$expectedResultType)) return $result->$expectedResultType; return $result; } } <file_sep>/public/assets/jsdev/main.js $.ajaxSetup({ headers: { 'X-CSRF-Token': TOKEN } }); $(function(){ // initialise nav bar is nav bar exists $('#nav').exists(function() { new Navigation( this , $('.hero-nav-change') ); }); // initialise masonry if masonry container exists $('.masonry').exists(function() { new Masonry( this ); }) // initialise user profile if user profile exists /* $('#user-nav-bar').exists(function() { new Profile(this); }); */ // used to change a button on click $('.toggle-switch').exists(function() { $(document).on('click', '.toggle-switch', function(e){ new ToggleSwitch($(e.target)); }) }); $('.map_canvas').exists(function() { map = new Map(this); }); $('.lazy').exists(function() { $("img.lazy").lazyload(); }); $('.mb-scroll').exists(function(){ $(this).mCustomScrollbar({ scrollSpeed: 50, mouseWheelPixels: 50, autoHideScrollbar: false, scrollInertia: 0 }); }) $('.holder').exists(function(){ new ImagePlaceholder(); }) $('#register-form').exists(function(){ new registerUser(this); }) $('#register-trainer').exists(function(){ new registerTrainer(this); }) $('.hide-by-class').exists(function(){ var i = 0; $('.hide-by-class').each(function(){ var self = this; $('.'+$(this).attr('href').substr(1)).exists(function(){ if(i == 0){ $(self).addClass('active'); $(self).parent().removeClass('hidden-mob'); $(this).removeClass('hide'); } else{ } $(self).removeClass('disabled'); i++; }) }) this.click(function(){ $('.hide-by-class').removeClass('active'); $(this).addClass('active'); $('.hide-by-class-element').addClass('hide'); $('.'+ $(this).attr('href').substr(1)).removeClass('hide'); }) }) $('.login-form').exists(function(){ new Login(this); }) $('.edit-class-inline').exists(function(){ new EditClass(this); $(document).on('submit', '.add-session', function(e){ e.preventDefault(); new AjaxRequest($(e.target), newSessionAdded); }) }) $(document).on('submit', '.remove-session', function(e){ e.preventDefault(); new AjaxRequest($(e.target), removeSessionRow); }) // always run cart cart = new Cart(this); $('#find_gallery_image_by_category').exists(function(){ new categorySelect($(this) ); }) $('#image-cropper').exists(function(){ new imageCropper(this); }) $('#create-venue').exists(function(){ new createVenue(this); }) $('#add-session').exists(function(){ // new AddSessions(this); new AddSessionsToCalendar(this); }) $('#update-sessions').exists(function(){ new UpdateSessions(this); }) $('#create-class').exists(function(){ new createClass(this); }) $('#preview').exists(function(){ new previewBox(this); }) $('#publish-class').exists(function(){ new publishClass(this); }) $('#register-fb').exists(function(){ new facebookRedirect(this); }) $('#scroll-to').exists(function(){ new scrollTo(this); }) $('#profile-nav').exists(function(){ new profileNav(this) /* window.addEventListener("popstate", function(e) { console.log(e); var activeTab = $('[href=' + location.hash + ']'); console.log(activeTab); if (activeTab.length) { activeTab.tab('show'); } else { $('.nav-tabs a:first').tab('show'); } }); */ }) $('.rate-it').exists(function(){ new RateIt(this); }) $('#add-topup').exists(function(){ new topUp(this); }) $('#change-password').exists(function(){ new changePassword(this); }) $('#location-auto-complete').exists(function(){ autocomplete = new LocationAutoComplete(this); }) $('#checkout').exists(function(){ new checkout(this); }) $('#voucher').exists(function(){ new voucher(this); }) $('#refer-a-friend').exists(function(){ new Referral(this); }) $('#update-user-form').exists(function(){ new updateProfile(this); }) $('#list-accordion').exists(function(){ new listAccordion(this); }) $('#hero-carousel , #image-carousel').exists(function() { $(this).carousel({ interval: 5000 }) }) $('.mail-popup').exists(function(){ new MailPopup(this); }) $('#withdraw-funds').exists(function(){ new Withdrawal(this); }) $('.remove-session').exists(function(){ new RemoveSession(this); }) $('.landing-popup').exists(function(){ $(document).on('click', '.close', function(){ $('.landing-popup').addClass('hidden'); $('.landing-mask').addClass('hidden'); }) }) $('#passwords_reset').exists(function(){ $(document).on('submit', '#passwords_reset', function(e){ e.preventDefault(); new AjaxRequest($(e.target), redirectTo); }) }) $('.trapezium').exists(function(){ new trapezium(this); }) $('.category-select').exists(function(){ new categoryAutoComplete(this); }) if (navigator.geolocation) { new myLocation(); } $(".select-box").selectbox(); $('.sticky').exists(function(){ var sticky = this; var top = sticky.offset().top; $(window).scroll(function(){ var y = $(this).scrollTop(); if( y >= top){ sticky.addClass('fixed'); } else{ sticky.removeClass('fixed'); } }) }) $('#class-calendar').exists(function(){ //new classCalendar(this); }) });<file_sep>/app/controllers/SessionsController.php <?php use Carbon\Carbon; class SessionsController extends \BaseController { public function __construct() { parent::__construct(); } /** * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View */ public function setCheckoutSessionData() { $sessionIds = json_decode(Input::get('session-ids'), TRUE); $evercisegroupId = json_decode(Input::get('evercisegroup-id'), TRUE); Session::put('sessionIds', $sessionIds); Session::put('evercisegroupId', $evercisegroupId); } /** * Display a listing of the resource. * * @return Response */ public function index($evercisegroup_id = '') { } /** * Show the form for creating a new resource. * * @return Response */ public function create($evercisegroupId) { $class = Evercisegroup::find($evercisegroupId); if(!isset($class->user_id) || !isset($this->user->id)) { return Redirect::route('home')->with('success', 'You don\'t have permissions to view that page. '.$evercisegroupId); } if($class->user_id != $this->user->id) { return Redirect::route('home')->with('success', 'You don\'t have permissions to view that page'); } //$sessions = $class->futuresessions; $sessions = Evercisesession::where('evercisegroup_id', $evercisegroupId) ->where('date_time', '>=', Carbon::now()) ->orderBy('date_time', 'asc') ->paginate(50); $data = [ 'evercisegroup_id' => $evercisegroupId ]; return View::make('v3.classes.add_sessions')->with('data', $data)->with('sessions', $sessions); } /** * Show the popup form for mailing all users signed up to a session * * @param $id * @return \Illuminate\View\View */ public function getMailAll($sessionId) { //$session = Evercisesession::with('evercisegroup')->find($sessionId); return Response::json( [ 'view' => View::make('v3.classes.mail_all_members')->with('sessionId', $sessionId)->render() ] ); //return View::make('v3.classes.mail_all_members')->with('sessionId', $sessionId); } /** * Send the mail to all users signed up to a session * * @param $sessionId * @return \Illuminate\Http\JsonResponse */ public function postMailAll($sessionId) { $subject = Input::get('mail_subject'); $body = Input::get('mail_body'); $userList = []; $session = Evercisesession::find($sessionId); $participants = Evercisesession::getMembers($sessionId); //Log::info('participants: '.$participants); foreach ($participants as $user) { $userList[$user->pivot->user_id] = $user; //Log::info('USERLIST: '.$user->pivot->user_id); } if ( $response = Evercisesession::validateMail() ) return $response; /** Add message to TBmsg */ foreach ($userList as $id => $user) { Messages::sendMessage($this->user->id, $id, $body); } return Evercisesession::mailMembers($session, $userList, $subject, $body); } /** * Show the form to send a mail to a single user * * @param $sessionId * @param $userId * @return \Illuminate\View\View */ public function getMailOne($sessionId, $userId) { $userDetails = User::where('id', $userId)->select('first_name', 'last_name')->first(); $name = $userDetails['first_name'] . ' ' . $userDetails['last_name']; return View::make('sessions.mail_one')->with('sessionId', $sessionId)->with('userId', $userId)->with( 'firstName', $name ); } /** * Send the mail to a single user * * @param $sessionId * @param $userId * @return \Illuminate\Http\JsonResponse */ public function postMailOne($sessionId, $userId) { $subject = Input::get('mail_subject'); $body = Input::get('mail_body'); $userDetails = User::getNameAndEmail($userId); $userList = [$userDetails['name'] => $userDetails['email']]; return Evercisesession::mailMembers($sessionId, $userList, $subject, $body); } /** * Get form to send an email to the trainer of a group * * @param $sessionId * @param $trainerId * @return \Illuminate\View\View */ public function getMailTrainer($sessionId, $trainerId) { $session = Evercisesession::with('evercisegroup')->find($sessionId); $dateTime = $session->date_time; $groupName = $session->evercisegroup->name; $name = User::getName($trainerId); return Response::json( [ 'view' => View::make('v3.classes.mail_trainer') ->with('sessionId', $sessionId) ->with('trainerId', $trainerId) ->with('userId', Sentry::getUser()->id) ->with('dateTime', $dateTime) ->with('groupName', $groupName) ->with('name', $name)->render() ] ); } /** * @param $sessionId * @param $trainerId * @return \Illuminate\Http\JsonResponse */ public function postMailTrainer($sessionId, $trainerId) { $subject = Input::get('mail_subject'); $body = Input::get('mail_body'); list($groupId, $groupName) = Evercisesession::mailTrainer($sessionId, $trainerId, $subject, $body); /** Add message to TBmsg */ Messages::sendMessage($this->user->id, $trainerId, $body); return Response::json( [ 'view' => View::make('v3.layouts.positive-alert')->with('message', 'your message was sent successfully')->with('fixed', true)->render() ] ); } /** * check login status and either direct to checkout, or open login box * * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View */ public function checkout() { $this->setCheckoutSessionData(); $redirect_after_login_url = 'sessions.join.get'; if (!Sentry::getUser()) { return View::make('auth.login')->with('redirect_after_login', TRUE)->with( 'redirect_after_login_url', $redirect_after_login_url ); } else { return Response::json(['status' => 'logged_in']); } } /** * * * confirmation for join sessions */ public function joinSessions() { $sessionIds = Session::get('sessionIds', FALSE); $evercisegroupId = Session::get('evercisegroupId', FALSE); if (!$sessionIds) { $sessionIds = json_decode(Input::get('session-ids'), TRUE); } if (!$evercisegroupId) { $evercisegroupId = Input::get('evercisegroup-id'); } if (empty($sessionIds)) { return Redirect::route('class.show', [$evercisegroupId]); } if ($joinParams = Evercisesession::confirmJoinSessions($evercisegroupId, $sessionIds)) { Session::put('sessionIds', $sessionIds); Session::put('amountToPay', $joinParams['totalPrice']); return View::make('sessions.join') ->with('evercisegroup', $joinParams['evercisegroup']) ->with('members', $joinParams['members']) ->with('userTrainer', $joinParams['userTrainer']) ->with('totalPrice', $joinParams['totalPrice']) ->with('totalPricePence', $joinParams['totalPricePence']) ->with('totalSessions', $joinParams['totalSessions']) ->with('sessionIds', $joinParams['sessionIds']); } else { return Response::json('USER HAS ALREADY JOINED SESSION'); } } /** * Get the form for leaving a session * * @param $evercisesessionId * @return \Illuminate\View\View */ function getLeaveSession($evercisesessionId) { $leaveParams = Evercisesession::getLeaveSessionForm($evercisesessionId); return View::make('sessions.leave') ->with('session', $leaveParams['session']) ->with('refund', $leaveParams['refund']) ->with('refundInEvercoins', $leaveParams['refundInEvercoins']) ->with('evercoinBalanceAfterRefund', $leaveParams['evercoinBalanceAfterRefund']) ->with('evercoin', $leaveParams['evercoin']) ->with('status', $leaveParams['status']); } public function postLeaveSession($id) { return Evercisesession::processLeaveSession($id); } public function redeemEvercoins($evercisegroupId) { $usecoins = Input::get('redeem'); $sessionIds = Session::get('sessionIds'); $evercoinParams = Evercisesession::getRedeemEvercoinsView($evercisegroupId, $usecoins, $sessionIds); Session::put('amountToPay', $evercoinParams['amountRemaining']); if ($evercoinParams['priceInEvercoins'] == $evercoinParams['usecoins']) { return Response::json( [ 'callback' => 'openPopup', 'popup' => (string)View::make('sessions.checkoutwithevercoins') ->with('evercisegroupId', $evercisegroupId) ->with('priceInEvercoins', $evercoinParams['priceInEvercoins']) ->with('evercoinBalance', $evercoinParams['evercoinBalance']) ->with('usecoinsInPounds', $evercoinParams['usecoinsInPounds']) ] ); } else { return Response::json( [ 'usecoins' => $usecoins, 'amountRemaining' => $evercoinParams['amountRemaining'], 'usecoinsInPounds' => $evercoinParams['usecoinsInPounds'], 'callback' => 'paidWithEvercoins' ] ); } } /** * Put evercoin payment details into the session and then add member to class * * @param $evercisegroupId * @return \Illuminate\View\View */ public function postPayWithEvercoins($evercisegroupId) { Session::put('paymentMethod', 'evercoins'); Session::put( 'transactionId', substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 1) . substr( str_shuffle('aBcEeFgHiJkLmNoPqRstUvWxYz0123456789'), 0, 10 ) ); return $this->payForSessions($evercisegroupId); } public function getRefund($id) { $session = Evercisesession::with('evercisegroup')->find($id); $sessionDate = new DateTime($session->date_time); $now = new DateTime(); $twodaystime = (new DateTime())->add(new DateInterval('P2D')); $fivedaystime = (new DateTime())->add(new DateInterval('P5D')); $evercoin = Evercoin::where('user_id', $session->evercisegroup->user_id)->first(); if ($sessionDate > $fivedaystime) { $status = 2; $refund = $session->price; } elseif ($sessionDate > $twodaystime) { $status = 1; $refund = $session->price / 2; } else { $status = 0; $refund = 0; } $refundInEvercoins = Evercoin::poundsToEvercoins($refund); $evercoinBalanceAfterRefund = $evercoin->balance + $refundInEvercoins; return View::make('sessions.refund_request') ->with('session', $session) ->with('refund', $refund) ->with('refundInEvercoins', $refundInEvercoins) ->with('evercoinBalanceAfterRefund', $evercoinBalanceAfterRefund) ->with('evercoin', $evercoin) ->with('status', $status); } public function postRefund($sessionId) { $validator = Validator::make( Input::all(), [ 'mail_subject' => 'required', 'mail_body' => 'required', ] ); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { $subject = Input::get('mail_subject'); $body = Input::get('mail_body'); $contact = '<EMAIL>'; $groupId = Evercisesession::where('id', $sessionId)->pluck('evercisegroup_id'); $groupName = Evercisegroup::where('id', $groupId)->pluck('name'); Event::fire( 'session.refund', [ 'email' => $contact, 'userName' => Sentry::getUser()->display_name, 'userEmail' => Sentry::getUser()->email, 'groupName' => $groupName, 'subject' => $subject, 'body' => $body ] ); } return Response::json(['callback' => 'successAndRefresh']); } }<file_sep>/public/assets/jsdev/prototypes/21-scroll-to.js function scrollTo(nav){ this.nav = nav; this.target = ''; this.top = $('#nav').outerHeight(); this.addListeners() } scrollTo.prototype = { constructor: scrollTo, addListeners : function(){ this.nav.find('a[target!="_blank"]').on('click', $.proxy(this.scroll, this)); }, scroll : function(e){ e.preventDefault(); this.target = $(e.target).attr('href'); $('html, body').animate({ scrollTop: $(this.target).offset().top - this.top }, 300); } }<file_sep>/app/database/migrations/2014_08_21_105454_add_indexes_to_mutiple_tables.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddIndexesToMutipleTables extends Migration { /** * Add Custom Indexes multiple tables * * @return void */ public function up() { //Adding a column at the start of the table is not really possible in Laravel (yet) //I have to do a raw query to accomplish it Schema::table( 'evercisegroups', function ($table) { $table->index('published')->unsigned(); } ); Schema::table( 'landings', function ($table) { $table->index('user_id')->unsigned(); $table->index('category_id')->unsigned(); } ); DB::statement( "ALTER TABLE `marketingpreferences` CHANGE `option` `option` ENUM( 'yes', 'no' ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT 'yes'" ); Schema::table( 'milestones', function ($table) { $table->index('facebook')->unsigned(); $table->index('twitter')->unsigned(); } ); Schema::table( 'ratings', function ($table) { $table->dropForeign('ratings_user_created_id_foreign'); $table->dropForeign('ratings_evercisegroup_id_foreign'); $table->dropForeign('ratings_session_id_foreign'); $table->dropForeign('ratings_sessionmember_id_foreign'); $table->index('sessionmember_id')->unsigned(); $table->index('session_id')->unsigned(); $table->index('evercisegroup_id')->unsigned(); $table->index('user_created_id')->unsigned(); $table->index('stars')->unsigned(); } ); Schema::table( 'referrals', function ($table) { $table->index('referee_id')->unsigned(); } ); Schema::table( 'trainers', function ($table) { $table->index('confirmed')->unsigned(); $table->index('specialities_id')->unsigned(); } ); DB::statement( 'ALTER TABLE `venue_facilities` ADD `venue_facilities_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' ); Schema::table( 'venues', function ($table) { $table->index('lat'); $table->index('lng'); } ); Schema::table( 'wallethistory', function ($table) { $table->index('sessionpayment_id'); } ); } } <file_sep>/app/database/migrations/2014_07_17_100130_create_migrate_sessions_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateMigrateSessionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('migrate_sessions')) { Schema::create('migrate_sessions', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id')->unsigned(); $table->integer('classDatetimeId')->unsigned(); $table->integer('evercisesession_id')->unsigned(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('migrate_sessions'); } } <file_sep>/app/controllers/BaseController.php <?php class BaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ public $user; public function __construct() { $this->beforeFilter('csrf', array('on' => 'post')); $this->user = false; $coupon = Session::get('coupon', false); $this->cart = EverciseCart::getCart($coupon); $this->cart_items = []; foreach($this->cart['sessions_grouped'] as $key_id => $val) { $this->cart_items[$key_id] = $val['qty']; } foreach($this->cart['packages'] as $key_id => $val) { $this->cart_items[$key_id] = 1; } View::share('cart_items', $this->cart_items); View::share('cart', View::make('v3.cart.dropdown')->with($this->cart)->render()); if (Sentry::check()) { $this->user = Sentry::getUser(); $userImage = $this->user->image ? (Config::get('evercise.upload_dir') . 'profiles' . '/' . $this->user->directory . '/' . $this->user->image) : 'img' . '/' . 'no-user-img.jpg'; View::share('userImage', isset($userImage) ? $userImage : ''); View::share('user', $this->user); View::share('newMessages', ['count' => Messages::unread($this->user->id), 'user' => Messages::getLastMessageDisplayName($this->user->id)] ); $header = $this->setupHeader('user'); } else { $header = $this->setupHeader('none'); } if (Request::is('cart/*')) { $header = $this->setupHeader('cart'); } View::share('header', $header); $version = include(base_path().'/.version.php'); View::share('version', $version); } protected function setupHeader($user_type = 'none') { $browse = false; if (Request::is('uk/*')) { $browse = true; } switch ($user_type) { case 'none': return View::make('v3.layouts.navigation')->with('browse',$browse)->render(); break; case 'user': return View::make('v3.layouts.navigation-user')->with('browse',$browse)->render(); break; case 'cart': return View::make('v3.layouts.navigation-cart')->render(); break; } } protected function setupLayout() { if (!is_null($this->layout)) { $this->layout = View::make($this->layout); } } /** * Check if the user is logged in and redirect if needed * * @return bool */ public function checkLogin() { return Sentry::check(); } }<file_sep>/app/composers/RefineComposer.php <?php namespace composers; use Input; use Category; class RefineComposer { public function compose($view) { $radiuses = array( '1' => '1 mile', '5' => '5 miles', '10' => '10 miles', '15' => '15 miles', '25' => '25 miles', '201' => 'anywhere' ); $selectedRadius = Input::get('radius'); $types = Category::lists('name', 'id'); $selectedCategory = Input::get('category'); $selectedLocation = Input::get('location'); $types = [null => 'Im looking for...'] + $types; $view->with('radiuses', $radiuses) ->with('selectedRadius', $selectedRadius) ->with('selectedCategory', $selectedCategory) ->with('selectedLocation', $selectedLocation) ->with('types', $types); } }<file_sep>/app/config/image.php <?php return array( // Maximum image size of 2Mb 'max_size' => 2000000, );<file_sep>/public/assets/jsdev/prototypes/10-modal-cropper.js function imageCropper(elem){ this.elem = elem; this.modal = this.elem.find(".modal-cropper"); this.modalImage = this.modal.find("#uploaded-image"); this.uploadForm = this.elem.find("#image-upload-form"); this.galleryRow = $('#gallery-row'); this.galleryImage = ''; this.galleryValue = ''; this.croppedForm = this.modal.find("#cropped-image"); this.uploadButton = this.modal.find("input[name='file']"); this.imageSelect = this.uploadForm.find(".image-select"); this.image = this.modal.find(".bootstrap-modal-cropper img"); this.xInput = this.modal.find("input[name='x']"); this.yInput = this.modal.find("input[name='y']"); this.wInput = this.modal.find("input[name='width']"); this.hInput = this.modal.find("input[name='height']"); this.bwInput = this.modal.find("input[name='box_width']"); this.bhInput = this.modal.find("input[name='box_height']"); this.originalData = {}; this.ratio = ( this.modal.data('ratio')) ? this.modal.data('ratio') : 2.35; this.imageType = (this.ratio == 2.35 )? '/cover_' : '/medium_'; this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.bw = 0; this.bh = 0; this.init(); } imageCropper.prototype = { constructor: imageCropper, init: function(){ if(typeof(window.FileReader)!="undefined"){ $('#get_file_content').closest('form').remove(); } else{ $('#image-select').remove(); } this.addListener(); if($('input[name="cloned"]').val() != ''){ this.galleryImage = '<img src="/'+$('input[name="cloned"]').val()+'" alt="cover photo" class="img-responsive">'; } }, addListener: function () { $(document).on("click", '.image-select' ,$.proxy(this.upload, this)); this.uploadButton.on("change", $.proxy(this.getImage, this)) this.galleryRow.on("change", $.proxy(this.updatedRow, this)) this.modalImage.on("load", $.proxy(this.openModal, this)) this.modal.on("shown.bs.modal", $.proxy(this.crop, this)); this.modal.on("hidden.bs.modal", $.proxy(this.destroyCrop, this)); this.croppedForm.on("submit", $.proxy(this.submitForm, this)); $(document).on("click", '.gallery-option' ,$.proxy(this.clickGalleryOption, this)); $(document).on("change", '#get_file_content' ,$.proxy(this.getFileContent, this)); }, upload: function(e){ this.uploadButton.trigger('click'); }, getImage: function(e){ self = this; if (e.target.files && e.target.files[0]) { var reader = new FileReader(); reader.onload = function (e) { self.modalImage.attr('src', e.target.result); } reader.readAsDataURL(e.target.files[0]); } }, getFileContent : function(e){ var form = $(e.target).closest('form'), file = $(e.target), data = new FormData(form[0]), self = this; console.log(file.val()); $.ajax(form.attr('action'), { type: "post", data: data, processData: false, contentType: false, beforeSend: function () { }, success: function (data) { file.addClass('opacity'); self.modalImage.attr('src','/'+data.file); self.modal.find("input[name='file']").replaceWith(file); self.modal.find("input[name='deletion']").val(data.file); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); } }); }, openModal: function(){ this.modal.modal('show'); }, closeModal: function(){ this.modal.modal('hide'); }, crop: function(){ self = this; this.image = this.modal.find(".bootstrap-modal-cropper img"); this.image.cropper({ data: this.originalData, aspectRatio: this.ratio, done: function(data) { self.x = data.x; self.y = data.y; self.w = data.width; self.h = data.height; } }); }, destroyCrop: function(){ this.image.cropper("destroy"); self.modalImage.attr('src',null); this.uploadButton.val(''); if(self.modal.find('#get_file_content').length){ $('#no-file-reader-form').append(self.modal.find('#get_file_content').removeClass('opacity')); } }, submitForm: function(e){ e.preventDefault(); this.bw = this.image.cropper("getImageData").width; this.bh = this.image.cropper("getImageData").height; this.xInput.val(this.x); this.yInput.val(this.y); this.wInput.val(this.w); this.hInput.val(this.h); this.bwInput.val(this.bw); this.bhInput.val(this.bh); this.ajaxUpload(); }, ajaxUpload: function () { var url = this.croppedForm.attr("action"), data = new FormData(this.croppedForm[0]), self = this; $.ajax(url, { type: "post", data: data, processData: false, contentType: false, beforeSend: function () { self.croppedForm.find("input[type='submit']").prop('disabled', true).after('<span id="cropping-loading" class="icon icon-loading ml10"></span>'); self.image.cropper("disable"); }, success: function (data) { self.galleryValue = data.filename; self.galleryImage = '<img src="/'+data.folder + self.imageType +data.filename +'" alt="cover photo" class="img-responsive">'; self.croppedForm.find("input[type=submit]").prop('disabled', false); self.uploadForm.append(self.galleryImage); if( $('#first-img')){ $('#first-img').html(self.galleryImage); $('#first-img').append('<div class="holder-add-more"><span class="image-select icon-lg icon-md-camera hover"></span>'); } if($('input[name="gallery_image"]').length){ $('input[name="gallery_image"]').val(false); } $('input[name="image"]').val(self.galleryValue).trigger('change'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { $('#cropping-loading').remove(); self.closeModal(); } }); }, clickGalleryOption: function(e){ this.galleryValue = $(e.target).data("id"); this.uploadForm.append('<img src="'+$(e.target).data("large")+'" alt="cover image" class="img-responsive">'); $('input[name="image"]').val(this.galleryValue).trigger('change'); if($('input[name="gallery_image"]').length){ $('input[name="gallery_image"]').val(true); } }, updatedRow: function(){ if(this.galleryImage != '' && this.galleryImage != '<img src="/undefined" alt="cover photo" class="img-responsive">') { $('#first-img').html(this.galleryImage); $('#first-img').append('<div class="holder-add-more"><span class="image-select icon-lg icon-md-camera hover"></span>'); } } }<file_sep>/app/views/admin/yukonhtml/index.php <?php define("admin_access", true); //include('php/variables.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Yukon Admin HTML <?php echo $admin_version; ?>(<?php echo $sPage; ?>)</title> <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <!-- favicon --> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <!-- bootstrap framework --> <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <!-- icon sets --> <!-- elegant icons --> <link href="assets/icons/elegant/style.css" rel="stylesheet" media="screen"> <!-- elusive icons --> <link href="assets/icons/elusive/css/elusive-webfont.css" rel="stylesheet" media="screen"> <!-- flags --> <link rel="stylesheet" href="assets/icons/flags/flags.css"> <?php if (isset($css)) {?> <!-- page specific stylesheets --> <?php echo $css; }?> <!-- select2 --> <link href="assets/lib/select2/select2.css" rel="stylesheet" media="screen"> <!-- google webfonts --> <link href='http://fonts.googleapis.com/css?family=Open+Sans&amp;subset=latin,latin-ext' rel='stylesheet' type='text/css'> <!-- main stylesheet --> <link href="assets/css/main.css" rel="stylesheet" media="screen" id="mainCss"> <!-- moment.js (date library) --> <script src="assets/js/moment-with-langs.min.js"></script> </head> <body class="side_menu_active side_menu_expanded fx_width"> <div id="page_wrapper"> <?php include('php/pages/partials/header.blade.php')?> <?php include('php/pages/partials/breadcrumbs.php')?> <!-- main content --> <div id="main_wrapper"> <div class="container-fluid"> <?php if (isset($includePage)) { echo($includePage); } else { echo '<div class="alert alert-danger text-center">Page not found</div>'; } ?> </div> </div> <?php include('php/pages/partials/side_menu.php')?> </div> <!-- jQuery --> <script src="assets/js/jquery.min.js"></script> <!-- jQuery Cookie --> <script src="assets/js/jqueryCookie.min.js"></script> <!-- Bootstrap Framework --> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <!-- retina images --> <script src="assets/js/retina.min.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <!-- Yukon Admin functions --> <script src="assets/js/yukon_all.js"></script> <?php if (isset($script)) { ?> <!-- page specific plugins --> <?php echo $script; }; ?> <?php include('php/pages/partials/style_switcher.php')?> <script> var DEBUG_APP = <?=getenv('DEBUG_APP') ? 'true' : 'false'?>; var BASE_URL = '<?=getenv('APP_URL')?>'; </script> <script src="/assets/application.js?version=2.9"></script> <!-- select2 --> <script src="assets/lib/select2/select2.min.js"></script> <script> function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null } var category_updates = {}; var urlParams = {}; urlParams.status = getURLParameter('status'); urlParams.search = getURLParameter('search'); urlParams.order = getURLParameter('order'); var pageName = (window.location.href.split('/').pop()).split('?')[0]; $( document ).ready( function(){ $('#select_user_type').change(function(){ window.location.href = $(this).val(); }); $('#select_category_type').change(function(){ window.location.href = $(this).val(); }); $('#select_status').change(function(){ urlParams.status = $(this).val(); reloadWithParams(); }); initPut('{"selector": ".reset_password"}'); initPut('{"selector": ".unapprove_trainer"}'); $('#user_list li').click(function(){ $(this).find('.user-table').slideToggle(500); }); /* $('.user-table tr').click(function(e){ e.stopPropagation(); trace($(this).attr('id')); });*/ // ----- TRAINERS, GROUPS ----- $('#search button').click(function(e){ e.stopPropagation(); urlParams.search = $('#search input').val(); reloadWithParams(); window.location.href = linkTo; }); // ----- SUBCATEGORIES ----- $('#category_list select').change(function(){ //trace( $(this).val() ); //trace( $(this).attr('name') ); var row = $(this).closest('tr'); var sub = row.data('subid'); var selects = row.find('select'); var values = ''; for (var i=0; i<selects.length; i++) { //trace(selects[i].value); if (i!=0) values += '_'; values += selects[i].value; } category_updates[sub] = values ; var output = ''; for (var key in category_updates) { output = output + key+'='+category_updates[key]+'-'; } $('#update_categories').val(output); console.debug(output); }); //yukon_select2.p_forms_extended(); $('.associations_label').click(function(e){ var input = $(this).next('input'); if(input.length) { var update_associations = $('#update_associations'); update_associations.val(update_associations.val() + input.data('id')+','); trace(update_associations.val()); $(this).hide(); input.show(); input.val(input.data('value')); input.select2({ placeholder: "Type here...", tags:[], tokenSeparators: [",", " "] }); //input.focus(); } }); // ----- CATEGORIES ----- $('.categories_label').click(function(e){ //trace(category_list); var category_array = $.parseJSON(category_list); var input = $(this).next('input'); if(input.length) { var update_categories = $('#update_categories'); update_categories.val(update_categories.val() + input.data('id')+','); //trace(update_categories.val()); $(this).hide(); input.show(); input.val(input.data('value')); input.select2({ placeholder: "Type here...", tags:category_array, tokenSeparators: [","] }); //input.focus(); } }); $('.featured').click(function(e){ var update_categories = $('#update_categories'); update_categories.val(update_categories.val() + $(this).data('id')+','); }); $('#sort_by_name').click(function(e){ urlParams.order = 'name'; reloadWithParams(); }); $('#sort_by_id').click(function(e){ urlParams.order = 'id'; reloadWithParams(); }); initPut('{"selector": "#edit_subcategories"}'); initPut('{"selector": "#add_subcategory"}'); initPut('{"selector": "#edit_classes"}'); }); function reloadWithParams() { var linkTo = pageName+'?' + (urlParams.status ? 'status='+urlParams.status+'&' : '') + (urlParams.order ? 'order='+urlParams.order+'&' : '') + (urlParams.search ? 'search='+urlParams.search+'' : ''); window.location.href = linkTo; } </script> </body> </html> <file_sep>/app/assets/javascripts/evercisegroups.js // evercisegroups.js function initEvercisegroups() { trace('initEvercisegroups'); if(typeof laracasts !== 'undefined') { if(typeof laracasts.categoryDescriptions !== 'undefined') { categoryDescriptions = JSON.parse(laracasts.categoryDescriptions); // TODO - This is here ready to add the little rollover descriptions to the category selections. } } // create a new evercisegroup $('.hub-block #delete_group').click(function(){ var url = $(this).attr('href'); $.ajax({ url: url, type: 'POST', data: '', dataType: 'html' }) .done( function(data) { trace(data); $('.mask').show(); $('.container').append(data); bindDelete(); } ); return false; }); bindCalendar(); // Also doubles as undo function $(document).on('click','.session-delete', function(){ var url = $(this).attr('href'); var EGindex = $(this).attr('EGindex'); //trace('EGindex: '+EGindex); var id = $(this).attr('id'); var undo = $(this).data('undo'); //trace("deleting session.. "+url); $.ajax({ url: url, type: 'DELETE', dataType: 'html', data: 'EGindex='+EGindex+'&undo='+undo }) .done( function(data) { //$('#date-list-'+EGindex).html(data); var details = $.parseJSON(data); if (details.mode == 'delete') { trace(details.user_id); $('#'+id).parent().addClass('session-undo'); $('#'+id).html('undo'); $('#'+id).data('undo', data); } else if (details.mode == 'undo') { $('#'+id).parent().removeClass('session-undo'); $('#'+id).attr('href', 'sessions/'+details.session_id); $('#'+id).html('x'); } else if (details.mode == 'hack') { trace('Did your mother never tell you not to touch over peoples stuff'); } //initChart('total-members-bookings-'+EGindex); // This was causing an error } ); return false; }); } registerInitFunction('initEvercisegroups'); function initEvercisegroupsShow() { $('.mail_all').click(function(){ // If no members, do not open mail dialogue if ($(this).closest('ul').find('.session-members-row').length === 0) return false; var url = this.href; $.ajax({ url: url, type: 'GET', dataType: 'html' }) .done( function(data) { //trace('id: '+ data); $('.mask').show(); $('.container').append(data); } ); return false; }); } registerInitFunction('initEvercisegroupsShow'); function bindDelete() { $('#delete_evercisegroup').click(function(){ var url = $(this).attr('href'); $.ajax({ url: url, type: 'DELETE', dataType: 'html' }) .done( function(data) { trace(data); //$('.mask').show(); //$('.container').append(data); var details = $.parseJSON(data); if (details.mode == 'hack') { loaded(); alert('the class you are trying to delete does not belong to you'); }else{ setTimeout(function() { window.location.href = details.url; }, 300); } } ); return false; }); } function bindCalendar() { // Bring up new session view, based on date selected $('#calendar .calendar-row a').click(function(){ var year = $('#year').val(); var month = $('#month').val(); var href = $(this).attr('href'); var date = href.replace('day_', ''); var evercisegroupId = $('#evercisegroupId').val(); var originalPrice = $('#originalprice').val(); //var completeDate = date+'-'+month+'-'+year; var session_class_name = $('#evercisegroupName').val(); var evercisegroupDuration = $('#evercisegroupDuration').val(); var url = 'sessions/create'; $.ajax({ url: url, type: 'GET', data: 'year='+year+'&month='+month+'&date='+date+'&evercisegroupId='+evercisegroupId+'', dataType: 'html' }) .done( function(data) { $('.mask').show(); $('.container').append(data); // $('#s-year').val(year); // $('#s-month').val(month); // $('#s-date').val(date); //$('#s-evercisegroupId').val(evercisegroupId); //$('#s-evercisegroupDuration').val(evercisegroupDuration); //$('#price').val(originalPrice); //$('#complete-date span').html(completeDate); //$('#session-class-name span').html(session_class_name); //$('#session-class-price span').html(originalPrice); session_overview(); } ); return false; }); // Change month of calendar $('#calendar .calendar-head a').click(function(){ var monthyear = this.id.split("?")[1]; var year = monthyear.split("&")[0].split("=")[1]; var month = monthyear.split("&")[1].split("=")[1]; //trace("ID: "+month); $('#month').val(month); $('#year').val(year); var url = 'widgets/calendar'; $.ajax({ url: url, type: 'POST', data: 'month='+month+'&year='+year, dataType: 'html' }) .done( function(data) { //trace('id: '+ data); $('#calendar-wrapper').html(data); bindCalendar(); } ); return false; }); } //1400235562274 function initJoinEvercisegroup(params) { if (JSON.parse(params) != '1') { var params = JSON.parse(params); var sessions = params.sessions; var total = params.total; var price = params.price; }else{ var sessions = []; var total = 0; var price = 0; } /* $(document).on('click','.btn-join-session,.undo-btn-reverse',function(){ var sessionId = $(this).data('session'); var sessionPrice = $(this).data('price'); sessions.push(sessionId); var session = JSON.stringify(sessions); // add session id's to hidden field in form $('#session-ids').val(session); // change button to undo button depending on existing button if($(this).attr('class') == 'undo-btn-reverse'){ $(this).replaceWith('<button data-price="'+sessionPrice+'" data-session="'+sessionId+'" class="btn-cancel-session btn btn-red">Cancel</button>'); }else{ $(this).replaceWith('<button class="undo-btn" data-price="'+sessionPrice+'" data-session="'+sessionId+'" ><img src="/img/undo.png" alt="undo"><span>Undo</span></button>'); } ++total; price = price + parseFloat(sessionPrice); $('#total-sessions').html(total); $('#total-price').html(price); if (total > 0) { $('#session-checkout').removeClass('disabled'); }; });*/ $(document).on('click','.btn-join-session,.undo-btn-reverse',function(){ var sessionId = $(this).data('session'); var sessionPrice = $(this).data('price'); // add session id's to hidden field in form $('#session-id').val(sessionId); // change button to undo button depending on existing button if($(this).attr('class') == 'undo-btn-reverse'){ $(this).replaceWith('<button data-price="'+sessionPrice+'" data-session="'+sessionId+'" class="btn-cancel-session btn btn-red">Cancel</button>'); }else{ $(this).replaceWith('<button class="undo-btn" data-price="'+sessionPrice+'" data-session="'+sessionId+'" ><img src="/img/undo.png" alt="undo"><span>Undo</span></button>'); } ++total; price = price + parseFloat(sessionPrice); $('#total-sessions').html(total); $('#total-price').html(price); if (total > 0) { $('#session-checkout').removeClass('disabled'); }; $('#add-to-cart').submit(); }); $(document).on('click','.undo-btn' , function(){ var sessionId = $(this).data('session'); var sessionPrice = $(this).data('price'); $(this).replaceWith('<button data-price="'+sessionPrice+'" data-session="'+sessionId+'" class="btn-join-session btn btn-yellow">Join Session</button>') sessions = jQuery.grep(sessions, function(value) { return value != sessionId; }); var session = JSON.stringify(sessions); // add session id's to hidden field in form $('#session-ids').val(session); --total; price = price - parseFloat(sessionPrice); $('#total-sessions').html(total); $('#total-price').html(price); if (total == 0) { $('#session-checkout').addClass('disabled'); }; }); $(document).on('click','.btn-cancel-session' , function(){ var sessionId = $(this).data('session'); var sessionPrice = $(this).data('price'); sessions = jQuery.grep(sessions, function(value) { return value != sessionId; }); var session = JSON.stringify(sessions); // add session id's to hidden field in form $('.session-ids').val(session); --total; price = price - parseFloat(sessionPrice); evercoin = $('#evercoin-redeemed').html(); trace(evercoin); $('#cart-row-'+sessionId).remove(); $('#sub-total').html(price); $('#balance-to-pay').html(price - evercoin); }); $(document).on('click','#expand-sessions' , function(){ $(this).find('.extra').toggleClass('hidden'); $('.session-list-row.extra').toggleClass('hidden'); /* remove click event so that the offsets dont stack for the page scrolling */ $('a[href*=#]').each(function() { $(this).unbind('click'); }); initScrollAnchor(); }); $('#join-sessions').submit(function(event){ event.preventDefault(); var url = '/auth/checkout'; $.ajax({ url: url, type: 'POST', dataType: 'html', data: $( this ).serialize() }) .done( function(data) { try { var parsedData = JSON.parse(data); trace(parsedData.status); if (parsedData.status == 'logged_in') { $(event.currentTarget).unbind('submit'); event.currentTarget.submit(); } } catch(e) { $('.mask').show(); $('.lower_footer').append(data); login(); } } ); return false; }); } registerInitFunction('initJoinEvercisegroup'); function initClassBlock(){ $(document).on('click', '#more-sessions', function(){ $(this).closest('div').find('.future-session-list').slideToggle(300); $(this).closest('div').find('#block-body-wrap').slideToggle(300); $(this).toggleClass('active'); }) } registerInitFunction('initClassBlock'); <file_sep>/app/views/admin/yukonhtml/php/pages/components-gallery.php <div class="gallery_filer"> <div class="row"> <div class="col-sm-6"> <input class="form-control" type="text" placeholder="Filter by name, tag etc..." id="gallery_search" /> <span class="help-block">Eg. business, creative, photoshop</span> </div> </div> </div> <hr/> <ul class="gallery_grid"> <?php for($i=1;$i<=20;$i++) { ?> <li> <a href="assets/img/gallery/Image0<?php if($i<10) echo '0'; echo $i; ?>.jpg" class="img_wrapper" title="<?php echo $faker->sentence(4); ?>"> <img src="assets/img/gallery/Image0<?php if($i<10) echo '0'; echo $i; ?>.jpg" alt=""/> <span class="gallery_image_zoom"> <span class="arrow_expand"></span> </span> <span class="hide gallery_image_tags"> <?php $rand_tags = rand(2,4); for($ii=1;$ii<=$rand_tags;$ii++) { ?> <span><?php echo $tags[array_rand($tags)]; if($ii < $rand_tags) echo ',';?></span> <?php }; ?> </span> </a> </li> <?php }; ?> </ul> <file_sep>/app/composers/UsersResetPasswordComposer.php <?php namespace composers; use JavaScript; class UsersResetPasswordComposer { public function compose($view) { JavaScript::put( [ 'initPut' => json_encode(['selector' => '#passwords_reset']) ] ); // Initialise init put for submission. } }<file_sep>/app/models/Search.php <?php use Carbon\Carbon; /** * Class Evercisegroup */ class Search { /** * @var */ protected $elastic; /** * @var */ protected $evercisegroup; /** * @var */ protected $log; /** * @param $elastic * @param $evercisegroup * @param $log */ public function __construct($elastic, $evercisegroup, $log) { $this->elastic = $elastic; $this->evercisegroup = $evercisegroup; $this->log = $log; $this->cart = EverciseCart::getCart(); $this->cart_items = []; foreach ($this->cart['sessions_grouped'] as $key_id => $val) { $this->cart_items[$key_id] = $val['qty']; } } /** * Get results for a specific Place * @param Place $area * @param array $params * @param bool $all * @return mixed */ public function getMapResults(Place $area, $params = [], $all = FALSE) { /** Set Defaults */ $defaults = [ 'radius' => $params['radius'], 'size' => $params['size'], 'from' => $params['from'], 'fields' => ['id', 'venue.id', 'venue.name', 'venue.lat', 'venue.lon'] ]; foreach ($defaults as $key => $val) { if (!isset($params[$key])) { $params[$key] = $val; } } $results = $this->elastic->searchEvercisegroups($area, $params); return $this->formatMapResults($results, $area); } /** * Get results for a specific Place * @param Place $area * @param array $params * @param bool $all * @return mixed */ public function getResults(Place $area, $params = [], $dates = FALSE) { /** Set Defaults */ $defaults = [ 'radius' => $params['radius'], 'size' => $params['size'], 'from' => $params['from'] ]; foreach ($defaults as $key => $val) { if (!isset($params[$key])) { $params[$key] = $val; } } $results = $this->elastic->searchEvercisegroups($area, $params, $dates); if ($dates) { return $this->formatDates($results, $area); } return $this->formatResults($results, $area, $params); } /** * Get a single Result from Elastic * @param int $id * @return mixed */ public function getSingle($id = 0) { $results = $this->elastic->getSingle($id); return $this->formatResults($results, FALSE); } /** * Format Results * @param $results * @return mixed */ public function formatResults($results, $area = FALSE, $params) { $all_results = []; foreach ($results->hits as $r) { $all_results[] = $this->formatSingle($r, $area, $params); } $results->hits = $all_results; return $results; } public function formatDates($results) { $all_dates = []; $now = date('Y-m-d H:i:s'); foreach ($results->hits as $r) { $fields = (array)$r->fields; foreach ($fields['futuresessions.date_time'] as $date) { $short_date = date('Y-m-d', strtotime($date)); if ($short_date > date('Y-m-d', strtotime('+2 months')) || $short_date < date('Y-m-d')) { continue; } if (!isset($all_dates[$short_date])) { $all_dates[$short_date] = []; } if (!in_array($fields['id'][0], $all_dates[$short_date])) { if ($date > $now) { array_push($all_dates[$short_date], $fields['id'][0]); } } } } ksort($all_dates); foreach ($all_dates as $date => $ids) { $all_dates[$date] = count($ids); } return $all_dates; } /** * Format Results * @param $results * @return mixed */ public function formatMapResults($results) { $mapResults = []; foreach ($results->hits as $r) { $fields = (array)$r->_source; $id = $fields['id']; $venue_id = $fields['venue_id']; $mapResults[$venue_id][$id]['location'] = [$fields['venue']->lon => $fields['venue']->lat]; $mapResults[$venue_id][$id]['classes'][] = $id; $mapResults[$venue_id][$id]['total'] = count($mapResults[$venue_id][$id]['classes']); } return $mapResults; } /** * Format a single Result * @param $row * @return mixed */ public function formatSingle($row, $area, $params = []) { $not_needed = [ 'global' => [ 'default_duration', 'published', 'created_at', 'updated_at', 'venue_id', 'title', 'gender' ], 'user' => ['id', 'display_name', 'first_name', 'last_name', 'email', 'image', 'phone'], 'venue' => [ 'image'], 'ratings' => ['user_id', 'comment'] ]; $row->_source->score = $row->_score; /** UNSET everything else that we don't need! */ foreach ($not_needed['global'] as $n) { if (isset($row->_source->{$n})) { unset($row->_source->{$n}); } } foreach ($not_needed['user'] as $n) { if (isset($row->_source->user->{$n})) { unset($row->_source->user->{$n}); } } foreach ($not_needed['venue'] as $n) { if (isset($row->_source->venue->{$n})) { unset($row->_source->venue->{$n}); } } foreach ($not_needed['ratings'] as $n) { if (isset($row->_source->ratings->{$n})) { unset($row->_source->ratings->{$n}); } } $times = []; foreach ($row->_source->futuresessions as $key => $s) { $date = new Carbon($s->date_time); $row->_source->futuresessions[$key]->date_time = $date->format('M jS, g:ia'); if (!empty($params['date'])) { if ($params['date'] == $date->format('Y-m-d') && !isset($times[$date->format('g:ia')])) { $times[$date->format('g:ia')] = $s->id; } } } $row->_source->times = $times; /** Add Lat and Lon to the venue */ if (!empty($row->_source->venue->location->geohash) && $area) { try { $decoded = $this->elastic->decodeLocationHash($row->_source->venue->location->geohash); $row->_source->venue->lat = $decoded['latitude']; $row->_source->venue->lng = $decoded['longtitude']; if (!empty($row->sort[0])) { $row->_source->distance = round($row->sort[0], 2); } else { $row->_source->distance = round($this->getDistance($decoded['latitude'], $decoded['longtitude'], $area->lat, $area->lng, 'M'), 2); } } catch (Exception $e) { /** We don't have a location for this guys.. lets just skip */ $this->log->error('Missing LOCATION for ' . $row->id); $row->_source->venue->lat = ''; $row->_source->venue->lng = ''; $row->_source->distance = ''; } } /** Set Default Amount*/ $i = 0; foreach ($row->_source->futuresessions as $s) { if (!empty($this->cart_items[$s->id])) { $row->_source->futuresessions[$i]->default_tickets = $this->cart_items[$s->id]; } $i++; } if (!empty($params['clean'])) { // unset($row->_source->futuresessions); } return $row->_source; } private function getDistance($lat1 = FALSE, $lon1 = FALSE, $lat2 = FALSE, $lon2 = FALSE, $unit = 'K') { if (!$lat1 || !$lon1 || !$lat2 || !$lon2) { return ''; } $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else { if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } } } /** * Clean the results for the MAP * @param $results * @return array */ public function cleanMapResults($results) { $mapResult = []; $not_needed = [ 'global' => [ 'default_duration', 'published', 'created_at', 'updated_at', 'venue_id', 'title', 'gender' ], 'user' => ['id', 'display_name', 'first_name', 'last_name', 'email', 'image', 'phone'], 'venue' => ['id', 'address', 'postcode', 'location', 'image'], 'ratings' => ['user_id', 'comment'] ]; foreach ($results->hits as $k => $row) { /** UNSET everything else that we don't need! */ foreach ($not_needed['global'] as $n) { if (isset($row->{$n})) { unset($row->{$n}); } } foreach ($not_needed['user'] as $n) { if (isset($row->user->{$n})) { unset($row->user->{$n}); } } foreach ($not_needed['venue'] as $n) { if (isset($row->venue->{$n})) { unset($row->venue->{$n}); } } foreach ($not_needed['ratings'] as $n) { if (isset($row->ratings->{$n})) { unset($row->ratings->{$n}); } } $futuresessions = []; if (count($row->futuresessions) > 4) { $total = 0; foreach ($row->futuresessions as $s) { if ($total > 3) { $row->futuresessions = $futuresessions; break; } if ($s->remaining > 0) { $futuresessions[] = $s; $total++; } } } $mapResult[] = $row; } return $mapResult; } /** * Clean a Single Results * @param $results * @return array */ public function cleanSingleResults($results) { $mapResult = []; $not_needed = [ 'global' => [ 'created_at', 'updated_at', 'venue_id', ], 'venue' => ['id', 'address', 'postcode', 'location', 'image'], 'ratings' => ['user_id'] ]; foreach ($results->hits as $row) { /** UNSET everything else that we don't need! */ foreach ($not_needed['global'] as $n) { if (isset($row->{$n})) { unset($row->{$n}); } } foreach ($not_needed['venue'] as $n) { if (isset($row->venue->{$n})) { unset($row->venue->{$n}); } } foreach ($not_needed['ratings'] as $n) { if (isset($row->ratings->{$n})) { unset($row->ratings->{$n}); } } $mapResult[] = $row; } return $mapResult; } }<file_sep>/app/models/Historytype.php <?php /** * Class Historytype */ class Historytype extends \Eloquent { /** * @var array */ protected $fillable = []; }<file_sep>/app/controllers/PaypalPaymentController.php <?php use Omnipay\Omnipay; class PaypalPaymentController extends BaseController { /* * Create payment using credit card * url:payment/create */ public function create() { /* get session ids from Cart*/ $cartRows = Cart::content(); foreach ($cartRows as $row) { array_push($sessionIds, $row->options->sessionId); } //$sessionIdsRaw = Input::get('session-ids'); //$sessionIds = json_decode(Input::get('session-ids'), true); Session::put('sessionIds', $sessionIds); /* create confirmation view */ $evercisegroupId = Input::get('evercisegroup-id'); Session::put('evercisegroupId', $evercisegroupId); //return var_dump(Session::get('sessionIds')); $evercisegroup = Evercisegroup::with([ 'evercisesession' => function ($query) use (&$sessionIds) { $query->whereIn('id', $sessionIds); } ], 'evercisesession')->find($evercisegroupId); //Make sure there is not already a matching entry in sessionmembers if (Sessionmember::where('user_id', $this->user->id)->whereIn('evercisesession_id', $sessionIds)->count()) { throw new Exception('User ' . $this->user->id . ' has already joined session '); } $total = 0; $price = 0; foreach ($evercisegroup->evercisesession as $key => $value) { ++$total; $price = $price + $value->price; } $amountToPay = (NULL !== Session::get('amountToPay')) ? Session::get('amountToPay') : $price; $evercoin = Evercoin::where('user_id', $this->user->id)->first(); if ($amountToPay + Evercoin::evercoinsToPounds($evercoin->balance) < $price) { throw new Exception('User has not got enough evercoins to make this transaction. required:' . $amountToPay); } $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('<PASSWORD>')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); $response = $gateway->purchase( [ 'cancelUrl' => URL::to('/'), 'returnUrl' => URL::to('payment', [$evercisegroupId]), 'amount' => $amountToPay, 'currency' => 'GBP' ] )->setItems([ ['name' => 'item1', 'quantity' => 2, 'price' => '10.00'], ['name' => 'item2', 'quantity' => 1, 'price' => '50.00'] ])->send(); $response->redirect(); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { /* get session ids from Cart*/ $cartRows = Cart::content(); foreach ($cartRows as $row) { array_push($sessionIds, $row->options->sessionId); } /* create confirmation view */ $evercisegroupId = $id; //return var_dump(Session::get('sessionIds')); $evercisegroup = Evercisegroup::with([ 'evercisesession' => function ($query) use (&$sessionIds) { $query->whereIn('id', $sessionIds); } ], 'evercisesession')->find($evercisegroupId); //Make sure there is not already a matching entry in sessionmembers if (Sessionmember::where('user_id', $this->user->id)->whereIn('evercisesession_id', $sessionIds)->count()) { throw new Exception('User ' . $this->user->id . ' has already joined session '); } $total = 0; $price = 0; foreach ($evercisegroup->evercisesession as $key => $value) { ++$total; $price = $price + $value->price; } $amountToPay = (NULL !== Session::get('amountToPay')) ? Session::get('amountToPay') : $price; $evercoin = Evercoin::where('user_id', $this->user->id)->first(); if ($amountToPay + Evercoin::evercoinsToPounds($evercoin->balance) < $price) { throw new Exception('User has not got enough evercoins to make this transaction. required:' . $amountToPay); } $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername(getenv('PAYPAL_USER')); $gateway->setPassword(getenv('<PASSWORD>')); $gateway->setSignature(getenv('PAYPAL_SIGNATURE')); $gateway->setTestMode(getenv('PAYPAL_TESTMODE')); try { $response = $gateway->completePurchase( [ 'amount' => $amountToPay, 'currency' => 'GBP', 'Description' => $evercisegroup->name ] )->send(); } catch (Exception $e) { return $e; } //return var_dump($response); if ($response->isSuccessful()) { $data = $response->getData(); // this is the raw response object //return var_dump($data); return Redirect::to('sessions/' . $evercisegroupId . '/pay') ->with('token', $data['TOKEN']) ->with('transactionId', $data['PAYMENTINFO_0_TRANSACTIONID']) ->with('payerId', $data['PAYMENTINFO_0_SECUREMERCHANTACCOUNTID']) ->with('paymentMethod', 'PayPal_Express'); //return Redirect::action('SessionsController@payForSessions'); } else { return var_dump($response); } } }<file_sep>/public/assets/jsdev/prototypes/39-category-select.js function categoryAutoComplete(select){ this.elem = select; this.inputBox = this.elem.parent().find('input'); this.selected = ''; this.form this.addListenners(); } categoryAutoComplete.prototype = { constructor : categoryAutoComplete, addListenners : function(){ this.elem.find('a').on('click', $.proxy(this.select, this)); }, select: function(e){ e.preventDefault(); var target = $(e.target); this.form = target.closest('form'); this.selected = target.text(); this.form.find('input[name="search"]').val( this.selected ); } }<file_sep>/app/database/seeds/FacilitiesTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class FacilitiesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('facilities')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Facility::create(array('name' => 'Air Conditioning', 'category' => 'Amenity', 'image' => 'air-conditioning.svg')); Facility::create(array('name' => 'Satellite TV', 'category' => 'Amenity', 'image' => 'sattelite-tv.svg')); Facility::create(array('name' => 'Cafe', 'category' => 'Amenity', 'image' => 'Cafe.svg')); Facility::create(array('name' => 'Wi-Fi', 'category' => 'Amenity', 'image' => 'wifi.svg')); Facility::create(array('name' => 'Parking', 'category' => 'Amenity', 'image' => 'parking.svg')); Facility::create(array('name' => 'Locker', 'category' => 'Amenity', 'image' => 'lockers.svg')); Facility::create(array('name' => 'Changing rooms', 'category' => 'Amenity', 'image' => 'changing-rooms.svg')); Facility::create(array('name' => 'Crèche', 'category' => 'Amenity', 'image' => 'creche.svg')); Facility::create(array('name' => 'No Contract', 'category' => 'Amenity', 'image' => 'no-contract.svg')); Facility::create(array('name' => 'Open 24/7', 'category' => 'Amenity', 'image' => 'open-247.svg')); Facility::create(array('name' => 'High tech equipment', 'category' => 'Amenity', 'image' => 'hi-tech.svg')); Facility::create(array('name' => 'Swimming Pool', 'category' => 'facility', 'image' => 'swimming.svg')); Facility::create(array('name' => 'Cardio Machines', 'category' => 'facility', 'image' => 'cardio.svg')); Facility::create(array('name' => 'Free weights', 'category' => 'facility', 'image' => 'free-weights.svg')); Facility::create(array('name' => 'Resistance Machines', 'category' => 'facility', 'image' => 'resistance-machine.svg')); Facility::create(array('name' => 'Sauna', 'category' => 'facility', 'image' => 'sauna.svg')); Facility::create(array('name' => 'Steam Room', 'category' => 'facility', 'image' => 'steam-room.svg')); Facility::create(array('name' => 'Sun beds', 'category' => 'facility', 'image' => 'sunbeds.svg')); Facility::create(array('name' => 'Jacuzzi', 'category' => 'facility', 'image' => 'jacuzzi.svg')); Facility::create(array('name' => 'Personal Training', 'category' => 'facility', 'image' => 'personal-training.svg')); Facility::create(array('name' => 'Spa facilities', 'category' => 'facility', 'image' => 'spa-facilities.svg')); Facility::create(array('name' => 'Mat area', 'category' => 'facility', 'image' => 'mat-area.svg')); Facility::create(array('name' => 'Towels', 'category' => 'facility', 'image' => 'towels.svg')); Facility::create(array('name' => 'PowerPlate', 'category' => 'facility', 'image' => 'powerplate.svg')); Facility::create(array('name' => 'Group Exercise Studio', 'category' => 'facility', 'image' => 'group-exercise.svg')); Facility::create(array('name' => 'Squash', 'category' => 'facility', 'image' => 'squash.svg')); Facility::create(array('name' => 'Punch Bags', 'category' => 'facility', 'image' => 'punch-bag.svg')); Facility::create(array('name' => 'Boxing Ring', 'category' => 'facility', 'image' => 'boxing-ring.svg')); Facility::create(array('name' => 'Massage', 'category' => 'facility', 'image' => 'massage.svg')); Facility::create(array('name' => 'Outdoor training area', 'category' => 'facility', 'image' => 'outdoor-training.svg')); Facility::create(array('name' => 'Olympic Weights', 'category' => 'facility', 'image' => 'olympic-weights.svg')); } }<file_sep>/app/assets/javascripts/widgets/map.js $(function () { var form_changed = false; $('#location').on('input', function () { $('#area_id').remove(); $('#search-by-location').prop('action', BASE_URL + 'uk'); form_changed = true; }); $('#search-by-location').submit(function (e) { $(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled"); if (!form_changed) { $(this.location).prop('disabled', true); $(this.area_id).remove(); } return true; }); }); function MapWidgetInit() { $(document).on('click', '#findLocation', function () { var pathname = (window.location.pathname.split('/dev/')).length > 1 ? '/dev' : ''; if (pathname != '') { var url = pathname + '/widgets/postGeo'; } else { var url = '/widgets/postGeo'; } var data = { street: $('#street').val(), city: $('#city').val(), post_code: $('#postcode').val() } $.ajax({ url: url, type: 'POST', data: data, dataType: 'json' }) .done( function (data) { $('#latbox').val(data.lat); $('#lngbox').val(data.lng); MapWidgetInit(); } ); return false; }) /* style the map */ var styles = [ { featureType: 'water', elementType: 'geometry.fill', stylers: [ {color: '#5bc0de'} ] }, { featureType: 'landscape.natural', elementType: 'all', stylers: [ {hue: '#00a651'}, {lightness: 0} ] } ]; /* set lat and long */ // Added these defaults to stop errors. (TRIS) var latitude = 0; var longitude = 0; if ($('#latbox').val() != 0) { latitude = $('#latbox').val(); longitude = $('#lngbox').val(); } else { if (typeof laracasts !== 'undefined') { if (typeof laracasts.latitude !== 'undefined') { latitude = laracasts.latitude; } if (typeof laracasts.latitude !== 'undefined') { longitude = laracasts.longitude; } } } ; var myLatLng = new google.maps.LatLng(latitude, longitude); if (document.getElementById("latbox")) document.getElementById("latbox").value = latitude; if (document.getElementById("lngbox")) document.getElementById("lngbox").value = longitude; // set ap options var mapOptions = { styles: styles, zoom: 14, center: new google.maps.LatLng(latitude, longitude), disableDefaultUI: true }; // set map var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // add marker trace('and now, mapPointerDraggable IS ' + mapPointerDraggable) var image = '/img/mapmark.png'; var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: image, draggable: mapPointerDraggable }); google.maps.event.addListener(marker, 'dragend', function (event) { document.getElementById("latbox").value = this.getPosition().lat(); document.getElementById("lngbox").value = this.getPosition().lng(); }); } function DiscoverMapWidgetInit() { /* style the map */ markerClusterer(); infoBubble(); var everciseGroups = JSON.parse(EVERCISE_GROUPS); var evercisePolygon = JSON.parse(EVERCISE_POLYGON); if (!everciseGroups.length) { $('#map-canvas').html('<h5>' + laracasts.zero_results + '</h5>'); } else { var styles = [ { featureType: 'water', elementType: 'geometry.fill', stylers: [ {color: '#5bc0de'} ] }, { featureType: 'landscape.natural', elementType: 'all', stylers: [ {hue: '#00a651'}, {lightness: 0} ] } ]; // set ap options var mapOptions = { styles: styles, zoom: 15, maxZoom: 16, center: new google.maps.LatLng(51.5143825, -0.11134839999999713), zoomControl: true, disableDefaultUI: true }; // set map var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //set up marker // multiple markers var clusterStyles = [ { textSize: '0', url: '/img/mapmarks_multi.png', height: 73, width: 48 } ]; var mcOptions = { gridSize: 8, maxZoom: 20, zoom: 15, styles: clusterStyles }; var markers = []; var bounds = new google.maps.LatLngBounds(); var icon = '/img/mapmark.png'; var infos = []; for (i = 0; i < everciseGroups.length; i++) { var evercisegroup = everciseGroups[i]; var venue = evercisegroup.venue; var sessions = evercisegroup.futuresessions; if (venue) { marker = new google.maps.Marker({ position: new google.maps.LatLng(venue.lat, venue.lng), icon: icon, map: map }); var latlng = new google.maps.LatLng( parseFloat(venue.lat), parseFloat(venue.lng)); bounds.extend(latlng); // bounds.extend(marker.position); var rating = 0; for (j = 0; j < evercisegroup.ratings.length; j++) { rating += evercisegroup.ratings[j].stars; } rating /= evercisegroup.ratings.length; //trace(i, true); var infowindow = new InfoBubble({ maxWidth: 350, minHeight: 130 }); //. var content = '<div class="info-window recommended-block"><div class="block-header"><a href="/evercisegroups/'+evercisegroup.id+'">'+evercisegroup.name+'</a></div><div class="recommended-info"><div class="recommended-aside"><p>'+getStars(rating)+'</p></div><div class="recommended-aside"><img class="date-icon" src="/img/date_icon.png"><span>'+moment(sessions[0].date_time).format('DD MMM YYYY - hh:mma')+'</span></div></div><div class="block-footer"><span>price: &pound;'+evercisegroup.default_price+'<span></div></div>'; var content = '<div class="info-window recommended-block">' + '<div class="block-header">' + '<a href="/evercisegroups/' + evercisegroup.id + '">' + evercisegroup.name + '</a>' + '</div>' + '<div class="recommended-info">' + '<div class="recommended-aside">' + '<p>' + getStars(rating) + '</p>' + '</div>' + '<div class="recommended-aside">' + '<img class="date-icon" src="/img/date_icon.png">' + '<span>' + moment(sessions[0].date_time).format('DD MMM YYYY - hh:mma') + '</span>' + '</div>' + '</div>' + '<div class="block-footer">' + '<span>price: &pound;' + evercisegroup.default_price + '<span>' + '</div>' + '</div>'; var group = everciseGroups[i].name; var venue = venue.name; google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow, group, venue) { return function () { /* close the previous info-window */ closeInfos(infos); infowindow.setContent(content); infowindow.open(map, this); /* keep the handle, in order to close it on next click event */ infos[0] = infowindow; }; })(marker, content, infowindow, group, venue)); marker.set('content', content); marker.set('name', group); marker.set('venue', venue); markers.push(marker); } map.setCenter(bounds.getCenter()); map.fitBounds(bounds); } var markerCluster = new MarkerClusterer(map, markers, mcOptions); google.maps.event.addListener(markerCluster, 'clusterclick', function (cluster) { var infobubble = new InfoBubble({ maxWidth: 350, tabClassName: 'bubbleTabs', minHeight: 130 }); //Get markers var markers = cluster.getMarkers(); content = ''; // create tab for each marker for (var i = 0; i < markers.length; i++) { content = ''; content += markers[i].get('content'); position = markers[i].getPosition(); name = markers[i].get('name').substring(0, 15); infobubble.addTab(name, content); } map.setCenter(cluster.getCenter()); closeInfos(infos); // set window position infobubble.setPosition(cluster.getCenter()); //closeInfos(infos); infobubble.close(); // open window infobubble.open(map); // keep the handle, in order to close it on next click event infos[0] = infobubble; }) if(evercisePolygon.length > 0) { var polygonCoords = []; for (i = 0; i < evercisePolygon.length; i++) { // Define the LatLng coordinates for the polygon's path. polygonCoords.push(new google.maps.LatLng(evercisePolygon[i][0], evercisePolygon[i][1])); } // Construct the polygon. var polygonMap = new google.maps.Polygon({ paths: polygonCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35 }); console.log(polygonCoords); polygonMap.setMap(map); } } } function closeInfos(infos) { if (infos.length > 0) { /* detach the info-window from the marker ... undocumented in the API docs */ infos[0].set("marker", null); /* and close it */ infos[0].close(); /* blank the array */ infos.length = 0; } } function MapWidgetloadScript(params) { params = params ? params : 1; var func = 'MapWidgetInit'; params = JSON.parse(params); trace('mapPointerDraggable IS ' + params.mapPointerDraggable); mapPointerDraggable = typeof params.mapPointerDraggable !== 'undefined' ? params.mapPointerDraggable : true; if (typeof params.discover !== 'undefined') { func = 'DiscoverMapWidgetInit'; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=DiscoverMapWidgetInit&libraries=places'; document.body.appendChild(script); } else { func = 'MapWidgetInit'; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=MapWidgetInit&libraries=places'; document.body.appendChild(script); } } //window.onload = MapWidgetloadScript; // Initialised from general.js using laracast. registerInitFunction('MapWidgetloadScript'); var mapPointerDraggable = false; function InitSearchForm() { $(".search-form").submit(function () { var isFormValid = true; $("input").each(function () { if ($.trim($(this).val()).length == 0) { $(this).addClass("highlight"); $(this).val($(this).data('default')); isFormValid = true; } else { $(this).removeClass("highlight"); } }); // if (!isFormValid) alert("Please fill in all the required fields (indicated by *)"); return isFormValid; }); } registerInitFunction('InitSearchForm'); function getStars(rating) { var returnHtml = ''; for (var i = 0; i < 5; i++) { if (i < Math.floor(rating)) returnHtml += '<img src="/img/yellow_star.png" class="star-icons" alt="stars">'; else if (i < Math.ceil(rating)) returnHtml += '<img src="/img/yellow_halfstar.png" class="star-icons" alt="stars">'; else returnHtml += '<img src="/img/yellow_emptystar.png" class="star-icons" alt="stars">'; } return returnHtml; }<file_sep>/app/database/migrations/2014_08_28_151818_edit_columns_tokens.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EditColumnsTokens extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement('ALTER TABLE tokens MODIFY COLUMN facebook varchar(255)'); DB::statement('ALTER TABLE tokens MODIFY COLUMN twitter varchar(255)'); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/models/Rating.php <?php /** * Class Rating */ class Rating extends \Eloquent { /** * @var array */ protected $fillable = array( 'id', 'user_id', 'sessionmember_id', 'session_id', 'evercisegroup_id', 'user_created_id', 'stars', 'comment' ); /** * @var string */ protected $table = 'ratings'; /* the user this rating belongs to */ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User', 'user_id'); } /* the user that rated this class */ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function rator() { return $this->belongsTo('User', 'user_created_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function evercisegroup() { return $this->belongsTo('evercisegroup', 'evercisegroup_id'); } }<file_sep>/app/controllers/ReferralsController.php <?php class ReferralsController extends \BaseController { /** * Store a newly created resource in storage. * * @return Response */ public function store() { $validator = Referral::validateEmail(Input::all()); if($validator->fails()) { return Response::json([ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]); } else { $refereeEmail = Input::get('referee_email'); $referralCode = Functions::randomPassword(20); $referralAndMessage = Referral::checkAndStore($this->user->id, $refereeEmail, $referralCode); if ($referralAndMessage['referral']) { event('referral.invite', [ 'email' => $refereeEmail, 'referralCode' => $referralCode, 'referrerName' => $this->user->first_name.' '.$this->user->last_name, 'referrerEmail' => $this->user->email, 'balanceWithBonus' => ($this->user->balance + Config::get('values')['milestones']['referral']['reward']) ]); } return Response::json( [ 'view' => View::make('v3.layouts.positive-alert')->with('message', $referralAndMessage['message'])->with('fixed', TRUE)->render(), 'referral' => $this->user->countPendingReferrals() ] ); } } // Accept a code from a friend referral public function submitCode($code) { Session::put('referralCode', $code); return Redirect::to('register'); } }<file_sep>/app/views/v3/angular/total-results.php <strong>Your search returned <span class="text-primary">{{ results }}</span> results</strong><file_sep>/app/models/ValidationHelper.php <?php /** * Class ValidationHelper * @package App\Models */ class ValidationHelper { /** * Forward to doRegex * * @param $attr * @param $value * @param $params * @return bool */ public static function hasRegex($attr, $value, $params) { return self::doRegex($attr, $value, $params, true); } /** * Forward to doRegex * * @param $attr * @param $value * @param $params * @return bool */ public static function hasNotRegex($attr, $value, $params) { return self::doRegex($attr, $value, $params, false); } /** * Check the Regex for the validation class * @param $attr * @param $value * @param $params * @param bool $has * @return bool * @throws InvalidArgumentException */ private static function doRegex($attr, $value, $params, $has = true) { if (!count($params)) { throw new \Exception('The has validation rule expects at least one parameter, 0 given.'); } foreach ($params as $param) { switch ($param) { case 'num': $regex = '/\pN/'; break; case 'letter': $regex = '/\pL/'; break; case 'lower': $regex = '/\p{Ll}/'; break; case 'upper': $regex = '/\p{Lu}/'; break; case 'special': $regex = '/[\pP\pS]/'; break; default: $regex = $param; } if($has && !preg_match($regex, $value)) { return false; } if(!$has && preg_match($regex, $value)) { return false; } } return true; } }<file_sep>/app/database/seeds/SpecialitiesTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class SpecialitiesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('specialities')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Speciality::create(array('name' => 'kickboxing', 'titles' => 'coach')); Speciality::create(array('name' => 'kickboxing', 'titles' => 'trainer')); Speciality::create(array('name' => 'yoga', 'titles' => 'guy')); Speciality::create(array('name' => 'yoga', 'titles' => 'girl')); Speciality::create(array('name' => 'yoga', 'titles' => 'trainer')); } }<file_sep>/app/cronjobs/SendReminderEmailsCron.php <?php namespace cronjobs; use Illuminate\Log\Writer; use Illuminate\Console\Application as Artisan; class SendReminderEmailsCron { private $log; /** * @var \Artisan */ private $artisan; public function __construct(Writer $log, Artisan $artisan) { $this->log = $log; $this->artisan = $artisan; } function run() { $this->log->info('Reminder Email Command has Run!'); //$output = new BufferedOutput; $this->artisan->call('email:remind'); //return $output->fetch(); } }<file_sep>/public/assets/jsdev/prototypes/6-image-placeholder.js var ImagePlaceholder = function () { this.colour = '#ebedee'; this.size = 0; this.themes(); } ImagePlaceholder.prototype = { constructor: ImagePlaceholder, themes: function(){ self = this; Holder.addTheme("upload", { background: self.colour, foreground: self.colour, size: self.size }); } }<file_sep>/app/composers/ProgressBarComposer.php <?php namespace composers; class ProgressBarComposer { public function compose($view) { $viewdata = $view->getData(); $members = $viewdata['mem'] ? $viewdata['mem'] : 0; $capacity = $viewdata['cap']; $progress = ($members / $capacity) * 100; $view->with('progress', $progress); } }<file_sep>/app/controllers/HomeController.php <?php class HomeController extends BaseController { /** * @var Slider */ private $slider; /** * @var Articles */ private $articles; public function __construct(Slider $slider, Articles $articles) { $this->slider = $slider; $this->articles = $articles; } /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function showWelcome() { $slider = $this->slider->getItems(5); $articles = $this->articles->getMainPageArticles(3); $searchController = App::make('SearchController'); $blocks = []; $homepage = Config::get('homepage'); $tester = Input::get('t', false); if($tester) { $tester = View::make('v3.landing.tester', ['email' => $tester])->render(); } foreach ($homepage['blocks'] as $key => $block) { $blocks[$key] = array_except($block, ['params']); $blocks[$key]['results'] = $searchController->getClasses($block['params'], TRUE); } unset($homepage['blocks']); /** AVAILABLE */ /** * $blocks > All class blocks with titles, links and results. Some have Backgrounds attached to them. * $homepage['popular_searches'] > Dropdown Popular Searches * $homepage['category_blocks'] > Colored Category blocks on the page * $homepage['category_tags'] > Tag Cloud of Categories */ /** * foreach($slider as $slide) * $image = 'files/slider/$prefix_$slide->image' * * $evercisegroup = $slide->evercisegroup */ return View::make('v3.home', compact('blocks', 'slider', 'articles', 'homepage', 'tester')); } }<file_sep>/app/tests/SearchTest.php <?php namespace app\tests; use Mockery as m; use Link, Place, Artisan; class SearchTest extends TestCase { public function tearDown() { m::close(); } public function setUp() { parent::setUp(); $place = Place::where('place_type', 1)->get(); foreach($place as $p) { $p->link()->delete(); $p->delete(); } // Artisan::call('migrate'); //Artisan::call('indexer:geo'); $this->search_pages_old = [ 'london', 'london/area/kings-cross', 'london/station/kings-cross', 'london?page=2' ]; $this->search_pages_new = [ ['location' => 'Queen street, London, United Kingdom', 'radius' => '2mi', 'expected' => 'uk/london/area/queen-street?radius=2mi'], ['location' => 'Embankment, City of Westminster, United Kingdom', 'radius' => '2mi', 'expected' => 'uk/london/area/embankment-city-of-westminster?radius=2mi'], ['location' => 'London Eye, Westminster Bridge Road, London, United Kingdom', 'radius' => '2mi', 'expected' => 'uk/london/area/eye-westminster-bridge-road?radius=2mi'], ['location' => 'Asda Leyton', 'radius' => '2mi', 'expected' => 'uk/london/area/asda-leyton?radius=2mi'], ['location' => 'Westfield London, London, United Kingdom', 'radius' => '2mi', 'expected' => 'uk/london/area/westfield?radius=2mi'] ]; } /** @test */ public function checklink_is_finding_the_places_and_returning_LINK_Class() { foreach ($this->search_pages_old as $page) { /** Remove all optional values */ $link = explode('?', $page); $LinkClass = Link::checkLink($link[0]); $this->assertTrue(is_a($LinkClass, 'Link')); } } /** @test */ public function checklink_is_parsing_the_location_and_creating_a_new_place() { foreach ($this->search_pages_new as $params) { $expected = $params['expected']; unset($params['expected']); $response = $this->call('GET', 'uk', $params); /** The system should redirect to the expected location */ $this->assertRedirectedTo($expected); /** We should have the expect URL in the database */ $permalink = explode('?', str_replace('uk/','',$expected)); $this->assertEquals(1, Link::where('permalink', $permalink[0])->get()->count()); } } }<file_sep>/docs/seed_power_rangers.sql ALTER TABLE `evercisesessions` DROP CONSTRAINT `evercisesessions_evercisegroup_id_foreign`; -- -- Dumping data for table `evercisegroups` -- INSERT INTO `evercisegroups` (`id`, `user_id`, `category_id`, `venue_id`, `name`, `title`, `description`, `address`, `town`, `postcode`, `lat`, `lng`, `image`, `capacity`, `default_duration`, `default_price`, `published`, `created_at`, `updated_at`) VALUES (1, 2, 4, 2, 'Zool Class', '', 'Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403018955_zool.png', 13, 35, '7.50', 0, '2014-06-17 14:30:53', '2014-06-17 14:30:53'), (2, 2, 2, 3, 'Ducktales', '', 'Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo ', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403019080_Duck_Tales_Art.png', 15, 35, '24.00', 0, '2014-06-17 14:33:39', '2014-06-17 14:33:39'), (3, 2, 3, 4, 'Adventure time', '', 'Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. ', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403019250_adventure_time.jpg', 97, 80, '11.50', 0, '2014-06-17 14:35:14', '2014-06-17 14:35:14'); -- -- Dumping data for table `facilities` -- INSERT INTO `facilities` (`id`, `name`, `category`, `image`, `created_at`, `updated_at`) VALUES (1, 'Rowing Machine', 'facility', 'rowing.png', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'Toilets', 'Amenity', 'toilets', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'Car Park', 'Amenity', 'carpark', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (4, 'Hall', 'facility', 'hall', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -- Dumping data for table `ratings` -- INSERT INTO `ratings` (`id`, `user_id`, `sessionmember_id`, `session_id`, `evercisegroup_id`, `user_created_id`, `stars`, `comment`, `created_at`, `updated_at`) VALUES (7, 2, 10, 12, 2, 4, 2, 'It was pretty exciting', '2014-06-17 15:29:27', '2014-06-17 15:29:27'), (16, 1, 7, 14, 1, 4, 5, 'asdfs', '2014-06-18 10:18:13', '2014-06-18 10:18:13'); -- -- Dumping data for table `sessionmembers` -- INSERT INTO `sessionmembers` (`id`, `user_id`, `evercisesession_id`, `price`, `reviewed`, `created_at`, `updated_at`) VALUES (6, 3, 6, '0.00', 0, '2014-06-17 14:50:50', '2014-06-17 14:50:50'), (7, 4, 14, '0.00', 0, '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (8, 4, 10, '0.00', 0, '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (9, 4, 11, '0.00', 0, '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (10, 4, 12, '0.00', 0, '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (11, 5, 15, '0.00', 0, '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (12, 5, 12, '0.00', 0, '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (13, 5, 1, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (14, 5, 2, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (15, 5, 3, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (16, 5, 6, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (17, 4, 6, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (18, 4, 4, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (19, 4, 3, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'); -- -- Dumping data for table `throttle` -- INSERT INTO `throttle` (`id`, `user_id`, `ip_address`, `attempts`, `suspended`, `banned`, `last_attempt_at`, `suspended_at`, `banned_at`) VALUES (1, 2, NULL, 0, 0, 0, NULL, NULL, NULL), (2, 3, '::1', 0, 0, 0, NULL, NULL, NULL), (3, 4, '::1', 0, 0, 0, NULL, NULL, NULL), (4, 5, '::1', 0, 0, 0, NULL, NULL, NULL); -- -- Dumping data for table `trainerhistory` -- INSERT INTO `trainerhistory` (`id`, `user_id`, `historytype_id`, `message`, `created_at`, `updated_at`) VALUES (1, 2, 1, 'Tristan_Allen created Class Zool Class', '2014-06-17 14:30:53', '2014-06-17 14:30:53'), (2, 2, 1, 'Tristan_Allen created Class Ducktales', '2014-06-17 14:33:39', '2014-06-17 14:33:39'), (3, 2, 1, 'Tristan_Allen created Class Adventure time', '2014-06-17 14:35:14', '2014-06-17 14:35:14'), (4, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 18th June 2014', '2014-06-17 14:35:25', '2014-06-17 14:35:25'), (5, 2, 2, 'Tristan_Allen added a new date to Adventure time at 05:00pm on the 19th June 2014', '2014-06-17 14:35:35', '2014-06-17 14:35:35'), (6, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 14:35:42', '2014-06-17 14:35:42'), (7, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 26th July 2014', '2014-06-17 14:35:52', '2014-06-17 14:35:52'), (8, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 25th August 2014', '2014-06-17 14:36:03', '2014-06-17 14:36:03'), (9, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:36:13', '2014-06-17 14:36:13'), (10, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 19th June 2014', '2014-06-17 14:36:20', '2014-06-17 14:36:20'), (11, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 18th July 2014', '2014-06-17 14:36:28', '2014-06-17 14:36:28'), (12, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 06th August 2014', '2014-06-17 14:36:37', '2014-06-17 14:36:37'), (13, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 19th July 2014', '2014-06-17 14:37:01', '2014-06-17 14:37:01'), (14, 2, 2, 'Tristan_Allen added a new date to Ducktales at 07:00pm on the 18th June 2014', '2014-06-17 14:37:13', '2014-06-17 14:37:13'), (15, 2, 2, 'Tristan_Allen added a new date to Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:37:24', '2014-06-17 14:37:24'), (16, 2, 2, 'Tristan_Allen added a new date to Ducktales at 12:00pm on the 09th August 2014', '2014-06-17 14:37:33', '2014-06-17 14:37:33'), (17, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 05th July 2014', '2014-06-17 14:37:39', '2014-06-17 14:37:39'), (18, 2, 2, 'Tristan_Allen added a new date to Ducktales at 12:00pm on the 25th August 2014', '2014-06-17 14:37:49', '2014-06-17 14:37:49'), (22, 2, 5, 'red ranger has joined Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:50:50', '2014-06-17 14:50:50'), (23, 2, 5, 'yellow ranger has joined Zool Class at 12:00pm on the 05th July 2014', '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (24, 2, 5, 'yellow ranger has joined Zool Class at 12:00pm on the 19th July 2014', '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (25, 2, 5, 'yellow ranger has joined Ducktales at 07:00pm on the 18th June 2014', '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (26, 2, 5, 'yellow ranger has joined Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (27, 2, 5, 'green ranger has joined Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (28, 2, 5, 'green ranger has joined Ducktales at 12:00pm on the 25th August 2014', '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (29, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 18th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (30, 2, 5, 'green ranger has joined Adventure time at 05:00pm on the 19th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (31, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (32, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (33, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 23rd May 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (34, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (35, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 26th July 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (37, 2, 6, 'yellow ranger has left a review of Zool Class at 12:00pm on the 18th June 2014', '2014-06-17 15:29:27', '2014-06-17 15:29:27'), (39, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:00:58', '2014-06-18 10:00:58'), (40, 2, 6, 'yellow ranger has left a review of Ducktales at 12:00pm on the 23rd May 2014', '2014-06-18 10:02:33', '2014-06-18 10:02:33'), (41, 1, 6, 'yellow ranger has left a review of Adventure time at 12:00pm on the 23rd May 2014', '2014-06-18 10:11:13', '2014-06-18 10:11:13'), (42, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:13:34', '2014-06-18 10:13:34'), (43, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:14:01', '2014-06-18 10:14:01'), (44, 2, 6, 'yellow ranger has left a review of Adventure time at 12:00pm on the 23rd May 2014', '2014-06-18 10:14:52', '2014-06-18 10:14:52'), (45, 4, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:17:08', '2014-06-18 10:17:08'), (46, 1, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:18:13', '2014-06-18 10:18:13'), (47, 2, 6, 'yellow ranger has left a review of Zool Class at 12:00pm on the 23rd May 2014', '2014-06-18 10:23:23', '2014-06-18 10:23:23'); -- -- Dumping data for table `trainers` -- INSERT INTO `trainers` (`id`, `user_id`, `bio`, `website`, `specialities_id`, `created_at`, `updated_at`) VALUES (1, 2, 'Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim ', '', 5, '2014-06-17 14:28:17', '2014-06-17 14:28:17'); -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `password`, `permissions`, `activated`, `activation_code`, `activated_at`, `last_login`, `persist_code`, `reset_password_code`, `first_name`, `last_name`, `created_at`, `updated_at`, `display_name`, `gender`, `dob`, `phone`, `directory`, `image`, `categories`, `remember_token`) VALUES (1, '<EMAIL>', <PASSWORD>', NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2014-06-17 14:20:21', '2014-06-17 14:20:21', '', 0, '0000-00-00 00:00:00', '', '', '', '', NULL), (2, '<EMAIL>', <PASSWORD>', NULL, 1, NULL, NULL, '2014-06-18 13:41:13', '$2y$10$VcozfeYGFzEnQxANPSoCc.9Vz8MHfMzMsSZoGGmsvJeo2bVo49pGu', NULL, 'Invader', 'Zim', '2014-06-17 14:20:36', '2014-06-18 13:41:13', 'Tristan_Allen', 1, '1970-01-22 00:00:00', '', '2014-06/2_Tristan_Allen', '1403018463_4226.jpg', '', NULL), (3, '<EMAIL>', <PASSWORD>', NULL, 1, '', NULL, '2014-06-17 14:58:37', '$2y$10$gX.WLalIjmPV1Y53BDmuJ.aYsWY87GRhqX0foo6X9KW.FLhohUYpm', NULL, 'red', 'ranger', '2014-06-17 14:22:33', '2014-06-17 14:58:37', 'red ranger', 1, '1984-06-06 23:00:00', '', '2014-06/3_red ranger', '1403019513_6177574_orig.jpg', '', NULL), (4, '<EMAIL>', '$2y$10$tfuZV/f11td0rRvQ4ivQDuMrJxfH.O4ntG2oy5oJ.GSQjKuSG5FxW', NULL, 1, '', NULL, '2014-06-18 09:07:11', '$2y$10$YmxK3kSE5RNZqmma02DP4.RE30siQwEhuzI74QzhB.KOdHBGGOPpe', NULL, 'yellow', 'ranger', '2014-06-17 14:23:22', '2014-06-18 09:07:11', 'yellow ranger', 2, '1984-06-28 23:00:00', '', '2014-06/4_yellow ranger', '1403020755_6177574_orig.jpg', '', NULL), (5, '<EMAIL>', '$2y$10$suFT9/bSLDSDmbZacP7iBenrkHdVz/AA2Mrkq/C2IIuiOAJisCCZ2', NULL, 1, '', NULL, '2014-06-17 14:52:51', '$2y$10$Nbq0RyuIz93123AAy1eKreMT9ZSFbuUkBUBNQPmfbZsEHP5nNlHAS', NULL, 'green', 'ranger', '2014-06-17 14:24:03', '2014-06-17 14:53:15', 'green ranger', 1, '1974-06-05 23:00:00', '', '2014-06/5_green ranger', '1403020393_6177574_orig.jpg', '', NULL); -- -- Dumping data for table `users_groups` -- INSERT INTO `users_groups` (`user_id`, `group_id`) VALUES (1, 4), (2, 1), (2, 2), (2, 3), (3, 1), (4, 1), (5, 1); -- -- Dumping data for table `user_marketingpreferences` -- INSERT INTO `user_marketingpreferences` (`user_id`, `marketingpreference_id`, `created_at`, `updated_at`) VALUES (2, 1, '2014-06-17 14:20:36', '2014-06-17 14:20:36'); -- -- Dumping data for table `venues` -- INSERT INTO `venues` (`id`, `user_id`, `name`, `address`, `town`, `postcode`, `lat`, `lng`, `image`, `created_at`, `updated_at`) VALUES (1, 1, 'Greenlight', 'Cally Road', 'London', 'h4', '51.50682494', '-0.15704746', '', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 2, 'brent cross', '', 'Londonbrent cross', '', '51.57635890', '-0.22369560', '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (3, 2, 'Abergavenny', '', 'abergavenny', '', '51.82536600', '-3.01942300', '', '2014-06-17 14:33:31', '2014-06-17 14:33:31'), (4, 2, 'Ooo', '', 'ooo', '', '36.01075890', '10.31169500', '', '2014-06-17 14:35:04', '2014-06-17 14:35:04'); -- -- Dumping data for table `venue_facilities` -- INSERT INTO `venue_facilities` (`venue_id`, `facility_id`, `details`, `created_at`, `updated_at`) VALUES (2, 2, '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (2, 3, '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (3, 1, '', '2014-06-17 14:33:31', '2014-06-17 14:33:31'), (4, 2, '', '2014-06-17 14:35:04', '2014-06-17 14:35:04'); -- -- Constraints for table `evercisegroups` -- ALTER TABLE `evercisegroups` ADD CONSTRAINT `evercisegroups_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`), ADD CONSTRAINT `evercisegroups_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`), ADD CONSTRAINT `evercisegroups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `evercisesessions` -- ALTER TABLE `evercisesessions` ADD CONSTRAINT `evercisesessions_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`); -- -- Constraints for table `featuredgymgroups` -- ALTER TABLE `featuredgymgroups` ADD CONSTRAINT `featuredgymgroups_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`), ADD CONSTRAINT `featuredgymgroups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `gyms` -- ALTER TABLE `gyms` ADD CONSTRAINT `gyms_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `gym_has_trainers` -- ALTER TABLE `gym_has_trainers` ADD CONSTRAINT `gym_has_trainers_gym_id_foreign` FOREIGN KEY (`gym_id`) REFERENCES `gyms` (`id`), ADD CONSTRAINT `gym_has_trainers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `ratings` -- ALTER TABLE `ratings` ADD CONSTRAINT `ratings_user_created_id_foreign` FOREIGN KEY (`user_created_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `ratings_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`), ADD CONSTRAINT `ratings_sessionmember_id_foreign` FOREIGN KEY (`sessionmember_id`) REFERENCES `sessionmembers` (`id`), ADD CONSTRAINT `ratings_session_id_foreign` FOREIGN KEY (`session_id`) REFERENCES `evercisesessions` (`id`), ADD CONSTRAINT `ratings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `sessionmembers` -- ALTER TABLE `sessionmembers` ADD CONSTRAINT `sessionmembers_evercisesession_id_foreign` FOREIGN KEY (`evercisesession_id`) REFERENCES `evercisesessions` (`id`), ADD CONSTRAINT `sessionmembers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainerhistory` -- ALTER TABLE `trainerhistory` ADD CONSTRAINT `trainerhistory_historytype_id_foreign` FOREIGN KEY (`historytype_id`) REFERENCES `historytypes` (`id`), ADD CONSTRAINT `trainerhistory_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainers` -- ALTER TABLE `trainers` ADD CONSTRAINT `trainers_specialities_id_foreign` FOREIGN KEY (`specialities_id`) REFERENCES `specialities` (`id`), ADD CONSTRAINT `trainers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_has_categories` -- ALTER TABLE `user_has_categories` ADD CONSTRAINT `user_has_categories_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`), ADD CONSTRAINT `user_has_categories_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_marketingpreferences` -- ALTER TABLE `user_marketingpreferences` ADD CONSTRAINT `user_marketingpreferences_marketingpreference_id_foreign` FOREIGN KEY (`marketingpreference_id`) REFERENCES `marketingpreferences` (`id`), ADD CONSTRAINT `user_marketingpreferences_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venues` -- ALTER TABLE `venues` ADD CONSTRAINT `venues_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venue_facilities` -- ALTER TABLE `venue_facilities` ADD CONSTRAINT `venue_facilities_facility_id_foreign` FOREIGN KEY (`facility_id`) REFERENCES `facilities` (`id`), ADD CONSTRAINT `venue_facilities_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`); <file_sep>/app/models/Elastic.php <?php /** * Simple Class that interacts with the Elastic Search engine */ class Elastic { /** * @var Evercisegroup */ protected $evercisegroup; /** * @var Geotools */ protected $geotools; /** * @var Es */ protected $elasticsearch; /** * @var Illuminate\Log\Writer */ protected $log; /** * Inject all used classes.. Set defaults just in case * * @param $evercisegroup * @param $geotools * @param $elasticsearch * @param $log */ public function __construct($geotools, $evercisegroup, $elasticsearch, $log) { $this->geotools = $geotools; $this->evercisegroup = $evercisegroup; $this->elasticsearch = $elasticsearch; $this->log = $log; $this->elastic_index = (getenv('ELASTIC_INDEX') ?: 'evercise'); $this->elastic_type = (getenv('ELASTIC_TYPE') ?: 'evercise'); $this->elastic_polygon = getenv('ELASTIC_POLYGON'); } /** * Search Evercisegroups Index * * @param Place $area * @param array $params * @return array * @throws Exception */ public function searchEvercisegroups(Place $area, $params = [], $dates = FALSE) { $searchParams['index'] = $this->elastic_index; $searchParams['type'] = $this->elastic_type; $searchParams['size'] = $params['size']; $searchParams['from'] = $params['from']; /** Are we going to Search Something? */ $search = FALSE; $searchParams['body']['min_score'] = getenv('ELASTIC_MINIMAL_SCORE') ?: 0.15; if (!empty($params['search'])) { $configIndex = implode(',', array_map(function ($v, $k) { return $k . '^' . $v; }, Config::get('searchindex'), array_keys(Config::get('searchindex')))); $searchParams['body']['query']['filtered']['query'] = [ 'multi_match' => [ 'query' => $params['search'], 'fields' => explode(',', $configIndex), ], ]; $search = TRUE; } if (!empty($params['price'])) { $price = []; if (!empty($params['price']['under'])) { $price['lte'] = $params['price']['under']; } if (!empty($params['price']['over'])) { $price['gte'] = $params['price']['over']; } $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["range"] = ['default_price' => $price]; } if (!isset($params['all'])) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["term"] = ['published' => TRUE]; // $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["range"] = ['futuresessions.date_time' => ['gte' => date('Y-m-d H:i:s')]]; $searchParams['body']['query']['filtered']['filter']['bool']['must_not']['missing'] = [ 'field' => 'futuresessions.members', 'existence' => TRUE, 'null_value' => TRUE ]; $search = TRUE; } if (!empty($params['date'])) { if ($params['date'] == date('Y-m-d')) { $from = date('Y-m-d H:i:s'); } else { $from = $params['date'] . ' 00:00:00'; } $to = date('Y-m-d', strtotime($params['date'] . ' +1 day')) . ' 00:00:00'; $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["range"] = [ 'futuresessions.date_time' => [ 'gte' => $from, 'lte' => $to ] ]; } else { if(!isset($params['all'])) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["range"] = ['futuresessions.date_time' => ['gte' => date('Y-m-d H:i:s')]]; } } if ($dates) { $searchParams['size'] = '200'; $searchParams['body']['fields'] = ['id','futuresessions.date_time']; } if (!empty($params['featured'])) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["term"] = ['featured' => TRUE]; $search = TRUE; } if (!empty($params['venue_id'])) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]["term"] = ['venue.id' => $params['venue_id']]; $search = TRUE; } if (!$search) { /** Guess not! */ $searchParams['body']['query']['filtered']['query']['match_all'] = []; } if (!empty($params['sort'])) { $searchParams['body']['sort'] = $params['sort']; } /** What Are we Searching For */ if ($area->coordinate_type == 'polygon' && !empty($area->poly_coordinates) && $this->elastic_polygon) { $location_points = []; foreach (json_decode($area->poly_coordinates) as $part) { try { $location_points[] = $this->getLocationHash($part[0], $part[1]); } catch (Exception $e) { $this->log->error( 'GeoHash cant hash Area ' . $area->id . ' for lat_lon ' . $part[0] . ', ' . $part[1] ); } } if (count($location_points) > 0) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]['geo_polygon']['venue.location']['points'] = $location_points; } else { $this->log->error('Area ' . $area->id . ' is set to be Polygon but has 0 valid datapoints'); } } else { if (!empty($area->lat) && !empty($area->lng)) { $searchParams['body']['query']['filtered']['filter']['bool']['must'][]['geo_distance'] = [ 'distance' => $params['radius'], 'venue.location' => $this->getLocationHash($area->lat, $area->lng) ]; } } $result = $this->elasticsearch->search($searchParams)['hits']; $result_object = json_decode(json_encode($result), FALSE); return $result_object; } /** * Search Evercisegroups Index * * @param Place $area * @param array $params * @return array * @throws Exception */ public function searchStats($params = []) { $searchParams['index'] = 'search_stats'; $searchParams['type'] = 'search'; $searchParams['size'] = $params['size']; $searchParams['from'] = $params['from']; /** Are we going to Search Something? */ if (!empty($params['search'])) { $searchParams['body']['query']['filtered']['query'] = [ 'flt' => [ 'like_text' => $params['search'], 'max_query_terms' => 12, ], ]; } else { /** Guess not! */ $searchParams['body']['query']['filtered']['query']['match_all'] = []; } $result = $this->elasticsearch->search($searchParams)['hits']; $result_object = json_decode(json_encode($result), FALSE); return $result_object; } /** * @param int $id * @return mixed */ public function getSingle($id = 0) { $searchParams['index'] = $this->elastic_index; $searchParams['type'] = $this->elastic_type; $searchParams['size'] = 1; $searchParams['from'] = 0; if (is_numeric($id)) { $searchParams['body']['query']['match'] = ['id' => $id]; } else { $searchParams['body']['query']['match'] = ['slug' => $id]; } $result = $this->elasticsearch->search($searchParams)['hits']; $result_object = json_decode(json_encode($result), FALSE); return $result_object; } /** * Encode Latitude and Longtitude into GEOHASH * * @param bool $lat * @param bool $lon * @throws Exception */ public function getLocationHash($lat = FALSE, $lon = FALSE) { try { $geohash = $this->geotools->coordinate($lat . ',' . $lon); $encoded = $this->geotools->geohash()->encode($geohash); return $encoded->getGeohash(); } catch (Exception $e) { throw new Exception('Cant GeoHash ' . $lat . ', ' . $lon); } } /** * Decode Location GEOHASH * * @param bool $geohash * @throws Exception */ public function decodeLocationHash($geohash = FALSE) { try { $decoded = $this->geotools->geohash()->decode($geohash); return [ 'latitude' => $decoded->getCoordinate()->getLatitude(), 'longtitude' => $decoded->getCoordinate()->getLongitude() ]; } catch (Exception $e) { throw new Exception('Cant decode GEOHASH ' . $geohash); } } /** * @return bool */ public function indexEvercisegroups($id = 0) { $total_indexed = 0; $with_session = 0; $this->log->info('Indexing Evercise Groups started ' . date('d H:i:s')); if ($id == 0) { $all = $this->evercisegroup->with('futuresessions') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } else { $all = $this->evercisegroup->with('futuresessions') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->where('id', $id) ->get(); } $this->log->info('Get all Indexing data ' . date('d H:i:s')); foreach ($all as $a) { if (!empty($a->venue->lat) && !empty($a->venue->lng)) { $geohash = $this->geotools->coordinate($a->venue->lat . ',' . $a->venue->lng); $encoded = $this->geotools->geohash()->encode($geohash); $hash = $encoded->getGeohash(); } else { $hash = ''; } $index = [ 'id' => (int)$a->id, 'user_id' => (int)$a->user_id, 'venue_id' => (int)$a->venue_id, 'counter' => (int)$a->counter, 'name' => $a->name, 'title' => $a->title, 'slug' => $a->slug, 'gender' => $a->gender, 'description' => $a->description, 'image' => $a->image, 'capacity' => round($a->futuresessions()->avg('tickets'), 0), 'default_duration' => (int)$a->default_duration, 'default_price' => (double)$a->default_price, 'created_at' => $a->created_at->toDateTimeString(), 'published' => ($a->published == 0 ? FALSE : TRUE), 'featured' => ($a->isfeatured() ? TRUE : FALSE), 'user' => [ 'id' => (int)$a->user->id, 'email' => $a->user->email, 'first_name' => $a->user->first_name, 'last_name' => $a->user->last_name, 'display_name' => $a->user->display_name, 'image' => $a->user->image, 'directory' => $a->user->directory, 'phone' => $a->user->phone, ], 'venue' => [ 'id' => (int)$a->venue->id, 'name' => $a->venue->name, 'address' => $a->venue->address, 'postcode' => $a->venue->postcode, 'town' => $a->venue->town, 'lat' => $a->venue->lat, 'lon' => $a->venue->lng, 'location' => [ 'geohash' => $hash, ], 'image' => $a->venue->image ], 'ratings' => [], 'futuresessions' => [] ]; foreach ($a->ratings as $s) { $user = $s->rator; $index['ratings'][] = [ 'user_id' => (int)$s->user_id, 'image' => $user->directory . '/small_' . $user->image, 'name' => $user->first_name . ' ' . $user->last_name, 'stars' => (int)$s->stars, 'comment' => $s->comment, 'date_left' => $s->created_at->format('M jS, g:ia') ]; } $price = 0; foreach ($a->futuresessions()->orderBy('date_time', 'asc')->get() as $s) { if ($price == 0) { $price = (double)$s->price; } if ($price > (double)$s->price) { $price = (double)$s->price; } $index['futuresessions'][] = [ 'id' => (int)$s->id, 'members' => (int)$s->members, 'date_time' => $s->date_time->toDateTimeString(), 'price' => (double)$s->price, 'duration' => (int)$s->duration, 'members_emailed' => (int)$s->members_emailed, 'tickets' => (int)$s->tickets, 'remaining' => (int)$s->remainingTickets(), 'default_tickets' => 1 ]; $with_session++; } /** Categories */ $categories = []; foreach ($a->subcategories()->get() as $sub) { if (!in_array($sub->name, $categories)) { $categories[] = $sub->name; if (!empty($sub->associations)) { $categories[] = $sub->associations; } } foreach ($sub->categories()->get() as $cat) { if (!in_array($cat->name, $categories)) { $categories[] = $cat->name; } } } $index['categories'] = str_replace(',', ' , ', implode(',', $categories)); if ($price > 0) { $index['default_price'] = $price; } $params = []; $params['body'] = $index; $params['index'] = $this->elastic_index; $params['type'] = $this->elastic_type; $params['id'] = $a->id; try { $this->elasticsearch->index($params); $total_indexed++; } catch (Exception $e) { $this->log->error('Cant Index Elasticgroup::id(' . $a->id . ') row. Got error: ' . $e->getMessage()); } } $this->log->info('Indexing Completed ' . date('d H:i:s')); return 'classes: ' . $total_indexed . ' sessions: ' . $with_session; } /** * Save Search Stats to elastic.. we will use this later * @param $user_id * @param $user_ip * @param $area * @param array $params * @param int $results */ public function saveStats($user_id = 0, $user_ip = 0, Place $area, $params = [], $results = 0) { try { $data = [ 'index' => 'search_stats', 'type' => 'search', 'id' => str_random(20), 'body' => [ 'search' => $params['search'], 'size' => $params['size'], 'user_id' => $user_id, 'user_ip' => $user_ip, 'radius' => $params['radius'], 'url' => $area->link->permalink, 'url_type' => $area->link->type, 'name' => $area->name, 'lat' => $area->lat, 'lng' => $area->lng, 'results' => $results, 'date' => date('Y-m-d H:i:s') ] ]; $this->elasticsearch->index($data); } catch (Exception $e) { // Log it and move on Do Nothing... $this->log->error('SEARCH INDEX ERROR: ' . $e->getMessage()); } } /** * @param $id * @return array */ public function deleteSingle($id) { return $this->elasticsearch->delete( ['id' => $id, 'type' => $this->elastic_type, 'index' => $this->elastic_index] ); } /** * @param string $index * @param string $type * @return array|bool */ public function resetIndex($index = FALSE, $type = FALSE) { $mapping = []; $params['index'] = ($index ?: $this->elastic_index); $params['type'] = ($type ?: $this->elastic_type); switch ($type) { case 'evercise': $mapping = [ '_source' => ['enabled' => TRUE], 'properties' => [ '_all' => ['enabled' => TRUE], 'id' => [ 'type' => 'string', 'index' => 'not_analyzed', 'include_in_all' => FALSE ], 'slug' => ['type' => 'string', 'include_in_all' => FALSE], 'name' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'counter' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'title' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'venue_id' => ['type' => 'integer', 'include_in_all' => TRUE], 'user_id' => ['type' => 'integer', 'include_in_all' => TRUE], 'gender' => ['type' => 'integer'], 'categories' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'default_price' => ['type' => 'integer'], 'capacity' => ['type' => 'integer'], 'default_duration' => ['type' => 'integer'], 'published' => ['type' => 'boolean'], 'description' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'image' => ['type' => 'string'], 'created_at' => ['type' => 'date', 'format' => 'yyyy-MM-dd HH:mm:ss'], 'venue' => [ 'dynamic' => TRUE, 'properties' => [ 'id' => ['type' => 'integer'], 'name' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'address' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'postcode' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'town' => ['type' => 'string', 'include_in_all' => TRUE], 'location' => [ 'type' => 'geo_point', 'geohash' => TRUE, 'lat_lon' => TRUE, 'fielddata' => [ 'format' => 'compressed' ] ] ] ], 'user' => [ 'dynamic' => TRUE, 'properties' => [ 'id' => ['type' => 'integer'], 'email' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'first_name' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'last_name' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'display_name' => ['type' => 'string', 'index' => 'analyzed', 'include_in_all' => TRUE], 'phone' => ['type' => 'string'], 'image' => ['type' => 'string'], 'directory' => ['type' => 'string'], ] ], 'ratings' => [ 'dynamic' => TRUE, 'properties' => [ 'user_id' => ['type' => 'integer'], 'stars' => ['type' => 'integer', 'include_in_all' => TRUE], 'comment' => ['type' => 'string', 'include_in_all' => TRUE] ] ], 'futuresessions' => [ 'dynamic' => TRUE, 'properties' => [ 'id' => ['type' => 'integer'], 'members' => ['type' => 'integer'], 'price' => ['type' => 'double'], 'duration' => ['type' => 'integer'], 'tickets' => ['type' => 'integer'], 'remaining' => ['type' => 'integer'], 'date_time' => [ 'type' => 'date', 'format' => 'yyyy-MM-dd HH:mm:ss', 'include_in_all' => TRUE ], 'comment' => ['type' => 'string', 'include_in_all' => TRUE] ] ], ], ]; break; case 'search': $mapping = [ '_source' => ['enabled' => TRUE], 'properties' => [ '_all' => ['enabled' => TRUE], 'id' => [ 'type' => 'string', 'index' => 'not_analyzed', 'include_in_all' => FALSE ], 'search' => ['type' => 'string', 'include_in_all' => TRUE], 'size' => ['type' => 'string', 'include_in_all' => TRUE], 'radius' => ['type' => 'string', 'include_in_all' => TRUE], 'url' => ['type' => 'string', 'include_in_all' => TRUE], 'url_type' => ['type' => 'string', 'include_in_all' => TRUE], 'user_ip' => ['type' => 'string', 'include_in_all' => TRUE], 'user_id' => ['type' => 'string', 'include_in_all' => TRUE], 'name' => ['type' => 'string', 'include_in_all' => TRUE], 'lat' => ['type' => 'string', 'include_in_all' => TRUE], 'lng' => ['type' => 'string', 'include_in_all' => TRUE], 'results' => ['type' => 'integer'], 'date' => ['type' => 'date', 'format' => 'yyyy-MM-dd HH:mm:ss'], ], ]; break; } if (count($mapping) > 0) { $params['body'] = $mapping; return $this->elasticsearch->indices()->putMapping($params); } else { return FALSE; } } /** * @param bool $index * @return bool */ public function deleteIndex($index = FALSE) { $params['index'] = ($index ?: $this->elastic_index); try { $this->elasticsearch->indices()->delete($params); } catch (Exception $e) { // There is no Index.. so we dont really care! } return TRUE; } /** * @param bool $index * @return bool */ public function createIndex($index = FALSE) { $params['index'] = ($index ?: $this->elastic_index); try { $this->elasticsearch->indices()->create($params); } catch (Exception $e) { dd($e->getMessage()); } return TRUE; } /** * Ping ElasticSearch Instance * @return bool */ public function ping() { return $this->elasticsearch->ping(); } } <file_sep>/app/database/migrations/2014_06_10_103106_create_venues_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateVenuesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('venues')) { Schema::create('venues', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key; $table->string('name', 45); $table->string('address', 45); $table->string('town', 45); $table->string('postcode', 45); $table->decimal('lat', 10, 8); $table->decimal('lng', 11, 8); $table->string('image', 45); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('venues'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/database/migrations/2014_06_10_104338_create_venue_facilities_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateVenueFacilitiesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('venue_facilities')) { Schema::create('venue_facilities', function(Blueprint $table) { $table->engine = "InnoDB"; $table->integer('venue_id')->unsigned();// Foreign key; $table->integer('facility_id')->unsigned();// Foreign key; $table->string('details'); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('venue_facilities'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/database/migrations/2015_01_21_101131_create_search_stats.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateSearchStats extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('search_stats', function(Blueprint $table) { $table->increments('id'); $table->string('search'); $table->integer('size'); $table->integer('user_id'); $table->string('user_ip'); $table->string('radius'); $table->string('url'); $table->string('url_type'); $table->string('name'); $table->string('lat'); $table->string('lng'); $table->integer('results'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('search_stats'); } } <file_sep>/app/views/trainers/editForm.blade - with specialities not professions.php {{ Form::open(array('id' => 'trainer_create', 'url' => 'trainers/'.$trainer->id, 'method' => 'PUT', 'class' => 'create-form')) }} @include('form.select', array('fieldname'=>'discipline', 'label'=>'Discipline', 'values'=>$disciplines, 'selected'=>$speciality->name)) @if ($errors->has('discipline')) {{ $errors->first('discipline', '<p class="error-msg">:message</p>')}} @endif @include('form.select', array('fieldname'=>'title', 'label'=>'Title', 'values'=>array('0'=>'Select a discipline'))) @if ($errors->has('title')) {{ $errors->first('title', '<p class="error-msg">:message</p>')}} @endif @include('form.textfield', array('fieldname'=>'bio', 'placeholder'=>'between 50 and 500 characters', 'maxlength'=>500, 'label'=>'Add your bio', 'fieldtext'=>'This is the bio that is displayed to our users', 'default'=>$bio )) @if ($errors->has('bio')) {{ $errors->first('bio', '<p class="error-msg">:message</p>')}} @endif @include('form.textfield', array('fieldname'=>'website', 'placeholder'=>'website address', 'maxlength'=>100, 'label'=>'Add your website', 'fieldtext'=>'(Optional) - If you want users to learn more about you and what you do, you can include your web address, which will be visible on your profile.' )) @if ($errors->has('website')) {{ $errors->first('website', '<p class="error-msg">:message</p>')}} @endif <div class="center-btn-wrapper" > {{ Form::submit('Save changes' , array('class'=>'btn-yellow ')) }} </div> <div class="success_msg">Details updated</div> {{ Form::close() }} <file_sep>/app/models/featuredClasses.php <?php class FeaturedClasses extends \Eloquent { /** * @var array */ protected $fillable = ['evercisegroup_id']; /** * The database table used by the model. * * @var string */ protected $table = 'featured_evercisegroups'; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function evercisegroup() { return $this->belongsTo('evercisegroup', 'evercisegroup_id'); } public function featureGroups($ids) { } }<file_sep>/app/controllers/email/Mailer.php <?php namespace email; use Mail, HTML; abstract class Mailer { public function sendTo($email, $subject, $view, $data = array()) { Mail::queue($view, $data, function($message) use($email, $subject) { $message->to($email) ->subject($subject); }); } public function sendToAttachment($email, $subject, $view, $data = array(),$attachment) { Mail::queue($view, $data, function($message) use($email, $subject, $attachment) { $message->to($email) ->subject($subject); $message->attach($attachment); }); } }<file_sep>/app/controllers/ajax/EvercisegroupsController.php <?php namespace ajax; use Input, Response, Evercisegroup, Sentry, View; class EvercisegroupsController extends AjaxBaseController { public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } /** * POST variables: * name * venue_id * description * image * category_array (array of id's) * * @return \Illuminate\Http\JsonResponse */ public function store() { $inputs = Input::all(); $response = Evercisegroup::validateAndStore($inputs, $this->user); return $response; } /** * POST variables: * name * venue_id * description * image * category_array (array of id's) * * @param $id * @throws \Exception * @return \Illuminate\Http\JsonResponse */ public function update($id) { $inputs = Input::all(); $group = Evercisegroup::find($id); if ($group->user_id != $this->user->id) { return Response::json([ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'Class does not belong to user')->with('fixed', TRUE)->render() ]); } $response = $group->validateAndUpdate($inputs, $this->user); return $response; } public function publish() { $id = Input::get('id', FALSE); $publish = Input::get('publish', FALSE); $group = Evercisegroup::find($id); if ($group->user_id == $this->user->id || $this->user->hasPermission('admin')) { if ($group) { $group->publish($publish); event('class.' . ($publish ? 'published' : 'unpublished'), [$group, $this->user]); } else { return Response::json( [ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'Class not found')->with('fixed', TRUE)->render(), 'state' => 'error' ] ); } return Response::json( [ 'view' => View::make('v3.layouts.positive-alert')->with('message', 'Class ' . ($publish ? '' : 'un') . 'published')->with('fixed', TRUE)->render(), 'state' => $publish ] ); } return Response::json( [ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'Class does not belong to user')->with('fixed', TRUE)->render(), 'state' => 'hack' ] ); } }<file_sep>/public/assets/jsdev/prototypes/41-class-calendar.js function classCalendar(calendar){ this.calendar = calendar; this.sessions = calendar.find('input[name="sessions"]').val(); this.rows = []; this.init(); } classCalendar.prototype = { constructor : classCalendar, init : function(){ var obj = JSON.parse(this.sessions); var self = this; this.calendar.datepicker({ format: "yyyy-mm-dd", startDate: "+1d", weekStart : 1, multidate: true, beforeShowDay: function(d) { var date = d.getFullYear() + '-' + ('0' + (d.getMonth() +1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) var result = $.grep(obj, function(e){ var dt = e.date_time; dt = dt.split(/\s+/); return dt[0] == date; }); if(result.length > 0){ var ids = []; for(var key in result){ ids.push(result[key].id); self.rows.push({ 'id' : result[key].id, 'list' : '<li>'+result[key].date_time+'</li>', 'show' : false }) } return { enabled : true, classes : 'session', session : ids }; } else{ return { enabled : false, classes : false, session : false }; } } }) this.addListeners(); }, addListeners : function(){ this.calendar.find('.day').on('click', $.proxy(this.dateSelected, this)); }, dateSelected : function(e){ e.preventDefault(); e.stopPropagation(); var arr = $(e.target).data('session').split(','); var self = this; for(var i = 0; i<arr.length; i++){ $.grep(self.rows, function(e){ if(e.id == arr[i]){ self.calendar.after(e.list); } }); } } }<file_sep>/app/composers/AdminLogComposer.php <?php namespace composers; class AdminLogComposer { public function compose($view) { $logFile = file_get_contents('../app/storage/logs/laravel.log', true); $logFile = str_replace('[] []', '[] []<br><br><br>', $logFile); $logFile = str_replace('#', '<br><span style="color:red;">#</span>', $logFile); $view ->with('log', $logFile); } }<file_sep>/app/composers/CartRowsComposer.php <?php namespace composers; class CartRowsComposer { public function compose($view) { $viewdata= $view->getData(); $sessionId = $viewdata['sessionId']; $sessionIds = $viewdata['sessionIds']; if(($key = array_search($sessionId, $sessionIds)) !== false) { unset($sessionIds[$key]); } $view->with('session_ids' , $sessionIds); } }<file_sep>/app/views/admin/yukonhtml/php/pages/pages-user_list.php <div class="row"> <div class="col-md-12"> <div class="ul_main_info"> Showing <strong class="countUsers"></strong> contact(s) </div> <ul id="user_list"> <?php for($i=1;$i<=120;$i++) { ?> <li> <h3 class="ul_userName"><span class="ul_firstName"><?php echo $faker->firstName; ?></span> <span class="ul_lastName"><?php echo $faker->firstName; ?></span></h3> <p class="ul_company"><small class="text-muted">Company:</small> <?php echo $faker->company; ?></p> <p><small class="text-muted">Phone:</small> <span class="ul_phone"><?php echo $faker->phoneNumber; ?></span>; <small class="text-muted">E-mail:</small> <span class="ul_email"><?php echo $faker->email; ?></span></p> </li> <?php }; ?> </ul> </div> </div> <file_sep>/public/assets/jsdev/angular/browse-controller.js if(typeof angular != 'undefined') { app.controller('browseController', ["$scope", "$http" , function ($scope, $http) { angular.element(document).ready(function () { $scope.getCats(); }); // set height of tab bar $scope.browseTabHeight = function(){ var sideBarHeight = $('.nav-browse .items').outerHeight(); } $scope.searchTerm = laracasts.results.search; $scope.location = laracasts.results.area.name; $scope.area = laracasts.results.area.id; // area clear $('#near-me').click(function(){ $scope.area = ''; $scope.$apply(); }) $('input[name="location"]').change(function(){ $scope.area = ''; $scope.$apply(); }) $scope.activeCatSwitch = function(cat){ $scope.activeCat = cat; }; // browse box $scope.subCategories = function(e, cat){ e.preventDefault(); $scope.browse = cat; $scope.browseIsVisible = true; } $scope.closeBrowse = function(e){ $scope.browseIsVisible = false; } $scope.getCats = function(){ var path = '/ajax/categories/browse'; var req = { method: 'POST', url: path, headers: { 'X-CSRF-Token': TOKEN } } var responsePromise = $http(req); responsePromise.success(function(data) { $scope.categories = data; }); responsePromise.error(function(data) { }); } $scope.submit = function(term){ $scope.searchTerm = term; $scope.location = ''; $scope.area = ''; setTimeout(function() { $('#search-form').trigger('submit'); }, 500) } }]) }<file_sep>/app/database/migrations/2014_11_27_113826_create_transactions.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTransactions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('transactions', function(Blueprint $table) { $table->increments('id'); $table->tinyInteger('processed'); $table->integer('user_id'); $table->integer('coupon_id'); $table->decimal('total', 8, 2); $table->decimal('total_after_fees', 8, 2); $table->decimal('commission', 8, 2); $table->string('payment_method'); $table->string('token'); $table->string('transaction'); $table->string('payer_id'); $table->timestamps(); }); Schema::create('transaction_items', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('transaction_id'); $table->string('type'); $table->integer('evercisesession_id'); $table->integer('package_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('transactions'); } } <file_sep>/public/admin/pendingwithdrawals.php <div id="page_wrapper"> <!-- header --> <header id="main_header"></header> <!-- breadcrumbs --> <nav id="breadcrumbs"></nav> <!-- main content --> <div id="main_wrapper"></div> <!-- main menu --> <nav id="main_menu"></nav> <h1>Pending Withdrawals</h1> <table class="admin_table"> <tr> <th>user</th> <th>payment type</th> <th>payment details</th> <th>amount</th> <th>action</th> </tr> <?php foreach($pendingWithdrawals as $key => $withdrawal) { ?> <tr> <td><?php echo $withdrawal->user->first_name.' '.$withdrawal->user->last_name ?></td> <td><?php echo $withdrawal->acc_type ?></td> <td><?php echo $withdrawal->account ?> </td> <td><?php echo $withdrawal->transaction_amount ?> </td> <td> <?php echo Form::open(array('id' => 'process'.$key, 'url' => 'admin/process_withdrawal', 'method' => 'post', 'class' => '')) ?> <?php echo Form::hidden( 'withdrawal_id' , $withdrawal->id, array('id' => 'withdrawal_id')) ?> <?php echo Form::submit('Mark Processed' , array('class'=>'btn-yellow ')) ?> <?php echo Form::close() ?> </td> </tr> <?php } ?> </table> <br> <br> <br> <h1>Recently Processed Withdrawals</h1> <table class="admin_table"> <tr> <th>user</th> <th>payment type</th> <th>payment details</th> <th>amount</th> <th>processed</th> </tr> <?php foreach($processedWithdrawals as $key => $withdrawal) { ?> <tr> <td><?php echo $withdrawal->user->first_name.' '.$withdrawal->user->last_name ?></td> <td><?php echo $withdrawal->acc_type ?></td> <td><?php echo $withdrawal->account ?> </td> <td><?php echo $withdrawal->amount ?> </td> <td><?php echo $withdrawal->updated_at?></td> </tr> <?php } ?> </table> </div> <!-- js plugins --> <!-- style switcher --> <div id="style_switcher"></div> <file_sep>/app/composers/PayWithEvercoinsComposer.php <?php namespace composers; use JavaScript; use Evercoin; use Sentry; class PayWithEvercoinsComposer { public function compose($view) { $viewdata = $view->getData(); $priceInEvercoins = Evercoin::poundsToEvercoins($viewdata['totalPrice']); $user = Sentry::getUser(); $evercoins = Evercoin::where('user_id', $user->id)->pluck('balance'); JavaScript::put(array('initPut' => json_encode(['selector' => '#paywithevercoinsform']) )); // Initialise init put js. JavaScript::put(array('initRedeemEvercoin' => json_encode(['balance'=> $evercoins , 'priceInEvercoins' => $priceInEvercoins]) )); $view->with('evercoins', $evercoins) ->with('priceInEvercoins', $priceInEvercoins); } }<file_sep>/app/controllers/ajax/UsersController.php <?php namespace ajax; use User, UserHelper, Session, Input, Config, Sentry, Event, Response, Wallet, Trainer, Request, Redirect, Milestone, Log, Validator; use View; use Withdrawalrequest; class UsersController extends AjaxBaseController { public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // check user passes validation $valid_user = User::validUserSignup(Input::all()); if ($valid_user['validation_failed'] == 0) { // register user and add to user group $user = User::registerUser(Input::all()); UserHelper::generateUserDefaults($user->id); UserHelper::checkAndUseReferralCode(Session::get('referralCode'), $user->id); UserHelper::checkAndUseLandingCode(Session::get('ppcCode'), $user->id); Session::forget('email'); if ($user) { User::makeUserDir($user); User::createImage($user); $user->save(); $this->user = $user; // check for newsletter and if so add to mailchimp $this->setNewsletter(Input::get('userNewsletter', FALSE)); Sentry::login($user, TRUE); event('user.registered', [$user]); if (Input::has('redirect')) { return Response::json( [ 'callback' => 'gotoUrl', 'url' => route(Input::get('redirect')) ] ); } else { if (Input::get('trainer', 'no') == 'yes') { return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('trainers.create') ] ); } else { User::sendWelcomeEmail($user); return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('finished.user.registration') ] ); } } } } else { return Response::json($valid_user); } } public function storeGuest() { $inputs = Input::except(['_token', 'redirect', 'userNewsletter']); $validator = Validator::make( $inputs, [ 'email' => 'required|email|unique:users' ] ); // check user passes validation if ($validator->fails()) { $valid_user = [ 'callback' => 'error', 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; // log errors Log::notice($validator->errors()->toArray()); } else { // if validation passes return validation_failed false $valid_user = [ 'validation_failed' => 0 ]; } if ($valid_user['validation_failed'] == 0) { $slug = explode('@', $inputs['email']); $inputs['password'] = str_<PASSWORD>(12); $inputs['display_name'] = User::uniqueDisplayName(slugIt($slug[0])); $inputs['first_name'] = $slug[0]; $inputs['last_name'] = ''; $inputs['activated'] = TRUE; $inputs['gender'] = 0; // register user and add to user group $user = User::registerUser($inputs); UserHelper::generateUserDefaults($user->id); UserHelper::checkAndUseReferralCode(Session::get('referralCode'), $user->id); UserHelper::checkAndUseLandingCode(Session::get('ppcCode'), $user->id); Session::forget('email'); if ($user) { User::makeUserDir($user); User::createImage($user); $user->save(); $this->user = $user; // check for newsletter and if so add to mailchimp $this->setNewsletter(Input::get('userNewsletter')); Sentry::login($user, TRUE); event('user.registered', [$user]); User::sendGuestWelcomeEmail($user); return Response::json( [ 'callback' => 'success' ] ); } } else { return Response::json($valid_user); } } /** * Update the specified resource in storage. * * @return Response */ public function update() { if (!$this->checkLogin()) { return Redirect::route('home'); } $valid_user = User::validUserEdit(Input::all(), $this->user->isTrainer()); if (!$valid_user['validation_failed']) { // Actually update the user record $params = [ 'first_name' => Input::get('first_name'), 'last_name' => Input::get('last_name'), 'dob' => Input::get('dob'), 'gender' => (Input::get('gender') == 'male' ? 1 : (Input::get('gender') == 'female' ? 2 : -1) ), 'image' => Input::get('image'), 'area_code' => Input::get('areacode'), 'phone' => Input::get('phone'), 'password' => <PASSWORD>('<PASSWORD>'), 'email' => Input::get('email'), ]; $this->user->updateUser($params); if ($this->user->isTrainer()) { $this->user->trainer->updateTrainer([ 'profession' => Input::get('profession', 0), 'bio' => Input::get('bio', 0), 'website' => Input::get('website', 0), ]); } $this->user->checkProfileMilestones(); $this->setNewsletter(Input::get('newsletter')); event(Trainer::isTrainerLoggedIn() ? 'trainer' : 'user' . '.edit', [$this->user]); return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('users.edit', [$this->user->display_name, 'edit']) ] ); } else { return Response::json($valid_user); } } /** * Check if the user is logged in and redirect if needed * * @return bool */ public function checkLogin() { return Sentry::check(); } function setLocation() { $lat = Input::get('lat'); $lon = Input::get('lon'); Session::put('location', ['lat' => $lat, 'lon' => $lon]); $user = Sentry::getUser(); if (!empty($user->id)) { $user->lat = $lat; $user->lon = $lon; $user->save(); } return Response::json(['stored' => TRUE]); } /** * @return \Illuminate\Http\JsonResponse */ function getLocation() { $value = Session::get('location', function () { $user = Sentry::getUser(); return [ 'lat' => ($user->lat == '0.00' ? '' : $user->lat), 'lon' => ($user->lon == '0.00' ? '' : $user->lon) ]; }); return Response::json($value); } private function setNewsletter($newsletter = FALSE) { if (is_null($this->user->newsletter) || $this->user->newsletter()->count() == 0) { $this->user->marketingpreferences()->sync([1]); } if ($newsletter) { $this->user->marketingpreferences()->sync([1]); if (FALSE) { User::subscribeMailchimpNewsletter(Config::get('mailchimp')['newsletter'], $this->user->email, $this->user->first_name, $this->user->last_name ); } } else { $this->user->marketingpreferences()->sync([2]); if (FALSE) { User::unSubscribeMailchimpNewsletter(Config::get('mailchimp')['newsletter'], $this->user->email ); } } } public function requestWithdrawal() { if (!empty($this->user->id)) { $res = [ 'user' => $this->user, 'wallet' => $this->user->getWallet(), 'payment_date' => Config::get('evercise.payments_to_trainers') ]; $view = View::make('v3.users.withdrawal', $res)->render(); return Response::json(['view' => $view]); } else { return Response::json(['error' => 'You need to be logged in to use this feature']); } } public function makeWithdrawal() { if (!Sentry::check()) { return Response::json(['error' => 'You need to be logged in to use this feature']); } $inputs = Input::all(); $messages = [ 'min' => 'Minimum amount you can withdraw is £' . Config::get('evercise.minimim_withdraw'), 'max' => 'Max amount you can withdraw is £' . number_format($this->user->getWallet()->balance) ]; $validations = [ 'paypal' => 'required|email', 'amount' => 'required|integer|min:' . Config::get('evercise.minimim_withdraw') . '|max:' . round($this->user->getWallet()->balance, 0) ]; $validator = Validator::make( $inputs, $validations, $messages ); // if fails add errors to results if ($validator->fails()) { $result = [ 'callback' => 'error', 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; Log::error($validator->errors()->toArray()); return Response::json($result); } $amount = $inputs['amount']; $paypal = $inputs['paypal']; $wallet = $this->user->getWallet(); $this->user->paypal_email = $paypal; $this->user->save(); $withdrawal = Withdrawalrequest::create( [ 'user_id' => $this->user->id, 'transaction_amount' => number_format($amount, 2), 'account' => $paypal, 'acc_type' => 'paypal', 'processed' => 0 ] ); if ($withdrawal) { $wallet->withdraw($amount, 'Withdrawal request', 'withdraw'); $result = [ 'callback' => 'success', 'validation_failed' => 0, 'errors' => FALSE ]; } else { $result = [ 'callback' => 'error', 'validation_failed' => 1, 'errors' => ['We could not process your request. Please try again later'] ]; Log::error('Cant process Request ' . $this->user->id . ' amount: ' . $amount); } return $result; } } <file_sep>/app/models/WithdrawalPayment.php <?php use Illuminate\Log\Writer; use Illuminate\Config\Repository; /** * @property mixed paypal_config */ class WithdrawalPayment { private $paypal_config; private $paypal; private $subject = 'Trainer Payment'; private $currency = 'GBP'; private $receivertype = 'EmailAddress'; private $recipients = []; /** * @return array */ public function getRecipients() { return $this->recipients; } private $fields; public function __construct(Writer $log, Repository $config) { $this->paypal_config = [ 'Sandbox' => getenv('PAYPAL_TESTMODE') ?: TRUE, 'APIUsername' => getenv('PAYPAL_USER') ?: FALSE, 'APIPassword' => getenv('PAYPAL_PASS') ?: FALSE, 'APISignature' => getenv('PAYPAL_SIGNATURE') ?: FALSE, 'PrintHeaders' => FALSE, 'LogResults' => TRUE, 'LogPath' => storage_path() . '/logs/PayPal.log', ]; $this->paypal = new angelleye\PayPal\PayPal($this->paypal_config); } /** * @param string $currenctyCode */ public function setCurrency($currenctyCode) { $this->currency = $currenctyCode; return $this; } /** * @param string $emailSubject */ public function setSubject($emailSubject) { $this->subject = $emailSubject; return $this; } public function addUser($params = []) { $this->recipients[] = [ 'l_email' => $params['email'], 'l_amt' => number_format($params['amount'], 2), 'l_uniqueid' => $params['id'], 'l_note' => '' ]; return $this; } public function pay() { if (count($this->recipients) == 0) { throw new \Exception('Please Add Recipients'); } $this->setFields(); $PayPalRequestData = ['MPFields' => $this->fields, 'MPItems' => $this->recipients]; // Pass data into class for processing with PayPal and load the response array into $PayPalResult $PayPalResult = $this->paypal->MassPay($PayPalRequestData); Log::info($PayPalResult); return $PayPalResult; } private function setFields() { $this->fields = [ 'emailsubject' => $this->subject, 'currencycode' => $this->currency, 'receivertype' => $this->receivertype ]; } } <file_sep>/app/models/PdfHelper.php <?php /** * Class PdfHelper */ class PdfHelper { /** * @param $evercisegroup * @param $evercisesession * @param $sessionmembers * @return \Illuminate\View\View */ public static function pdfView($evercisegroup, $evercisesession, $sessionmembers) { $pdfPage = View::make('v3.pdf.session_members') ->with('evercisegroup', $evercisegroup) ->with('evercisesession', $evercisesession) ->with('sessionmembers', $sessionmembers); return $pdfPage; } }<file_sep>/app/database/seeds/SentrySeeder.php <?php use App\Models\User; class SentrySeeder extends Seeder { public function run() { DB::table('users')->delete(); DB::table('groups')->delete(); DB::table('users_groups')->delete(); Sentry::getUserProvider()->create(array( 'email' => '<EMAIL>', 'password' => "<PASSWORD>", 'activated' => 1, )); Sentry::getGroupProvider()->create(array( 'name' => 'User', 'permissions' => array('user' => 1), )); Sentry::getGroupProvider()->create(array( 'name' => 'Facebook', 'permissions' => array('facebook' => 1), )); Sentry::getGroupProvider()->create(array( 'name' => 'Trainer', 'permissions' => array('trainer' => 1), )); Sentry::getGroupProvider()->create(array( 'name' => 'Admin', 'permissions' => array('admin' => 1), )); Sentry::getGroupProvider()->create(array( 'name' => 'Tester', 'permissions' => array('tester' => 1), )); Sentry::getGroupProvider()->create(array( 'name' => 'Fakeuser', 'permissions' => array('fakeuser' => 1), )); // Assign user permissions $adminUser = Sentry::getUserProvider()->findByLogin('<EMAIL>'); $adminGroup = Sentry::getGroupProvider()->findByName('Admin'); $adminUser->addGroup($adminGroup); } }<file_sep>/public/assets/jsdev/prototypes/34-login.js function Login(form){ this.form = form; this.addListeners(); } Login.prototype = { constructor: Login, addListeners : function(){ this.form.on('submit', $.proxy(this.submit, this)); this.form.find('input').on('input', $.proxy(this.removeError, this)); }, removeError: function(){ this.form.find('.alert').remove(); }, submit: function(e){ e.preventDefault(); this.form = $(e.target); this.ajax(); }, ajax: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true); self.form.find(".has-error").removeClass('has-error'); $("#login-error-msg").remove(); self.removeError(); }, success: function (data) { if( data.validation_failed == 1 ){ self.failedValidation(data); } else{ window.location.href = data.url; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false) } }); }, failedValidation: function(data) { self = this; var arr = data.errors; //self.form.find("input[name = 'password']").after('<div class="mt10 alert alert-danger alert-dismissible" role="alert">' + arr + '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button></div>'); self.form.find("input[name = 'password']").parent().after('<div id="login-error-msg" class="form-control mb10 input-lg input-group has-error">' + arr + '</div>'); } }<file_sep>/app/database/migrations/2014_11_12_141755_add_tickets_evercisesessions.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddTicketsEvercisesessions extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement('ALTER TABLE evercisesessions CHANGE members tickets INT'); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('ALTER TABLE evercisesessions CHANGE tickets members INT'); } } <file_sep>/public/assets/jsdev/prototypes/50-ajax.js var AjaxRequest = function (form, callback){ this.form = form; this.actionUrl = form.attr('action'); this.method = form.attr('method'); this.data = form.serialize(); this.dataType = 'json'; this.validationScrollSpeed = 200; this.validationoffset = 85; this.validationscroll = false; this.callbackname = callback; this.disableButton(); this.init(); } AjaxRequest.prototype = { constuctor: AjaxRequest, init: function(){ self = this; $.ajax({ url: self.actionUrl, type: self.method, data: self.data, dataType: self.dataType }).done( function(data) { self.callbackSelctor(data); } ); }, disableButton: function(){ this.form.find('input[type="submit"]').prop('disabled', true); }, renableButton: function(){ this.form.find('input[type="submit"]').prop('disabled', false); }, callbackSelctor: function(data){ if(data.callback == 'error') { self.failedValidation(data); } else { self.callbackname(data); } }, failedValidation: function(data){ self = this; var arr = data.errors; if(self.form.attr('id') == 'login-form'){ self.form.find("input[name = 'password']").after('<div class="mt10 alert alert-danger alert-dismissible" role="alert">'+arr+'<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button></div>'); } else { $.each(arr, function(index, value) { if (self.validationscroll == false) { self.form.find("#" + index).focus(); $('html, body').animate({ scrollTop: self.form.find("#" + index).offset().top - self.validationoffset }, self.validationScrollSpeed); self.validationscroll = true; } self.form.find('#' + index).parent().addClass('has-error'); self.form.find('#' + index).parent().find('.glyphicon').remove(); self.form.find('input[name="' + index + '"]').parent().find('.help-block:visible').remove(); self.form.find('#' + index).after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="'+index+'" data-bv-result="INVALID">'+value+'</small>'); self.form.find('#' + index).after('<i class="form-control-feedback glyphicon glyphicon-remove" data-bv-icon-for="'+index+'" style="display: block;"></i>'); }) } self.renableButton(); } } <file_sep>/app/database/migrations/2014_04_28_162518_create_trainers_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTrainersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('trainers')) { Schema::create('trainers', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key $table->string('bio', 500); $table->string('website', 45); $table->boolean('confirmed')->default(0); $table->integer('specialities_id')->unsigned();// Foreign key $table->string('profession', 50); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('trainers'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/models/Coupons.php <?php class Coupons extends Eloquent { protected $table = 'coupons'; protected $fillable = [ 'id', 'usage', 'coupon', 'description', 'type', 'amount', 'package_id', 'expires_at', 'active_from' ]; public static function check($coupon = false) { if (!$coupon) { return false; } return static::where('coupon', $coupon) ->where('usage', '>', 0) ->where('expires_at', '>', date('Y-m-d H:i:s')) ->where('active_from', '<', date('Y-m-d H:i:s')) ->first(); } public static function processCoupon($coupon, $user) { if($coupon = self::check($coupon)) { $coupon->decrement('usage'); Event::fire('activity.user.coupon', [$coupon, $user]); return $coupon->id; } return false; } }<file_sep>/app/models/Transactions.php <?php class Transactions extends Eloquent { protected $table = 'transactions'; protected $fillable = [ 'id', 'user_id', 'total', 'total_after_fees', 'coupon_id', 'commission', 'processed', 'token', 'transaction', 'payer_id', 'payment_method' ]; /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function items() { return $this->hasMany('TransactionItems', 'transaction_id'); } public function formattedDate() { return date('M jS Y', strtotime($this->created_at)); } public function makeBookingHashes() { $hashes = []; foreach($this->items as $item) { $original_id = $this->id . $item->id; $hashes[$item->id] = base_convert($original_id, 10, 36); } return $hashes; } public function makeBookingHashBySession($sessionId) { $hashes = []; foreach($this->items as $item) { $original_id = $this->id . $item->id; if($item->sessionmember) if($item->sessionmember->evercisesession_id == $sessionId) $hashes[$item->id] = base_convert($original_id, 10, 36); } return $hashes; } public static function decodeBookingHash($hash) { $unhashed = base_convert($hash, 36, 10); $characters = str_split($unhashed); $transactionId = implode('', array_slice($characters, 0, 7)); $itemId = implode('', array_slice($characters, 7)); return [ 'transaction_id' => $transactionId, 'item_id' => $itemId ]; } }<file_sep>/app/models/EverciseSession.php <?php /** * Class Evercisesession */ class Evercisesession extends \Eloquent { /** * @var array */ protected $fillable = ['evercisegroup_id', 'date_time', 'price', 'duration', 'members_emailed', 'tickets']; protected $editable = ['date_time', 'price', 'duration', 'members']; /** * The database table used by the model. * * @var string */ protected $table = 'evercisesessions'; protected $dates = ['date_time']; /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function sessionmembers() { return $this->hasMany('Sessionmember'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function userSessionmembers($user_id) { return $this->hasMany('Sessionmember') ->where('user_id', $user_id)->get(); } public function userRating($user_id) { /* This could do with being turned into a proper relationship instead of a dirty-ass loop */ $sessionmembers = $this->userSessionmembers($user_id); foreach($sessionmembers as $sm) if($sm->rating) return $sm->rating; return null; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function evercisegroup() { return $this->belongsTo('Evercisegroup'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function users() { return $this->belongsToMany('User', 'sessionmembers', 'evercisesession_id', 'user_id')->withPivot('id', 'transaction_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function sessionpayment() { return $this->hasOne('Sessionpayment'); } /** * @param $inputs * @return \Illuminate\View\View */ public static function getCreateForm($inputs) { $date = sprintf("%02s", Input::get('date')); $displayMonth = date('M', strtotime($inputs['year'] . '-' . $inputs['month'] . '-' . $date)); $evercisegroup = Evercisegroup::select('default_duration', 'default_price', 'name' )->where('id', $inputs['evercisegroupId'])->first(); $duration = $evercisegroup->default_duration; $price = $evercisegroup->default_price; $name = $evercisegroup->name; /* Set default time */ $hour = 12; $minute = 00; return [ 'year' => $inputs['year'], 'month' => $inputs['month'], 'displayMonth' => $displayMonth, 'date' => $date, 'evercisegroupId' => $inputs['evercisegroupId'], 'duration' => $duration, 'price' => $price, 'name' => $name, 'hour' => $hour, 'minute' => $minute ]; } /** * $sessionData = [evercisegroup_id, date, time, duration, tickets, price] * * @return \Illuminate\Http\JsonResponse */ public static function validateAndStore($sessionData) { $validator = Validator::make( $sessionData, [ 'evercisegroup_id' => 'required', 'date' => 'required', 'time' => 'required', 'tickets' => 'required', 'price' => 'required|numeric|between:1,'.Config::get('values')['max_price'], 'duration' => 'required|numeric|between:10,240', ] ); if ($validator->fails()) { return false; } else { $date_time = $sessionData['date'] . ' ' . $sessionData['time'].':00'; $session = Evercisesession::create([ 'evercisegroup_id' => $sessionData['evercisegroup_id'], 'date_time' => new \Carbon\Carbon($date_time), 'price' => $sessionData['price'], 'duration' => $sessionData['duration'], 'tickets' => $sessionData['tickets'], ]); $evercisegroupName = $session->evercisegroup->name; $timestamp = strtotime($date_time); $niceTime = date('h:ia', $timestamp); $niceDate = date('dS F Y', $timestamp); Trainerhistory::create(array('user_id' => Sentry::getUser()->id, 'type' => 'created_session', 'display_name' => Sentry::getUser()->display_name, 'name' => $evercisegroupName, 'time' => $niceTime, 'date' => $niceDate)); /* callback */ event('session.create', [Sentry::getUser() ]); return true; } } public static function toDateTime($date, $time) { $date = strtotime($date); $date_str = date("Y-m-d H:i:s", $date); $date_time_str = str_replace('00:00:00', $time, $date_str); $date_time = strtotime($date_time_str); } public function validateAndUpdate($sessionData, $userId) { $validator = Validator::make( $sessionData, [ 'tickets' => 'required', 'time' => 'required', 'price' => 'required|numeric|between:1,'.Config::get('values')['max_price'], 'duration' => 'required|numeric', ] ); if ($validator->fails()) { return ['validation_failed' => 1, 'errors' => $validator->errors()->toArray()]; } else { if (! $this->evercisegroup->user_id == $userId) return ['validation_failed' => 1, 'errors' => ['user' => 'user ids do not match']]; $currentDate = strtotime($this->date_time); $date_str = date("Y-m-d", $currentDate); $date_time_str = $date_str . ' ' . $sessionData['time'].':00'; $this->update([ 'date_time' => new \Carbon\Carbon($date_time_str), 'price' => $sessionData['price'], 'duration' => ($sessionData['duration'] >= 10) ? $sessionData['duration'] : 10, 'tickets' => $sessionData['tickets'], ]); return ['validation_failed' => 0]; } } /** * @param $id * @return \Illuminate\Http\JsonResponse */ public static function deleteById($id) { try { $evercisesession = Evercisesession::findOrFail($id); $evercisegroupId = $evercisesession->evercisegroup_id; $user_id = Evercisegroup::where('id', $evercisegroupId)->pluck('user_id'); if ($user_id != Sentry::getUser()->id) { Log::error('Attempted deletion of session by unauthorised user'); return Response::json(['mode' => 'hack']); } $dateTime = $evercisesession->date_time; $price = $evercisesession->price; $duration = $evercisesession->duration; $undoDetails = ['mode' => 'delete', 'id' => $id, 'evercisegroup_id' => $evercisegroupId, 'date_time' => $dateTime, 'price' => $price, 'duration' => $duration, 'user_id' => $user_id]; Evercisesession::destroy($id); event('session.delete', [Sentry::getUser(), $evercisesession ]); return Response::json($undoDetails); } catch (Exception $e) { $undoDetails = json_decode(Input::get('undo')); $evercisesession = Evercisesession::create(array( 'evercisegroup_id' => $undoDetails->evercisegroup_id, 'date_time' => new \Carbon\Carbon($undoDetails->date_time), 'price' => $undoDetails->price, 'duration' => $undoDetails->duration )); event('session.create', [Sentry::getUser(), $evercisesession ]); return Response::json(['mode' => 'undo', 'session_id' => $evercisesession->id]); } } /** * @param $session * @param $userList * @param $subject * @param $body * @return \Illuminate\Http\JsonResponse */ public static function mailMembers($session, $userList, $subject, $body) { $group = Evercisegroup::where('id', $session->evercisegroup_id)->with(['User' => function($query) { $query->select('first_name', 'last_name'); } ])->first(); event('session.mail_all', [ $userList, $group, $session, $subject, $body ]); Log::info('Members of Session '. $session->id .' mailed by trainer'); return Response::json(['message' => 'group: ' . $group->id . ': ' . $group->name . ', session: ' . $session->id]); } /** * Return false if validation passes, otherwise return the error response * * @return bool|\Illuminate\Http\JsonResponse */ public static function validateMail() { $validator = Validator::make( Input::all(), array( 'mail_body' => 'required', ) ); if ($validator->fails()) { $result = array( 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ); return Response::json($result); } else { return false; } } /** * Return details of all the members signed up to a particular session * * @param $sessionId * @return \Illuminate\Database\Eloquent\Model|mixed|null|static */ public static function getMembers($sessionId) { $session = Evercisesession::where('id', $sessionId)->select('id')->with(['users' => function ($query) { $query->select('first_name', 'last_name', 'email'); } ])->first(); return $session->users; } /** * @param $sessionId * @param $trainerId * @return array */ public static function mailTrainer($sessionId, $trainerId, $subject, $body) { //$subject = Input::get('mail_subject'); //$body = Input::get('mail_body'); $session = Evercisesession::find($sessionId); $evercisegroup = $session->evercisegroup()->first(); $trainer = User::find($trainerId); $user = Sentry::getUser(); event('session.mail_trainer', [$trainer, $user, $evercisegroup, $session, $subject, $body]); return [$evercisegroup->id, $evercisegroup->name]; } /** * @param $evercisegroupId * @param $sessionIds * @return \Illuminate\View\View */ public static function confirmJoinSessions($evercisegroupId, $sessionIds) { $evercisegroup = Evercisegroup::with(array('evercisesession' => function ($query) use (&$sessionIds) { $query->whereIn('id', $sessionIds); }), 'evercisesession')->find($evercisegroupId); if (Sessionmember::where('user_id', Sentry::getUser()->id)->whereIn('evercisesession_id', $sessionIds)->count()) { return 0; } $userTrainer = User::find($evercisegroup->user_id); $members = []; $total = 0; $price = 0; foreach ($evercisegroup->evercisesession as $key => $value) { $members[] = count($value->sessionmembers); // Count those members ++$total; $price = $price + $value->price; } $pricePence = SessionPayment::poundsToPennies($price); return [ 'evercisegroup' => $evercisegroup, 'members' => $members, 'userTrainer' => $userTrainer, 'totalPrice' => $price, 'totalPricePence' => $pricePence, 'totalSessions' => $total, 'sessionIds' => $sessionIds, ]; } /** * Adds the user to the sessions they have purchased. Takes an array of Cart rows, which must be of the same Evercisegroup * * @param $evercisegroupId * @param $cartRows * @param $token * @param $transactionId * @param $paymentMethod * @param $amount * @param $user * @return bool */ public static function addSessionMember($evercisegroupId, $cartRows, $token, $transactionId, $paymentMethod, $amount, $user) { /* get session ids from Cart*/ $sessionIds = []; foreach($cartRows as $row) array_push($sessionIds, $row->options->sessionId); $evercisegroup = Evercisegroup::getGroupWithSpecificSessions($evercisegroupId, $sessionIds); //Make sure there is not already a matching entry in sessionmember /* if (Sessionmember::where('user_id', $user->id)->whereIn('evercisesession_id', $sessionIds)->count()) { return Response::json('error: USER HAS ALREADY JOINED SESSION'); }*/ $userTrainer = User::find($evercisegroup->user_id); $members = []; $total = 0; $price = 0; foreach ($evercisegroup->evercisesession as $key => $value) { $members[] = count($value->sessionmembers); // Count those members ++$total; $price = $price + $value->price; $timestamp = strtotime($value->date_time); $niceTime = date('h:ia', $timestamp); $niceDate = date('dS F Y', $timestamp); Trainerhistory::create(array('user_id' => $evercisegroup->user_id, 'type' => 'joined_session', 'display_name' => $user->display_name, 'name' => $evercisegroup->name, 'time' => $niceTime, 'date' => $niceDate)); } //return var_dump($user); /* Pivot current user with session via session members */ $user->sessions()->attach($sessionIds, ['token' => $token, 'transaction_id' => $transactionId, 'payer_id' => $user->id, 'payment_method' => $paymentMethod]); self::sendSessionJoinedEmail($evercisegroup, $userTrainer, $transactionId); event('session.payed', [$user, $evercisegroup]); event('class.index.single', ['id' => $evercisegroup->id]); Log::info('User '.$user->display_name.' has paid for sessions '.implode(',', $sessionIds).' of group '.$evercisegroupId); self::newMemberAnalytics($transactionId, $amount, $evercisegroup, $sessionIds); return 'done'; } /** * @param $transactionId * @param $amountToPay * @param $evercisegroup * @param $sessionIds */ public static function newMemberAnalytics($transactionId, $amountToPay, $evercisegroup, $sessionIds) { // Grab the "foo" instance $gaTracker = UniversalAnalytics::get('trackerName'); // Require the ecommerce JS file: $gaTracker->ga('require', 'ecommerce', 'ecommerce.js'); // Setup a transaction: $gaTracker->ga('ecommerce:addTransaction', [ 'id' => $transactionId, 'affiliation' => 'evercise', 'revenue' => $amountToPay, ]); // Setup a item for the class: $gaTracker->ga('ecommerce:addItem', [ 'id' => $evercisegroup->id, 'name' => $evercisegroup->name, 'quantity' => count($sessionIds), ]); } /** * Generate the for for leaving a session * * @param $evercisesessionId * @return \Illuminate\View\View */ public static function getLeaveSessionForm($evercisesessionId) { $session = Evercisesession::with('evercisegroup') ->find($evercisesessionId); $sessionDate = new DateTime($session->date_time); $evercoin = Evercoin::where('user_id', Sentry::getUser()->id)->first(); if ($sessionDate > Evercisesession::getFullRefundCutOff()) { $status = 2; $refund = $session->price; } elseif ($sessionDate > Evercisesession::getHalfRefundCutOff()) { $status = 1; $refund = $session->price / 2; } else { $status = 0; $refund = 0; } $refundInEvercoins = Evercoin::poundsToEvercoins($refund); $evercoinBalanceAfterRefund = $evercoin->balance + $refundInEvercoins; return [ 'session' => $session, 'refund' => $refund, 'refundInEvercoins' => $refundInEvercoins, 'evercoinBalanceAfterRefund' => $evercoinBalanceAfterRefund, 'evercoin' => $evercoin, 'status' => $status, ]; } /** * @return DateTime */ public static function getFullRefundCutOff() { return (new DateTime())->add(new DateInterval('P'.Config::get('values')['full_refund_cut_off'].'D')); } /** * @return DateTime */ public static function getHalfRefundCutOff() { return (new DateTime())->add(new DateInterval('P'.Config::get('values')['half_refund_cut_off'].'D')); } /** * @param $evercisesessionId * @return \Illuminate\Http\JsonResponse */ public static function processLeaveSession($evercisesessionId) { $session = Evercisesession::find($evercisesessionId); $sessionDate = new DateTime($session->date_time); /* Determine whether the user can leave, and how much they will receive in refund */ if ($sessionDate > Evercisesession::getFullRefundCutOff()) $status = 2; else if ($sessionDate > Evercisesession::getHalfRefundCutOff()) $status = 1; else $status = 0; if ($status > 0) { Sentry::getUser()->sessions()->detach($session->id); $refund = ($status == 1 ? ($session->price / 2) : $session->price); $refundInEvercoins = Evercoin::poundsToEvercoins($refund); // EVERCOINS NO LONGER EXIST - REPLACE WITH WALLET DEPOSIT //$evercoin = Evercoin::where('user_id', Sentry::getUser()->id)->first(); //$evercoin->deposit($refundInEvercoins); $evercisegroup = Evercisegroup::find($session->evercisegroup_id); $niceTime = date('h:ia', strtotime($session->date_time)); $niceDate = date('dS F Y', strtotime($session->date_time)); Trainerhistory::create(array('user_id' => $evercisegroup->user_id, 'type' => 'left_session_' . ($status == 1 ? 'half' : 'full'), 'display_name' => Sentry::getUser()->display_name, 'name' => $evercisegroup->name, 'time' => $niceTime, 'date' => $niceDate)); $trainer = User::find($evercisegroup->user_id); self::sendLeavingEmails($trainer, $evercisegroup, date('dS M y', strtotime($session->date_time))); event('session.left', [Sentry::getUser(), $evercisegroup, $session]); return Response::json(['message' => ' session: ' . $evercisesessionId, 'callback' => 'leftSession']); } else { return Response::json(['message' => ' Cannot leave session ']); } } /** * @param $trainer * @param $evercisegroup * @param $sessionDate */ public static function sendLeavingEmails($trainer, $evercisegroup, $sessionDate) { event('session.userLeft', [Sentry::getUser(), $trainer, $evercisegroup, $sessionDate]); } /** * @param $evercisegroupId * @param $usecoins * @param $sessionIds * @return \Illuminate\Http\JsonResponse */ public static function getRedeemEvercoinsView($evercisegroupId, $usecoins, $sessionIds) { $evercisegroup = Evercisegroup::with(array('evercisesession' => function ($query) use (&$sessionIds) { $query->whereIn('id', $sessionIds); }))->find($evercisegroupId); $price = 0; foreach ($evercisegroup->evercisesession as $key => $value) $price = $price + $value->price; $priceInEvercoins = Evercoin::poundsToEvercoins($price); // Check if more coins are selected than are needed. if ($usecoins > $priceInEvercoins) $usecoins = $priceInEvercoins; //Check user has tried to use more evercoins than they have. if so, use every last one. $evercoin = Evercoin::where('user_id', Sentry::getUser()->id)->first(); if ($usecoins > $evercoin->balance) $usecoins = $evercoin->balance; $usecoinsInPounds = Evercoin::evercoinsToPounds($usecoins); $amountRemaining = $price - $usecoinsInPounds; $evercoin = Evercoin::where('user_id', Sentry::getUser()->id)->first(); return [ 'priceInEvercoins' => $priceInEvercoins, 'usecoins' => $usecoins, 'evercoinBalance' => $evercoin->balance, 'usecoinsInPounds' => $usecoinsInPounds, 'amountRemaining' => $amountRemaining, ]; } /** * Generates some details for the evercoin payment, and returns them instead of getting them from the session. * to be used by 'addSessionMember()' * * @return array */ public static function generateEvercoinPaymentDetails() { $transactionId = Functions::randomPassword(16); return [ 'paymentMethod' => 'evercoins', 'token' => 'ever' . $transactionId, 'transactionId' => $transactionId ]; } public function formattedDuration() { $hours = floor($this->duration / 60); $minutes = $this->duration % 60; return ($hours ? $hours . ' hours ' : '') . ( $minutes . ' minutes'); } public function formattedDate() { return date('D jS M Y', strtotime($this->date_time)); } public function formattedTime() { return date('h:i A', strtotime($this->date_time)); } public function remainingTickets() { return $this->tickets - count($this->sessionmembers); } public function isInPast() { if (new DateTime($this->date_time) < new DateTime()) return true; else return false; } }<file_sep>/app/controllers/CartController.php <?php class CartController extends \BaseController { /** * @var Packages */ private $packages; public function __construct(Packages $packages) { $this->packages = $packages; } public function getCart() { $coupon = Session::get('coupon', FALSE); $data = [ 'cart' => EverciseCart::getCart($coupon), ]; /** Figure out how the hell are we going to display the Cart */ return View::make('v3.cart.checkout') ->with('data', $data); } public function checkout($step = 0) { $coupon = Session::get('coupon', FALSE); $data = EverciseCart::getCart($coupon); if (empty($data['sessions_grouped']) && empty($data['packages']) && empty($data['sessions'])) { return Redirect::route('home'); } $packages = []; foreach ($this->packages->orderBy('classes', 'asc')->orderBy('price', 'asc')->get() as $package) { $packages[$package->style][] = $package; } $data['coupon'] = $coupon; $data['step'] = $step; $data['user'] = Sentry::getUser(); $data['packages_available'] = $packages; $data['cart'] = View::make('v3.cart.dropdown')->with(EverciseCart::getCart())->render(); return View::make('v3.cart.checkout', $data); } public function paymentError() { die('shit'); } }<file_sep>/public/assets/jsdev/angular/search-controller.js if(typeof angular != 'undefined') { app.controller('searchController', ["$scope", "$http" , "uiGmapGoogleMapApi", "Angularytics", function ($scope, $http, uiGmapGoogleMapApi, Angularytics) { $scope.groupHeight = function(){ var windowWidth = $(window).width(); if(windowWidth >992 ){ var resultsHeight = $('.results').outerHeight(); var headHeight = $('.results .heading').outerHeight(); var tabHeight = $('.results .nav-tabs').outerHeight(); var dateHeight = $('.results .date-picker-inline').outerHeight(); var groupHeight = resultsHeight - headHeight - tabHeight - dateHeight; return{ height : groupHeight+'px' } } else { return { height: 'auto' } } } $scope.width = window.innerWidth; $scope.results = laracasts.results; $scope.resultsLoading = false; $scope.view = 'list'; // switch the view $scope.switchView = function(view){ $scope.resultsLoading = true; $scope.view = view; $scope.resultsLoading = false; } // map options $scope.mapOptions = { disableDefaultUI: true, zoomControl : true, backgroundColor: '#383d48', panControl: false } // cluster options $scope.clusterStyles = [ { textColor: 'white', url: '/assets/img/icon_default_small_pin_number.png', height: 43, width: 33, anchorText: [-14,9] } ]; $scope.clusterOptions = { title: 'click to expand', gridSize: 5, maxZoom: 20, styles: $scope.clusterStyles, zoomOnClick: false }; $scope.markerEvents = { click: function (marker,e,model) { // remove select venue $scope.selectedVenueIds = false; // toggle markers $scope.lastActiveMarker.icon = '/assets/img/icon_default_small_pin.png'; $scope.lastActiveMarker = model; model.icon = '/assets/img/icon_default_large_pink.png'; panToMarker(model); setTimeout(function() { $('.mb-scroll').mCustomScrollbar("scrollTo", $('#group-'+model.id), { scrollInertia: 500, timeout: 20 }); }, 500) }, mouseover: function (marker,e,model) { $('#venue-'+model.id).addClass('active'); }, mouseout: function (marker,e,model) { $('#venue-'+model.id).removeClass('active'); } } $scope.selectedVenueIds = false; $scope.selectedVenueName = false; $scope.clusterEvents = { click: function (cluster, clusterModels) { $scope.selectedVenueIds = false; var center = cluster.getCenter(); // zoom into cluster var map = $scope.map.control.getGMap(); var newlatlng = new google.maps.LatLng(center.lat(), center.lng()); map.panTo(newlatlng); var svi = []; angular.forEach(clusterModels,function(value,key){ svi.push(value.id); } ) $scope.selectedVenueIds = svi; $scope.selectedVenueName = clusterModels[0].venue.name; // toggle markers $scope.lastActiveMarker.icon = '/assets/img/icon_default_small_pin.png'; $scope.lastActiveMarker = cluster; }, mouseover: function (cluster, clusterModels) { angular.forEach(clusterModels,function(value,key){ $('#venue-'+value.id).addClass('active'); } ) }, mouseout: function (cluster, clusterModels) { angular.forEach(clusterModels,function(value,key){ $('#venue-'+value.id).removeClass('active'); } ) } }; // current search radius $scope.radius = $scope.results.radius; // set initial zoom $scope.initialZoom = function(){ var radius = $scope.results.radius.substring(0, $scope.results.radius.length - 2); var results = $scope.results.results.total; if(results == 1){ var distance = $scope.results.results.hits[0].distance; if(distance > 7){ return 10 } else if(distance > 5){ return 12 } else if(distance > 2){ return 14 } } if(radius == 1){ return 14 } else if(radius == 3) { return 13 } else if(radius == 5){ return 12 } else if(radius == 10){ return 11 } } $scope.circleOptions = { center: { latitude: $scope.results.area.lat, longitude: $scope.results.area.lng }, stroke: { color: '#50c3e2', weight: 2 }, fill: { opacity: 0 }, radius: $scope.results.radius.substring(0, $scope.results.radius.length - 2) * 1609.344 } // map object $scope.setMapCenter = function(){ var radius = $scope.results.radius.substring(0, $scope.results.radius.length - 2); var lng = $scope.results.area.lng; if($scope.width >= 992 ){ if(radius == 10){ return lng + 0.13; } if(radius == 5){ return lng + 0.09; } if(radius == 3){ return lng + 0.04; } if(radius == 1){ return lng + 0.02; } } else{ return lng; } } $scope.map = { zoom: $scope.initialZoom(), maxZoom: 16, center: { latitude: $scope.results.area.lat, longitude: $scope.setMapCenter()}, control: {}, clusterOptions: $scope.clusterOptions }; // map events $scope.mapEvents = {} // class results $scope.lastActiveMarker = {}; shapeEverciseGroups = function(){ var groups = []; angular.forEach($scope.results.results.hits, function(v,k){ groups.push({ id : v.id, name : v.name, icon : '/assets/img/icon_default_small_pin.png', venue : { id : v.id, name : v.venue.name, postcode : v.venue.postcode, latitude : v.venue.lat, longitude : v.venue.lng }, slug: v.slug, remaining: v.futuresessions[0].remaining, times : v.times , price : v.default_price, image : '/'+v.user.directory+'/preview_'+v.image }) }) return groups; } $scope.everciseGroups = shapeEverciseGroups(); // pan to var panToMarker = function(marker){ var map = $scope.map.control.getGMap(); var newlatlng = new google.maps.LatLng(marker.venue.latitude, marker.venue.longitude); map.panTo(newlatlng); } // scroll dates $scope.scrollWidth = function(){ var singleWidth = $('.date-picker-inline li .day').outerWidth(); var noOfDates = Object.keys($scope.results.available_dates).length; return { width: (singleWidth * noOfDates) + 'px' } } $scope.scrollBtnWidth = function(){ if($scope.width < 992) { var containerWidth = $scope.width - ($('.date-picker-inline .scroll').outerWidth() * 2 ); if($scope.width > 767) { var dateWidth = containerWidth / 14; } else{ var dateWidth = containerWidth / 5; } return { width: dateWidth + 'px' } } } $scope.scroll_clicked = false; $scope.scrollDates = function(direction, e){ e.preventDefault(); $scope.scroll_clicked = true; var par = $(e.target).parent(); if($scope.width < 992){ var width = par.outerWidth() - ($('.date-picker-inline .scroll').outerWidth() * 2 ); } else{ var width = par.width(); } var content = par.find('.content'); var mg = parseInt(content.css('margin-left')); var contentWidth = -content.width(); if(direction == 'right'){ var newMg = mg - width; } else{ var newMg = mg + width; } if(newMg <= 0 && newMg >= contentWidth){ par.find('.content').css({ 'margin-left' : newMg+'px' }) } setTimeout(function() { $scope.scroll_clicked = false; }, 500) } // the selected date $scope.selectedDate = $scope.results.selected_date; // date clicked $scope.changeSelectedDate = function(e, date){ e.preventDefault(); $scope.selectedDate = date; $scope.getData(); } // update filter results $scope.openFilter = null; $(document).on('click','.filter-btn, .sort-btn', function(e){ e.preventDefault(); closeTab($(this)); } ) var closeTab = function(tab){ if(tab.attr('class') == $scope.openFilter){ $scope.openFilter = null; window.setTimeout(function(){ $(".tab-pane").removeClass('active'); tab.parent('li').removeClass('active'); },1); }else{ $scope.openFilter = tab.attr('class'); } } // sort results $scope.sortChanged = function(e, sort){ e.preventDefault(); $scope.results.sort = sort; $scope.getData(); } // url to use for ajax calls $scope.url = $scope.results.url; // function used for getting data from the server $scope.getData = function(){ var path = '/ajax/uk/'; var req = { method: 'POST', url: path+$scope.url, headers: { 'X-CSRF-Token': TOKEN }, data: { date : $scope.selectedDate, radius : $scope.results.radius, sort : $scope.results.sort, search : $scope.results.search } } var responsePromise = $http(req); // close tab $scope.openFilter = null; $(".tab-pane").removeClass('active'); $('.filter-btn, .sort-btn').parent().removeClass('active'); // bring up mask $scope.resultsLoading = true; responsePromise.success(function(data) { $scope.results = data; $scope.selectedDate = $scope.results.selected_date; $scope.everciseGroups = shapeEverciseGroups(); $scope.resultsLoading = false; $scope.circleOptions = { center: { latitude: $scope.results.area.lat, longitude: $scope.results.area.lng }, stroke: { color: '#50c3e2', weight: 2 }, fill: { opacity: 0 }, radius: $scope.results.radius.substring(0, $scope.results.radius.length - 2) * 1609.344 } $scope.map.center = { latitude: $scope.results.area.lat, longitude: $scope.setMapCenter() }; $scope.map.zoom = $scope.initialZoom(); }); responsePromise.error(function(data) { $scope.resultsLoading = false; }); } $(window).resize(function(){ $scope.width = window.innerWidth; }); $scope.$watch('width', function(value) { if(value < 768){ $scope.view = 'list'; } }); // google anayltics $scope.gaEventTrigger = function(cat,action, label ) { Angularytics.trackEvent(cat, action, label); } }]) }<file_sep>/app/controllers/MessageController.php <?php class MessageController extends \BaseController { public function getConversation($displayName) { $convId = Messages::getConversationIdByDisplayName($this->user->id, $displayName); if(! ($convId > 0)) return Redirect::route('users.edit', [$this->user->id]); $conv = Messages::getMessages($this->user->id, $convId); // Flip list of messages so they read top to bottom. $messages = []; foreach ( $conv->getAllMessages() as $msg ) { array_unshift($messages, [ 'display_name'=> ($msg->getSender() == $this->user->id ? $this->user->display_name : $displayName), 'message' => $msg ]); } $conversations = Messages::getConversations($this->user->id); Messages::markRead($this->user->id, $convId); return View::make('v3.users.messages.conversation') ->with('user', $this->user) ->with('buddysDisplayName', $displayName) ->with('messages', $messages) ->with('conversations', $conversations); } public function postMessage($displayName) { $body = Input::get('mail_body'); $recipient = \User::where('display_name', $displayName)->first(); Messages::sendMessageByDisplayName($this->user->id, $displayName, $body); event('user.message.reply', [ 'sender' => $this->user, 'recipient' => $recipient, 'body' => $body ]); return Redirect::route('conversation', [$displayName])->with('message', 'Message sent!'); } }<file_sep>/app/events/Stats.php <?php namespace events; use Log, Event; class Stats { public function classViewed($class) { Log::info('Class Viewed '.$class->id); if(!$class instanceof \Evercisegroup) { $class = \Evercisegroup::find($class->id); } $class->increment('counter'); } }<file_sep>/app/composers/UpcomingPastSessions.php <?php namespace composers; class UpcomingPastSessions { public function compose($view) { // get view data $viewdata= $view->getData(); // set arrays $futureDates = array(); $pastDates = array(); $dt = date('Y-m-d H:i:s'); // loop through view data array with session dates key foreach ($viewdata['sessionDates'] as $key => $value) { if (empty($value) ) { $futureDates[] = null; $pastDates[] = null; }else{ foreach ($value as $k => $val) { if (strtotime($val) >= strtotime($dt) ) { $futureDates[$key][$k] = $val; }else{ $pastDates[$key][$k] = $val; } } } } $key = (isset($viewdata['EGindex'])) ? $viewdata['EGindex'] : $viewdata['key']; //$key = $viewdata['EGindex'] ; // $view->with('futureDates', $futureDates)->with('pastDates', $pastDates)->with('key', $key); } }<file_sep>/app/database/migrations/2014_07_30_143812_create_foreign_keys_3.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateForeignKeys3 extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users_groups', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); $table->foreign('group_id')->references('id')->on('groups'); }); Schema::table('sessionpayments', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); //$table->foreign('evercisesession_id')->references('id')->on('evercisesessions'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users_groups', function(Blueprint $table) { $table->dropForeign('users_groups_user_id_foreign'); $table->dropForeign('users_groups_group_id_foreign'); }); Schema::table('sessionpayments', function(Blueprint $table) { $table->dropForeign('sessionpayments_user_id_foreign'); //$table->dropForeign('sessionpayments_evercisesession_id_foreign'); }); } } <file_sep>/app/start/artisan.php <?php /* |-------------------------------------------------------------------------- | Register The Artisan Commands |-------------------------------------------------------------------------- | | Each available Artisan command must be registered with the console so | that it is available to be called. We'll register every command so | the console gets access to each of the command object instances. | */ Artisan::add(new CheckSessions); Artisan::add(new CheckPayments); Artisan::add(new SendEmails); Artisan::add(new SendExtraEmails); Artisan::add(new SalesForceCommand); Artisan::add(new IndexerCreate); Artisan::add(new IndexerIndex); Artisan::add(new IndexerImport); Artisan::add(new IndexerGeo); Artisan::add(new ConvertImages); Artisan::add(new GenerateUrls); Artisan::add(new GalleryImport); Artisan::add(new FixImages); Artisan::add(new FixDisplayNames); Artisan::add(new UpdateUserNewsletter); Artisan::add(new FixLocation); <file_sep>/app/config/evercise.php <?php $timeArray = []; $durationArray = []; $priceArray = []; foreach (range(strtotime("00:00"), strtotime("24:00"), 15 * 60) as $time) { $timeArray[date("H:i", $time)] = date("H:i", $time); } foreach (range(0, 125, 5) as $mins) { $durationArray[str_pad($mins, 2, '0', STR_PAD_LEFT)] = str_pad($mins, 2, '0', STR_PAD_LEFT) . ' mins'; } foreach (range(1, 300) as $pounds) { $priceArray[number_format($pounds / 2, 2)] = '£' . number_format($pounds / 2, 2); } return [ 'mindbody' => [ 'api_key' => 'Evercise', 'api_secret' => '<KEY> ], 'stripe_testing' => false, 'stripe_api_key' => getenv('STRIPE_API_KEY') ?: false, 'stripe_pub_key' => getenv('STRIPE_PUB_KEY') ?: false, 'stripe_api_key_test' => getenv('STRIPE_API_KEY_TEST') ?: false, 'stripe_pub_key_test' => getenv('STRIPE_PUB_KEY_TEST') ?: false, 'transaction_types' => [ 'wallettoppup', 'cartcompleted', 'topupcompleted', 'milestonecompleted', 'withdrawcompleted' ], 'minimim_withdraw' => 5, 'payments_to_trainers' => 'Monday 4pm', 'pending_emails' => ['<EMAIL>'], 'commission' => 10, //Default commission 'upload_dir' => 'files/', 'testing_ips' => ['192.168.127.12', '192.168', '127.0.0'], 'per_page' => [3, 12, 24, 48, 96], 'default_per_page' => 96, 'max_display_map_results' => 300, 'radius' => [ '1/2 mile' => '0.5mi', '1 mile' => '1mi', '2 miles' => '2mi', '3 miles' => '3mi', '5 miles' => '5mi', '10 miles' => '10mi', '25 miles' => '25mi' ], 'time' => $timeArray, 'duration' => $durationArray, 'tickets' => array_combine(range(1, 120), range(1, 120)), 'price' => $priceArray, 'default_radius' => '10mi', 'article_main_image' => [ 'regular' => [ 'width' => 600, 'height' => 284 ], 'thumb' => [ 'width' => 200, 'height' => 200 ] ], 'user' => [ 'activities' => 100, // Limit ], 'article_category_main_image' => [ 'width' => 600, 'height' => 284 ], 'venue_images' => [ 'regular' => [ 'width' => 1000, 'height' => 750 ], 'thumb' => [ 'width' => 200, 'height' => 150 ] ], 'cover_image' => [ 'regular' => [ 'width' => 1000, 'height' => 400 ], 'thumb' => [ 'width' => 200, 'height' => 80 ] ], 'class_images' => [ ['prefix' => 'cover', 'width' => 1920, 'height' => 820], [ 'prefix' => 'preview', 'width' => 409, 'height' => 308 ], [ 'prefix' => 'module', 'width' => 315, 'height' => 250 ], [ 'prefix' => 'thumb', 'width' => 150, 'height' => 166 ], [ 'prefix' => 'search', 'width' => 125, 'height' => 120 ] ], 'user_images' => [ ['prefix' => 'large', 'width' => 300, 'height' => 300], ['prefix' => 'medium', 'width' => 200, 'height' => 200], ['prefix' => 'small', 'width' => 100, 'height' => 100] ], 'slider_images' => [ ['prefix' => 'cover', 'width' => 2000, 'height' => 1000], ['prefix' => 'medium', 'width' => 1000, 'height' => 500], ['prefix' => 'thumb', 'width' => 200, 'height' => 200] ], /** SEO CRAP */ 'seo_keywords' => [ 'Excercise', 'Remind', 'Iggy', 'TO', 'ADD', 'KEYWORDS', '!!!!!' ], 'blog' => [ 'title' => 'Evercise Gym and Fitness Events Blog', 'keywords' => 'fitness blog, evercise', 'description' => 'Evercise London Fitness Events blog provides various information related to Fitness programs, Fitness tips and Events information with pictures and videos.' ], 'gallery' => [ 'image_counter' => 3, 'sizes' => [ ['prefix' => 'main', 'width' => 1920, 'height' => 820], ['prefix' => 'thumb', 'width' => 205, 'height' => 87] ] ], 'article_no_img' => '/files/article/no-img.jpg' ];<file_sep>/public/assets/jsdev/prototypes/25-topup.js function topUp(form){ this.form = form; this.amount = 0; this.payAmount = 0 this.stripe = {}; this.init(); } topUp.prototype = { constructor: topUp, init: function(){ $('#stripe-button').prop('disabled', true); $('#fb-pay').addClass('disabled'); this.addListeners(); }, addListeners : function(){ this.form.find('.add-btn').on('click', $.proxy(this.topUpAmount, this)) this.form.find('input[name="custom"]').on('keyup change', $.proxy(this.topUpAmount, this)) this.form.find('#cancel-btn').on('click', $.proxy(this.cancelTopUp, this)) this.form.find('input[name="amount"]').on('change', $.proxy(this.amountChanged, this)) this.form.find('#stripe-button').on('click', $.proxy(this.openStripe, this)) $(window).on('popstate', $.proxy(this.closeStripe, this)); this.form.on('submit', $.proxy(this.submitForm, this)) }, topUpAmount: function(e){ e.preventDefault(); this.amount = $(e.target).val() ? $(e.target).val() : $(e.target).data('amount'); this.form.find('.add-btn').removeClass('btn-primary'); this.form.find('input[name="custom"]').removeClass('btn-primary'); $(e.target).addClass('btn-primary'); this.updateAmountInput() }, cancelTopUp: function(e){ e.preventDefault(); this.amount = 0 this.form.find('.add-btn').removeClass('btn-primary'); this.form.find('input[name="custom"]').removeClass('btn-primary'); this.updateAmountInput() }, updateAmountInput: function(){ this.form.find('input[name="amount"]').val( this.amount).trigger('change'); }, amountChanged: function(){ $('#stripe-button').prop('disabled', true) $('#fb-pay').addClass('disabled'); if( this.amount > 0 ){ var oldValue = this.amount; var self = this; // gives the user 1 second for them to click another value setTimeout(function() { var newValue = self.amount; if(oldValue == newValue){ self.form.trigger('submit'); } },1000); } }, openStripe: function(e){ var self = this; // Open Checkout with further options handler.open({ name: 'Evercise', description: 'Top up', amount: self.payAmount }); e.preventDefault(); }, closeStripe: function(e){ handler.close(); }, submitForm: function(e){ e.preventDefault(); this.ajaxUpload(); }, ajaxUpload: function () { var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find('.add-btn').prop('disabled', true); self.form.find('input[name="custom"]').prop('disabled', true); }, success: function (data) { $('#stripe-button').prop('disabled', false); $('#fb-pay').removeClass('disabled'); self.payAmount = data.amount; }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find('.add-btn').prop('disabled', false); self.form.find('input[name="custom"]').prop('disabled', false); } }); } }<file_sep>/app/assets/javascripts/video.js function initPlayVideo(){ $("#playButton").click(function(e){ var url = this.href; $.ajax({ url: url, type: 'GET', dataType: 'html' }) .done( function(data) { $('.mask').show(); $('.lower_footer').append(data); videoControl(); } ); return false; }); } registerInitFunction('initPlayVideo'); /*** * auto play the video ***/ function videoControl(){ $('.video').get(0).play(); }<file_sep>/app/composers/AutocompleteLocationComposer.php <?php namespace composers; use JavaScript; class AutocompleteLocationComposer { public function compose($view) { JavaScript::put(array('initAutocompleteLocation' => 1) ); } }<file_sep>/app/models/Marketingpreference.php <?php /** * Class Marketingpreference */ class Marketingpreference extends \Eloquent { /** * @var array */ protected $guarded = array('id', 'name', 'option'); /** * The database table used by the model. * * @var string */ protected $table = 'marketingpreferences'; /* public function User_marketingpreferences() { return $this->belongsToMany('User', 'user_marketingpreferences', 'user_id', 'marketingpreferences_id'); } */ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function users() { return $this->belongsToMany('User'); } }<file_sep>/app/cronjobs/CheckPayments.php <?php namespace cronjobs; use Illuminate\Log\Writer; use Illuminate\Console\Application as Artisan; class CheckPayments { private $log; private $artisan; public function __construct(Writer $log, Artisan $artisan) { $this->log = $log; $this->artisan = $artisan; } function run() { $this->log->info('Moving all sessions to payments'); $this->artisan->call('check:payments'); $this->log->info('Move Money to User Wallet'); $this->artisan->call('check:sessions'); } } <file_sep>/public/assets/jsdev/angular/01-services.js if(typeof angular != 'undefined') { /*app.service('dataService', function ($http) { delete $http.defaults.headers.common['X-Requested-With']; this.getData = function () { // $http() returns a $promise that we can add handlers with .then() return $http({ method: 'Post', url: '/ajax/map/uk/london‏', params: '', headers: {'Authorization': 'Token token='} }); } }); */ }<file_sep>/app/controllers/TransactionController.php <?php use Illuminate\Log\Writer; class TransactionController extends BaseController { /** * @var Transactions */ private $transactions; /** * @var TransactionItems */ private $items; /** * @var Writer */ private $log; public function __construct(Transactions $transactions, TransactionItems $items, Writer $log) { parent::__construct(); $this->transactions = $transactions; $this->items = $items; $this->log = $log; } public function show($id) { $transaction = $this->transactions->find($id); if ($this->user->id != $transaction->user_id) { return Redirect::route('home'); } $items = $transaction->items; $total = 0; foreach ($items as $item) { $total += $item->amount; } $single = TRUE; $content = View::make('v3.cart.invoice', compact('transaction', 'items', 'total', 'single'))->render(); return View::make('v3.cart.invoice_wrapper', compact('content')); } public function download($id) { $transaction = $this->transactions->find($id); if ($this->user->id != $transaction->user_id) { return Redirect::route('home'); } $items = $transaction->items; $total = 0; foreach ($items as $item) { $total += $item->amount; } $view = View::make('v3.cart.invoice', compact('transaction', 'items', 'total')); return PDF::load($view, 'A4', 'portrait')->download('Invoice_' . $id.'.pdf'); } }<file_sep>/app/config/elasticsearch.php <?php use Monolog\Logger; return [ 'hosts' => [ (getenv('ELASTIC_HOST') ?: 'ec2-54-72-203-163.eu-west-1.compute.amazonaws.com:9200') ], 'logPath' => storage_path().'/logs/elasticsaerch.log', 'logLevel' => Logger::INFO ];<file_sep>/app/models/Articles.php <?php /** * Articles Models */ class Articles extends Eloquent { /** * @var array */ protected $fillable = array( 'id', 'category_id', 'page', 'title', 'main_image', 'meta_title', 'thumb_image', 'onmain', 'description', 'intro', 'keywords', 'content', 'permalink', 'status', 'published_on' ); protected $dates = ['published_on']; /** * The database table used by the model. * * @var string */ protected $table = 'articles'; public function category() { return $this->hasOne('ArticleCategories', 'id', 'category_id'); } public static function createUrl($article, $full = false) { $url = ''; if ($article->category_id > 0 && $article->page == 0) { $url .= $article->category->permalink . '/'; } $url .= $article->permalink; if($full) { return URL::to($url); } return $url; } public function getMainPageArticles($limit = 3) { return static::where('onmain', 1)->limit($limit)->get(); } } <file_sep>/public/assets/jsdev/prototypes/2-user-profile.js var Profile = function (nav) { this.nav = nav; this.top = 0; this.speed = 400; this.init(); } Profile.prototype = { constructor: Profile, // tempary switch between views init: function () { this.top = Math.floor( this.nav.offset().top - this.nav.outerHeight(true) ); var self = this; $(document).on('click', '.nav-pills li a', function(){ destination = $(this).attr('href'); $('.nav-pills li').removeClass('active'); $(this).parent().addClass('active'); $('.profile-panels').addClass('hidden'); $(destination).removeClass('hidden'); new Masonry( $('.masonry') ); self.scroll(); }) }, scroll: function(){ // $('html, body').animate({scrollTop : this.top }, this.speed); } }<file_sep>/app/models/Mindbody.php <?php use Carbon\Carbon; use MindbodyAPI\structures\UserCredentials; use MindbodyAPI\MindbodyClient; class Mindbody { private $siteId; private $api_key; private $api_secret; private static $service = NULL; public function __construct(User $user) { $this->user = $user; $this->siteId = $user->mindbody->site_id; $this->api_key = Config::get('evercise.mindbody.api_key'); $this->api_secret = Config::get('evercise.mindbody.api_secret'); $this->user_credentials = new UserCredentials(); $this->user_credentials->Username = $user->mindbody->user_login; $this->user_credentials->Password = <PASSWORD>; $this->user_credentials->SiteIDs = [(int)$user->mindbody->site_id]; } /************ VENUES ***************/ public function importVenues() { $venues = $this->getVenues(); $ids = []; foreach ($venues as $v) { $v = array_filter($v); $venue = VenueImport::where($v); if ($venue->count() == 0) { $venue = VenueImport::create($v); echo 'NEW <br/>'; } else { $venue = $venue->first(); echo 'OLD <br/>'; } /** Not Sure what to do with the venue here */ $ids[] = $venue->id; } return $ids; } public function getVenues() { $service = $this->getService('SiteService'); $request = $service::request('GetLocations', $this->credentials); $apiLocations = $service->GetLocations($request); $locations = []; if ($apiLocations->ErrorCode == 200) { if ($apiLocations->ResultCount == 0) { return FALSE; } foreach ($apiLocations->Locations->Location as $l) { $locations[] = [ 'user_id' => $this->user->id, 'external_id' => $l->ID, 'name' => $l->Name, 'source' => 'mindbody', 'address' => $l->Address, 'town' => $l->City, 'postcode' => $l->PostalCode, 'lat' => $l->Latitude, 'lng' => $l->Longitude, 'image' => $l->ImageURL ]; } } return $locations; } public function getUserMindbodyId($user) { $client = [ 'Email' => $user-><EMAIL>', 'City' => 'London', 'FirstName' => $user->first_name, 'LastName' => $user->last_name, 'BirthDate' => '1950-10-10T10:10:10', 'AddressLine1' => '4 Wessley Terrace', 'State' => 'London', 'PostalCode' => 'N1 7NA', 'MobilePhone' => '07654566543', 'ReferredBy' => '100015649' ]; $service = $this->getService('ClientService'); $request = $service::request('AddOrUpdateClients', $this->credentials, null, ['Clients' => (object)['Client' => (object)$client]]); try { $apiClasses = $service->AddOrUpdateClients($request); } catch( SoapFault $e) { d($e); } d($apiClasses, false); return $apiClasses->Clients->Client->ID; } public function addUserToClass($classId= 0, User $user){ $client_ID = $this->getUserMindbodyId($user); // $client_ID = 100015649; $unset = [ 'RequirePayment', 'Waitlist', 'SendEmail' ]; $service = $this->getService('ClassService'); $request = $service::request('AddClientsToClasses', $this->credentials, $this->user_credentials, ['Test' => true, 'ClientIDs' => [$client_ID], 'ClassIDs' => [$classId]], $unset); $apiClasses = $service->AddClientsToClasses($request); return $apiClasses; } /************ CLASSES ***************/ public function importClasses() { $classes = $this->getClassSchedules(); $ids = []; foreach ($classes as $c) { $v = array_filter($v); $venue = VenueImport::where($v); if ($venue->count() == 0) { $venue = VenueImport::create($v); echo 'NEW <br/>'; } else { $venue = $venue->first(); echo 'OLD <br/>'; } /** Not Sure what to do with the venue here */ $ids[] = $venue->id; } d($ids); } //['ClassScheduleIDs' => [2206] public function getClassScheduless($classID = 0) { $service = $this->getService('ClassService'); $request = $service::request('GetClassSchedules', $this->credentials, null); $apiClasses = $service->GetClassSchedules($request); return $apiClasses; } public function getClassVisits($classID = 0) { $service = $this->getService('ClassService'); $request = $service::request('GetClassVisits', $this->credentials, null, ['ClassID' => 2152]); $apiClasses = $service->GetClassVisits($request); return $apiClasses; } public function getSchedules() { $service = $this->getService('ClassService'); $request = $service::request('GetClassSchedules', $this->credentials); $apiClasses = $service->GetClassSchedules($request); return $apiClasses; $schedules = []; if ($apiClasses->ErrorCode == 200) { if ($apiClasses->ResultCount == 0) { return FALSE; } foreach ($apiClasses->ClassSchedules->ClassSchedule as $c) { $schedules[$c->ClassScheduleID] = [ // 'visits' => $ ]; } } return $classes; } public function getEnrollments($classId = 0) { $service = $this->getService('ClassService'); $request = $service::request('GetEnrollments', $this->credentials, null); $apiClasses = $service->GetEnrollments($request); return $apiClasses; } public function formatClassDescription($class) { return [ 'user_id' => $this->user->id, 'evercisegroup_id' => 0, 'external_id' => $class->ClassDescription->ID, 'external_venue_id' => $class->Location->ID, 'source' => 'mindbody', 'name' => $class->ClassDescription->Name, 'description' => $class->ClassDescription->Description, 'image' => $class->ClassDescription->ImageURL ]; } public function getClassSchedules() { $service = $this->getService('ClassService'); $request = $service::request('GetClassSchedules', $this->credentials); $apiClasses = $service->GetClassSchedules($request); return $apiClasses; $classes = []; if ($apiClasses->ErrorCode == 200) { if ($apiClasses->ResultCount == 0) { return FALSE; } foreach ($apiClasses->ClassSchedules->ClassSchedule as $c) { /** Pull Out the actual Class of this */ $class = $this->formatClassDescription($c); $sessions = $this->formatClassSessions($c); d($class); /** * $class = [ * * * * ]; * $classes[] = [ * 'external_id' => $c->ClassDescription->ID, * 'user_id' => $this->user->id, * 'name' => $c->Name, * 'title' => $c->Name, * 'description' => $c->Description, * 'image' => $c->ImageURL, * ]; * * +Classes: null * +Clients: null * +Course: null * +SemesterID: null * +IsAvailable: null * +Action: null * +ID: 2255 * +ClassDescription: ClassDescription {#1051 ▼ * +ImageURL: null * +Level: Level {#1052 ▶} * +Action: null * +ID: 69 * +Name: "<NAME>" * +Description: "As the name suggests, this class places a strong and fast demand on one’s awareness, agility and strength. We will walk you into the inner depths of your practice and help you cultivate the strength, alertness and concentration needed to achieve improved vitality. Not recommended for the faint hearted!" * +Prereq: "" * +Notes: "" * +LastUpdated: "2011-03-03T06:17:11" * +Program: Program {#1053 ▶} * +SessionType: SessionType {#1054 ▶} * } * +DaySunday: false * +DayMonday: true * +DayTuesday: true * +DayWednesday: true * +DayThursday: false * +DayFriday: true * +DaySaturday: true * +StartTime: "1899-12-30T16:30:00" * +EndTime: "1899-12-30T17:45:00" * +StartDate: "2015-01-21T00:00:00" * +EndDate: "2016-01-21T00:00:00" * +Staff: Staff {#1055 ▼ * +Appointments: null * +Unavailabilities: null * +Availabilities: null * +Email: null * +MobilePhone: null * +HomePhone: null * +WorkPhone: null * +Address: null * +Address2: null * +City: null * +State: "CA" * +Country: null * +PostalCode: null * +ForeignZip: null * +LoginLocations: null * +Action: null * +ID: 100000279 * +Name: "<NAME>" * +FirstName: "Ashley" * +LastName: "Knight" * +ImageURL: "https://clients.mindbodyonline.com/studios/DemoAPISandboxRestore/staff/100000279_large.jpg?imageversion=1423538749" * +Bio: null * +isMale: false * +"SortOrder": 0 * } * +Location: Location {#1056 ▼ * +BusinessID: null * +SiteID: -99 * +BusinessDescription: "YEGFit PASS is part of the YEG Fitness Family. Bringing you all things fitness and wellness in the Edmonton area." * +AdditionalImageURLs: {#1057} * +FacilitySquareFeet: null * +TreatmentRooms: null * +ProSpaFinderSite: null * +HasClasses: false * +PhoneExtension: "" * +Action: null * +ID: 1 * +Name: "Clubville" * +Address: "4051 S Broad St" * +Address2: "San Luis Obispo, CA 93401" * +Tax1: 0.08 * +Tax2: 0.05 * +Tax3: 0.05 * +Tax4: 0.0 * +Tax5: 0.0 * +Phone: "8777554279" * +City: "San Luis Obispo" * +StateProvCode: "CA" * +PostalCode: "93401" * +Latitude: 35.2470788 * +Longitude: -120.6426145 * +DistanceInMiles: null * +ImageURL: null * +Description: null * +HasSite: null * +CanBook: null * } **/ } } } public function getProducts() { $service = $this->getService('SaleService'); $request = $service::requestBody('GetServices', $this->credentials, $this->user_credentials, ['LocationID' => 'null', 'HideRelatedPrograms' => 'null']); try { $apiClasses = $service->GetServices($request); } catch (SoapFault $e) { d($service, FALSE); d($service->__getLastRequest(), FALSE); echo $e->getMessage(); die('done'); } return $apiClasses; } public function getClasses() { $service = $this->getService('ClassService'); $request = $service::request('GetClasses', $this->credentials, $this->user_credentials); $apiClasses = $service->GetClasses($request); return $apiClasses; } public function getSessions() { $service = $this->getService('ClassService'); $request = $service::request('GetClasses', $this->credentials); $apiClasses = $service->GetClasses($request); return $apiClasses; $sessions = []; if ($apiClasses->ErrorCode == 200) { if ($apiClasses->ResultCount == 0) { return FALSE; } foreach ($apiClasses->Classes->Class as $c) { $start = date('Y-m-d'); $carbon = \Carbon\Carbon::parse($c->StartDateTime); $sessions[] = [ 'external_id' => $c->ID, 'external_site_id' => $this->siteId, 'external_venue_id' => $c->Location->ID, 'external_class_id' => $c->ClassDescription->ID, 'date_time' => $carbon->toDateTimeString(), 'duration' => $carbon->diffInMinutes(\Carbon\Carbon::parse($c->EndDateTime)), 'price' => $c->ClassDescription->Name, 'description' => $c->ClassDescription->description, 'capacity' => $c->MaxCapacity, 'image' => $c->ClassDescription->ImageURL, ]; ['evercisegroup_id', 'date_time', 'price', 'duration', 'members_emailed', 'tickets']; $classes[] = [ 'user_id', 'category_id', 'venue_id', 'name', 'title', 'slug', 'description', 'image', 'gender', 'capacity', 'default_duration', 'default_price', 'published' ]; } } return $classes; } /** STUPID STATIC LIBRARY!!! */ public function getService($serviceType) { $service = MindbodyClient::service($serviceType); $this->credentials = $service::credentials( $this->api_key, $this->api_secret, [$this->siteId] ); return $service; } private function formatClassSessions($class) { $sessions = []; $startDate = new \Carbon\Carbon($class->StartDate); $endDate = new \Carbon\Carbon($class->EndDate); foreach (range(0, $startDate->diffInDays($endDate)) as $days) { $session = []; $day = $startDate->addDays($days); $timeStart = strtotime(str_replace('1899-12-30T', '', $class->StartTime)); $timeEnd = strtotime(str_replace('1899-12-30T', '', $class->EndTime)); $duration = round(($timeEnd - $timeStart) / 60, 0); $days = [ 0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday' ]; $dayVar = 'Day' . $days[$day->dayOfWeek]; if ($class->{$dayVar}) { $session = [ 'external_class_id' => $class->ClassDescription->ID, 'external_id' => $class->ID, 'duration' => (int)$duration, 'date_time' => $day->hour(date('H', $timeStart))->minute(date('i', $timeStart))->second(date('s', $timeStart)), ]; } } } }<file_sep>/app/controllers/VideoController.php <?php class VideoController extends \BaseController { /** * show video modal. * * @return Response */ public function create() { return Redirect::to('/'); return View::make('layouts.videoModal'); } }<file_sep>/app/composers/MapComposer.php <?php namespace composers; use JavaScript; use Functions; class MapComposer { public function compose($view) { $geocode = Functions::getPosition(); JavaScript::put([ 'latitude' => json_encode( $geocode->getLatitude()) , 'longitude' => json_encode( $geocode->getLongitude()) ]); $view->with('address', $geocode->getStreetNumber().$geocode->getStreetName())->with('streetName', $geocode->getStreetName())->with('city', $geocode->getCity())->with('postCode', $geocode->getZipcode()); } }<file_sep>/app/commands/IndexerImport.php <?php use Illuminate\Console\Command; class IndexerImport extends Command { /** * The console command name. * * @var string */ protected $name = 'indexer:import'; /** * The console command description. * * @var string */ protected $description = 'Import stuff'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { die(' THIS IS ONLY FOR IMPORTING THE FIRST TIME the CSV we GOT FROM RYAN!!!! '); $time_start = microtime(true); $db_table = 'TABLE_41'; if (!Schema::hasColumn($db_table, 'coordinate_type')) { Schema::table( $db_table, function ($table) { $table->renameColumn('place_type', 'coordinate_type'); } ); } if (!Schema::hasColumn($db_table, 'place_type')) { Schema::table( $db_table, function ($table) { $table->integer('place_type')->default(0); } ); } DB::update( 'update ' . $db_table . ' set coordinate_type = "radius" where coordinate_type = ?', array('$db_table') ); DB::update( 'update ' . $db_table . ' set coordinate_type = "polygon" where coordinate_type = ?', array('Polygon') ); DB::update('update ' . $db_table . ' set lat = "" where lat = ?', array('0.01')); DB::update('update ' . $db_table . ' set lng = "" where lng = ?', array('0.01')); DB::update( 'update ' . $db_table . ' set category_name = "station" where category_name = ?', array('London Underground') ); DB::update( 'update ' . $db_table . ' set category_name = "area" where category_name = ?', array('London Areas') ); $db = DB::table($db_table)->get(); foreach ($db as $t) { $link_db = [ 'permalink' => ($t->category_name == 'station' ? 'london/station/' : 'london/area/') . $t->permalink, 'type' => $t->category_name ]; $link = new Link($link_db); $data = [ 'name' => (string) $t->name, 'place_type' => 0, 'lng' => $t->lng, 'lat' => $t->lat, 'zone' => $t->zone, 'poly_coordinates' => $this->fix_coordinates($t->poly_coordinates), 'coordinate_type' => $t->place_type ]; Place::create($data)->link()->save($link); } $this->info('Transfer Completed'); $this->update_geo(); $time = microtime(true) - $time_start; $this->info('Index a total of ' . round($time, 2) . ' seconds'); } public function update_geo() { $this->info('Fix Missing Lat and Lng'); $place = Place::where('lat', 0)->get(); $total = 0; foreach($place as $p) { $total++; $geo = Place::getGeo($p->name, true, false); $p->lng = $geo['lng']; $p->lat = $geo['lat']; $p->save(); } $this->info('Total Missing fixed: '.$total); } public function fix_coordinates($cords) { $coordinates = []; if(strpos($cords, '),') !== false) { $cc = explode('),', $cords); foreach($cc as $c) { $coordinates[] = explode(',',str_replace(array('(',')'),'', $c)); } } else { $cords = str_replace("\r\n", "\n", $cords); foreach(explode(",", $cords) as $c) { $coordinates[] = explode("\n", $c); } } return (count($coordinates) > 0 ? json_encode($coordinates) : ''); } } <file_sep>/app/views/admin/yukonhtml/php/pages/pages-mailbox.php <div class="row"> <div class="col-md-3 col-lg-2"> <button class="btn btn-info btn-outline btn-sm">Compose</button> <hr/> <div class="list-group mailbox_menu"> <a href="pages-mailbox.html" class="active list-group-item"> <span class="badge badge-danger">96</span> <span class="menu_icon icon_download"></span>Inbox </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_upload"></span>Sent </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="badge badge-danger">52</span> <span class="menu_icon icon_error-circle_alt"></span>Spam </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_pencil-edit"></span>Drafts </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_trash_alt"></span>Trash </a> </div> </div> <div class="col-md-9 col-lg-10"> <div class="row"> <div class="col-md-5 col-md-push-7"> <input id="message_filter" type="text" class="form-control input-sm" placeholder="Search..."/> </div> <div class="col-md-5 col-md-pull-5"> <div class="btn-group btn-group-sm"> <button type="button" class="btn btn-default">Reply</button> <button type="button" class="btn btn-default">Spam</button> <button type="button" class="btn btn-default text-danger">Delete</button> </div> </div> </div> <hr/> <table id="mailbox_table" class="table table-yuk2 bg-fill toggle-arrow-tiny" data-page-size="20" data-filter="#message_filter"> <thead> <tr> <th class="cw footable_toggler"></th> <th class="cw"><input type="checkbox" id="msgSelectAll"></th> <th class="cw"></th> <th data-hide="phone,tablet">From</th> <th>Subject</th> <th data-hide="phone">Date</th> </tr> </thead> <tbody> <?php $arr_dates = dateRange( 'Tue 01.07.2015', 'Tue 01.12.2015'); $arr_dates_rev = array_reverse($arr_dates); $rand_mark = array('4','6','11','17','25','27','34','51','65'); for($i=1;$i<=96;$i++) { ?> <tr<?php if($i<7) { echo ' class="unreaded"'; }; ?>> <td></td> <td><div><input type="checkbox" class="msgSelect"></div></td> <td class="mbox_star<?php if(in_array($i,$rand_mark)) { echo ' marked'; }; ?>"><span class="<?php if(in_array($i,$rand_mark)) { echo 'icon_star'; } else { echo 'icon_star_alt'; }; ?>"></span></td> <td><?php echo $faker->name; ?></td> <td><a href="pages-mailbox_message.html"><?php echo $faker->sentence(6); ?></a></td> <td><?php echo $arr_dates_rev[$i]; ?></td> </tr> <?php }; ?> </tbody> <tfoot class="hide-if-no-paging"> <tr> <td colspan="6"> <ul class="pagination pagination-sm"></ul> </td> </tr> </tfoot> </table> </div> </div> <file_sep>/app/start/local.php <?php /* Mail::extend('logMessage', function() { $emails = implode(', ', array_keys((array) $message->getTo())); $body = $message->getBody(); $this->logger->info("Pretending to mail message to: {$emails} :-: {$body}"); } ); */ //<file_sep>/app/views/trainers/create.blade - with specialities not professions.php @extends('layouts.master') @section('content') @include('layouts.pagetitle', array('title'=>'Become a Trainer', 'subtitle'=>'Fill in your details below.')) <div class="col10 push1"> <div id="upload_wrapper"> @include('widgets.upload-form', array('uploadImage' => $userImage, 'default_image' => 'add_users.png' , 'label' => 'Upload your user image', 'fieldtext'=>'This image will appear on your profile and will be visible to Evercise members.')) </div> {{ Form::open(array('id' => 'trainer_create', 'url' => 'trainers', 'method' => 'post', 'class' => 'create-form')) }} @include('form.select', array('fieldname'=>'discipline', 'label'=>'Discipline', 'values'=>$disciplines)) @if ($errors->has('discipline')) {{ $errors->first('discipline', '<p class="error-msg">:message</p>')}} @endif @include('form.select', array('fieldname'=>'title', 'label'=>'Title', 'values'=>array('0'=>'Select a discipline'))) @if ($errors->has('title')) {{ $errors->first('title', '<p class="error-msg">:message</p>')}} @endif @include('form.textfield', array('fieldname'=>'bio', 'placeholder'=>'between 50 and 500 characters', 'maxlength'=>500, 'label'=>'Add your bio', 'fieldtext'=>'Your biography will be visible on your profile and will give members a more personal insight into you as an instructor. (example: Kayla is a qualified pool yoga instructor with 5 years of experience helping swimmers improve strength and flexibility in the pool. She is excited to meet new swimmers and help them improve their practice while decreasing chances of injury. She loves canoeing and camping, and is very happy to be a part of the evercise team!)' )) @if ($errors->has('bio')) {{ $errors->first('bio', '<p class="error-msg">:message</p>')}} @endif @include('form.phone', array('default_area' => $user->area_code , 'default' => $user->phone , 'fieldname'=>'phone', 'placeholder'=>'Add you phone number', 'maxlength'=>32, 'label'=>'Add you phone number', 'fieldtext'=>'Please add your phone number including area code')) @if ($errors->has('phone')) {{ $errors->first('phone', '<p class="error-msg">:message</p>')}} @endif @include('form.textfield', array('fieldname'=>'website', 'placeholder'=>'website address', 'maxlength'=>100, 'label'=>'Add your website', 'fieldtext'=>'(Optional) - If you want users to learn more about you and what you do, you can include your web address, which will be visible on your profile.' )) @if ($errors->has('website')) {{ $errors->first('website', '<p class="error-msg">:message</p>')}} @endif @if(basename($user->image) != 'no-user-img.jpg') {{ Form::hidden( 'image' , basename($user->image), array('id' => 'thumbFilename')) }} @else {{ Form::hidden( 'image' , null, array('id' => 'thumbFilename')) }} @endif <div class="center-btn-wrapper" > {{ Form::submit('Sign Up' , array('class'=>'btn-yellow ')) }} </div> {{ Form::close() }} </div> @stop<file_sep>/app/observables.php <?php // Subscribe to User Mailer events Event::subscribe('email\UserMailer'); Event::subscribe('email\SessionMailer'); /* Dynamically load Events from Config */ $events = Config::get('events'); foreach ($events as $priority => $event_arr) { foreach ($event_arr as $event) { foreach ($event as $name => $class) { Event::listen($name, '\events\\'.$class, $priority); } } }<file_sep>/app/models/ExternalService.php <?php class ExternalService extends Eloquent { protected $table = 'external_services'; protected $fillable = ['id', 'service', 'user_id', 'site_id', 'user_login', 'user_login', 'user_pass', 'information']; public function user() { $this->belongsTo('User'); } }<file_sep>/app/models/Evercisegroup.php <?php use Carbon\Carbon; /** * Class Evercisegroup */ class Evercisegroup extends \Eloquent { /** * @var array */ protected $fillable = [ 'user_id', 'category_id', 'venue_id', 'name', 'title', 'slug', 'description', 'image', 'gender', 'capacity', 'default_duration', 'default_price', 'published' ]; protected $editable = [ 'name', 'venue_id', 'description', 'image', 'category1', 'category2', 'category3', ]; /** * The database table used by the model. * * @var string */ protected $table = 'evercisegroups'; private static function validateInputs($inputs) { $validator = Validator::make( $inputs, [ 'class_name' => 'required|max:50|min:3', 'class_description' => 'required|max:500|min:50', 'image' => 'required', 'venue_select' => 'required', ] ); return $validator; } /** * @param $inputs * @param $user * @return \Illuminate\Http\JsonResponse */ public static function validateAndStore($inputs, $user) { $validator = static::validateInputs($inputs); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { $classname = $inputs['class_name']; $description = $inputs['class_description']; $image = $inputs['image']; if ($inputs['gallery_image'] == 'true') { $image = Gallery::selectImage($image, $user, $classname); } $venueId = $inputs['venue_select']; if (!Venue::find($venueId)) { return Response::json( ['validation_failed' => 1, 'errors' => ['venue_select' => 'Please select or create a new venue']] ); } // Push categories into an array, and fail if there are none. //$categories = static::categoriesToArray($inputs); if (count($inputs['category_array']) == 1) $categoryNames = explode(',', $inputs['category_array'][0]); else $categoryNames = $inputs['category_array']; $categoryIds = Subcategory::namesToIds($categoryNames); if (empty($categoryIds)) { return Response::json( ['validation_failed' => 1, 'errors' => ['category-select' => 'You must choose at least one category']] ); } $evercisegroup = static::create( [ 'name' => $classname, 'user_id' => $user->id, 'venue_id' => $venueId, 'description' => $description, 'image' => $image, 'slug' => str_random(12), ] ); $slug = self::uniqueSlug($evercisegroup); $evercisegroup->slug = $slug; $evercisegroup->save(); $evercisegroup->subcategories()->attach($categoryIds); Trainerhistory::create( [ 'user_id' => $user->id, 'type' => 'created_evercisegroup', 'display_name' => $user->display_name, 'name' => $evercisegroup->name ] ); event('class.created', [$evercisegroup, $user]); return Response::json( [ 'url' => route('sessions.add', $evercisegroup->id), 'success' => 'true', 'id' => $evercisegroup->id ] ); } } private static function categoriesToArray($inputs) { $categories = []; if (isset($inputs['category1']) != '') { array_push($categories, $inputs['category1']); } if (isset($inputs['category2']) != '') { array_push($categories, $inputs['category2']); } if (isset($inputs['category3']) != '') { array_push($categories, $inputs['category3']); } return $categories; } public static function uniqueSlug($class) { $venue = $class->venue()->first(); $name = [ slugIt($class->name) ]; $name = implode('_', $name); if(!self::slugTaken($name)) { return $name; } $name .= '_'.slugIt($venue->name); if(!self::slugTaken($name)) { return $name; } /** Looks like its Taken */ /** Stick the ID at the end and forget it */ $name = $name.'_'.$class->id; return $name; } private static function slugTaken($slug) { return static::where('slug', $slug)->first(); } public function validateAndUpdate($inputs, $user) { $validator = static::validateInputs($inputs); if ($validator->fails()) { return Response::json([ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]); } else { /* foreach ($inputs as $name => $value) { if (!in_array($name, $this->editable)) { return Response::json([ 'validation_failed' => 1, 'errors' => ['classname' => 'Trying to edit uneditable/non-existant field: ' . $name] ]); } }*/ $classname = $inputs['class_name']; $description = $inputs['class_description']; $image = $inputs['image']; $venueId = $inputs['venue_select']; // Push categories into an array, and fail if there are none. //$categories = static::categoriesToArray($inputs); $categories = $inputs['category_array']; $this->update([ 'name' => $classname, 'venue_id' => $venueId, 'description' => $description, 'image' => $image, ]); if (!empty($categories)) { $this->subcategories()->sync($categories); } Trainerhistory::create( [ 'user_id' => $user->id, 'type' => 'edited_evercisegroup', 'display_name' => $user->display_name, 'name' => $this->name ] ); event('class.updated', [$user, $this]); } return TRUE; } private $classStats = []; /** * @param $user * @return \Illuminate\View\View */ public static function getUserHub($user) { $currentDate = new DateTime(); $sessionmember_ids = []; // For rating $pastSessions = []; $futureSessions = []; $nextSessions = []; // Links past session with the next Future session (of the same group) which this member has signed up for $pastSessionsAwaitingFutureBuddy = []; foreach ($user->sessions()->orderBy('date_time', 'desc')->get() as $key => $session) { // Past sessions if (new DateTime($session->date_time) < $currentDate) { if (!array_key_exists($session->id, $futureSessions)) { $pastSessions[$session->id] = $session; } foreach ($session->sessionmembers as $sessionmember) { $sessionmember_ids[$session->id] = $sessionmember->id; } $pastSessionsAwaitingFutureBuddy[$session->evercisegroup->id] = $session->id; } // Future sessions else { if (!array_key_exists($session->id, $futureSessions)) { $futureSessions[$session->id] = $session; } if (array_key_exists($session->evercisegroup->id, $pastSessionsAwaitingFutureBuddy)) { $nextSessions[$pastSessionsAwaitingFutureBuddy[$session->evercisegroup->id]] = $session->id; } } } krsort($futureSessions); $data = [ 'past_sessions' => $pastSessions, 'future_sessions' => $futureSessions, 'sessionmember_ids' => $sessionmember_ids, 'user_id' => $user->id, 'next_sessions' => $nextSessions, ]; return $data; } public static function getTrainerHub($user) { $data = static::getUserHub($user); $trainerGroups = static::with('evercisesession.sessionmembers') ->with('futuresessions.sessionmembers') ->with('pastsessions') ->with('venue') ->where('user_id', $user->id)->get(); $data = array_merge($data, [ 'trainer_groups' => $trainerGroups ?: [], ]); return $data; } public static function parseSegments($segments) { /** Is this a permalink or something */ if (!empty($segments[2])) { /** * If we get more Users.. this entire thing should be cached as one array just used like that * For now i wont do that */ $default['type'] = 'search'; $default['sub_type'] = 'station'; if (!empty($segments[3])) { $default['location'] = $segments[3]; } else { throw new \Exception('No Location Defined'); } return $default; } return $default; } /** * @param $location * @param $category * @param $radius * @param $user * @return \Illuminate\View\View */ public static function newSearch($options, $user) { //return $location['address']; if (isset($location['lat']) && isset($location['lng'])) { $latitude = $location['lat']; $longitude = $location['lng']; } else { $latlng = Geo::getLatLng($location['address']); $latitude = $latlng['lat']; $longitude = $latlng['lng']; } $page = Input::get('page', 1); $testers = Sentry::findGroupById(5); $testerLoggedIn = $user ? $user->inGroup($testers) : FALSE; $haversine = '(3959 * acos(cos(radians(' . $latitude . ')) * cos(radians(lat)) * cos(radians(lng) - radians(' . $longitude . ')) + sin(radians(' . $latitude . ')) * sin(radians(lat))))'; /* set the number of arrays needed per level */ $results = [[], [], [], [], []]; // SEARCH LEVEL 1 $results[0] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->where( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->whereHas( 'subcategories', function ($query) use ($category) { $query->where('name', 'LIKE', '%' . $category . '%'); } ) ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); // SEARCH LEVEL 2 ( if level 1 returns less than 9 results) if (count($results[0]) < 9) { $results[1] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->whereHas( 'subcategories', function ($query) use ($category) { $query->whereHas( 'categories', function ($subquery) use ($category) { $subquery->where('name', 'LIKE', '%' . $category . '%'); } ); } ) //->with('categories') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } //return var_dump($level2results); // SEARCH LEVEL 3 ( if level 1 and level 2 return less than 9 results) if (count($results[0]) + count($results[1]) < 9) { $results[2] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->where('name', 'LIKE', '%' . $category . '%') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 4 ( if level 1, 2 and 3 return less than 9 results) if (count($results[0]) + count($results[1]) + count($results[2]) < 9) { $results[3] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->where('description', 'LIKE', '%' . $category . '%') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 5 if (count($results[0]) + count($results[1]) + count($results[2]) + count($results[3]) < 9) { $results[4] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 6 if (count($results[0]) + count($results[1]) + count($results[2]) + count($results[3]) + count( $results[4] ) < 9 ) { $results[5] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has( 'tester', '<', $testerLoggedIn ? 5 : 1 )// testing to make sure class does not belong to the tester ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } $allResults = Evercisegroup::concatenateResults($results); $perPage = 12; if ($page > count($allResults) or $page < 1) { $page = 1; } $offset = ($page * $perPage) - $perPage; $articles = array_slice($allResults, $offset, $perPage); $paginatedResults = Paginator::make($articles, count($allResults), $perPage); foreach ($allResults as $result) { unset($result['description']); unset($result['default_duration']); unset($result['published']); unset($result['created_at']); unset($result['updated_at']); unset($result['user']); unset($result['venue_id']); unset($result['title']); unset($result['gender']); $mapResult[] = $result->toJson(); } //return json_encode($mapResult); return View::make('evercisegroups.search') ->with('places', json_encode($mapResult)) ->with('evercisegroups', $paginatedResults); } /** * @param $location * @param $category * @param $radius * @param $user * @return \Illuminate\View\View */ public static function doSearch($location, $category, $radius, $user) { //return $location['address']; if (isset($location['lat']) && isset($location['lng'])) { $latitude = $location['lat']; $longitude = $location['lng']; } else { $latlng = Geo::getLatLng($location['address']); $latitude = $latlng['lat']; $longitude = $latlng['lng']; } $page = Input::get('page', 1); $testers = Sentry::findGroupById(5); $testerLoggedIn = $user ? $user->inGroup($testers) : FALSE; $haversine = '(3959 * acos(cos(radians(' . $latitude . ')) * cos(radians(lat)) * cos(radians(lng) - radians(' . $longitude . ')) + sin(radians(' . $latitude . ')) * sin(radians(lat))))'; /* set the number of arrays needed per level */ $results = [[], [], [], [], []]; // SEARCH LEVEL 1 $results[0] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->whereHas( 'subcategories', function ($query) use ($category) { $query->where('name', 'LIKE', '%' . $category . '%'); } ) ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); // SEARCH LEVEL 2 ( if level 1 returns less than 9 results) if (count($results[0]) < 9) { $results[1] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->whereHas( 'subcategories', function ($query) use ($category) { $query->whereHas( 'categories', function ($subquery) use ($category) { $subquery->where('name', 'LIKE', '%' . $category . '%'); } ); } ) //->with('categories') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } //return var_dump($level2results); // SEARCH LEVEL 3 ( if level 1 and level 2 return less than 9 results) if (count($results[0]) + count($results[1]) < 9) { $results[2] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->where('name', 'LIKE', '%' . $category . '%') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 4 ( if level 1, 2 and 3 return less than 9 results) if (count($results[0]) + count($results[1]) + count($results[2]) < 9) { $results[3] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->where('description', 'LIKE', '%' . $category . '%') ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 5 if (count($results[0]) + count($results[1]) + count($results[2]) + count($results[3]) < 9) { $results[4] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1)// testing to make sure class does not belong to the tester ->whereHas( 'venue', function ($query) use (&$haversine, &$radius) { $query->select([DB::raw($haversine . ' as distance')]) ->having('distance', '<', $radius); } ) ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } // SEARCH LEVEL 6 if (count($results[0]) + count($results[1]) + count($results[2]) + count($results[3]) + count( $results[4] ) < 9 ) { $results[5] = Evercisegroup::has('futuresessions') ->has('confirmed') ->has( 'tester', '<', $testerLoggedIn ? 5 : 1 )// testing to make sure class does not belong to the tester ->with('venue') ->with('user') ->with('ratings') ->with('futuresessions') ->get(); } $allResults = Evercisegroup::concatenateResults($results); $perPage = 12; if ($page > count($allResults) or $page < 1) { $page = 1; } $offset = ($page * $perPage) - $perPage; $articles = array_slice($allResults, $offset, $perPage); $paginatedResults = Paginator::make($articles, count($allResults), $perPage); foreach ($allResults as $result) { unset($result['description']); unset($result['default_duration']); unset($result['published']); unset($result['created_at']); unset($result['updated_at']); unset($result['user']); unset($result['venue_id']); unset($result['title']); unset($result['gender']); $mapResult[] = $result->toJson(); } //return json_encode($mapResult); return View::make('evercisegroups.search') ->with('places', json_encode($mapResult)) ->with('evercisegroups', $paginatedResults); } /** * @param $categories * @param $evercisegroup */ public static function adminAddSubcategories($categories, $evercisegroup) { foreach ($categories as $key => $category) { $categories[$key] = Subcategory::where('name', $category)->pluck('id'); } $evercisegroup->subcategories()->detach(); if (!empty($categories)) { $evercisegroup->subcategories()->attach($categories); } } /** * @param $featured */ public function adminMakeClassFeatured($featured) { if ($featured) { FeaturedClasses::firstOrCreate(['evercisegroup_id' => $this->id]); } else { $id = FeaturedClasses::where('evercisegroup_id', $this->id)->pluck('id'); if ($id) { FeaturedClasses::destroy($id); } } } /** * @return mixed */ public function evercisesession() { return $this->hasMany('Evercisesession')->orderBy('date_time', 'asc'); } /** * @return mixed */ public function futuresessions() { return $this ->hasMany('Evercisesession') ->where('date_time', '>', Carbon::now()) ->orderBy('date_time', 'asc'); } /** * @return mixed */ public function getNextFutureSession() { return $this->hasMany('Evercisesession') ->where('date_time', '>=', Carbon::now()) ->first(); } /** * @return mixed */ public function pastsessions() { return $this->hasMany('Evercisesession') ->where('date_time', '<', Carbon::now()) ->orderBy( 'date_time', 'asc' ); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function venue() { return $this->belongsTo('Venue'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough */ public function Sessionmember() { return $this->hasManyThrough('Sessionmember', 'Evercisesession'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } /** * @return mixed */ public function confirmed() { //return $this->belongsToMany('Trainer', 'User', 'user_id', 'user_id')->withPivot('id'); return $this->belongsTo('Trainer', 'user_id', 'user_id')->where('confirmed', 1); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function ratings() { return $this->hasMany('Rating'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function fakeRatings() { return $this->hasMany('FakeRating'); } /** * @return mixed */ public function stars() { return $this->hasMany('Rating')->select(['evercisegroup_id', 'stars']); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function subcategories() { return $this->belongsToMany( 'Subcategory', 'evercisegroup_subcategories', 'evercisegroup_id', 'subcategory_id' )->withTimestamps(); } public function getSubcategoryIds() { return $this->subcategories->lists('id'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough */ public function categories() { return $this->hasManyThrough('Category', 'Subcategory'); } public function scopeLocation($query, $latitude, $longitude, $radius = 1) { $haversine = '(3959 * acos(cos(radians(' . $latitude . ')) * cos(radians(lat)) * cos(radians(lng) - radians(' . $longitude . ')) + sin(radians(' . $latitude . ')) * sin(radians(lat))))'; return $query->whereIn( 'venue_id', function ($query) use ($haversine, $radius) { $query->select('id') ->from(with(new Venue)->getTable()) ->where(DB::raw($haversine), '<=', $radius); } ); } /** * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough */ public function featuredClasses() { return $this->hasOne('FeaturedClasses'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough */ public function slider() { return $this->hasOne('Slider'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough */ public function isFeatured() { return FeaturedClasses::where('evercisegroup_id', $this->id)->first(); } /** * @return mixed */ public function tester() { return $this->belongsTo('Users_groups', 'user_id', 'user_id')->where('group_id', 5); } /** * Concatenate Results * @param $resultsArray * @return array */ public static function concatenateResults($resultsArray) { $allResults = []; foreach ($resultsArray as $results) { $theseResults = []; foreach ($results as $result) { //Remove duplicates if (!in_array($result, $allResults)) { $date = $result->futuresessions[0]->date_time; array_push($theseResults, $result); } } usort($theseResults, ['Evercisegroup', "sortFunction"]); $allResults = array_merge($allResults, $theseResults); } return $allResults; } /** * Sort Sessions * @param $a * @param $b * @return int */ public static function sortFunction($a, $b) { return strtotime($a->futuresessions[0]->date_time) - strtotime($b->futuresessions[0]->date_time); } /** * Get Star Rating * * @return float|int */ public function getStars() { if (isset($this->classStats['stars'])) { return $this->classStats['stars']; } $stars = 0; foreach ($this->ratings as $key => $rating) { $stars += $rating->stars; } $stars = count($this->ratings) ? $stars / count($this->ratings) : 0; $this->classStats['stars'] = $stars; return $stars; } public function placesFilled() { $members = []; foreach ($this->futuresessions as $evercisesession) { $members[] = count($evercisesession->sessionmembers); } return array_sum($members); } public function averageClassBooking() { $members = []; foreach ($this->evercisesession as $evercisesession) { $members[] = count($evercisesession->sessionmembers); } if (count($members) > 0) { $average = round(array_sum($members) / count($members)); } else { $average = 0; } return $average; } public function checkIfUserOwnsClass($user) { if ($this->user_id != $user->id) { return FALSE; } else { return TRUE; } } /** * @param $id * @return mixed|null */ public static function getById($id) { return static::find($id); } /** * @param $user * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View */ public function showAsOwner($user) { if ($this->user_id == $user->id) { //$evercisegroup_id; if (!Sentry::check()) { return 'Not logged in'; } $directory = $user->directory; if ($this['futuresessions']->isEmpty()) { return View::make('evercisegroups.trainer_show') ->with('evercisegroup', $this) ->with('directory', $directory) ->with('members', 0); } else { $totalSessions = 0; $totalSessionMembers = 0; $totalCapacity = 0; $revenue = 0; $totalRevenue = 0; $members = []; foreach ($this->evercisesession as $key => $evercisesession) { $totalCapacity = $totalCapacity + $this->capacity; $members[$key] = count($evercisesession['Sessionmembers']); // Count those members $totalSessionMembers = $totalSessionMembers + $members[$key]; $revenue = $revenue + ($members[$key] * $evercisesession->price); $totalRevenue = $totalRevenue + ($evercisesession->price * $this->capacity); ++$totalSessions; } $averageSessionMembers = round($totalSessionMembers / $totalSessions, 1); $averageCapacity = round($totalCapacity / $totalSessions, 1); $averageRevenue = round($revenue / $totalSessions, 1); $averageTotalRevenue = round($totalRevenue / $totalSessions, 1); return View::make('evercisegroups.trainer_show') ->with('evercisegroup', $this) ->with('directory', $directory) ->with('totalSessionMembers', $totalSessionMembers) ->with('totalCapacity', $totalCapacity) ->with('averageSessionMembers', $averageSessionMembers) ->with('averageCapacity', $averageCapacity) ->with('revenue', $revenue) ->with('totalRevenue', $totalRevenue) ->with('averageTotalRevenue', $averageTotalRevenue) ->with('averageRevenue', $averageRevenue) ->with('members', $members); } } JavaScript::put(['initPut' => json_encode(['selector' => '#fakerating_create'])]); return View::make('evercisegroups.show') ->with('evercisegroup', $this); // change to trainer show view } /** * @param $user * @return \Illuminate\View\View */ public function showAsNonOwner($user) { try { $trainer = Trainer::with('user') ->where('user_id', $this->user_id) ->first(); } catch (Exception $e) { /* if there is not a trainer then return to discover page */ return ['error' => 'not trainer']; } // create a array containing all members $members = []; $membersIds = []; $memberAllIds = []; $memberUsers = []; foreach ($this->evercisesession as $key => $evercisesession) { $members[$evercisesession->id] = count($evercisesession['sessionmembers']); // Count those members foreach ($evercisesession['sessionmembers'] as $k => $sessionmember) { $membersIds[$evercisesession->id][] = $sessionmember->user_id; $memberAllIds[] = $sessionmember->user_id; } } if (!empty($memberAllIds)) { $memberUsers = User::whereIn('id', $memberAllIds)->distinct()->get(); } $venue = Venue::with('facilities')->find($this->venue_id); $ratings = Rating::with('rator')->where('evercisegroup_id', $this->id)->orderBy('created_at')->get(); $fakeRatings = FakeRating::with('rator')->where('evercisegroup_id', $this->id)->orderBy('created_at')->get(); if ($memberUsers) { $memberUsersArray = $memberUsers->toArray(); } else { $memberUsersArray = []; } foreach ($fakeRatings as $fakeRating) { if (!in_array($fakeRating->rator->id, $memberAllIds)) { array_push($memberUsersArray, $fakeRating->rator->toArray()); } } // Concatinate real and fake ratings into one array $allRatings = array_merge($ratings->toArray(), $fakeRatings->toArray()); /* open graph meta tags */ /* git site https://github.com/chriskonnertz/open-graph */ $og = new OpenGraph(); /* try to create og if fails redirect to discover page */ try { $og->title($this->name) ->type('article') ->image( url() . '/' . $trainer->user->directory . '/thumb_' . $this->image, [ 'width' => 150, 'height' => 156 ] ) ->description($this->description) ->url(); } catch (Exception $e) { return ['error' => 'not trainer']; } $fakeUserGroup = Sentry::findGroupByName('Fakeuser'); $fakeUsers = Sentry::findAllUsersInGroup($fakeUserGroup)->lists('display_name', 'id'); return [ 'evercisegroup' => $this, 'trainer' => $trainer, 'members' => $members, 'membersIds' => $membersIds, 'memberUsers' => $memberUsersArray, 'venue' => $venue, 'allRatings' => $allRatings, 'fakeUsers' => $fakeUsers, 'og' => $og, ]; } /** * @param $user * @return \Illuminate\Http\JsonResponse */ public function deleteGroup($user) { if ($this->user_id != $user->id) { return Response::json(['mode' => 'hack']); } // Check user id against group if ($user->id == $this->user_id) { // Only delete if there's no members joined if (count($this->sessionmember) == 0) { // If Evercisegroup contains Evercisesessions, delete them all. if (!$this['Evercisesession']->isEmpty()) { foreach ($this['Evercisesession'] as $value) { $value->delete(); } } // Now, delete actual Evercisegroup too. $evercisegroupForDeletion = Evercisegroup::find($this->id); $evercisegroupForDeletion->delete(); Trainerhistory::create( [ 'user_id' => $user->id, 'type' => 'deleted_evercisegroup', 'display_name' => $user->display_name, 'name' => $this->name ] ); } } return Response::json(['mode' => 'redirect', 'url' => route('evercisegroups.index')]); } public function adminDeleteIfNoSessions() { if (!count($this->evercisesession)) { $this->delete(); return TRUE; } return FALSE; } public static function getGroupWithSpecificSessions($evercisegroupId, $sessionIds) { return static::with( [ 'evercisesession' => function ($query) use (&$sessionIds) { $query->whereIn('id', $sessionIds); } ], 'evercisesession' ) ->find($evercisegroupId); } public static function editSubcats($subcatChanges) { foreach ($subcatChanges as $subcat) { foreach ($subcat as $key => $subcatData) { $evercisegroup = static::find($key); if ($evercisegroup) { $evercisegroup->subcategories()->detach(); if (!empty($subcatData)) { $subcatNames = explode(',', $subcatData); $subcatIds = []; foreach ($subcatNames as $subcatName) { array_push($subcatIds, Subcategory::where('name', $subcatName)->pluck('id')); } $evercisegroup->subcategories()->attach($subcatIds); } } } } return TRUE; } public function publish($publish) { $this->published = $publish ? 1 : 0; $this->save(); } public static function getSlug($id) { return static::find($id)->slug; } }<file_sep>/app/config/mixpanel.php <?php /* * Mix Panel Settings */ return [ 'token' => (getenv('MIXPANEL_TOKEN') ?: '01df8b97db47118465ac0ac3b70b4a12') ];<file_sep>/app/lang/en/footer.php <?php return array( 'discover_fitness_classes' => 'Discover fitness classes', 'be_a_pro' => 'Be a pro', 'what_is_Evercise' => 'What is Evercise?', 'class_guidelines' => 'Class Guidelines', 'help' => 'Help', 'meet_the_team' => 'Meet the team', 'contact_us' => 'Contact us', 'follow_us' => 'Follow us', 'terms_of_use' => 'Terms of Use', 'privacy_policy' => 'Privacy Policy', 'copyright' => '© 2014 Qin Technology. Inc.', );<file_sep>/app/events/Trainer.php <?php namespace events; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Events\Dispatcher; /** * Class Trainer * @package events */ class Trainer { /** * @var Repository */ protected $config; /** * @var Writer */ protected $log; /** * @var Dispatcher */ protected $event; /** * @var Activity */ protected $activity; /** * @var Indexer */ protected $indexer; /** * @var Mail */ protected $mail; /** * @var Tracking */ protected $track; /** * @param Writer $log * @param Repository $config * @param Dispatcher $event * @param Activity $activity * @param Indexer $indexer * @param Mail $mail * @param Tracking $track */ public function __construct( Writer $log, Repository $config, Dispatcher $event, Activity $activity, Indexer $indexer, Mail $mail, Tracking $track ) { $this->config = $config; $this->log = $log; $this->event = $event; $this->activity = $activity; $this->indexer = $indexer; $this->mail = $mail; $this->track = $track; } /** * @param $trainer */ public function registered($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has registered'); $this->activity->userRegistered($trainer); $this->activity->trainerRegistered($trainer); $this->mail->trainerRegistered($trainer); } /** * @param $trainer */ public function registeredPpc($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has registered'); $this->activity->userRegistered($trainer); $this->activity->trainerRegistered($trainer); $this->mail->trainerRegisteredPpc($trainer); } /** * @param $trainer */ public function edit($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has edited his account'); $this->track->trainerEdit($trainer); } /** * @param $trainer */ public function whyNotCompleteProfile($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has been reminded to complete their profile'); $this->mail->trainerWhyNotCompleteProfile($trainer); } /** * @param $trainer */ public function whyNotCreateFirstClass($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has been reminded to create their first class'); $this->mail->trainerWhyNotCreateFirstClass($trainer); } /** * @param $trainer */ public function notReturnedTrainer($trainer) { $this->log->info('Trainer ' . $trainer->id . ' has been reminded to return after 10 days or so'); $this->mail->notReturnedTrainer($trainer); } public function relaunch($user) { $this->log->info('relaunch message sent ' . $user->id); $this->mail->relaunch($user); } /** * @param $user * @param $trainer * @param $session * @param $everciseGroup * @param $transactionId */ public function sessionsJoined($trainerId, $sessionDetails) { $this->log->info('Trainer ' . $trainerId . ' has been notified of someone joining their class. ' . count($sessionDetails)); $this->mail->userJoinedTrainersSession($trainerId, $sessionDetails); } }<file_sep>/app/shortcodes.php <?php /* Dynamically load ShortCode Parsables from Config */ $shortcodes = Config::get('shortcodes'); foreach ($shortcodes as $tag => $class) { Shortcode::register($tag, $class); } <file_sep>/server/install_server.sh sudo su # create the old database mysql -uroot -f -e "DROP DATABASE IF EXISTS evercise" mysql -uroot -f -e "DROP DATABASE IF EXISTS evercise_v1" echo "CREATE DATABASE evercise;" | mysql -u root echo "CREATE DATABASE evercise_v1;" | mysql -u root mysql -u root evercise_v1 < /var/www/html/server/evercisedb_v1.sql mysql -u root evercise < /var/www/html/server/evercise.sql mkdir /var/www/hosts/ touch /var/www/hosts/evercise.conf # Setup hosts file VHOST=$(cat <<EOF <VirtualHost *:80> DocumentRoot "/var/www/html/public" ServerName dev.evercise.com SetEnv ENVIRONMENT production <Directory "/var/www/html/public"> AllowOverride All </Directory> </VirtualHost> EOF ) echo "${VHOST}" > /var/www/hosts/evercise.conf service httpd restart<file_sep>/app/database/migrations/2014_06_30_091156_create_milestones_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateMilestonesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('milestones')) { Schema::create('milestones', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key; $table->integer('referrals'); $table->integer('profile'); $table->integer('facebook'); $table->integer('twitter'); $table->integer('reviews'); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('milestones'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/public/assets/jsdev/ajax-callbacks.js function redirectTo(data){ window.location.href = data.url; } function editClass(data){ $('#'+ data.id).html(data.view); $('#edit-'+ data.id).removeClass('disabled'); $('#submit-'+ data.id).hide(); $('#'+ data.id).parent().collapse('show'); $('#infoToggle-'+data.id).removeClass('hide'); datepick(); } function updateHubRow(data){ $('#hub-edit-row-'+data.id).after(data.view); } function newSessionAdded(data){ $('#'+ data.id).html(data.view); datepick(); } function removeSessionRow(data){ $('#hub-edit-row-'+data.id).fadeOut(400); }<file_sep>/app/database/migrations/2014_12_05_111417_update_packages.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class UpdatePackages extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('packages', function(Blueprint $table) { $table->dropColumn('savings'); $table->string('style'); }); $package = [ 'name' => 'WARM UP', 'description' => 'New to Evercise? This is a great way to sample the Evercise experience and pay as little as £3.99 per class.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 5, 'price' => 19.99, 'style' => 'green', 'active' => 1, 'max_class_price' => '6.99' ]; Packages::create($package); $package = [ 'name' => 'ENDURE', 'description' => 'Keep on moving! Pick up the pace and bag a 40% discount with this five-class package.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 5, 'price' => 39.99, 'style' => 'blue', 'active' => 1, 'max_class_price' => '11.99' ]; Packages::create($package); $package = [ 'name' => 'BURN', 'description' => 'Get fully motivated with our top five-class package. Complete access to the Evercise network means this is perfect for discovering new fitness challenges.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 5, 'price' => 59.99, 'style' => 'pink', 'active' => 1, 'max_class_price' => '16.99' ]; Packages::create($package); $package = [ 'name' => 'TONED', 'description' => 'Perfect if you’re starting out. Save money on the standard price without making a big commitment.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 10, 'price' => 34.99, 'style' => 'green', 'active' => 1, 'max_class_price' => '6.99' ]; Packages::create($package); $package = [ 'name' => 'PUMPED', 'description' => 'A great package if you’re serious about getting fit and staying fit. With a price per class of just £6.99 you’ll be making fitness gains without the financial pains.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 10, 'price' => 69.99, 'style' => 'blue', 'active' => 1, 'max_class_price' => '11.99' ]; Packages::create($package); $package = [ 'name' => 'RIPPED', 'description' => 'Fitness fanatics look no further. Our top package maximises your Evercise access allowing you to explore our full range of classes.', 'bullets' => 'Easy check out – no card details required|Waiting list priority – Head straight to the front of the line!', 'classes' => 10, 'price' => 99.99, 'style' => 'pink', 'active' => 1, 'max_class_price' => '16.99' ]; Packages::create($package); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('packages', function(Blueprint $table) { $table->dropColumn('style'); $table->string('savings'); }); Packages::limit(10)->delete(); } } <file_sep>/app/commands/IndexerIndex.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; class IndexerIndex extends Command { /** * The console command name. * * @var string */ protected $name = 'indexer:index'; /** * The console command description. * * @var string */ protected $description = 'Index Elasticgroups'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); /** Load a partial instance of the Elastic thingy... no need for everything to be injected!*/ $this->elastic = new Elastic( Geotools::getFacadeRoot(), new Evercisegroup(), Es::getFacadeRoot(), Log::getFacadeRoot() ); $this->elastic_index = getenv('ELASTIC_INDEX'); $this->elastic_type = getenv('ELASTIC_TYPE'); } /** * Execute the console command. * * @return mixed */ public function fire() { $time_start = microtime(true); Artisan::call('indexer:create'); if (!$this->elastic_index) { $this->error('YOU NEED TO UPDATE YOUR .env.php file.'); $this->error('Please check EXAMPLE.env.php'); return; } $id = $this->option('id'); $this->info('Indexing All fields from Evercisegroups'); $total_indexed = $this->elastic->indexEvercisegroups($id); $time = microtime(true) - $time_start; $this->info('Index a total of ' . $total_indexed . ' evercisegroups in ' . round($time, 2) . ' seconds'); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('id', null, InputOption::VALUE_OPTIONAL, 'Index Single Evercise Group', 0), ); } } <file_sep>/app/composers/AreacodeComposer.php <?php namespace composers; use Areacodes; class AreacodeComposer { public function compose($view) { $areacodes = Areacodes::get(); $view->with('areacodes', $areacodes); } }<file_sep>/app/controllers/TrainersController.php <?php class TrainersController extends \BaseController { /** * Display a listing of the resource. * * @return Response */ public function index() { return View::make('trainers.index'); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { if (!Sentry::check()) { return Redirect::route('register'); } //$user = Sentry::getUser(); $trainerGroup = Sentry::findGroupByName('trainer'); if ($this->user->inGroup($trainerGroup)) { return Redirect::route('trainers.edit', $this->user->id); } $specialities = Speciality::all(); $disciplines = []; $titles = []; foreach ($specialities as $sp) { if (!isset($titles[$sp->name])) { $disciplines[$sp->name] = $sp->name; $titles[$sp->name] = [$sp->titles]; } else { array_push($titles[$sp->name], $sp->titles); } } // http://image.intervention.io/methods/crop // http://odyniec.net/projects/imgareaselect return View::make('v3.trainers.create') ->with('disciplines', $disciplines); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id, $tab = 0) { } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id = 'me') { if ($id == 'me') { $user = Sentry::getUser(); if (!$user) { return Redirect::route('home')->with('notification', 'Please log in'); } $id = $user->id; } $user = User::where((is_numeric($id) ? 'id' : 'display_name'), $id)->first(); if ($user) { if(is_numeric($id)) { return Redirect::route('trainer.show', ['id' => $user->display_name]); } try { $trainer = $user->trainer()->first(); } catch (Exception $e) { return Redirect::route('home')->with('notification', 'this trainer does not exist'); } } else { return Redirect::route('home')->with('notification', 'this trainer does not exist'); } // check if trainer has classes else redirect them home try { $evercisegroups = Evercisegroup::has('futuresessions') ->with('futuresessions') ->with('venue') ->where('user_id', $trainer->user->id)->get(); } catch (Exception $e) { return Redirect::route('home')->with('notification', 'this trainer does not exist'); } $stars = []; $totalStars = 0; $evercisegroup_ids = []; foreach ($evercisegroups as $key => $evercisegroup) { $evercisegroup_ids[] = $evercisegroup->id; } if (!empty($evercisegroup_ids)) { $ratings = Rating::with('rator')->whereIn('evercisegroup_id', $evercisegroup_ids)->orderBy('created_at')->get(); foreach ($ratings as $key => $rating) { $stars[$rating->evercisegroup_id][] = $rating->stars; $totalStars = $totalStars + $rating->stars; } } else { $ratings = []; } $params = [ 'title' => (!empty($user->first_name) ? $user->first_name.' '.$user->last_name : $user->display_name).' '.$trainer->profession.' | Evercise', 'metaDescription' => str_limit($trainer->bio, 160, $end = '...'), 'tab' => 0, 'data' => [ 'trainer' => $trainer, 'evercisegroups' => $evercisegroups, 'stars' => $stars, 'totalStars' => $totalStars, 'ratings' => $ratings, ] ]; return View::make('v3.trainers.show', $params); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $validator = Validator::make( Input::all(), [ 'bio' => 'required|max:500|min:50', 'profession' => 'required|max:50|min:5', ] ); if ($validator->fails()) { if (Request::ajax()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { return Redirect::route('trainers.edit') ->withErrors($validator) ->withInput(); } } else { // Actually update the trainer record $bio = Input::get('bio'); $website = Input::get('website'); $profession = Input::get('profession'); $trainer = Trainer::find($id); if ($this->user->id != $trainer->user_id) { return Response::json(['callback' => 'fail']); } $trainer->update([ 'bio' => $bio, 'website' => $website, 'profession' => $profession, //'specialities_id' => $speciality->id, ]); $result = [ 'callback' => 'gotoUrl', 'url' => '/trainers/2/edit/trainer' ]; Event::fire('trainer.editTrainerDetails', [$this->user]); return Response::json($result); } } }<file_sep>/app/composers/EvercisegroupsShowComposer.php <?php namespace composers; use JavaScript; class EvercisegroupsShowComposer { public function compose($view) { JavaScript::put( [ 'initJoinEvercisegroup' => 1, 'initSwitchView' => 1, 'initScrollAnchor' => 1, 'MapWidgetloadScript' => json_encode(['mapPointerDraggable' => false]), 'initToolTip' => 1, 'zero_results' => trans('discover.zero_results') ] ); $view; } }<file_sep>/app/config/composers.php <?php return [ ['home' => 'HomePageComposer'], ['home' => 'RecommendedClassesComposer'], // users ['users.edit_form' => 'UserEditComposer'], ['users.changepassword' => 'ChangePasswordComposer'], ['users.edit' => 'UserClassesComposer'], ['users.register' => 'AccordionComposer'], ['users.register' => 'UsersCreateComposer'], ['users.resetpassword' => 'UsersResetPasswordComposer'], ['evercoins.show' => 'ShowEvercoinComposer'], //trainers ['trainers.create' => 'TrainersCreateComposer'], ['trainers.edit' => 'UserClassesComposer'], ['trainers.editForm' => 'TrainerEditFormComposer'], ['trainers.trainerHistory' => 'TrainerHistoryComposer'], ['trainers.upcoming' => 'UpcomingTrainerSessionsComposer'], ['trainers.trainerBlock' => 'TrainerBlockComposer'], ['wallets.show' => 'ShowWalletComposer'], // evercisegroups ['evercisegroups.class_hub' => 'ClassHubComposer'], ['evercisegroups.create' => 'EvercisegroupCreateComposer'], ['evercisegroups.refine' => 'SearchClassesComposer'], ['evercisegroups.refine' => 'RefineComposer'], ['evercisegroups.category_box' => 'CategoryBoxComposer'], ['evercisegroups.recommended' => 'RecommendedClassesComposer'], ['evercisegroups.trainer_show' => 'TrainerShowComposer'], ['evercisegroups.show' => 'EvercisegroupsShowComposer'], ['evercisegroups.search' => 'EvercisegroupsSearchComposer'], // landing pages ['layouts.create' => 'PpcLandingComposer'], // sessions ['sessions.join' => 'JoinSessionsComposer'], ['sessions.confirmation' => 'ClassPurchaseComposer'], // venues ['venues.select' => 'VenueComposer'], ['venues.edit_form' => 'VenueComposer'], // statis pages ['static.how_it_works' => 'GroupSetComposer'], ['static.how_it_works' => 'AccordionComposer'], // widgets ['widgets.calendar' => 'CalendarComposer'], ['widgets.mapForm' => 'MapComposer'], ['widgets.time' => 'TimeComposer'], ['widgets.donutChart' => 'DonutChartComposer'], ['widgets.autocomplete-location' => 'AutocompleteLocationComposer'], ['widgets.autocomplete-category' => 'AutocompleteCategoryComposer'], // layouts ['layouts.header' => 'GroupSetComposer'], ['form.password' => '<PASSWORD>'], ['form.phone' => 'AreacodeComposer'], ['form.phone' => 'PhoneComposer'], // payments ['payments.paywithevercoins' => 'PayWithEvercoinsComposer'], //['payments.cartrows' => 'CartRowsComposer'], // admin ['admin.groups' => 'AdminGroupComposer'], ['admin.pendingwithdrawals' => 'AdminPendingWithdrawalComposer'], ['admin.users' => 'AdminShowUsersComposer'], ['admin.trainers' => 'AdminShowUsersComposer'], ['admin.pendingtrainers' => 'AdminPendingTrainersComposer'], ['admin.log' => 'AdminLogComposer'], ['admin.categories' => 'AdminCategoriesComposer'], ['admin.subcategories' => 'AdminSubcategoriesComposer'], ['admin.searchassociations' => 'AdminAssociationsComposer'], ];<file_sep>/app/config/facebook.php <?php // app/config/facebook.php // Facebook app Config return array( 'appId' => getenv('FACEBOOK_ID'), 'secret' => getenv('FACEBOOK_SECRET') ); <file_sep>/app/composers/VenueComposer.php <?php namespace composers; use JavaScript; use Venue; use Facility; use Sentry; class VenueComposer { public function compose($view) { // Run the MapComposer composer, because it doesn't seem to run by itself (new MapComposer)->compose($view); //$venues = Venue::lists('name', 'id'); $user = Sentry::getUser(); $venues = Venue::where('user_id', $user->id)->lists('name', 'id'); $facilities = Facility::get(); JavaScript::put( [ 'initVenues' => 1, 'MapWidgetloadScript' => 1 ] ); $view->with('venues', $venues)->with('facilities', $facilities); } }<file_sep>/app/composers/TrainerBlockComposer.php <?php namespace composers; use JavaScript; use DateTime; class TrainerBlockComposer { public function compose($view) { $viewdata = $view->getData(); $userTrainer = $viewdata['trainer']->user; $trainerDetails = $viewdata['trainer']; $orientation = $viewdata['orientation']; $gender = $userTrainer->gender; if ($gender == 0) { $gender = 'female'; } else { $gender = 'male'; } $dob = $userTrainer->dob; $from = new DateTime($dob); $to = new DateTime('today'); $age = $from->diff($to)->y; $trainerDetails = $viewdata['trainer']; $bio = $trainerDetails->bio; $profession = $trainerDetails->profession; if ($orientation == 'landscape') { JavaScript::put(array('initReadMore' => 1)); // Initialise read more. } $view ->with('gender', $gender) ->with('age', $age) ->with('bio', $bio) ->with('profession', $profession); } } <file_sep>/app/database/seeds/HistorytypesTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class HistorytypesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('historytypes')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Historytype::create(array( 'name' => 'created_class', 'description' => 'a new evercisegroup has been created by a trainer')); Historytype::create(array( 'name' => 'added_session', 'description' => 'a trainer has added a new session to evercise group')); Historytype::create(array( 'name' => 'deleted_group', 'description' => 'a trainer has deleted an evercisegroup / class')); Historytype::create(array( 'name' => 'deleted_session', 'description' => 'a trainer has deleted a session')); Historytype::create(array( 'name' => 'joined_group', 'description' => 'a user joined an evercisegroup / class')); Historytype::create(array( 'name' => 'rated_session', 'description' => 'a user has left a rating for a session')); Historytype::create(array( 'name' => 'left_session_full', 'description' => 'A user has left a session with full refund')); Historytype::create(array( 'name' => 'left_session_half', 'description' => 'A user has left a session with 50% refund')); } }<file_sep>/app/events/Admin.php <?php namespace events; use Log, Mail; class Admin { public function hasCreatedTrainer($user, $trainer) { Log::info('Admin Created a Trainer with id '.$user->id); $resetCode = $user->getResetPasswordCode(); Mail::send('emails.admin.createTrainer', compact('user', 'trainer', 'resetCode'), function($message) use($user) { $message->to($user->email) ->subject('Welcome to Evercise'); }); } }<file_sep>/public/assets/jsdev/prototypes/19.register-user.js function registerUser(form){ this.form = form; this.validIcon = 'glyphicon glyphicon-ok'; this.invalidIcon = 'glyphicon glyphicon-remove'; this.validatingIcon = 'glyphicon glyphicon-refresh'; this.displayName = { message: 'Your username is not valid', validators: { notEmpty: { message: 'Your display name is required' }, stringLength: { min: 5, max: 20, message: 'Your display name must be more than 5 and less than 20 characters long' }, regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: 'Your display name must consist of alphanumeric characters and underscores' } } }; this.email = { validators: { notEmpty: { message: 'Your email is required and cannot be empty' }, emailAddress: { message: 'Your email is not a valid email address' } } }; this.first_name = { validators: { regexp: { regexp: /^[a-zA-Z]+$/, message: 'Your first name can only contain letters' }, notEmpty: { message: 'Your first name is required and cannot be empty' }, stringLength: { min: 2, max: 15, message: 'Your first name must be more than 2 and less than 15 characters long' } } }; this.last_name = { validators: { regexp: { regexp: /^[a-zA-Z]+$/, message: 'Your surname name can only contain letters' }, notEmpty: { message: 'Your surname is required and cannot be empty' }, stringLength: { min: 2, max: 15, message: 'Your surname must be more than 2 and less than 15 characters long' } } }; this.password = { validators: { notEmpty: { message: 'Your password is required and cannot be empty' }, stringLength: { min: 6, max: 32, message: 'Your Password must be more than 6 and less than 32 characters long' }, identical: { field: 'password_confirmation', message: 'Your passwords do not match' } } }; this.confirmed_password = { validators: { notEmpty: { message: 'Your password is required and cannot be empty' }, stringLength: { min: 6, max: 32, message: 'Your Password must be more than 6 and less than 32 characters long' }, identical: { field: 'password', message: 'Your passwords do not match' } } }; this.phone = { validators: { phone: { country: 'areacode', message: 'The value is not valid %s phone number' } } } this.init(); } registerUser.prototype = { constructor: registerUser, init: function(){ this.form.find("input[type='submit']").prop('disabled', true); this.validation(); this.addListeners(); }, addListeners : function(){ this.form.find('input[name="terms"]').on('change', $.proxy(this.reVal, this)); }, reVal: function(e){ if($(e.target).is(':checked') && this.form.data('bootstrapValidator').isValid()){ this.form.find("input[type='submit']").prop('disabled', false); } }, validation: function(){ var self = this; this.form.bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: this.validIcon, invalid: this.invalidIcon, validating: this.validatingIcon }, fields: { display_name: this.displayName, email: this.email, first_name: this.first_name, last_name: this.last_name, password: <PASSWORD>, password_confirmation: this.confirmed_password, phone : this.phone } }) .on('success.form.bv', function(e) { e.preventDefault(); if(self.form.find('input[name="terms"]').is(':checked') || self.form.find('input[name="terms"]').length == 0) { self.ajaxUpload(); } else{ self.form.find('input[name="terms"]').parent().append('<span class="center-block text-danger help-box">You must accept our terms and conditions before continuing</span>') }; }); }, ajaxUpload: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).after('<br><span id="register-loading" class="icon icon-loading ml10"></span>'); }, success: function (data) { if( data.validation_failed == 1 ){ self.failedValidation(data); } else{ window.location.href = data.url; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type=submit]").prop('disabled', false); $('#register-loading').remove(); } }); }, failedValidation: function(data){ self = this; var arr = data.errors; $.each(arr, function(index, value) { if(self.form.find('input[name="' + index+ '"]').parent().hasClass('input-group')){ self.form.find('input[name="' + index + '"]').parent().parent().addClass('has-error'); self.form.find('input[name="' + index + '"]').parent().after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); self.form.find('input[name="' + index + '"]').parent().after('<i class="form-control-feedback glyphicon glyphicon-remove" data-bv-icon-for="' + index + '"></i>'); } else { self.form.find('input[name="' + index + '"]').parent().addClass('has-error'); self.form.find('input[name="' + index + '"]').parent().find('.glyphicon').remove(); self.form.find('input[name="' + index + '"]').parent().find('.help-block:visible').remove(); self.form.find('input[name="' + index + '"]').after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); self.form.find('input[name="' + index + '"]').after('<i class="form-control-feedback glyphicon glyphicon-remove" data-bv-icon-for="' + index + '"></i>'); } }) } }<file_sep>/app/composers/ShowEvercoinComposer.php <?php namespace composers; use Config; use Evercoin; use Sentry; use Evercoinhistory; use User; class ShowEvercoinComposer { public function compose($view) { $user = User::where('id', Sentry::getUser()->id)->with('referrals')->with('milestone')->first(); $evercoin = Evercoin::where('user_id', $user->id)->first(); $evercoinHistory = Evercoinhistory::where('user_id', $user->id)->get(); $evercoinBalance = $evercoin->balance; $priceInEvercoins = Evercoin::evercoinsToPounds($evercoinBalance); $fb = $user->token->facebook ? true : false; $tw = $user->token->twitter ? true : false; $referrals = $user->referrals; $profile = $user->milestone->profile; $referralConfig = Config::get('values')['milestones']['referral']; $numReferrals = $user->milestone->referrals; $totalReferrals = ceil($numReferrals / $referralConfig['count']) * $referralConfig['count']; $profile = 60; // 60 + the 4 tests below = 100% $profile += $user->gender ? 10 : 0; $profile += $user->dob ? 10 : 0; $profile += $user->phone ? 10 : 0; $profile += $user->image ? 10 : 0; // JavaScript::put(array('initPut' => json_encode(['selector' => '#send_invite']) )); $view ->with('evercoinBalance', $evercoinBalance) ->with('priceInEvercoins', $priceInEvercoins) ->with('evercoinHistory', $evercoinHistory) ->with('fb', $fb) ->with('tw', $tw) ->with('referrals', $referrals) ->with('numReferrals', $numReferrals) ->with('totalReferrals', $totalReferrals) ->with('profile', $profile) ->with('id', $user->id); } }<file_sep>/app/composers/TrainersCreateComposer.php <?php namespace composers; use JavaScript; class TrainersCreateComposer { public function compose($view) { JavaScript::put( [ 'initPut' => json_encode(['selector' => '#trainer_create']), 'initImage' => json_encode(['ratio' => 'user_ratio']), 'initToolTip' => 1 ] ); //Initialise tooltip JS. } }<file_sep>/app/commands/FixImages.php <?php ini_set('gd.jpeg_ignore_warning', TRUE); use Illuminate\Console\Command; use Symfony\Component\Debug\Exception\FatalErrorException; class FixImages extends Command { protected $name = 'images:fix'; protected $description = 'Fix Missing Images'; public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $users = User::all(); $sizes = Config::get('evercise.user_images'); foreach ($users as $user) { $this->line('Starting user '.$user->display_name); $done = FALSE; foreach ($sizes as $s) { if ($done) { break; } foreach(range(1, 10) as $num) { $file_name = slugIt(implode(' ', [$user->display_name, $num])); $name = $s['prefix'] . '_' . $file_name; $full = 'public/' . $user->directory . '/' . $name; if (file_exists($full.'.jpg')) { $user->image = $file_name.'.jpg'; $this->line('Fixed '.$user->directory . '/' . $name); $user->save(); $done = TRUE; break; } if (file_exists($full.'.png')) { $user->image = $file_name.'.png'; $this->line('Fixed '.$user->directory . '/' . $name); $user->save(); $done = TRUE; break; } } } } } }<file_sep>/app/database/migrations/2015_02_05_150628_create_evercisegroup_import_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEvercisegroupImportTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::dropIfExists('venue_import'); Schema::create('venue_import', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('evercisegroup_id'); $table->integer('external_id'); $table->integer('external_site_id'); $table->integer('external_venue_id'); $table->string('source'); $table->string('name'); $table->string('description'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('venue_import'); } } <file_sep>/app/controllers/AdminController.php <?php /** * Class AdminController */ class AdminController extends Controller { public $user; public $data; public function __construct() { $this->beforeFilter('csrf', array('on' => 'post')); $this->user = Sentry::getUser(); $this->data = [ 'user' => $this->user ]; } } <file_sep>/app/controllers/ajax/AuthController.php <?php namespace ajax; use Input, Sentry, Event, Response, Exception, Trainer; use Cartalyst\Sentry\Users\UserNotActivatedException; use Cartalyst\Sentry\Users\UserNotFoundException; use Cartalyst\Sentry\Users\WrongPasswordException; use Cartalyst\Sentry\Throttling\UserSuspendedException; class AuthController extends AjaxBaseController { /** * Login action * @return Redirect */ public function postLogin() { $credentials = array( 'email' => Input::get('email'), 'password' => Input::get('password') ); $redirect_after_login = Input::get('redirect_after_login'); $redirect_after_login_url = Input::get('redirect_after_login_url'); $result = ''; try { $user = Sentry::authenticate($credentials, false); if ($user) { Sentry::loginAndRemember($user); if ($redirect_after_login) { return Response::json( [ 'callback' => 'gotoUrl', 'url' => route($redirect_after_login_url) ] ); } else { return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('users.edit', $user->display_name) ] ); } } } catch(WrongPasswordException $e) { $result = 'Incorrect email or password'; } catch(UserNotFoundException $e) { $result = 'Incorrect email or password'; } catch(UserNotActivatedException $e) { $result = 'Your account has not been activated'; } catch(UserSuspendedException $e) { $result = 'Your account has been suspended'; } catch(Exception $e) { $result = $e->getMessage(); } return Response::json([ 'callback' => 'error', 'validation_failed' => 1, 'errors' => $result ]); } }<file_sep>/app/commands/SendEmails.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class SendEmails extends Command { /** * The console command name. * * @var string */ protected $name = 'email:remind'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; protected $cutOff; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $cutOffDate = Config::get('pardot.reminders.usercutoff'); $this->cutOff = new DateTime(); $this->cutOff->setDate($cutOffDate['year'], $cutOffDate['month'], $cutOffDate['day']); } /** * Execute the console command. * * @return mixed */ public function fire() { $output = $this->remindSessions(); $this->whyNotReview(); return $output; } /** * check for users who: * have attended a class > 4 hours ago but during the last day * does not have an entry in 'email_out' matching type 'mail.rateclass' * signed up after 01/12/14 * * If user has no active package, * * @return mixed */ public function whyNotReview() { $numHours = Config::get('pardot.reminders.whynotreview.hourssinceclass'); $this->info('whyNotReview - Searching for users who have bought a class which took place '.$numHours.' hours ago'); $afewhoursago = (new DateTime())->sub(new DateInterval('PT'.$numHours.'H')); $yesterday = (new DateTime())->sub(new DateInterval('P1D')); $users = User::whereHas('sessions', function($query) use (&$afewhoursago, &$yesterday){ $query->where('date_time', '<', $afewhoursago) ->where('date_time', '>', $yesterday); }) ->where('created_at', '>', $this->cutOff) ->with(['emailOut' => function($query){ $query->where('type', '=', 'mail.rateclass'); }]) ->get(); $emailsSent = 0; foreach($users as $user) { if(! count($user->emailOut)) { if (! \UserPackages::hasActivePackage($user)) { /** hasActivePackage FUNCTION IS DODGY - NEEDS FIXING */ $emailsSent++; $this->info('user: ' . $user->id); event('user.class.rate', [$user]); } else { $this->info('user: ' . $user->id . 'has active package'); event('user.class.rate.haspackage', [$user]); } } } $this->info('user count: '.$emailsSent); } /** * Check for sessions happening in less than 2 days * Send a reminder email to all users * Send a participant list to the trainer * * @return mixed */ public function remindSessions() { $this->info('remindSessions - Searching for Sessions in the next 1 day, which have not yet fired out emails'); $today = new DateTime(); $onedaystime = (new DateTime())->add(new DateInterval('P1D')); $evercisegroup = Evercisegroup::with(array('evercisesession' => function($query) use (&$onedaystime, &$today) { $query ->where('date_time', '<', $onedaystime) ->where('date_time', '>', $today) ->whereHas('sessionmembers', function($query2){}); //$query->whereIn('id', [1,2,6]); }), 'user', 'venue')->get(); $numSessions = 0; $emails = []; $sessionIds = []; foreach ($evercisegroup as $group) { $numSessions += count($group->evercisesession); foreach ($group->evercisesession as $session) { if ($session->members_emailed == 0) { $userList = []; foreach ($session->users as $user) { $userList[$user->first_name.' '.$user->last_name] = [ 'email' => $user->email, 'transactionId'=>$user->pivot->transaction_id, ]; } $emails[] = [ 'groupName'=>$group->name, 'group'=>$group, 'dateTime'=>$session->date_time, 'userList' =>$userList, 'trainer'=>$group->user, 'location'=>$group->venue->address.', '.$group->venue->town.', '.$group->venue->postcode, 'classId' => $group->id, 'sessionId' => $session->id, ]; $sessionIds[] = $session->id; } } } if (count($emails)) { $this->info('Number of Sessions to be emailed: '.$numSessions); foreach($emails as $email) { $this->info(''); $this->info('Session: '.$email['groupName'].' - '.$email['dateTime']); $this->info('Trainer: '.$email['trainer']->id.' - '.$email['trainer']->display_name); $this->info('Venue: '.$email['location']); foreach ($email['userList'] as $name => $details) { $this->info(' -- '.$name.' : '.$details['email']); } // Pang out an email with a list of users Event::fire('session.upcoming_session', [ 'userList' => $email['userList'], 'group' => $email['group'], 'location' => $email['location'], 'dateTime' => $email['dateTime'], 'trainerName' => $email['trainer']->first_name.' '.$email['trainer']->last_name, 'trainerEmail' => $email['trainer']->email, 'classId' => $email['classId'], 'sessionId' => $email['sessionId'], ]); } Evercisesession::whereIn('id', $sessionIds)->update(['members_emailed' => 1]); } else { $this->info('No sessions found which have not already sent out emails'); } return 'sessions mailed: '.$numSessions; } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( //array('days', null, InputOption::VALUE_OPTIONAL, 'How many days to search back.', 1), ); } } <file_sep>/app/controllers/PingController.php <?php use Illuminate\Database\DatabaseManager; use Illuminate\Foundation\Application; use Illuminate\Cache\Repository; /** * Class PingController */ class PingController extends Controller { /** * @var PingElastic */ private $pingElastic; /** * @var App */ private $app; /** * @var DatabaseManager */ private $db; /** * @var Repository */ private $cache; /** * @param PingElastic $pingElastic * @param Application $app * @param DatabaseManager $db * @param Repository $cache */ public function __construct(PingElastic $pingElastic, Application $app, DatabaseManager $db, Repository $cache) { $this->pingElastic = $pingElastic; $this->app = $app; $this->db = $db; $this->cache = $cache; } /** * Check all Services * @return string */ public function check() { $this->checkElastic(); $this->checkMysql(); $this->checkCache(); return 'All is good!'; } /** * Check if ElasticIsWorking */ public function checkElastic() { if (!$this->pingElastic->check()) { $this->app->abort(404); } } /** * Check if Mysql is Connecting */ public function checkMysql() { if (!$this->db->connection()->getDatabaseName()) { $this->app->abort(404); } } /** * Check if Cache is Connecting */ public function checkCache() { $rand_cache_id = str_random(); $this->cache->add($rand_cache_id, $rand_cache_id, 300); if (!$this->cache->has($rand_cache_id)) { $this->app->abort(404); } $this->cache->forget($rand_cache_id); } }<file_sep>/app/composers/CategoryBoxComposer.php <?php namespace composers; class CategoryBoxComposer { public function compose($view) { $viewdata = $view->getData(); $subcategories = $viewdata['subcategories']; /*loop through the sub cats to get category pivot */ foreach ($subcategories as $key => $subcategory) { $subcats[] = $subcategory->categories; } /*loop though pivot to get catehory */ $categories = []; $categoryIds = []; foreach ($subcats as $key => $subcat) { foreach ($subcat as $key => $cat) { if (!in_array($cat->id, $categoryIds)) { $categoryIds[] = $cat->id; $categories[] = $cat; } } } $view->with('categories', $categories); } }<file_sep>/app/controllers/ajax/GalleryController.php <?php namespace ajax; use Illuminate\Http\Request; use Gallery; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\View; class GalleryController extends AjaxBaseController { private $gallery; private $request; private $response; private $view; public function __construct( Gallery $gallery, Request $request, Response $response, View $view ) { $this->gallery = $gallery; $this->request = $request; $this->response = $response; $this->view = $view; } public function getDefaults() { $gallery = 0; $find = $this->request->get('keywords', FALSE); if ($find) { $find = explode(',', $find); // foreach ($find as $key) { // // $subcategory = \Subcategory::with('categories')->where('name', $key)->first(); // // $find[] = $subcategory->categories()->first()->name; // } $gallery = $this->gallery->where('counter', '>', 0) ->where(function ($query) use ($find) { foreach ($find as $key) { $query->orWhere('keywords', 'like', '%' . $key . '%'); } }) ->limit(20)->get(); } if (count($gallery) == 0) { $gallery = $this->gallery->where('counter', '>', 0)->limit(20)->get(); } //return $this->response->json($gallery->toArray()); return $this->response->json([ 'view' => View::make('v3.widgets.class_gallery_row')->with('gallery', $gallery->toArray())->render() ]); } }<file_sep>/app/start/cronjobs.php <?php /* Dynamically load Events from Config */ $cronjobs = Config::get('cronjob'); /** Kill if not active */ if (!$cronjobs['active']) { return; } /** Since we sometimes have issues with CronLocks not working */ $lock_file = storage_path() . '/cron.lock'; if (is_file($lock_file)) { $lock_created_ago = time() - filemtime($lock_file); Log::info('Lock Active '.$lock_created_ago); /** Delete if the limit passed */ if ($lock_created_ago > $cronjobs['lock_limit']) { unlink($lock_file); } } Event::listen('cron.collectJobs', function () use ($cronjobs) { foreach ($cronjobs['jobs'] as $name => $time) { Cron::add($name, $time, function () use ($name) { $class_string = 'cronjobs\\' . $name; $jobClass = App::make($class_string); return $jobClass->run(); }); } }); Event::listen('cron.jobError', function ($name, $return, $runtime, $rundate) { Log::error('Job with the name ' . $name . ' returned an error. ' . $return); });<file_sep>/app/controllers/ajax/SessionsController.php <?php namespace ajax; use DateTime; use Input, Response, Evercisegroup, Evercisesession, View; use Carbon\Carbon; class SessionsController extends AjaxBaseController { public function getSessionsInline() { $evercisegroupId = Input::get('groupId'); $id = Input::get('id'); //$sessions = Evercisegroup::find($evercisegroupId)->futuresessions; $sessions = Evercisesession::where('evercisegroup_id', $evercisegroupId) ->where('date_time', '>=', Carbon::now()) ->orderBy('date_time', 'asc') ->paginate(5); $userId = \Sentry::getUser()->id; if ($id != $userId) { $type = 'user'; } else { $type = 'edit'; } return Response::json([ 'view' => View::make('v3.classes.sessions_inline') ->with('sessions', $sessions) ->with('evercisegroup_id', $evercisegroupId) ->with('mode', $type)->render(), 'id' => $evercisegroupId ]); } /** * Update a set of sessions. * * POST variables: * * id = [] * time = [] * duration = [] * tickets = [] * price = [] * * @return Response */ public function update() { $preview = Input::get('preview'); $sessionIds = Input::get('id'); $time_array = Input::get('time'); $duration_array = Input::get('duration'); $tickets_array = Input::get('tickets'); $price_array = Input::get('price'); $evercisegroupId = Input::get('evercisegroup_id'); //return 'id:'.\Evercisegroup::getSlug($evercisegroupId); $userId = \Sentry::getUser()->id; if (!empty($sessionIds)) { if (!is_array($sessionIds)) { $sessionIds = [$sessionIds]; } if (!is_array($time_array)) { $time_array = [$time_array]; } if (!is_array($duration_array)) { $duration_array = [$duration_array]; } if (!is_array($tickets_array)) { $tickets_array = [$tickets_array]; } if (!is_array($price_array)) { $price_array = [$price_array]; } foreach ($sessionIds as $key => $id) { $inputs = [ 'time' => $time_array[$key], 'duration' => $duration_array[$key], 'tickets' => $tickets_array[$key], 'price' => $price_array[$key], ]; $session = Evercisesession::find($id); if ($session) { //return $session->validateAndUpdate($inputs, $userId); $updateResponse = $session->validateAndUpdate($inputs, $userId); if ($updateResponse['validation_failed']) { return Response::json( [ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'Sessions could not be updated')->with('fixed', TRUE)->render(), 'errors' => $updateResponse, 'id' => $id ] ); } }else { return Response::json( [ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'Session '.$id.' could not be found')->with('fixed', TRUE)->render(), 'errors' => ['sessions'=>'session cannot be found'], 'id' => $id ] ); } } } if (isset($preview) && $preview == 'yes') { return Response::json( [ 'url' => route('class.show', [\Evercisegroup::getSlug($evercisegroupId), 'preview']) ] ); } else { //return 'here: '.$preview; return Response::json( [ 'view' => View::make('v3.layouts.positive-alert')->with('message', 'your sessions were updated successfully')->with('fixed', TRUE)->render(), 'id' => $id ] ); } } /** * Remove the specified resource from storage. * * @return Response */ public function destroy() { $id = Input::get('id', FALSE); return Evercisesession::deleteById($id); } /** Save a new set of sessions * * POST variables: * evercisegroup_id * duration * tickets * price * session_array = [date, date, ...] * * @return Response */ public function store() { $inputs = Input::all(); $evercisegroupId = isset($inputs['evercisegroup_id']) ? $inputs['evercisegroup_id'] : $inputs['evercisegroupId']; $time = $inputs['time']; $duration = $inputs['duration']; $tickets = isset($inputs['tickets']) ? $inputs['tickets'] : $inputs['members']; $price = $inputs['price']; if (Input::get('session_array', FALSE)) { $sessionArray = explode(',', $inputs['session_array']); } elseif (Input::get('date', FALSE)) { $sessionArray = [$inputs['date']]; } else { return Response::json([ 'view' => View::make('v3.layouts.negative-alert')->with('message', 'No sessions specified')->with('fixed', TRUE)->render() ]); } foreach ($sessionArray as $date) { if (!Evercisesession::validateAndStore([ 'date' => $date, 'time' => $time, 'evercisegroup_id' => $evercisegroupId, 'duration' => $duration, 'tickets' => $tickets, 'price' => $price, ]) ) { // A session has failed validation } } $sessions = Evercisegroup::find($evercisegroupId)->futuresessions; event('class.index.single', [$evercisegroupId]); $update = Input::get('update', FALSE); if($update){ return Response::json([ 'view' => View::make('v3.classes.update_sessions_inline')->with('sessions', $sessions)->render(), 'id' => $evercisegroupId ]); } else{ return Response::json([ 'view' => View::make('v3.classes.sessions_inline')->with('sessions', $sessions)->with('evercisegroup_id', $evercisegroupId)->render(), 'id' => $evercisegroupId ]); } } public function getParticipants() { $sessionId = Input::get('session_id'); $participants = Evercisesession::getMembers($sessionId); return view('v3.sessions.participants', compact('participants')); } public function getSlug() { return $this->evercisegroup->slug; } public function getMembers() { $user = \Sentry::getUser(); $session_id = Input::get('session_id', FALSE); if (!$session_id) { return Response::json([ 'view' => FALSE, 'error' => 'You need to specify a session id' ]); } $evercisesession = Evercisesession::find($session_id); $evercisegroup = Evercisegroup::find($evercisesession->evercisegroup_id); if ($user->id !== $evercisegroup->user_id) { return Response::json([ 'view' => FALSE, 'error' => 'You dont have permissions to view this list' ]); } if ($evercisesession->sessionmembers()->count() == 0) { return Response::json([ 'view' => FALSE, 'error' => 'No Members on this list' ]); } $sessionmembers = $evercisesession->users; return Response::json([ 'view' => View::make('v3.classes.sessions_list_users', compact('evercisesession', 'evercisegroup', 'sessionmembers'))->render() ]); } }<file_sep>/app/models/Category.php <?php /** * Class Category */ class Category extends Eloquent { /** * @var array */ protected $fillable = array( 'id', 'name', 'image', 'order', 'visible', 'description', 'popular_classes', 'popular_subcategories', ); /** * The database table used by the model. * * @var string */ protected $table = 'categories'; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function subcategories() { return $this->belongsToMany( 'Subcategory', 'subcategory_categories', 'category_id', 'subcategory_id' )->withTimestamps(); } public static function editOrder($newOrder) { foreach ($newOrder as $id => $place) { $cat = static::where('id', $id); if($cat) { $cat->update(['order' => $place]); } } } public static function assignVisible($visibleSettings) { foreach ($visibleSettings as $id => $v) { $cat = static::where('id', $id); if($cat) { $cat->update(['order' => $v]); } } } public function getPopularClassesString() { $groups = Evercisegroup::whereIn('id', explode(',', $this->popular_classes))->lists('name'); return implode(',', $groups); } public function getPopularClasses() { $groups = Evercisegroup::whereIn('id', explode(',', $this->popular_classes))->get(); $output = []; foreach ($groups as $group) { $output[$group->id] = [ 'name' => $group->name, 'slug' => $group->slug, ]; } return $output; } public function getPopularSubcategoriesString() { if ($this->popular_subcategories) { $subcats = Subcategory::whereIn('id', explode(',', $this->popular_subcategories))->lists('name'); //return $this->popular_subcategories return implode(',', $subcats); } else { return ''; } } public function getPopularSubcategories() { //$subcategories = Subcategory::take(15)->lists('name', 'id'); //return $this->popular_subcategories; if ($this->popular_subcategories) { $subcats = Subcategory::whereIn('id', explode(',', $this->popular_subcategories))->get(); $output = []; foreach ($subcats as $subcat) { $output[] = [ 'name' => $subcat->name, ]; } return $output; } else { return []; } } public function getPopularClassSubcatMix() { $subcats = $this->getPopularSubcategories(); $mix = $this->getPopularClasses(); $i = 0; while (count($mix) < 3) { if( isset( $subcats[$i] ) ) array_push( $mix, $subcats[$i] ); else break; $i++; } return $mix; } /** * Returns an array of subcategories * - up to 15 results * - linked to category instance * - ordered by num of classes in that category */ public function generatePopularSubcategories() { $categoryId = $this->id; $subcategories = Subcategory:: whereHas('categories', function ($query) use ($categoryId) { $query->where('categories.id', $categoryId); }) ->whereHas('evercisegroups', function($query){}) ->take(15) ->get() ->sortByDesc(function ($subcats) { return $subcats->evercisegroups->count(); }); $output = []; foreach ($subcategories as $subcat) { $output[] = [ 'name' => $subcat->name, 'classes' => $subcat->evercisegroups->count(), ]; } return $output; } /** return all categorys * - description * - popular subcategories (the chosen ones) * - subcategories (order by num classes, limit 15) * */ public static function browse() { $categories = static:: with('subcategories') ->get() ->sortBy(function ($subcats) { return $subcats->order; }); $output = []; foreach ($categories as $category) { $output[] = [ 'name' => $category->name, 'description' => $category->description, 'popular_subcategories' => $category->getPopularClassSubcatMix(), 'generated_subcategories' => $category->generatePopularSubcategories(), ]; } return $output; } } <file_sep>/app/models/UserPackageClasses.php <?php /** * Class UserPackageClasses */ class UserPackageClasses extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'package_id', 'status', 'evercisesession_id']; /** * @var string */ protected $table = 'user_package_classes'; public function user() { return $this->belongsTo('User', 'user_id'); } public function package() { return $this->belongsTo('UserPackage', 'user_package_id'); } }<file_sep>/app/models/LandingPages.php <?php class LandingPages extends Eloquent { protected $table = 'landing_pages'; protected $fillable = ['id', 'slug', 'main_image', 'params']; }<file_sep>/public/assets/jsdev/prototypes/18-add-sessions-to-calendar.js function AddSessionsToCalendar(form){ this.form = form; this.calendar = this.form.find('#calendar'); this.index = ''; this.dates = []; this.selectedDates = []; this.submitDates = []; this.currentMonthYear = []; this.init(); } AddSessionsToCalendar.prototype = { constructor: AddSessionsToCalendar, init: function(){ this.calendar.datepicker({ format: "yyyy-mm-dd", startDate: "+1d", todayHighlight: true, multidate: true }) .on('changeDate', $.proxy(this.getCurrentDates, this) ); this.addListener(); }, addListener: function () { $(document).on('click', '.dow', $.proxy(this.dayOfWeek, this) ); this.form.on("submit", $.proxy(this.submitForm, this)); }, getCurrentDates: function(e){ var self = this; this.selectedDates = e.dates; this.dates = []; // keep original dates intact $.each(this.selectedDates , function(i,v){ self.dates.push({ 'key': v.valueOf(), 'dates': v }) }) }, dayOfWeek : function(e){ this.currentMonthYear = $('.datepicker-switch').first().text().split(" "); var d = new Date(), month = this.getMonthNumber(this.currentMonthYear[0], this.currentMonthYear[1]), year = this.currentMonthYear[1], self = this; this.index = ($(e.target).index()); d.setDate(1); d.setMonth(month); d.setFullYear(year); // Get the first nth in the month while (d.getDay() !== this.index) { d.setDate(d.getDate() + 1); } // Get all the other nth in the month while (d.getMonth() === month) { var rd = d.getFullYear() + '-' + ('0' + (d.getMonth() +1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + ' 00:00:00 AM' ; rd = rd.replace(/-/g,"/"); var recurringDate = new Date(rd); var resultFound = $.grep(self.dates, function(e){ return e.key == recurringDate.valueOf(); }); var resultFoundPlusHour = $.grep(self.dates, function(e){ return e.key == (recurringDate.valueOf() - 3600000); }); if (resultFound.length == 0 && resultFoundPlusHour.length == 0 ) { self.dates.push({ 'key' : recurringDate.valueOf(), 'dates' : recurringDate } ); } else{ self.dates = self.dates.filter(function(el){ return el.key !== recurringDate.valueOf(); }) } d.setDate(d.getDate() + 7); } this.setCalendarDates(); }, setCalendarDates: function(){ var dates = []; var dateValues ={}; $.each(this.dates , function (index, value) { // check for duplicates if ( ! dateValues[ value.key ]){ dateValues[value.key] = true; dates.push(value.dates); } }); this.calendar.datepicker('setDates', dates ); }, getMonthNumber : function(mon , year){ var d = Date.parse(mon + "1, "+ year); if(!isNaN(d)){ return new Date(d).getMonth(); } return -1; }, submitForm: function(e){ e.preventDefault(); $('#duplicate').remove() var self =this; var checkDates = JSON.parse(self.form.find('input[name="checkDates"]').val()); var dontSubmit; $.each(this.calendar.datepicker('getDates') , function(i,v){ var day = v.getDate(); var month = (v.getMonth() + 1); var year = v.getFullYear(); self.submitDates.push(year + '-'+ month + '-' + day); if( self.checkDates(checkDates, year + '-'+ month + '-' + day + ' ' + $('select[name="time"]').val()) ){ dontSubmit = true; return false; } }) if(dontSubmit){ self.form.find('input[type="submit"]').parent().before('<div class="alert alert-danger text-center" id="duplicate">Duplicate Time and date found, please check</div>') } else{ $('input[name="session_array"]').val( this.submitDates ); this.ajaxUpload(); } }, checkDates: function(checkDates, selectedDate){ var duplicate; $.each(checkDates, function(i, val){ var ch = new Date(val.date); var sd = new Date(selectedDate); if(ch.valueOf() == sd.valueOf()){ duplicate = true; return false; } }) return duplicate; }, ajaxUpload: function () { var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).parent().after('<span id="session-loading" class="icon icon-loading ml10 mt10"></span>'); }, success: function (data) { $('#update-session').html(data.view); $('input[name="recurring"][value="no"]').click(); self.dates = []; self.submitDates = []; self.selectedDates = []; self.setCalendarDates(); $("html, body").animate({scrollTop: $('#update-container').offset().top -20 }, 1000); if(RemoveSession.length == 0){ new RemoveSession($('.remove-session')); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log('error'); //console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false) $('#session-loading').remove(); } }); } }<file_sep>/app/models/Wallethistory.php <?php class Wallethistory extends \Eloquent { protected $fillable = ['user_id', 'transaction_amount', 'new_balance', 'sessionmember_id', 'description']; protected $table = 'wallethistory'; public function getTransactionAmount() { return '&pound;' . sprintf('%0.2f', $this->transaction_amount); } }<file_sep>/app/controllers/UsersController.php <?php class UsersController extends \BaseController { /** * Display a listing of the resource. * * @return View */ public function index() { return Redirect::route('home'); } /** * Show the form for creating a new resource. * * @return View */ public function create($redirect = null) { // If a user is already logged in, kick em out so a new account can be created. Sentry::logout(); $referral = Referral::checkReferralCode(Session::get('referralCode')); $ppcCode = Landing::checkLandingCode(Session::get('ppcCode')); if(!$ppcCode) $ppcCode = StaticLanding::checkLandingCode(Session::get('ppcCode')); $ppcDb = Landing::where('code', Session::get('ppcCode'))->first(); $email = ''; if(!empty($ppcDb->email)) { $email = $ppcDb->email; } if(!empty($referral->email)) { $email = $referral->email; } return View::make('v3.users.create') ->with('referralCode', $referral ? $referral->code : null) ->with('redirect', $redirect) ->with('ppcCode', $ppcCode) ->with('email', $email); } public function guestCheckout() { $referral = Referral::checkReferralCode(Session::get('referralCode')); $ppcCode = Landing::checkLandingCode(Session::get('ppcCode')); return View::make('v3.users.guest') ->with('referralCode', $referral ? $referral->code : null) ->with('redirect', 'cart/checkout') ->with('ppcCode', $ppcCode) ->with('email', $referral ? $referral->email : ''); } public function fb_login($redirect_url = null, $params = '') { $getUser = User::getFacebookUser($redirect_url, $params); $me = $getUser['user_profile']; if(!empty($params)) { Session::put('FB_REDIRECT_PARAMS', $params); } if (empty($me)) { return Redirect::to('/')->with('message', 'There was an error communicating with Facebook'); } $inputs = []; $inputs['display_name'] = slugIt($me['name']); $inputs['first_name'] = $me['first_name']; $inputs['last_name'] = $me['last_name']; $inputs['dob'] = isset($me['birthday']) ? new DateTime($me['birthday']) : null; $inputs['email'] = $me['email']; $inputs['password'] = Functions::randomPassword(8); $inputs['activated'] = true; $inputs['gender'] = (isset($me['gender'])) ? (($me['gender'] == 'male') ? 1 : 2) : null; try { // register user and add to user group $user = User::registerUser($inputs); if ($user) { User::addToUserGroup($user); User::addToFbGroup($user); UserHelper::generateUserDefaults($user->id); UserHelper::checkAndUseReferralCode(Session::get('referralCode'), $user->id); UserHelper::checkAndUseLandingCode(Session::get('ppcCode'), $user->id); Session::forget('email'); $token = Token::where('user_id', $user->id)->first(); $token->addToken('facebook', Token::makeFacebookToken($getUser)); User::subscribeMailchimpNewsletter( Config::get('mailchimp')['newsletter'], $user->email, $user->first_name, $user->last_name ); User::sendFacebookWelcomEmail($user, $inputs); User::makeUserDir($user); User::grabFacebookImage($user, $me); Sentry::login($user, false); $result = User::facebookRedirectHandler($redirect_url, $user, trans('redirect-messages.facebook_signup'), $params); event('user.registeredFacebook', [$user]); } } catch (Cartalyst\Sentry\Users\UserExistsException $e) { try { $user = Sentry::findUserByLogin($me['email']); Sentry::login($user, false); if (Sentry::check()) { event('user.loginFacebook', [$user]); } //$result = User::facebookRedirectHandler($redirect_url, $user); $result = Redirect::route('users.edit', ['id'=>$user->display_name]); $params = []; if (Session::has('FB_REDIRECT_PARAMS')) { $data = explode(':', Session::get('FB_REDIRECT_PARAMS')); if (!empty($data[1])) { $params[$data[0]] = $data[1]; } Session::forget('FB_REDIRECT_PARAMS'); } if(!is_null($redirect_url)) { $result = Redirect::route($redirect_url, $params); } } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { Log::error($e->getMessage()); } } return $result; } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { if(!$this->checkLogin()) { return Redirect::route('home'); } return View::make('users.show'); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id, $tab = 0) { $activity = Activities::getAll($this->user->id, Config::get('evercise.user.activities', 100)); $activity_group = []; foreach($activity as $a) { $activity_group[$a->format_date][] = $a; } $user = $this->user; $data = [ 'user' => $user, 'activity' => $activity_group ]; if(Trainer::isTrainerLoggedIn()) { $hub = Evercisegroup::getTrainerHub($user); $data = array_merge($hub, $data); $view = 'v3.users.profile.master_trainer'; } else { $hub = Evercisegroup::getUserHub($user); $data = array_merge($hub, $data); $view = 'v3.users.profile.master_user'; } return View::make( $view ) ->with('data', $data) ->with('tab', $tab); } /** * Activate the user using the emailed hash * * @param int $id * @return Response */ public function pleaseActivate($display_name) { return View::make('users.activate')->with('display_name', $display_name); } /** * Reset the user's password using the emailed hash * * @param int $id * @return Response */ public function postChangePassword() { Validator::extend( 'has', function ($attr, $value, $params) { return ValidationHelper::hasRegex($attr, $value, $params); } ); $validator = Validator::make( Input::all(), [ 'old_password' => '<PASSWORD>', 'new_password' => '<PASSWORD>|min:6|max:32', ] ); $oldPassword = Input::get('old_password'); $newPassword = Input::get('new_password'); if ($validator->fails()) { return Response::json(['validation_failed' => 1, 'errors' => $validator->errors()->toArray()]); } else { if ($oldPassword == $newPassword) { return Response::json( [ 'validation_failed' => 1, 'errors' => ['new_password' => 'your new password <PASSWORD> your <PASSWORD>'] ] ); } if ($this->user->checkPassword($oldPassword)) { $this->user->password = $<PASSWORD>; $this->user->save(); event('user.changedPassword', [ $this->user ]); return Response::json(['result' => 'changed', 'callback' => 'successAndRefresh']); } return Response::json( ['validation_failed' => 1, 'errors' => ['old_password' => 'Current password incorrect']] ); } } /** * Reset the user's password using the emailed hash * * @param int $id * @return View */ public function getResetPassword($display_name, $code) { try { $user = Sentry::findUserByResetPasswordCode($code); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { return View::make('v3.auth.resetpassword')->with('message', 'Cannot find user'); } return View::make('v3.auth.resetpassword')->with('code', $code); } /** * Reset the user's password using the emailed hash * * @internal param int $id * @return Response */ public function postResetPassword() { Validator::extend( 'has', function ($attr, $value, $params) { return ValidationHelper::hasRegex($attr, $value, $params); } ); $validator = Validator::make( Input::all(), array( 'email' => 'required|email', 'password' => '<PASSWORD>', ), ['password.has' => 'The password must contain at least one number and can be a combination of lowercase letters and uppercase letters.',] ); $email = Input::get('email'); $password = Input::get('password'); $code = Input::get('code'); if ($validator->fails()) { return Response::json([ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]); } else { $success = false; try { $user = Sentry::findUserByLogin($email); if ($user->checkResetPasswordCode($code)) { $success = $user->attemptResetPassword($code, $password); } } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { //return View::make('v3.auth.resetpassword')->with('message', 'Could not find user. Please check your email address'); Session::flash( 'errorNotification', 'Sorry we are experiencing technical difficulties, please try again or contact our technical support at <EMAIL>' ); return Response::json(route('home')); } if ($success) { event('user.changedPassword', [$user]); Session::flash('notification', 'Password reset successful'); return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('home') ] ); } else { $result = array( 'validation_failed' => 1, 'errors' => array('email' => array(0 => 'Wrong email')) ); return Response::json($result); } } } public function getLoginStatus() { return View::make('users.loginStatus'); } /** * Logout Action * * @return Redirect */ public function logout() { if(!$this->checkLogin()) { return Redirect::route('home'); } $user = Sentry::getUser(); if (!empty($user->id)) { event('user.logout', [$user]); } Sentry::logout(); $cookie = Cookie::forget('PHPSESSID'); return Redirect::route('home')->withCookie($cookie); } public function replyToMessage($user_slug) { } public function fuck() { return 'COCK'; } }<file_sep>/app/composers/AdminSubcategoriesComposer.php <?php namespace composers; use JavaScript; class AdminSubcategoriesComposer { public function compose($view) { $subcategories = \Subcategory::with('categories')->get(); $categories = \Category::lists('name'); array_unshift($categories, ''); return $view ->with('categories', $categories) ->with('subcategories', $subcategories); } }<file_sep>/app/commands/ConvertTickets.php <?php use Illuminate\Console\Command; use Symfony\Component\Debug\Exception\FatalErrorException; class ConvertTickets extends Command { protected $name = 'convert:tickets'; protected $description = 'Convert Tickets in the DB'; public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $user_completed = []; $users = User::all(); $sizes = Config::get('evercise.user_images'); foreach($users as $user) { $dir = hashDir($user->id, 'u'); $user_completed[$user->id] = $user->directory; $user->directory = $dir; $user->save(); $user_file_name = slugIt(implode(' ', [$user->display_name, rand(1, 10)])); if (!empty($user->image) && strpos($user->image, '.') !== false) { $extension = explode('.', $user->image); $user_file_name .= '.' . end($extension); try { $this->info('public/profiles/' . $user_completed[$user->id] . '/' . $user->image); $file = Image::make('public/profiles/' . $user_completed[$user->id] . '/' . $user->image); } catch (Exception $e) { $this->error('Crap ' . $e->getMessage()); $this->error('public/profiles/' . $user_completed[$user->id] . '/' . $user->image); continue; } if ($file) { /** Save the images */ foreach ($sizes as $s) { $file_name = $s['prefix'] . '_' . $user_file_name; try { $this->info('public/profiles/' . $user_completed[$user->id] . '/' . $user->image); $file->fit($s['width'], $s['height'])->save('public/' . $dir . '/' . $file_name); $this->info('Success public/' . $dir . '/' . $file_name); } catch (Exception $e) { $this->error('Crap ' . $e->getMessage()); $this->error('public/' . $dir . '/' . $file_name); continue; } } $user->image = $user_file_name; $this->info('Success public/' . $dir . '/' . $user_file_name); } else { $this->error('Shit... Failed User Image'); $this->error('Copy From: public/profiles/' . $user_completed[$user->id] . '/' . $user->image); $this->error('Copy To: public/' . $dir . '/' . $user_file_name); } } } $all = Evercisegroup::all(); foreach ($all as $a) { $user = $a->user()->first(); if (!isset($user->id)) { continue; } $dir = hashDir($user->id, 'u'); /** Im Going TO Just copy the file to the new place.... just in case */ $title = [ $a->name, (!empty($user->display_name) ? $user->display_name : $user->first_name . ' ' . $user->last_name), rand(1, 100) ]; $extension = explode('.', $a->image); $sizes = Config::get('evercise.class_images'); $slug = slugIt(implode(',', $title)) . '.' . end($extension); try { $this->info('public/profiles/' . $user_completed[$user->id] . '/' . $a->image); $file = Image::make('public/profiles/' . $user_completed[$user->id] . '/' . $a->image); } catch (Exception $e) { $this->error('Crap ' . $e->getMessage()); $this->error('public/profiles/' . $user_completed[$user->id] . '/' . $a->image); continue; } if ($file) { /** Save the images */ foreach ($sizes as $s) { $file_name = $s['prefix'] . '_' . $slug; try { $this->info('public/' . $dir . '/' . $file_name); $file->fit($s['width'], $s['height'])->save('public/' . $dir . '/' . $file_name); $this->info('Success public/' . $dir . '/' . $file_name); } catch (Exception $e) { $this->error('Crap ' . $e->getMessage()); $this->error('public/' . $dir . '/' . $file_name); continue; } } $a->image = $slug; $a->save(); } else { $this->error('Shit... Failed'); $this->error('Copy From: public/profiles/' . $dir . '/' . $slug); } } } }<file_sep>/app/models/ArticleCategories.php <?php /** * Articles Models */ class ArticleCategories extends Eloquent { /** * @var array */ protected $fillable = array('id', 'parent_id', 'title', 'main_image', 'description', 'keywords', 'permalink'); /** * The database table used by the model. * * @var string */ protected $table = 'article_categories'; public function subcategories() { return $this->belongsTo('ArticleCategories', 'parent_id'); } }<file_sep>/app/composers/VenueEditComposer.php <?php namespace composers; use JavaScript; use Venue; use Facility; use Sentry; class VenueComposer { public function compose($view) { // Run the MapComposer composer, because it doesn't seem to run by itself (new MapComposer)->compose($view); //$venues = Venue::lists('name', 'id'); $user = Sentry::getUser(); $facilities = Facility::get(); $viewdata= $view->getData(); $venue = Venue::find($viewData['id']); $selectedFacilities = []; foreach($venue->facilities as $facility) { $selectedFacilities[] = $facility->id; } JavaScript::put(array('initVenues' => 1 )); $view->with('venue', $venue)->with('facilities', $facilities)->with('selectedFacilities', $selectedFacilities); } }<file_sep>/app/lang/en/general.php <?php return [ 'title' => 'Everyone exercise', 'meta_description' => 'Lower your barrier to enjoy fitness classes, Flexible schedule and multiple options across London.', 'class' => 'Class|Classes', 'classes' => 'Classes', 'session' => 'Session|Sessions', 'sessions' => 'Sessions', 'venue' => 'Venue|Venues', 'create' => 'Create', 'about' => 'About', 'stay_in_touch' => 'Stay in touch', 'register' => 'Register', 'step_1' => 'Search fitness classes', 'step_2' => 'Sign up to a class online', 'step_3' => 'Show up and shape up!', 'step_4' => 'Rate and review', 'gender' => 'Gender', 'currency_sign' => '&pound;', 'reviews' => 'Reviews', 'participants' => 'Participants', 'clone' => 'Clone', 'delete' => 'Delete', 'details' => 'Details', ];<file_sep>/public/assets/jsdev/prototypes/35-mail-popup.js function MailPopup(link){ this.link = link; this.target = ''; this.form = ''; this.id = ''; this.validIcon = 'glyphicon glyphicon-ok'; this.invalidIcon = 'glyphicon glyphicon-remove'; this.validatingIcon = 'glyphicon glyphicon-refresh'; this.body = { validators: { notEmpty: { message: 'Your message requires content' } } }; this.addListener(); } MailPopup.prototype = { constructor: MailPopup, addListener : function(){ $(document).on('click', '.mail-popup', $.proxy(this.grabPopup, this)); }, grabPopup: function(e){ e.preventDefault(); this.link = $(e.target); this.id = this.link.data('id'); this.target = $(e.target).attr('href'); this.link.addClass('icon-loading'); this.ajaxGet(); }, ajaxGet: function(){ var self = this; $.get( this.target, function(data) { self.link.after(data.view); $('#mail-trainer-'+self.id).modal('show'); var mt = self.link.css('margin-top').replace("px", ""); var mb = self.link.css('margin-bottom').replace("px", ""); var ml = self.link.css('margin-left').replace("px", ""); var mr = self.link.css('margin-right').replace("px", ""); self.link.replaceWith('<a href="#mail-trainer-'+ self.id+'" class="icon icon-mail mt'+mt+' mb'+mb+' mr'+mr+' ml'+ml+' hover" data-toggle="modal" data-target="#mail-trainer-'+ self.id+'"></a>'); self.form = $('#mail-trainer-'+self.id).find('form'); self.validation(); }) .fail(function() { alert( "error" ); }) .always(function() { self.link.removeClass('icon-loading'); }); }, validation: function(){ var self = this; this.form.bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: this.validIcon, invalid: this.invalidIcon, validating: this.validatingIcon }, fields: { mail_body: this.body } }) .on('success.form.bv', function(e) { e.preventDefault(); self.ajaxUpload(); }); }, ajaxUpload : function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).after('<span id="sending-loading" class="icon icon-loading ml10 mt15"></span>'); }, success: function (data) { self.form.find("input[type='submit']").after('<strong id="successfull-mail" class="text-primary">Message sent successfully!</strong><br>'); setTimeout(function(){ $('.modal').modal('hide'); },1500); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { setTimeout(function(){ self.form.find("input[type=submit]").prop('disabled', false); $('#sending-loading').remove(); $('#successfull-mail').remove(); },1500); } }); } }<file_sep>/app/config/packages/abodeo/laravel-stripe/stripe.php <?php return [ 'api_key' => getenv('STRIPE_API_KEY'), 'publishable_key' => getenv('STRIPE_PUB_KEY') ]; <file_sep>/app/models/VenueImages.php <?php class VenueImages extends Eloquent { protected $table = 'venue_images'; protected $fillable = ['venue_id', 'file', 'thumb']; public function venue() { return $this->belongsTo('Venue'); } }<file_sep>/app/models/Gallery.php <?php class Gallery extends Eloquent { protected $table = 'gallery_defaults'; protected $fillable = ['counter', 'keywords', 'image']; protected $hidden = ['created_at', 'updated_at']; public static function selectImage($image_id = 0, $user, $class_name) { $item = static::find($image_id); $item->decrement('counter'); $item->save(); $extension = explode('.', $item->image); $extension = end($extension); $name = slugIt($class_name); $file_name = FALSE; foreach (Config::get('evercise.class_images') as $img) { if (!$file_name) { $file_name = uniqueFile(public_path() . '/' . $user->directory . '/', $img['prefix'] . '_' . $name, $extension); $real_name = str_replace($img['prefix'] . '_', '', $file_name); } $image = Image::make('files/gallery_defaults/' . 'main_' . $item->image)->fit( $img['width'], $img['height'] )->save(public_path() . '/' . $user->directory . '/' . $img['prefix'] . '_' . $real_name); } return $real_name; } }<file_sep>/app/models/Referral.php <?php /** * Class Referral */ class Referral extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'email', 'code', 'referee_id']; /** * @var string */ protected $table = 'referrals'; /** * Check the Referral Code * * @param $rc * @return int */ public static function checkReferralCode($rc) { $referral = 0; if (!is_null($rc)) { $referral = static::where('code', $rc)->where('referee_id', 0)->first(); } return $referral; } /** * User Referral Code * @param $rc * @param $user_id * @return \Illuminate\Database\Eloquent\Model|int|null|static */ public static function useReferralCode($rc, $user_id) { $referral = 0; if (static::checkReferralCode($rc)) { $referral = static::where('code', $rc)->first(); $referral->update(['referee_id' => $user_id]); } return $referral; } public static function validateEmail($inputs) { $validator = Validator::make( $inputs, [ 'referee_email' => 'required|email|unique:users,email', ] ); return $validator; } public static function checkAndStore($user_id, $email, $code) { $message = 'Referral re-sent'; $referral = Referral::where('user_id', $user_id)->where('email', $email)->first(); if(!$referral) { $referral = static::create(['user_id' => $user_id, 'email' => $email, 'code' => $code, 'referee_id' => 0]); $message = 'Referral sent successfully'; } return ['referral' => $referral, 'message' => $message]; } }<file_sep>/app/views/admin/yukonhtml/php/pages/partials/breadcrumbs.php <!-- breadcrumbs --> <nav id="breadcrumbs"> <ul> <li><a href="dashboard.html">Home</a></li><?php if (isset($breadcrumbs)) { echo $breadcrumbs; }; ?> </ul> </nav> <file_sep>/public/assets/jsdev/prototypes/23-rate-it.js function RateIt(block){ this.block = block; this.currentBlock = ''; this.form = ''; this.hoverNth = null; this.selectedNth = null; this.stars = 0; this.emptyClass = 'icon-empty-star'; this.selectedClass = 'icon-full-star'; // validation this.validIcon = 'glyphicon glyphicon-ok'; this.invalidIcon = 'glyphicon glyphicon-remove'; this.validatingIcon = 'glyphicon glyphicon-refresh'; this.feedback_text = { message: 'Your must rate this class out of 5', validators: { notEmpty: { message: 'We need to know your thoughts on this class before you rate it' } } }; this.init(); } RateIt.prototype = { constructor: RateIt, init: function(){ this.block.find("input[type='submit']").prop('disabled', true); this.addListeners(); this.validation(); }, addListeners: function(){ this.block.find('span.icon').not('.selected').hover($.proxy(this.hoverState, this)); this.block.find('span.icon').on('click', $.proxy(this.selectRating, this)); this.block.find('textarea').on('focus', $.proxy(this.focusTextArea, this)); }, hoverState: function(e){ this.currentBlock = $(e.target).closest('.rate-it'); if(e.type == 'mouseenter'){ this.hoverNth = $(e.target).index(); } else{ this.hoverNth = null; } this.changeClassOnHover(); }, changeClassOnHover: function(){ if(this.hoverNth != null){ for( var i =0 ; i <= this.hoverNth ; i++){ this.currentBlock.find('span.icon').eq(i).removeClass(this.emptyClass).addClass(this.selectedClass); } } else{ this.currentBlock.find('span.icon').not('.selected').removeClass(this.selectedClass).addClass(this.emptyClass); } }, selectRating: function(e){ this.currentBlock = $(e.target).closest('.rate-it'); this.currentBlock.find('.alert').remove(); var self = this; setTimeout(function() { self.currentBlock.find('textarea[name="feedback_text"]').focus(); }, 1); this.selectedNth = $(e.target).index(); this.stars = ( this.selectedNth + 1 ); this.currentBlock.find('span.icon').removeClass(this.selectedClass).removeClass('selected').addClass(this.emptyClass); for( var i =0 ; i <= this.selectedNth ; i++){ this.currentBlock.find('span.icon').eq(i).removeClass(this.emptyClass).addClass(this.selectedClass).addClass('selected'); } this.currentBlock.find('input[name="stars"]').val(this.stars); }, focusTextArea: function(e){ this.currentBlock = $(e.target).closest('.rate-it'); this.currentBlock.find('.alert').remove(); if($(e.target).val()){ this.currentBlock.find("input[type='submit']").prop('disabled', false); } }, validation: function(){ var self = this; this.block.find('form').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: this.validIcon, invalid: this.invalidIcon, validating: this.validatingIcon }, fields: { feedback_text: this.feedback_text } }) .on('success.form.bv', function(e) { e.preventDefault(); self.form = $(e.target); self.currentBlock = self.form.closest('.rate-it'); self.currentBlock.find('.alert').remove(); self.ratingCheck(); }); }, ratingCheck: function(){ if( !this.form.find('input[name="stars"]').val() ){ this.currentBlock.find('span.icon').css({ transform: 'rotate(360deg)', WebkitTransition : 'transform 1s ease-in-out', MozTransition : 'transform 1s ease-in-out', MsTransition : 'transform 1s ease-in-out', OTransition : 'transform 1s ease-in-out', transition : 'transform 1s ease-in-out' }); this.form.append('<div class="alert alert-danger alert-dismissible fade in absolute alert-sm" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>You must add your star rating</div>'); } else{ this.ajaxUpload(); } }, ajaxUpload: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).after('<span id="rating-loading" class="icon icon-loading ml10"></span>'); }, success: function (data) { if( data.validation_failed == 1 ){ self.failedValidation(data); } else{ window.location.href = data.url; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type=submit]").prop('disabled', false); $('#rating-loading').remove(); } }); }, failedValidation: function(data){ self = this; var arr = data.errors; $.each(arr, function(index, value) { self.form.find('input[name="' + index+ '"]').parent().addClass('has-error'); self.form.find('input[name="' + index+ '"]').parent().find('.glyphicon').remove(); self.form.find('input[name="' + index + '"]').parent().find('.help-block:visible').remove(); self.form.find('input[name="' + index+ '"]').after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="'+index+'" data-bv-result="INVALID">'+value+'</small>'); }) } }<file_sep>/app/assets/javascripts/dashboard.js //dashboard.js function initDashboardPanel() { $(document).on('click','.dashboard-dropdown-selected' ,function(){ $('.dashboard-dropdown li:not(.selected)').slideToggle(200); } ) $(document).on('click', '.dashboard-tab li', function(){ /*$('li.selected').removeClass('selected'); selected = $(this); var view = selected.data('view'); selected.addClass('selected'); //$('.dashboard-dropdown li:not(.selected)').hide(); $('.dashboard-block').hide(); $('#'+view).show();*/ selectTab({'tab':$(this).data('view')}); }) /*$(document).on('click', '.dashboard-dropdown li:not(.selected)', function(){ $('li.selected').removeClass('selected'); selected = $(this); var clone = selected.clone(); var view = selected.data('view'); clone.addClass('selected'); $('.dashboard-dropdown-selected').html(clone); $('.dashboard-dropdown li:not(.selected)').hide(0); $('.dashboard-block').hide(); $('#'+view).show(); selectTab({'tab':$(this).data('view')}); })*/ $('.mail_trainer').click(function(){ var url = this.href; $.ajax({ url: url, type: 'GET', dataType: 'html' }) .done( function(data) { //trace('id: '+ data); $('.mask').show(); $('.container').append(data); initPut(); } ); return false; }); $('.btn-leave-session , .refund').click(function(){ var url = $(this).attr('href'); trace(url); $.ajax({ url: url, type: 'GET', dataType: 'html' }) .done( function(data) { trace(data); $('.mask').show(); $('.container').append(data); initPut(); } ); return false; }); /*$('#withdrawalform').on( 'submit', function() { var url = $(this).attr('action'); trace('URL: '+url); $.ajax({ url: url, type: 'GET', data: $( this ).serialize(), dataType: 'html' }) .done( function(data) { trace('data: '+ data); $('.mask').show(); $('.container').append(data); initPut(); } ); return false; });*/ } registerInitFunction('initDashboardPanel'); registerInitFunction('updateCountryCode'); function updateCountryCode() { $('.country_code').each(function(){ var val = $(this).closest('div').find('.areacode').val(); $(this).html(val); }) $('.areacode').on('change', function () { $(this).closest('div').find('.country_code').html($(this).val()); updateCountryCode(); }); } function openPopup(data) { trace(data.popup, true); $('.mask').show(); $('.container').append(data.popup); initPut(); } function openConfirmPopup(data) { trace(data.popup, true); $('.modal').remove(); $('.mask').show(); $('.container').append(data.popup); $('.close, .cancel').click(function(){ $('.mask').hide(); $('.modal').remove(); trace(data.url); gotoUrl(data); }); } function mailSent() { trace('mail sent'); $('.mask').hide(); $('.login_wrap, .modal').remove(); } function leftSession(data) { trace('left session : '+(data.message)); //$('.mask').hide(); //$('.login_wrap, .modal').remove(); setTimeout(function() { window.location.href = ''; }, 1000); } function selectTab(params) { defaultTab = $('.dashboard-tab li:first').data('view'); selected = $('*[data-view="'+params.tab+'"]'); selected = selected.length ? selected : $('*[data-view="'+defaultTab+'"]'); //trace("selectTab: "+selected.data('view')); var view = selected.data('view'); $('li.selected').removeClass('selected'); selected.addClass('selected'); $('.dashboard-block').hide(); $('#'+view).show(); } registerInitFunction('selectTab'); function confirmWithdrawal(data) { trace("withdrawal successful : "+data.amount); } <file_sep>/app/composers/GroupSetComposer.php <?php namespace composers; use Sentry; class GroupSetComposer { public function compose($view) { $trainerGroup = Sentry::findGroupByName('trainer'); $adminGroup = Sentry::findGroupByName('admin'); $view->with('adminGroup', $adminGroup) ->with('trainerGroup', $trainerGroup); } }<file_sep>/app/views/admin/yukonhtml/php/variables.php <?php require_once 'php/faker/autoload.php'; $faker = Faker\Factory::create(); $admin_version = '1.1'; function dateRange( $first, $last, $step = '+1 day', $format = 'D d.m.Y' ) { $dates = array(); $current = strtotime( $first ); $last = strtotime( $last ); while( $current <= $last ) { $dates[] = date( $format, $current ); $current = strtotime( $step, $current ); } return $dates; } $tags = array( 'advertising', 'ajax', 'business', 'company', 'creative', 'css', 'design', 'designer', 'developer', 'e-commerce', 'finance', 'graphic', 'home', 'internet', 'javascript', 'marketing', 'mysql', 'online', 'photoshop', 'service', 'software', 'webdesign', 'website' ); $sPage = $_GET['page']; if( !isset($sPage) ) $sPage = 'dashboard'; if($sPage == "dashboard") { $includePage = 'php/pages/dashboard.php'; $script = ' <!-- c3 charts --> <script src="assets/lib/d3/d3.min.js"></script> <script src="assets/lib/c3/c3.min.js"></script> <!-- vector maps --> <script src="assets/lib/jvectormap/jquery-jvectormap-1.2.2.min.js"></script> <script src="assets/lib/jvectormap/maps/jquery-jvectormap-world-mill-en.js"></script> <!-- countUp animation --> <script src="assets/js/countUp.min.js"></script> <!-- switchery --> <script src="assets/lib/switchery/dist/switchery.min.js"></script> <!-- easePie chart --> <script src="assets/lib/easy-pie-chart/dist/jquery.easypiechart.min.js"></script> <script> $(function() { // c3 charts yukon_charts.p_dashboard(); // countMeUp yukon_count_up.init(); // easy pie chart yukon_easyPie_chart.p_dashboard(); // vector maps yukon_vector_maps.p_dashboard(); // switchery yukon_switchery.init(); }) </script> '; } if($sPage == "forms-regular_elements") { $includePage = 'php/pages/forms-regular_elements.php'; $breadcrumbs = '<li><span>Forms</span></li><li><span>Regular Elements</span></li>'; } if($sPage == "forms-extended_elements") { $includePage = 'php/pages/forms-extended_elements.php'; $breadcrumbs = ' <li><span>Forms</span></li> <li><span>Extended Elements</span></li> '; $css = ' <!-- select2 --> <link href="assets/lib/select2/select2.css" rel="stylesheet" media="screen"> <!-- datepicker --> <link href="assets/lib/bootstrap-datepicker/css/datepicker3.css" rel="stylesheet" media="screen"> <!-- date range picker --> <link href="assets/lib/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" media="screen"> <!-- rangeSlider --> <link href="assets/lib/ion.rangeSlider/css/ion.rangeSlider.css" rel="stylesheet" media="screen"> <link href="assets/lib/ion.rangeSlider/css/ion.rangeSlider.skinFlat.css" rel="stylesheet" media="screen"> <!-- uplaoder --> <link href="assets/lib/plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css" rel="stylesheet" media="screen"> '; $script = ' <!-- select2 --> <script src="assets/lib/select2/select2.min.js"></script> <!-- datepicker --> <script src="assets/lib/bootstrap-datepicker/js/bootstrap-datepicker.js"></script> <!-- date range picker --> <script src="assets/lib/bootstrap-daterangepicker/daterangepicker.js"></script> <!-- rangeSlider --> <script src="assets/lib/ion.rangeSlider/js/ion-rangeSlider/ion.rangeSlider.min.js"></script> <!-- switchery --> <script src="assets/lib/switchery/dist/switchery.min.js"></script> <!-- autosize --> <script src="assets/lib/autosize/jquery.autosize.min.js"></script> <!-- inputmask --> <script src="assets/lib/jquery.inputmask/jquery.inputmask.bundle.min.js"></script> <!-- maxlength for textareas --> <script src="assets/lib/stopVerbosity/stopVerbosity.min.js"></script> <!-- uplaoder --> <script src="assets/lib/plupload/js/plupload.full.min.js"></script> <script src="assets/lib/plupload/js/jquery.plupload.queue/jquery.plupload.queue.min.js"></script> <!-- wysiwg editor --> <script src="assets/lib/ckeditor/ckeditor.js"></script> <script src="assets/lib/ckeditor/adapters/jquery.js"></script> <script> $(function() { // select2 yukon_select2.p_forms_extended(); // datepicker yukon_datepicker.p_forms_extended(); // date range picker yukon_date_range_picker.p_forms_extended(); // rangeSlider yukon_rangeSlider.p_forms_extended(); // switchery yukon_switchery.init(); // textarea autosize yukon_textarea_autosize.init(); // masked inputs yukon_maskedInputs.p_forms_extended(); // maxlength for textareas yukon_textarea_maxlength.p_forms_extended(); // multiuploader yukon_uploader.p_forms_extended(); // wysiwg editor yukon_wysiwg.p_forms_extended_elements(); }) </script> '; } if($sPage == "forms-gridforms") { $includePage = 'php/pages/forms-gridforms.php'; $breadcrumbs = ' <li><span>Forms</span></li> <li><span>Gridforms</span></li> '; $css = ' <!-- gridforms --> <link href="assets/lib/gridforms/gf-forms.min.css" rel="stylesheet" media="screen"> '; $script = ' <!-- gridforms --> <script src="assets/lib/gridforms/gf-forms.min.js"></script> '; } if($sPage == "forms-validation") { $includePage = 'php/pages/forms-validation.php'; $breadcrumbs = ' <li><span>Forms</span></li> <li><span>Validation</span></li> '; $css = ' <!-- select2 --> <link href="assets/lib/select2/select2.css" rel="stylesheet" media="screen"> '; $script = ' <!-- select2 --> <script src="assets/lib/select2/select2.min.js"></script> <!-- validation (parsley.js) --> <script src="assets/js/parsley.config.js"></script> <script src="assets/lib/parsley/dist/parsley.min.js"></script> <!-- wysiwg editor --> <script src="assets/lib/ckeditor/ckeditor.js"></script> <script src="assets/lib/ckeditor/adapters/jquery.js"></script> <script> $(function() { // wysiwg editor yukon_wysiwg.p_forms_validation(); // multiselect yukon_select2.p_forms_validation(); // validation yukon_parsley_validation.p_forms_validation(); }) </script> '; } if($sPage == "forms-wizard") { $includePage = 'php/pages/forms-wizard.php'; $breadcrumbs = ' <li><span>Forms</span></li> <li><span>Wizard</span></li> '; $css = ' <!-- select2 --> <link href="assets/lib/select2/select2.css" rel="stylesheet" media="screen"> <!-- prism highlight --> <link href="assets/lib/prism/prism_default.css" rel="stylesheet" media="screen"> <link href="assets/lib/prism/line_numbers.css" rel="stylesheet" media="screen"> '; $script = ' <!-- select2 --> <script src="assets/lib/select2/select2.min.js"></script> <!-- prism highlight --> <script src="assets/lib/prism/prism.min.js"></script> <!-- jquery steps --> <script src="assets/js/jquery.steps.custom.min.js"></script> <!-- validation (parsley.js) --> <script src="assets/js/parsley.config.js"></script> <script src="assets/lib/parsley/dist/parsley.min.js"></script> <script> $(function() { // wizard yukon_steps.init(); // select2 country,languages yukon_select2.p_forms_wizard(); // form validation yukon_parsley_validation.p_forms_wizard(); }) </script> '; } if($sPage == "pages-chat") { $includePage = 'php/pages/pages-chat.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>Chat</span></li> '; $script = ' <script> $(function() { // chat yukon_chat.init(); }) </script> '; } if($sPage == "pages-help_faq") { $includePage = 'php/pages/pages-help_faq.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>Help/Faq</span></li> '; } if($sPage == "pages-invoices") { $includePage = 'php/pages/pages-invoices.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>Invoices</span></li> '; $script = ' <!-- qrcode --> <script src="assets/lib/jquery-qrcode-0.10.1/jquery.qrcode-0.10.1.min"></script> <script> $(function() { // qrcode yukon_qrcode.p_pages_invoices(); }) </script> '; } if($sPage == "pages-mailbox") { $includePage = 'php/pages/pages-mailbox.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>Mailbox</span></li> '; $css = ' <!-- footable --> <link href="assets/lib/footable/css/footable.core.min.css" rel="stylesheet" media="screen"> '; $script = ' <!-- footable --> <script src="assets/lib/footable/footable.min.js"></script> <script src="assets/lib/footable/footable.paginate.min.js"></script> <script src="assets/lib/footable/footable.filter.min.js"></script> <script> $(function() { // footable yukon_footable.p_pages_mailbox(); yukon_mailbox.init(); }) </script> '; } if($sPage == "pages-mailbox_message") { $includePage = 'php/pages/pages-mailbox_message.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><a href="pages-mailbox.html">Mailbox</a></li> <li><span>Details</span></li> '; } if($sPage == "pages-search_page") { $includePage = 'php/pages/pages-search_page.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>Search Page</span></li> '; } if($sPage == "pages-user_list") { $includePage = 'php/pages/pages-user_list.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>User List</span></li> '; $script = ' <!-- iOS list --> <script src="assets/lib/jquery-listnav/dist/js/jquery-listnav-2.4.0.min.js"></script> <script> $(function() { // count users yukon_user_list.init(); // iOS list yukon_listNav.p_pages_user_list(); }) </script> '; } if($sPage == "pages-user_profile") { $includePage = 'php/pages/pages-user_profile.php'; $breadcrumbs = ' <li><span>Pages</span></li> <li><span>User Profile</span></li> '; $script = ' <!-- easePie chart --> <script src="assets/lib/easy-pie-chart/dist/jquery.easypiechart.min.js"></script> <script> $(function() { // easePie chart yukon_easyPie_chart.p_pages_user_profile(); }) </script> '; } if($sPage == "components-bootstrap") { $includePage = 'php/pages/components-bootstrap.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Bootstrap Framework</span></li> '; } if($sPage == "components-gallery") { $includePage = 'php/pages/components-gallery.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Gallery</span></li> '; $css = ' <!-- magnific --> <link href="assets/lib/magnific-popup/magnific-popup.css" rel="stylesheet" media="screen"> '; $script = ' <!-- magnific --> <script src="assets/lib/magnific-popup/jquery.magnific-popup.min.js"></script> <script> $(function() { // gallery filter yukon_gallery.search_gallery(); // magnific lightbox yukon_magnific.p_components_gallery(); }) </script> '; } if($sPage == "components-grid") { $includePage = 'php/pages/components-grid.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Grid</span></li> '; } if($sPage == "components-icons") { $includePage = 'php/pages/components-icons.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Icons</span></li> '; $script = ' <script> $(function() { // icon filter yukon_icons.search_icons(); }) </script> '; } if($sPage == "components-notifications_popups") { $includePage = 'php/pages/components-notifications_popups.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Notifications/Popups</span></li> '; $css = ' <!-- jBox --> <link href="assets/lib/jBox-0.3.0/Source/jBox.css" rel="stylesheet" media="screen"> <link href="assets/lib/jBox-0.3.0/Source/themes/NoticeBorder.css" rel="stylesheet" media="screen"> '; $script = ' <!-- jBox --> <script src="assets/lib/jBox-0.3.0/Source/jBox.min.js"></script> <script> $(function() { // jBox yukon_jBox.p_components_notifications_popups(); }) </script> '; } if($sPage == "components-typography") { $includePage = 'php/pages/components-typography.php'; $breadcrumbs = ' <li><span>Components</span></li> <li><span>Typography</span></li> '; } if($sPage == "plugins-calendar") { $includePage = 'php/pages/plugins-calendar.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Calendar</span></li> '; $css = ' <!-- full calendar --> <link href="assets/lib/fullcalendar/fullcalendar.css" rel="stylesheet" media="screen"> '; $script = ' <!-- jquery UI --> <script src="assets/lib/fullcalendar/lib/jquery-ui.custom.min.js"></script> <!-- full calendar --> <script src="assets/lib/fullcalendar/fullcalendar.min.js"></script> <script src="assets/lib/fullcalendar/gcal.js"></script> <script> $(function() { // full calendar yukon_fullCalendar.p_plugins_calendar(); }) </script> '; } if($sPage == "plugins-charts") { $includePage = 'php/pages/plugins-charts.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Charts</span></li> '; $script = ' <!-- c3 charts --> <script src="assets/lib/d3/d3.min.js"></script> <script src="assets/lib/c3/c3.min.js"></script> <script> $(function() { // c3 charts yukon_charts.p_plugins_charts(); }) </script> '; } if($sPage == "plugins-google_maps") { $includePage = 'php/pages/plugins-google_maps.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Google Maps</span></li> '; $script = ' <!-- gmaps --> <script src="assets/lib/gmaps/gmaps.js"></script> <script> $(function() { // gmaps yukon_gmaps.init(); }) </script> '; } if($sPage == "plugins-tables_footable") { $includePage = 'php/pages/plugins-tables_footable.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Tables</span></li> <li><span>Footable</span></li> '; $css = ' <!-- footable --> <link href="assets/lib/footable/css/footable.core.min.css" rel="stylesheet" media="screen"> '; $script = ' <!-- footable --> <script src="assets/lib/footable/footable.min.js"></script> <script src="assets/lib/footable/footable.paginate.min.js"></script> <script src="assets/lib/footable/footable.filter.min.js"></script> <script> $(function() { // footable yukon_footable.p_plugins_tables_footable(); }) </script> '; } if($sPage == "plugins-tables_datatable") { $includePage = 'php/pages/plugins-tables_datatable.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Tables</span></li> <li><span>Datatable</span></li> '; $script = ' <!-- datatable --> <script src="assets/lib/DataTables/media/js/jquery.dataTables.min.js"></script> <script src="assets/lib/DataTables/extensions/FixedHeader/js/dataTables.fixedHeader.min.js"></script> <script src="assets/lib/DataTables/media/js/dataTables.bootstrap.js"></script> <script> $(function() { // footable yukon_datatables.p_plugins_tables_datatable(); }) </script> '; } if($sPage == "plugins-vector_maps") { $includePage = 'php/pages/plugins-vector_maps.php'; $breadcrumbs = ' <li><span>Plugins</span></li> <li><span>Vector Maps</span></li> '; $script = ' <!-- vector maps --> <script src="assets/lib/jvectormap/jquery-jvectormap-1.2.2.min.js"></script> <script src="assets/lib/jvectormap/maps/jquery-jvectormap-world-mill-en.js"></script> <script src="assets/lib/jvectormap/maps/jquery-jvectormap-ca-mill-en.js"></script> <script> $(function() { // vector maps yukon_vector_maps.p_plugins_vector_maps(); }) </script> '; }<file_sep>/app/config/cronjob.php <?php /** * Simple Cronjob Config File. * Manage all cronjobs from here * * * * * * * * * - - - - - - * | | | | | | * | | | | | + year [optional] * | | | | +----- day of week (0 - 7) (Sunday=0 or 7) * | | | +---------- month (1 - 12) * | | +--------------- day of month (1 - 31) * | +-------------------- hour (0 - 23) * +------------------------- min (0 - 59) * * */ return [ 'active' => getenv('CRON_ACTIVE') ?: TRUE, 'lock_limit' => 300, 'jobs' => [ 'ReminderForPayments' => '10 9 * 1 *', 'SendReminderEmailsCron' => '15 * * * *', 'SendExtraEmailsCron' => '15 7 * * *', 'DailyIndexer' => '*/15 * * * *', 'CheckPayments' => '30 5 * * *', 'GenerateSalesforceSessionIds' => '*/5 * * * *', ] ];<file_sep>/docs/evercise_2_0 (18-06-2014).sql -- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 18, 2014 at 04:19 PM -- Server version: 5.6.12-log -- PHP Version: 5.4.12 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 */; -- -- Database: `evercise_2_0` -- CREATE DATABASE IF NOT EXISTS `evercise_2_0` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `evercise_2_0`; -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `name`, `description`, `created_at`, `updated_at`) VALUES (1, 'Workout', 'Do you want to be physically challenged? Is your goal to tone up, gain muscle, lose weight or combat stress? Choose a workout, either indoors or outdoors, with a qualified instructor who can offer you great advice on your training regime.', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'Sports', 'Do you want to be coached in a competitive sport involving teams, giving you a chance to meet and bond with new people? (or you can sign up with a group of people you know!) Work together to get fit, learn a skill and have great fun while youre at it!', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'Healthy Living', 'Do you want to learn about nutritional, physical, emotional and spiritual practices and how to balance these factors in order to achieve a healthy lifestyle? Find therapists, practitioners, dieticians and trainers to help you strike the balance!', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (4, 'Nutrition', 'Find nutritional specialists who will help you learn what, how and when to eat in order to boost your energy levels and achieve maximum health and fitness. Get nutritional advice from the experts and learn healthy recipes.', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (5, 'Injury Recovery', 'Is your goal to recover from an injury? Would you benefit from physiotherapy, or would you like to learn exercise techniques to overcome damage to the body, and the safest ways to exercise without aggravating an injury? Find specialists who offer expert t', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `evercisegroups` -- CREATE TABLE IF NOT EXISTS `evercisegroups` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `venue_id` int(10) unsigned NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `town` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `postcode` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `lat` decimal(10,8) NOT NULL, `lng` decimal(11,8) NOT NULL, `image` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `capacity` int(11) NOT NULL, `default_duration` int(11) NOT NULL, `default_price` decimal(6,2) NOT NULL DEFAULT '0.00', `published` tinyint(4) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercisegroups_user_id_foreign` (`user_id`), KEY `evercisegroups_category_id_foreign` (`category_id`), KEY `evercisegroups_venue_id_foreign` (`venue_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ; -- -- Dumping data for table `evercisegroups` -- INSERT INTO `evercisegroups` (`id`, `user_id`, `category_id`, `venue_id`, `name`, `title`, `description`, `address`, `town`, `postcode`, `lat`, `lng`, `image`, `capacity`, `default_duration`, `default_price`, `published`, `created_at`, `updated_at`) VALUES (1, 2, 4, 2, 'Zool Class', '', 'Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool Learn to play Zool', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403018955_zool.png', 13, 35, '7.50', 0, '2014-06-17 14:30:53', '2014-06-17 14:30:53'), (2, 2, 2, 3, 'Ducktales', '', 'Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo Ducktales woo-oo-oo ', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403019080_Duck_Tales_Art.png', 15, 35, '24.00', 0, '2014-06-17 14:33:39', '2014-06-17 14:33:39'), (3, 2, 3, 4, 'Adventure time', '', 'Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. Adventure time, go grab your friends. ', NULL, NULL, NULL, '0.00000000', '0.00000000', '1403019250_adventure_time.jpg', 97, 80, '11.50', 0, '2014-06-17 14:35:14', '2014-06-17 14:35:14'); -- -------------------------------------------------------- -- -- Table structure for table `evercisesessions` -- CREATE TABLE IF NOT EXISTS `evercisesessions` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `evercisegroup_id` int(10) unsigned NOT NULL, `date_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `members` int(11) NOT NULL DEFAULT '0', `price` decimal(6,2) NOT NULL DEFAULT '0.00', `duration` int(11) NOT NULL, `members_emailed` tinyint(1) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercisesessions_evercisegroup_id_foreign` (`evercisegroup_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=19 ; -- -- Dumping data for table `evercisesessions` -- INSERT INTO `evercisesessions` (`id`, `evercisegroup_id`, `date_time`, `members`, `price`, `duration`, `members_emailed`, `created_at`, `updated_at`) VALUES (1, 3, '2014-06-18 11:00:01', 0, '11.50', 80, 0, '2014-06-17 14:35:25', '2014-06-17 14:35:25'), (2, 3, '2014-06-19 16:00:00', 0, '11.50', 80, 0, '2014-06-17 14:35:35', '2014-06-17 14:35:35'), (3, 3, '2014-06-26 11:00:00', 0, '11.50', 80, 0, '2014-06-17 14:35:42', '2014-06-17 14:35:42'), (4, 3, '2014-07-26 11:00:00', 0, '67.50', 90, 0, '2014-06-17 14:35:52', '2014-06-17 14:35:52'), (5, 3, '2014-08-25 11:00:00', 0, '33.50', 50, 0, '2014-06-17 14:36:03', '2014-06-17 14:36:03'), (6, 3, '2014-05-23 11:00:00', 0, '11.50', 80, 0, '2014-06-17 14:36:13', '2014-06-17 14:36:13'), (7, 1, '2014-06-19 11:00:00', 0, '7.50', 35, 0, '2014-06-17 14:36:20', '2014-06-17 14:36:20'), (10, 1, '2014-07-19 11:00:00', 0, '7.50', 35, 0, '2014-06-17 14:37:01', '2014-06-17 14:37:01'), (11, 2, '2014-06-18 18:00:00', 0, '24.00', 35, 0, '2014-06-17 14:37:13', '2014-06-17 14:37:13'), (12, 2, '2014-04-03 16:00:00', 0, '55.50', 35, 0, '2014-06-17 14:37:24', '2014-06-17 14:37:24'), (13, 2, '2014-08-09 11:00:00', 0, '24.00', 35, 0, '2014-06-17 14:37:33', '2014-06-17 14:37:33'), (14, 1, '2014-03-07 12:03:03', 0, '7.50', 35, 0, '2014-06-17 14:37:39', '2014-06-17 14:37:39'), (15, 2, '2014-08-25 11:00:00', 0, '24.00', 35, 0, '2014-06-17 14:37:49', '2014-06-17 14:37:49'), (16, 1, '2014-08-06 11:00:00', 0, '7.50', 35, 0, '2014-06-18 13:52:36', '2014-06-18 13:52:36'), (18, 1, '2014-07-18 11:00:00', 0, '7.50', 35, 0, '2014-06-18 13:52:49', '2014-06-18 13:52:49'); -- -------------------------------------------------------- -- -- Table structure for table `facilities` -- CREATE TABLE IF NOT EXISTS `facilities` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `category` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; -- -- Dumping data for table `facilities` -- INSERT INTO `facilities` (`id`, `name`, `category`, `image`, `created_at`, `updated_at`) VALUES (1, 'Rowing Machine', 'facility', 'rowing.png', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'Toilets', 'Amenity', 'toilets', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'Car Park', 'Amenity', 'carpark', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (4, 'Hall', 'facility', 'hall', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `featuredgymgroups` -- CREATE TABLE IF NOT EXISTS `featuredgymgroups` ( `user_id` int(10) unsigned NOT NULL, `evercisegroup_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `featuredgymgroups_user_id_foreign` (`user_id`), KEY `featuredgymgroups_evercisegroup_id_foreign` (`evercisegroup_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `groups` -- CREATE TABLE IF NOT EXISTS `groups` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `permissions` text COLLATE utf8_unicode_ci, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `groups_name_unique` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; -- -- Dumping data for table `groups` -- INSERT INTO `groups` (`id`, `name`, `permissions`, `created_at`, `updated_at`) VALUES (1, 'User', '{"user":1}', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'Facebook', '{"facebook":1}', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'Trainer', '{"trainer":1}', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (4, 'Admin', '{"admin":1}', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `gyms` -- CREATE TABLE IF NOT EXISTS `gyms` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `directory` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `logo_image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `background_image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `gyms_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ; -- -- Dumping data for table `gyms` -- INSERT INTO `gyms` (`id`, `user_id`, `name`, `title`, `description`, `directory`, `logo_image`, `background_image`, `created_at`, `updated_at`) VALUES (1, 1, 'Evercise', 'Evercise Gym', 'Its super cool', '', '', '', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `gym_has_trainers` -- CREATE TABLE IF NOT EXISTS `gym_has_trainers` ( `status` tinyint(4) NOT NULL, `user_id` int(10) unsigned NOT NULL, `gym_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `gym_has_trainers_user_id_foreign` (`user_id`), KEY `gym_has_trainers_gym_id_foreign` (`gym_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `historytypes` -- CREATE TABLE IF NOT EXISTS `historytypes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ; -- -- Dumping data for table `historytypes` -- INSERT INTO `historytypes` (`id`, `name`, `description`, `created_at`, `updated_at`) VALUES (1, 'created_class', 'a new evercisegroup has been created by a trainer', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'added_session', 'a trainer has added a new session to evercisegroup', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'deleted_group', 'a trainer has deleted an evercisegroup / class', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (4, 'deleted_session', 'a trainer has deleted a session', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (5, 'joined_group', 'a user joined an evercisegroup / class', '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (6, 'rated_session', 'a user has left a rating for a session', '0000-00-00 00:00:00', '0000-00-00 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `marketingpreferences` -- CREATE TABLE IF NOT EXISTS `marketingpreferences` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `option` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ; -- -- Dumping data for table `marketingpreferences` -- INSERT INTO `marketingpreferences` (`id`, `name`, `option`, `created_at`, `updated_at`) VALUES (1, 'newsletter', 'yes', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'newsletter', 'no', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE IF NOT EXISTS `migrations` ( `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`migration`, `batch`) VALUES ('2014_04_10_131418_create_ratings_table', 1), ('2012_12_06_225921_migration_cartalyst_sentry_install_users', 2), ('2012_12_06_225929_migration_cartalyst_sentry_install_groups', 2), ('2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot', 2), ('2012_12_06_225988_migration_cartalyst_sentry_install_throttle', 2), ('2014_04_10_132455_create_users_table', 1), ('2014_04_10_133144_create_sessions_table', 1), ('2014_04_10_133231_create_gyms_table', 1), ('2014_04_28_162518_create_trainers_table', 1), ('2014_04_29_102623_create_evercisegroups_table', 1), ('2014_04_29_115814_create_trainerhistory_table', 1), ('2014_04_29_115921_create_categories_table', 1), ('2014_04_29_120027_create_user_has_categories_table', 1), ('2014_04_29_120131_create_user_has_marketingpreferences_table', 1), ('2014_04_29_120250_create_marketingpreferences_table', 1), ('2014_04_29_120401_create_sessionmembers_table', 1), ('2014_04_29_123525_create_featuredgymgroup_table', 1), ('2014_04_29_123635_create_specialities_table', 1), ('2014_05_02_104031_create_gym_has_trainers_table', 1), ('2014_06_10_103106_create_venues_table', 1), ('2014_06_10_104152_create_facilities_table', 1), ('2014_06_10_104338_create_venue_facilities_table', 1), ('2014_06_16_112856_create_historytypes_table', 1), ('2014_06_16_112956_create_foreign_keys', 1); -- -------------------------------------------------------- -- -- Table structure for table `ratings` -- CREATE TABLE IF NOT EXISTS `ratings` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `sessionmember_id` int(10) unsigned NOT NULL, `session_id` int(10) unsigned NOT NULL, `evercisegroup_id` int(10) unsigned NOT NULL, `user_created_id` int(10) unsigned NOT NULL, `stars` tinyint(4) NOT NULL, `comment` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `ratings_user_id_foreign` (`user_id`), KEY `ratings_sessionmember_id_foreign` (`sessionmember_id`), KEY `ratings_session_id_foreign` (`session_id`), KEY `ratings_evercisegroup_id_foreign` (`evercisegroup_id`), KEY `ratings_user_created_id_foreign` (`user_created_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=18 ; -- -- Dumping data for table `ratings` -- INSERT INTO `ratings` (`id`, `user_id`, `sessionmember_id`, `session_id`, `evercisegroup_id`, `user_created_id`, `stars`, `comment`, `created_at`, `updated_at`) VALUES (7, 2, 10, 12, 2, 4, 2, 'It was pretty exciting', '2014-06-17 15:29:27', '2014-06-17 15:29:27'), (16, 1, 7, 14, 1, 4, 5, 'asdfs', '2014-06-18 10:18:13', '2014-06-18 10:18:13'); -- -------------------------------------------------------- -- -- Table structure for table `sessionmembers` -- CREATE TABLE IF NOT EXISTS `sessionmembers` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `evercisesession_id` int(10) unsigned NOT NULL, `price` decimal(6,2) NOT NULL DEFAULT '0.00', `reviewed` tinyint(1) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `sessionmembers_user_id_foreign` (`user_id`), KEY `sessionmembers_evercisesession_id_foreign` (`evercisesession_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=20 ; -- -- Dumping data for table `sessionmembers` -- INSERT INTO `sessionmembers` (`id`, `user_id`, `evercisesession_id`, `price`, `reviewed`, `created_at`, `updated_at`) VALUES (6, 3, 6, '0.00', 0, '2014-06-17 14:50:50', '2014-06-17 14:50:50'), (7, 4, 14, '0.00', 0, '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (8, 4, 10, '0.00', 0, '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (9, 4, 11, '0.00', 0, '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (10, 4, 12, '0.00', 0, '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (11, 5, 15, '0.00', 0, '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (12, 5, 12, '0.00', 0, '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (13, 5, 1, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (14, 5, 2, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (15, 5, 3, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (16, 5, 6, '0.00', 0, '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (17, 4, 6, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (18, 4, 4, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (19, 4, 3, '0.00', 0, '2014-06-17 15:14:16', '2014-06-17 15:14:16'); -- -------------------------------------------------------- -- -- Table structure for table `specialities` -- CREATE TABLE IF NOT EXISTS `specialities` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `titles` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ; -- -- Dumping data for table `specialities` -- INSERT INTO `specialities` (`id`, `name`, `titles`, `created_at`, `updated_at`) VALUES (1, 'kickboxing', 'coach', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 'kickboxing', 'trainer', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (3, 'yoga', 'guy', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (4, 'yoga', 'girl', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (5, 'yoga', 'trainer', '2014-06-17 14:20:21', '2014-06-17 14:20:21'); -- -------------------------------------------------------- -- -- Table structure for table `throttle` -- CREATE TABLE IF NOT EXISTS `throttle` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned DEFAULT NULL, `ip_address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `attempts` int(11) NOT NULL DEFAULT '0', `suspended` tinyint(1) NOT NULL DEFAULT '0', `banned` tinyint(1) NOT NULL DEFAULT '0', `last_attempt_at` timestamp NULL DEFAULT NULL, `suspended_at` timestamp NULL DEFAULT NULL, `banned_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `throttle_user_id_index` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; -- -- Dumping data for table `throttle` -- INSERT INTO `throttle` (`id`, `user_id`, `ip_address`, `attempts`, `suspended`, `banned`, `last_attempt_at`, `suspended_at`, `banned_at`) VALUES (1, 2, NULL, 0, 0, 0, NULL, NULL, NULL), (2, 3, '::1', 0, 0, 0, NULL, NULL, NULL), (3, 4, '::1', 0, 0, 0, NULL, NULL, NULL), (4, 5, '::1', 0, 0, 0, NULL, NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `trainerhistory` -- CREATE TABLE IF NOT EXISTS `trainerhistory` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `historytype_id` int(10) unsigned NOT NULL, `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `trainerhistory_user_id_foreign` (`user_id`), KEY `trainerhistory_historytype_id_foreign` (`historytype_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=48 ; -- -- Dumping data for table `trainerhistory` -- INSERT INTO `trainerhistory` (`id`, `user_id`, `historytype_id`, `message`, `created_at`, `updated_at`) VALUES (1, 2, 1, 'Tristan_Allen created Class Zool Class', '2014-06-17 14:30:53', '2014-06-17 14:30:53'), (2, 2, 1, 'Tristan_Allen created Class Ducktales', '2014-06-17 14:33:39', '2014-06-17 14:33:39'), (3, 2, 1, 'Tristan_Allen created Class Adventure time', '2014-06-17 14:35:14', '2014-06-17 14:35:14'), (4, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 18th June 2014', '2014-06-17 14:35:25', '2014-06-17 14:35:25'), (5, 2, 2, 'Tristan_Allen added a new date to Adventure time at 05:00pm on the 19th June 2014', '2014-06-17 14:35:35', '2014-06-17 14:35:35'), (6, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 14:35:42', '2014-06-17 14:35:42'), (7, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 26th July 2014', '2014-06-17 14:35:52', '2014-06-17 14:35:52'), (8, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 25th August 2014', '2014-06-17 14:36:03', '2014-06-17 14:36:03'), (9, 2, 2, 'Tristan_Allen added a new date to Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:36:13', '2014-06-17 14:36:13'), (10, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 19th June 2014', '2014-06-17 14:36:20', '2014-06-17 14:36:20'), (11, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 18th July 2014', '2014-06-17 14:36:28', '2014-06-17 14:36:28'), (12, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 06th August 2014', '2014-06-17 14:36:37', '2014-06-17 14:36:37'), (13, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 19th July 2014', '2014-06-17 14:37:01', '2014-06-17 14:37:01'), (14, 2, 2, 'Tristan_Allen added a new date to Ducktales at 07:00pm on the 18th June 2014', '2014-06-17 14:37:13', '2014-06-17 14:37:13'), (15, 2, 2, 'Tristan_Allen added a new date to Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:37:24', '2014-06-17 14:37:24'), (16, 2, 2, 'Tristan_Allen added a new date to Ducktales at 12:00pm on the 09th August 2014', '2014-06-17 14:37:33', '2014-06-17 14:37:33'), (17, 2, 2, 'Tristan_Allen added a new date to Zool Class at 12:00pm on the 05th July 2014', '2014-06-17 14:37:39', '2014-06-17 14:37:39'), (18, 2, 2, 'Tristan_Allen added a new date to Ducktales at 12:00pm on the 25th August 2014', '2014-06-17 14:37:49', '2014-06-17 14:37:49'), (22, 2, 5, 'red ranger has joined Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:50:50', '2014-06-17 14:50:50'), (23, 2, 5, 'yellow ranger has joined Zool Class at 12:00pm on the 05th July 2014', '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (24, 2, 5, 'yellow ranger has joined Zool Class at 12:00pm on the 19th July 2014', '2014-06-17 14:51:51', '2014-06-17 14:51:51'), (25, 2, 5, 'yellow ranger has joined Ducktales at 07:00pm on the 18th June 2014', '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (26, 2, 5, 'yellow ranger has joined Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:52:23', '2014-06-17 14:52:23'), (27, 2, 5, 'green ranger has joined Ducktales at 05:00pm on the 03rd July 2014', '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (28, 2, 5, 'green ranger has joined Ducktales at 12:00pm on the 25th August 2014', '2014-06-17 14:56:45', '2014-06-17 14:56:45'), (29, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 18th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (30, 2, 5, 'green ranger has joined Adventure time at 05:00pm on the 19th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (31, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (32, 2, 5, 'green ranger has joined Adventure time at 12:00pm on the 23rd October 2014', '2014-06-17 14:57:10', '2014-06-17 14:57:10'), (33, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 23rd May 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (34, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 26th June 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (35, 2, 5, 'yellow ranger has joined Adventure time at 12:00pm on the 26th July 2014', '2014-06-17 15:14:16', '2014-06-17 15:14:16'), (37, 2, 6, 'yellow ranger has left a review of Zool Class at 12:00pm on the 18th June 2014', '2014-06-17 15:29:27', '2014-06-17 15:29:27'), (39, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:00:58', '2014-06-18 10:00:58'), (40, 2, 6, 'yellow ranger has left a review of Ducktales at 12:00pm on the 23rd May 2014', '2014-06-18 10:02:33', '2014-06-18 10:02:33'), (41, 1, 6, 'yellow ranger has left a review of Adventure time at 12:00pm on the 23rd May 2014', '2014-06-18 10:11:13', '2014-06-18 10:11:13'), (42, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:13:34', '2014-06-18 10:13:34'), (43, 2, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:14:01', '2014-06-18 10:14:01'), (44, 2, 6, 'yellow ranger has left a review of Adventure time at 12:00pm on the 23rd May 2014', '2014-06-18 10:14:52', '2014-06-18 10:14:52'), (45, 4, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:17:08', '2014-06-18 10:17:08'), (46, 1, 6, 'yellow ranger has left a review of Zool Class at 12:03pm on the 07th March 2014', '2014-06-18 10:18:13', '2014-06-18 10:18:13'), (47, 2, 6, 'yellow ranger has left a review of Zool Class at 12:00pm on the 23rd May 2014', '2014-06-18 10:23:23', '2014-06-18 10:23:23'); -- -------------------------------------------------------- -- -- Table structure for table `trainers` -- CREATE TABLE IF NOT EXISTS `trainers` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `bio` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `website` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `specialities_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `trainers_user_id_foreign` (`user_id`), KEY `trainers_specialities_id_foreign` (`specialities_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ; -- -- Dumping data for table `trainers` -- INSERT INTO `trainers` (`id`, `user_id`, `bio`, `website`, `specialities_id`, `created_at`, `updated_at`) VALUES (1, 2, 'Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim Invader Zim ', '', 5, '2014-06-17 14:28:17', '2014-06-17 14:28:17'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `permissions` text COLLATE utf8_unicode_ci, `activated` tinyint(1) NOT NULL DEFAULT '0', `activation_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `activated_at` timestamp NULL DEFAULT NULL, `last_login` timestamp NULL DEFAULT NULL, `persist_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `reset_password_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `first_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `last_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `display_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `gender` tinyint(4) NOT NULL, `dob` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `directory` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `categories` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `users_email_unique` (`email`), KEY `users_activation_code_index` (`activation_code`), KEY `users_reset_password_code_index` (`reset_password_code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `password`, `permissions`, `activated`, `activation_code`, `activated_at`, `last_login`, `persist_code`, `reset_password_code`, `first_name`, `last_name`, `created_at`, `updated_at`, `display_name`, `gender`, `dob`, `phone`, `directory`, `image`, `categories`, `remember_token`) VALUES (1, '<EMAIL>', <PASSWORD>', NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2014-06-17 14:20:21', '2014-06-17 14:20:21', '', 0, '0000-00-00 00:00:00', '', '', '', '', NULL), (2, '<EMAIL>', <PASSWORD>', NULL, 1, NULL, NULL, '2014-06-18 13:41:13', '$2y$10$VcozfeYGFzEnQxANPSoCc.9Vz8MHfMzMsSZoGGmsvJeo2bVo49pGu', NULL, 'Invader', 'Zim', '2014-06-17 14:20:36', '2014-06-18 13:41:13', 'Tristan_Allen', 1, '1970-01-22 00:00:00', '', '2014-06/2_Tristan_Allen', '1403018463_4226.jpg', '', NULL), (3, '<EMAIL>', '$2y$10$bD.lufaoOCbYtMUd3y2XueWzGsm4X4V4tB99Zhv4ZX0apW9igHDEO', NULL, 1, '', NULL, '2014-06-17 14:58:37', '$2y$10$gX.WLalIjmPV1Y53BDmuJ.aYsWY87GRhqX0foo6X9KW.FLhohUYpm', NULL, 'red', 'ranger', '2014-06-17 14:22:33', '2014-06-17 14:58:37', 'red ranger', 1, '1984-06-06 23:00:00', '', '2014-06/3_red ranger', '1403019513_6177574_orig.jpg', '', NULL), (4, '<EMAIL>', '$2y$10$tfuZV/f11td0rRvQ4ivQDuMrJxfH.O4ntG2oy5oJ.GSQjKuSG5FxW', NULL, 1, '', NULL, '2014-06-18 09:07:11', '$2y$10$YmxK3kSE5RNZqmma02DP4.RE30siQwEhuzI74QzhB.KOdHBGGOPpe', NULL, 'yellow', 'ranger', '2014-06-17 14:23:22', '2014-06-18 09:07:11', 'yellow ranger', 2, '1984-06-28 23:00:00', '', '2014-06/4_yellow ranger', '1403020755_6177574_orig.jpg', '', NULL), (5, '<EMAIL>', '$2y$10$suFT9/bSLDSDmbZacP7iBenrkHdVz/AA2Mrkq/C2IIuiOAJisCCZ2', NULL, 1, '', NULL, '2014-06-17 14:52:51', '$2y$10$Nbq0RyuIz93123AAy1eKreMT9ZSFbuUkBUBNQPmfbZsEHP5nNlHAS', NULL, 'green', 'ranger', '2014-06-17 14:24:03', '2014-06-17 14:53:15', 'green ranger', 1, '1974-06-05 23:00:00', '', '2014-06/5_green ranger', '1403020393_6177574_orig.jpg', '', NULL); -- -------------------------------------------------------- -- -- Table structure for table `users_groups` -- CREATE TABLE IF NOT EXISTS `users_groups` ( `user_id` int(10) unsigned NOT NULL, `group_id` int(10) unsigned NOT NULL, PRIMARY KEY (`user_id`,`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `users_groups` -- INSERT INTO `users_groups` (`user_id`, `group_id`) VALUES (1, 4), (2, 1), (2, 2), (2, 3), (3, 1), (4, 1), (5, 1); -- -------------------------------------------------------- -- -- Table structure for table `user_has_categories` -- CREATE TABLE IF NOT EXISTS `user_has_categories` ( `user_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `user_has_categories_user_id_foreign` (`user_id`), KEY `user_has_categories_category_id_foreign` (`category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `user_marketingpreferences` -- CREATE TABLE IF NOT EXISTS `user_marketingpreferences` ( `user_id` int(10) unsigned NOT NULL, `marketingpreference_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `user_marketingpreferences_user_id_foreign` (`user_id`), KEY `user_marketingpreferences_marketingpreference_id_foreign` (`marketingpreference_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `user_marketingpreferences` -- INSERT INTO `user_marketingpreferences` (`user_id`, `marketingpreference_id`, `created_at`, `updated_at`) VALUES (2, 1, '2014-06-17 14:20:36', '2014-06-17 14:20:36'); -- -------------------------------------------------------- -- -- Table structure for table `venues` -- CREATE TABLE IF NOT EXISTS `venues` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `town` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `postcode` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `lat` decimal(10,8) NOT NULL, `lng` decimal(11,8) NOT NULL, `image` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `venues_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; -- -- Dumping data for table `venues` -- INSERT INTO `venues` (`id`, `user_id`, `name`, `address`, `town`, `postcode`, `lat`, `lng`, `image`, `created_at`, `updated_at`) VALUES (1, 1, 'Greenlight', 'Cally Road', 'London', 'h4', '51.50682494', '-0.15704746', '', '2014-06-17 14:20:21', '2014-06-17 14:20:21'), (2, 2, 'brent cross', '', 'Londonbrent cross', '', '51.57635890', '-0.22369560', '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (3, 2, 'Abergavenny', '', 'abergavenny', '', '51.82536600', '-3.01942300', '', '2014-06-17 14:33:31', '2014-06-17 14:33:31'), (4, 2, 'Ooo', '', 'ooo', '', '36.01075890', '10.31169500', '', '2014-06-17 14:35:04', '2014-06-17 14:35:04'); -- -------------------------------------------------------- -- -- Table structure for table `venue_facilities` -- CREATE TABLE IF NOT EXISTS `venue_facilities` ( `venue_id` int(10) unsigned NOT NULL, `facility_id` int(10) unsigned NOT NULL, `details` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `venue_facilities_venue_id_foreign` (`venue_id`), KEY `venue_facilities_facility_id_foreign` (`facility_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `venue_facilities` -- INSERT INTO `venue_facilities` (`venue_id`, `facility_id`, `details`, `created_at`, `updated_at`) VALUES (2, 2, '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (2, 3, '', '2014-06-17 14:30:03', '2014-06-17 14:30:03'), (3, 1, '', '2014-06-17 14:33:31', '2014-06-17 14:33:31'), (4, 2, '', '2014-06-17 14:35:04', '2014-06-17 14:35:04'); -- -- Constraints for dumped tables -- -- -- Constraints for table `evercisegroups` -- ALTER TABLE `evercisegroups` ADD CONSTRAINT `evercisegroups_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`), ADD CONSTRAINT `evercisegroups_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`), ADD CONSTRAINT `evercisegroups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `evercisesessions` -- ALTER TABLE `evercisesessions` ADD CONSTRAINT `evercisesessions_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`); -- -- Constraints for table `featuredgymgroups` -- ALTER TABLE `featuredgymgroups` ADD CONSTRAINT `featuredgymgroups_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`), ADD CONSTRAINT `featuredgymgroups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `gyms` -- ALTER TABLE `gyms` ADD CONSTRAINT `gyms_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `gym_has_trainers` -- ALTER TABLE `gym_has_trainers` ADD CONSTRAINT `gym_has_trainers_gym_id_foreign` FOREIGN KEY (`gym_id`) REFERENCES `gyms` (`id`), ADD CONSTRAINT `gym_has_trainers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `ratings` -- ALTER TABLE `ratings` ADD CONSTRAINT `ratings_user_created_id_foreign` FOREIGN KEY (`user_created_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `ratings_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`), ADD CONSTRAINT `ratings_sessionmember_id_foreign` FOREIGN KEY (`sessionmember_id`) REFERENCES `sessionmembers` (`id`), ADD CONSTRAINT `ratings_session_id_foreign` FOREIGN KEY (`session_id`) REFERENCES `evercisesessions` (`id`), ADD CONSTRAINT `ratings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `sessionmembers` -- ALTER TABLE `sessionmembers` ADD CONSTRAINT `sessionmembers_evercisesession_id_foreign` FOREIGN KEY (`evercisesession_id`) REFERENCES `evercisesessions` (`id`), ADD CONSTRAINT `sessionmembers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainerhistory` -- ALTER TABLE `trainerhistory` ADD CONSTRAINT `trainerhistory_historytype_id_foreign` FOREIGN KEY (`historytype_id`) REFERENCES `historytypes` (`id`), ADD CONSTRAINT `trainerhistory_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainers` -- ALTER TABLE `trainers` ADD CONSTRAINT `trainers_specialities_id_foreign` FOREIGN KEY (`specialities_id`) REFERENCES `specialities` (`id`), ADD CONSTRAINT `trainers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_has_categories` -- ALTER TABLE `user_has_categories` ADD CONSTRAINT `user_has_categories_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`), ADD CONSTRAINT `user_has_categories_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_marketingpreferences` -- ALTER TABLE `user_marketingpreferences` ADD CONSTRAINT `user_marketingpreferences_marketingpreference_id_foreign` FOREIGN KEY (`marketingpreference_id`) REFERENCES `marketingpreferences` (`id`), ADD CONSTRAINT `user_marketingpreferences_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venues` -- ALTER TABLE `venues` ADD CONSTRAINT `venues_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venue_facilities` -- ALTER TABLE `venue_facilities` ADD CONSTRAINT `venue_facilities_facility_id_foreign` FOREIGN KEY (`facility_id`) REFERENCES `facilities` (`id`), ADD CONSTRAINT `venue_facilities_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`); /*!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>/app/commands/GalleryImport.php <?php ini_set('gd.jpeg_ignore_warning', TRUE); use Illuminate\Console\Command; use Symfony\Component\Debug\Exception\FatalErrorException; class GalleryImport extends Command { protected $name = 'images:gallery'; protected $description = 'Move All Gallery Images'; public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { Gallery::truncate(); $files = File::allFiles(base_path() . '/public/files/gallery_defaults/'); foreach ($files as $file) { @unlink($file); } $this->info('ALL files Deleted'); $folders = ['Bootcamp', 'Dance', 'Martial Arts', 'Yoga', 'Pilates', 'Spin', 'Workout']; foreach ($folders as $folder) { $files = File::allFiles(base_path() . '/public/files/gallery_new/' . $folder); $sizes = Config::get('evercise.gallery.sizes'); $this->info(count($files)); foreach ($files as $file) { $name = slugIt($folder . '_' . rand(1000, 60000)) . '.' . $file->getExtension(); /** Save the image name without the Prefix to the DB */ $save = FALSE; foreach ($sizes as $img) { try { $image = Image::make($file)->fit( $img['width'], $img['height'] )->save(public_path() . '/files/gallery_defaults/' . $img['prefix'] . '_' . $name); if ($image) { $save = TRUE; $this->line($img['prefix'] . '_' . $name); } } catch (Exception $e) { $this->error(base_path() . '/public/files/gallery_new/' . $folder . '/' . $file); $this->error($e->getMessage()); } } if ($save) { Gallery::create([ 'image' => $name, 'counter' => Config::get('evercise.gallery.image_counter', 3), 'keywords' => $folder ]); $this->info('/files/gallery_defaults/thumb_' . $name); } } } } }<file_sep>/app/controllers/ajax/TrainersController.php <?php namespace ajax; use User, UserHelper, Session, Input, Config, Sentry, Event, Response, Trainer, Wallet; class TrainersController extends AjaxBaseController { public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $valid_trainer = Trainer::validTrainerSignup(Input::all()); if ($valid_trainer['validation_failed'] == 0) { $image = Input::get('image'); $website = Input::get('website'); $profession = Input::get('profession'); $bio = Input::get('bio'); $trainer = Trainer::createOrFail(['user_id' => $this->user->id, 'bio' => $bio, 'website' => $website, 'profession' => $profession ]); // Duck out if record already exists if (!$trainer) { return Response::json(['result' => 'User is already a Trainer']); } // Should have already been made by user.create, but leave this to catch old accounts. Wallet::createIfDoesntExist($this->user->id); // update user image $this->user->image = $image; $this->user->save(); // add to trainer group $userGroup = Sentry::findGroupById(3); $this->user->addGroup($userGroup); event('trainer.registered', [$this->user]); return Response::json( [ 'callback' => 'gotoUrl', 'url' => route('users.edit', $this->user->display_name) ] ); } else { return Response::json($valid_trainer); } } } <file_sep>/app/database/migrations/2014_06_18_150925_create_session_payments_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateSessionPaymentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('sessionpayments')) { Schema::create('sessionpayments', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key $table->integer('evercisesession_id')->unsigned();// Foreign key $table->decimal('total', 19, 4); $table->decimal('total_after_fees', 19, 4); $table->decimal('commission', 19, 4); $table->integer('processed'); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('sessionpayments'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/public/assets/jsdev/prototypes/24-location-auto-complete.js function LocationAutoComplete(input){ this.input = input; this.autoCompleteStarted = false; this.addScript = false; this.mapOptions = {}; this.address_components = []; this.town = 'london'; this.width = 0; this.form; this.init(); } LocationAutoComplete.prototype = { constructor: LocationAutoComplete, init: function(){ // find form this.form = this.input.closest("form"); var self = this; //check if we are using angular as angualr is loading google maps api if (typeof angular != 'undefined') { if( window['google'] ){ this.load(); } else{ setTimeout(function() { self.init(); }, 1000); } } else { if(!self.addScript){ var script = document.createElement("script"); script.src = "//maps.googleapis.com/maps/api/js?libraries=places&callback=autocomplete.load"; script.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(script); self.addScript = true; } setTimeout(function() { self.init(); }, 500); } }, load: function(){ if (google.maps != undefined && !this.autoCompleteStarted) { this.autoCompleteStarted = true; this.addListeners(); } else { var self = this setTimeout(function() { self.load(); }, 500); } }, addListeners : function(){ var self = this; $('#location-auto-complete').on('focus', function (e) { $(this).parent().addClass('open'); }) $('body').on('click', function (e) { if (!$('#location-auto-complete').parent().is(e.target) && $('#location-auto-complete').parent().has(e.target).length === 0 && $('.open').has(e.target).length === 0) { $('#location-auto-complete').parent().removeClass('open'); } }); this.input.keyup( function(e) { if( this.value.length < 1 ) return; var service = new google.maps.places.AutocompleteService(); var res = service.getPlacePredictions({ input: self.input.val(), componentRestrictions: {country: 'uk'} }, function(predictions, status){ if (status != google.maps.places.PlacesServiceStatus.OK) { return; } $('#locaction-autocomplete .autocomplete-content').html(''); for (var i = 0, prediction; prediction = predictions[i]; i++) { $('#locaction-autocomplete .autocomplete-content').append('<li><a href="'+prediction.description+'">'+ prediction.description +'</a></li>'); } }); }); $(document).on('click', '#locaction-autocomplete .autocomplete-content a', $.proxy(this.changeLocation, this)); $(document).on('change', 'input[name="location"]', function(e){ if($(e.target).val() != ''){ $('.autocomplete-content li:first a').trigger('click'); } }); }, changeLocation : function(e){ e.preventDefault(); var value = $(e.target).attr('href'); var self = this; geocoder = new google.maps.Geocoder(); this.form = this.input.closest('form'); geocoder.geocode({'address': value}, function(results, status) { if (results[0] && status == 'OK') { var address = results[0].formatted_address; self.form.find('input[name="location"]').val(address); self.getTown(results[0].address_components); self.form.find('input[name="city"]').val(self.town); self.form.find('input[name="fullLocation"]').val(JSON.stringify(results[0])); } else{ console.log(status); } }) }, getTown : function(address_components){ var self = this; var result = address_components; for (var i = 0; i < result.length; ++i) { if (result[i].types[0] == "locality") { self.town = result[i].long_name ; } else if(result[i].types[0] == "political") { self.town = result[i].long_name ; } else if(result[i].types[0] == "postal_town"){ self.town = result[i].long_name ; } } } }<file_sep>/app/database/migrations/2015_02_07_130120_update_evercise_links_type.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class UpdateEverciseLinksType extends Migration { public function up() { DB::statement("ALTER TABLE evercise_links MODIFY COLUMN type ENUM('AREA', 'STATION', 'CLASS', 'ZIP', 'BOROUGH', 'CITY')"); } public function down() { DB::statement("ALTER TABLE evercise_links MODIFY COLUMN type ENUM('AREA', 'STATION', 'CLASS', 'ZIP')"); } } <file_sep>/app/controllers/ajax/AjaxBaseController.php <?php namespace ajax; use Controller; class AjaxBaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ public function __construct() { $this->beforeFilter('csrf'); } }<file_sep>/app/commands/SalesForceCommand.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; // php artisan check:sessions class SalesForceCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'salesforce'; /** * The console command description. * * @var string */ protected $description = 'Copies key tables from the main DB to the salesforce DB'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { // This doesn't work - come back to it later /* if (! DB::connection('salesforce')->hasTable('users')) { DB::connection('salesforce')->create('users', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string('email'); $table->string('first_name'); $table->string('last_name'); $table->string('display_name', 45); $table->tinyInteger('gender'); $table->date('dob'); $table->string('area_code', 20); $table->string('phone', 20); }); } else { DB::connection('salesforce')->table('users')->truncate(); }*/ $users = User::all()->toArray(); //$this->info(var_dump($users[0]->email)); foreach ($users as $user) { /* DB::connection('salesforce')->table('users')->insert([ 'id'=>$user['id'], 'email'=>$user['email'], 'first_name'=>$user['first_name'], 'last_name'=>$user['last_name'], 'display_name'=>$user['display_name'], 'gender'=>$user['gender'], 'dob'=>$user['dob'], 'area_code'=>$user['area_code'], 'phone'=>$user['phone'], ]);*/ $this->info(var_dump($user['email'])); } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( //array('days', null, InputOption::VALUE_OPTIONAL, 'How many days to search back.', 1), ); } } <file_sep>/public/assets/jsdev/app.js if(typeof angular != 'undefined') { var app = angular.module('everApp', [ "ng.deviceDetector", 'angularytics', 'google-maps'.ns() ] , ['$interpolateProvider',function ($interpolateProvider) { $interpolateProvider.startSymbol('{[{'); $interpolateProvider.endSymbol('}]}'); }]); app.config(['GoogleMapApiProvider'.ns(), 'AngularyticsProvider', function (GoogleMapApi, AngularyticsProvider) { GoogleMapApi.configure({ v: '3.17', libraries: 'places', uk: true }); AngularyticsProvider.setEventHandlers(['Console', 'GoogleUniversal']); }]).run([ 'Angularytics',function(Angularytics) { Angularytics.init(); }]); app.filter('truncate', function () { return function (text, length, end) { if (isNaN(length)) length = 10; if (end === undefined) end = "..."; if (text.length <= length || text.length - end.length <= length) { return text; } else { return String(text).substring(0, length-end.length) + end; } }; }); app.filter('repeat', function() { return function(val, range) { range = parseInt(range); for (var i=0; i<range; i++) val.push(i); return val; }; }); app.filter('objLimitTo', [function(){ return function(obj, limit){ var keys = Object.keys(obj); if(keys.length < 1){ return []; } var ret = new Object, count = 0; angular.forEach(keys, function(key, arrayIndex){ if(count >= limit){ return false; } ret[key] = obj[key]; count++; }); return ret; }; }]) app.directive('errSrc', function() { return { link: function(scope, element, attrs) { element.bind('error', function() { if (attrs.src != attrs.errSrc) { attrs.$set('src', attrs.errSrc); } }); } } }); } <file_sep>/app/models/Venue_facilities.php <?php class Venue_facilities extends \Eloquent { protected $fillable = array('venue_id', 'facility_id'); /** * The database table used by the model. * * @var string */ protected $table = 'venue_facilities'; /** * Concatenate name and title * * */ }<file_sep>/app/composers/ShowWalletComposer.php <?php namespace composers; use JavaScript; use Sentry; use Wallethistory; use Wallet; class ShowWalletComposer { public function compose($view) { $id = Sentry::getUser()->id; $wallet = Wallet::where('user_id', $id) ->first(); // Display balance to 2dp $balance = number_format((float) $wallet->balance, 2, '.', ''); $history = Wallethistory::where('user_id', $id) ->orderBy('id', 'asc') ->get(); $earningsThisMonth = (float) 0.00; $earningsLastMonth = (float) 0.00; foreach ($history as $key => $record) { if ($record->created_at >= date('Y-m-d H:i:s', strtotime('-1 months'))) { if ($record->transaction_amount > 0) { $earningsThisMonth += $record->transaction_amount; } } if ($record->created_at >= date('Y-m-d H:i:s', strtotime('-2 months')) && $record->created_at < date( 'Y-m-d H:i:s', strtotime('-1 months') ) ) { if ($record->transaction_amount > 0) { $earningsLastMonth += $record->transaction_amount; } } } // initialise init put for withdrawel JavaScript::put( [ 'initPut_wallet' => json_encode(['selector' => '#withdrawalform, #paypalform, #withdrawal-confirmation']) ] ); $view ->with('balance', $balance) ->with('wallet', $wallet) ->with('earningsThisMonth', $earningsThisMonth) ->with('earningsLastMonth', $earningsLastMonth) ->with('history', $history) ->with('paypal', $wallet->paypal); } }<file_sep>/app/controllers/auth/AuthController.php <?php namespace auth; use Auth, BaseController, Form, Input, Redirect, Sentry, View, Cookie; class AuthController extends \BaseController { /** * Display the login page * @return View */ public function getLogin() { return View::make('auth.login'); } /** * Logout action * @return Redirect */ public function getLogout() { Sentry::logout(); return Redirect::route('home'); } /** * Display the forgot password page * @return View */ public function getForgot() { return View::make('v3.auth.forgot'); } /** * Forgot password action * @return Redirect */ public function postForgot() { try { $email = Input::get('email'); $user = Sentry::findUserByLogin($email); $reset_code = $user->getResetPasswordCode(); $user->sendForgotPasswordEmail($reset_code); return View::make('v3.auth.forgot')->with('success','Now check your e-mails!')->with('message','You should have received an e-mail from us with a link to reset your password.' )->with('action', 'If you can&apos;t see the e-mail, please check your junk folder.<br>If it&apos;s not there either, contact us for further assistance.'); } catch(\Exception $e) { return Redirect::route('auth.forgot')->withErrors(['forgot' => $e->getMessage()]); } catch(\Cartalyst\Sentry\Users\UserNotFoundException $e) { return Redirect::route('auth.forgot')->withErrors(['forgot' => $e->getMessage()]); } } }<file_sep>/app/models/EmailOut.php <?php class EmailOut extends Eloquent { /** * @var array */ public $fillable = [ 'id', 'user_id', 'type', 'message_id', 'email', ]; protected $table = 'email_out'; public static function addRecord($user, $type, $message_id = '') { if(is_numeric($user)) { static::create(['user_id' => $user, 'type' => $type, 'message_id' => $message_id]); } else { static::create(['user_id' => 0, 'email' => $user, 'type' => $type, 'message_id' => $message_id]); } } public static function checkRecord($user_id, $type) { $record = static::where('user_id', $user_id) ->where('type', $type) ->first(); return $record; } }<file_sep>/app/composers/ChangePasswordComposer.php <?php namespace composers; use Javascript; class ChangePasswordComposer { public function compose($view) { JavaScript::put(array('initChangePassword' => 1 )); // Initialise Users JS. } }<file_sep>/app/composers/PpcLandingComposer.php <?php namespace composers; use JavaScript; class PpcLandingComposer { public function compose($view) { JavaScript::put( [ 'initPut' => json_encode(['selector' => '#send_ppc']) ] ); } }<file_sep>/app/lang/en/terms.php <?php return [ 'body' => ' <P>Terms of Use</P> <P>Please read these terms and conditions (&quot;Terms of Use&quot;) carefully as they apply to your use of www.evercise.com (the &quot;Website&quot;) and the service owned and offered (the &quot;Service&quot;) by Qin Technology Ltd. (&quot;We&quot;/&quot;Us&quot;/&quot;Our&quot;/&quot;Evercise&quot;/the &quot;Company&quot;). By using this Website and/or Service in any manner you agree to be bound by these Terms of Use. These Terms of Use apply to all users of the Website and/or Service, including all users who are also contributors of Content, information, and other materials or services on the Website. If you do not agree to these Terms of Use, you must not use the Website.</P> <P>Unless otherwise defined, all capitalised terms in these Terms of Use shall have the meanings set out in section 18 of these Terms of Use</P> <P>The Website is owned and operated by Qin Technology Ltd, a company limited by shares (trading as EVERCISE.COM), registered in England and Wales under company number: 08423324 and whose registered office at 13 Lock House, 35 Oval Road, London, NW1 7BF United Kingdom. Our business address is 1 Fetter Lane, London, EV4A 1BR.</P> <P><BR><BR> </P> <P>The term &quot;you&quot; refers to any user of the Website. Use of the Website includes accessing, browsing or registering to use the Website.</P> <P><BR><BR> </P> <P>By using the Website you agree to comply with and be bound by these Terms of Use which, together with Our Privacy Policy (available at http://www.evercise.com/privacy), Cookie Policy (available at '.HTML::linkRoute('static.privacy', 'Privacy Policy').'), and all other rules, policies and procedures and any additional terms and conditions that We may publish from time to time on the Website. </P> <P><BR><BR> </P> <P>We may revise these Terms of Use from time to time by updating this page. The revised Terms of Use will take effect from when you next use the Website and/or Service after they are published and your continued use of the Website constitutes your acceptance of any changes. We may also impose limits on certain features or Services or restrict your access to parts or all of the Service without notice or liability to you. </P> <P>You may not use Our Website or the Service if you are below the age of 18 or if you are otherwise unable to form a legally binding contract. We may, in Our sole discretion (and without being required to give a reason), refuse to offer the Service to any person or entity and change the eligibility criteria for access to the Website at any time.&nbsp;If you no longer meet the eligibility criteria for the Website your access may be suspended or terminated. </P> <P>SUMMARY OF SERVICE</P> <P>(a) Evercise.com is a platform where certain qualified users (&quot;Class Creators&quot;) create groups and offer services to other users (&quot;Participants&quot;). Through the Website, email and other media, the Service makes accessible various content, including, but not limited to, videos, photographs, images, artwork, graphics, audio clips, comments, data, text, software, scripts, projects, other material and information, and associated trademarks and copyrightable works (&quot;Content&quot;). Class Creators, Participants, and other visitors to the Website and users of the Service (collectively, &quot;Users&quot;) may have the ability to contribute, add, create, upload, submit, distribute, facilitate the distribution of, collect, post, or otherwise make accessible (&quot;Submit&quot;) Content. &quot;User Submissions&quot; means any Content Submitted by Users.</P> <P>ACCESS</P> <P>(b) You may be able to access parts of the Website without having to register any details with Us. However, from time to time certain areas of this Website may be accessible only if you are a registered User.</P> <P>(c) You are responsible for making all arrangements necessary for you to have access to Our Website. You are also responsible for ensuring that all persons who access Our Website through your internet connection are aware of these Terms of Use and other applicable terms and conditions, and that they comply with them.</P> <P>(d) We make reasonable efforts to ensure that this Website is available 24 hours a day throughout each year, however, this is not guaranteed. The Website may be temporarily unavailable at anytime because of: server or systems failure or other technical issues; reasons that are beyond Our control; required updating, maintenance or repair or any decision taken by Us to suspend the Website or any part of it. We may suspend, withdraw, discontinue or change all or any part of Our Website without notice. We will not be liable to you if for any reason Our Website is unavailable at any time or for any period or permanently.</P> <P>(e) Where possible We will try to give you advance warning of maintenance issues but shall not be obliged to do so.</P> <P>RULES AND CONDUCT</P> <P>(f) You may not use the Website or Service for any purpose that is prohibited by the Terms of Use or Applicable Law (including the jurisdiction you are in when you access the Website). The Website and Service are provided only for your own personal, non-commercial use (except as allowed by the terms set forth in section 5 of these Terms of Use, &quot;Classes: Activities and Commerce&quot;). You shall not use the Website or Service in any way or permit any third party using your account to use the Website in any way that:</P> <P>(f.i) breaches any Applicable Law;</P> <P>(f.ii) is unlawful or fraudulent, or has unlawful or fraudulent purpose or effect;</P> <P>(f.iii) is intended to harm or potentially harm any person;</P> <P>(f.iv) constitutes unsolicited or unauthorized advertising or promotional material or any junk mail, spam, or chain letters.</P> <P>(g) You also agree not to reproduce, duplicate, copy or re-sell any part of the Website in contravention of the provisions of the Terms of Use.</P> <P>(h) Additionally, you shall not: (a) take any action that interferes with, damages or disrupts, or may interfere with, damage or disrupt (as determined by the Company in its sole discretion) any equipment or network or software or hardware owned or used by the Company or any third party; (b) interfere or attempt to interfere with the proper working of the Service or any activities conducted on the Service; (c) bypass any measures the Company may use to prevent or restrict access to the Service (or other accounts, computer systems, or networks connected to the Service); (d) run Maillist, Listserv, or any form of auto-responder or &quot;spam&quot; on the Website; or (e) use manual or automated software, devices, or other processes to &quot;crawl&quot; or &quot;spider&quot; any page of the Website.</P> <P>(i) You shall not directly or indirectly: (a) decipher, decompile, disassemble, reverse engineer, or otherwise attempt to derive any source code or underlying ideas or algorithms of any part of the Website, except to the extent Applicable Laws specifically prohibit such restriction; (b) modify, translate, or otherwise create derivative works of any part of the Website; or (c) copy, rent, lease, distribute, or otherwise transfer any of the rights that you receive hereunder. You shall abide by all applicable local, state, national, and international laws and regulations.</P> <P>(j) Class Creators agree to not use other Users&rsquo; personal information for any purpose other than those explicitly specified in the Class Creator&rsquo;s Class Plan, or any purpose not related to fulfilling delivery of a product or service explicitly specified in the Class Creator&rsquo;s Class Plan.</P> <P>(k) Any Content Submitted by you must:</P> <P>(k.i) be accurate (where it state facts);</P> <P>(k.ii) be genuinely held (where it states opinions); and</P> <P>(k.iii) comply with Applicable Law.</P> <P>(l) Content must not:</P> <P>(l.i) contain any material which is defamatory of any person;</P> <P>(l.ii) contain any material which is obscene, offensive, hateful or inflammatory;</P> <P>(l.iii) contain any sexually explicit material;</P> <P>(l.iv) promote violence;</P> <P>(l.v) promote discrimination based on race, sex, religion, nationality, disability, sexual orientation or age;</P> <P>(l.vi) infringe any copyright, database right or trade mark of any other person;</P> <P>(l.vii) be likely to deceive any person;</P> <P>(l.viii) be made in breach of any legal duty owed to a third party;</P> <P>(l.ix) be threatening, abuse or invade another&rsquo;s privacy, or cause annoyance, inconvenience or needless anxiety;</P> <P>(l.x) be likely to harass, upset, embarrass, alarm or annoy any other person;</P> <P>(l.xi) be used to impersonate any person, or to misrepresent your identity or affiliation with any person;</P> <P>(l.xii) give the impression that it emanates from Us, if this is not the case.</P> <P>REGISTERING ON THIS WEBSITE</P> <P>(m) When registering on the Website you must choose a username and password. You are responsible for all actions taken by you or any third party when logged into the Website with your chosen username and password. If you have chosen to sign in via Facebook, then you will be deemed to have registered for the Website using your Facebook credentials as your username and password. </P> <P>(n) By registering on the Website you undertake:</P> <P>(n.i) that all the information you provide to Us are true, accurate, current and complete in all respects;</P> <P>(n.ii) to notify Us immediately of any changes to the information provided on registration;</P> <P>(n.iii) that you are 18 years old or over;</P> <P>(n.iv) to only use the Website using your own username and password;</P> <P>(n.v) to keep your username and password safe and confidential and not disclose either to any person or permit any other person to use them; and</P> <P>(n.vi) to change your password immediately upon discovering or suspecting that it has been compromised and promptly notify us of the same.</P> <P>(o) You authorise Us to transmit your name, address and other personal information supplied by you (included updated information) to third parties in order to obtain information about you from third parties, including, but not limited to, credit rating agencies so that We may authenticate your identity and eligibility to use the Website.</P> <P>(p) Evercise reserves the right to refuse registration of, or cancel, a username and domain in its sole discretion.</P> <P>(q) Registering with Evercise is free. However, we do retain a small proportion of the basic programme payment and service payment as a fee for Our Service in accordance with section 6 below. The total value of fees retained by Us is set out on the Website. Changes to any fees are effective as soon as notice is given on the Website. We may choose to temporarily change the fees for Our services for promotional events or new services, and such changes are effective when We post the temporary promotional event or new service on the Website.</P> <P>(r) You are responsible for paying all fees and applicable taxes associated with your use of the Website.</P> <P>Classes: ACTIVITIES AND COMMERCE</P> <P>(s) Class Creators may offer services to other Users by posting Class Plans on the Website. By posting a Class Plan, each Class Creator offers Users the opportunity to enter into a contract with that Class Creator (&quot;Offer&quot;) and join the Class. By clicking to join a Class, a Participant, accepts the Offer and agrees to enter into a contract with the Class Creator on the terms set out in &quot;Contract between Class Creator and Participant&quot; (&quot;Contract&quot;) and on no other terms. Words defined in the Contract have the same meaning in these Terms of Use. We are not a party to Contract however both the Participant and the Class Creator authorises Us to collect and make payment of the Class Fee pursuant to the Contract.</P> <P>(t) We do not check or verify the qualifications of Class Creators. You acknowledge that</P> <P>(t.i) we are under no obligation to confirm or ensure that a Class Creator has the relevant qualifications to undertake the activities detailed in the Class Plan created by such Class Creator; and </P> <P>(t.ii) we are not liable for any damage or loss incurred as a result of a Class Creator&rsquo;s qualifications or lack of qualifications. </P> <P>(u) We are not liable for your interactions or dealings with any organisations and/or individuals found on or through the Website or Service. We do not oversee, regulate or guarantee the performance, delivery or punctuality of Class Plans or payments of Class Fees and are not responsible for any damage or loss incurred as a result of any dealings between Class Creators and/or Participants and/or third parties. We are under no obligation to become involved in disputes between Class Creators and Participants or any third party. In the event of a dispute, you release Us, Our officers, employees, agents and successors from claims, damages and demands of every kind, known or unknown, suspected or unsuspected, disclosed or undisclosed, arising out of or in any way related to such disputes. </P> <P>(v) We shall not be liable for the actions of Class Creator or Participant. We reserve the right to cancel a Class and refund all Class Fees at any time for any reason. We reserve the right to remove a Class posting or Class Plan from the Website for any reason.</P> <P>(w) Where you are a Participant and you agree to join a Class you agree to make payment of the Class Fee through PayPal or by debit/credit card.</P> <P>(x) The Class Fee will be payable immediately upon a Participant accepting an Offer.</P> <P>(y) We will endeavour to forward all payments received in respect of the Class Fee (less any fees payable to Us and any applicable Transaction Fees) to the Class Creator&rsquo;s Evercise Wallet within 3 working days of the Class being completed.</P> <P>(z) When you use a Service for which a fee is payable you will have an opportunity to review and accept the fees that you will be charged. Changes to fees are effective after We provide you with notice by posting the changes on the Website. You are responsible for paying all fees and taxes associated with your use of the Service.</P> <P>(aa) If a Class proceeds, we shall charge Class Creators a fee of 10% of the Class Fee.</P> <P>(ab) All payments to and from us will be processed through a third-party payments processor. All applicable Transaction Fees will be deducted from the Class Fee before the relevant amount of the Class Fee is paid to the Class Creator. </P> <P>(ac) The Transactions Fees payable to Paypal are currently 5% plus &pound;0.05 of any payment of less than &pound;10.00, and 3% plus &pound;0.20 of any payment of &pound;10.00 or greater.</P> <P>(ad) Where payment of a Class Fee by a Participant is via Paypal, such payment will be subject to the terms and conditions of PayPal.</P> <P>CONTENT</P> <P>(ae) &quot;Intellectual Property Rights&quot; means copyright, trade marks, service marks, trade names and domain names, rights under licences, rights in get-up, rights in goodwill, patents, rights in designs, rights in computer software, database rights, rights in confidential information (including know-how and trade secrets) and any other intellectual property rights in each case whether or registered or unregistered. </P> <P>(af) Use, reproduction, modification, distribution or storage of any Content for other than personal, non-commercial use is expressly prohibited without prior written permission from Us, or from the copyright holder identified in such Content&rsquo;s copyright notice.&rsquo;</P> <P>(ag) You shall not sell, license, rent, reverse engineer (save to the extent permitted by applicable law) any Content consisting of downloadable software or otherwise use or exploit any Content for commercial use or in any way that violates any third party rights.</P> <P>(ah) Nothing you do on or in relation to the Website will transfer any Intellectual Property Rights to you. </P> <P>(ai) If you Submit Content to the Website, you grant Us, a non-exclusive, worldwide, perpetual, irrevocable, royalty-free, sub licensable (through multiple tiers) right to exercise any and all copyright, publicity, trademarks, database rights and Intellectual Property Rights you have in the Content and to grant the sub-licences in respect of the Content set out in these Terms of Use. In addition, you waive all moral rights you have in the Content to the fullest extent permitted by law.</P> <P>(aj) By Submitting any User Submission to the Website, you:</P> <P>(aj.i) are publishing that User Submission, and confirm that you may be identified publicly by your username in association with any such User Submission;</P> <P>(aj.ii) represent and warrant that you: (a) own or otherwise control all rights to all Content in your User Submissions; (b) have full authority to act on behalf of any and all owners of any right, title or interest in and to any Content in your User Submissions to use such Content as contemplated by these Terms of Use and to grant the license rights set forth above; (c) have permission to use the name and likeness of each identifiable individual person and to use such individual&rsquo;s identifying or personal information as contemplated by these Terms of Use; and (d) are authorised to grant all of the aforementioned rights to Us and all Users of the Website;</P> <P>(aj.iii) agree to pay all royalties and other amounts owed to any person or entity due to your Submission of any Content on the Website and hereby indemnify Us forthwith on demand against any royalties or other amounts We may have to pay to any third party in respect of the Content;</P> <P>(aj.iv) warrant that the use or other exploitation of such Content by Us and use or other exploitation by Users of the Website and Service as contemplated by these Terms of Use will not infringe or violate the rights of any third party, including without limitation any privacy rights, publicity rights, copyrights, contract rights, or any other intellectual property or proprietary rights; and</P> <P>(aj.v) grant us the right to and authorise Us to delete, edit, modify, reformat, excerpt, or translate any materials, Content or information Submitted by you; and that all information publicly posted or privately transmitted through the Website is the sole responsibility of the person from which such Content originated and that We will not be liable for any errors or omissions in any Content; and that We cannot guarantee the identity of any other Users with whom you may interact in the course of using the Service.</P> <P>(ak) We do not endorse and have no control over any User Submission on the Website. We do not guarantee the authenticity of any data which Users may provide about themselves. You acknowledge that all Content accessed by you using the Service is accessed and relied upon at your own risk and you will be solely responsible for any damage or loss that you or any third party may suffer resulting from accessing or relying on Content.</P> <P>(al) You acknowledge that the Intellectual Property Rights in the material and Content supplied as part of the Website shall remain with Us or Our licensors.</P> <P>(am) No licence is granted to you to use any of Our trade marks or those of Our affiliated companies.</P> <P>DISCLAIMER</P> <P>(an) It shall be your responsibility to ensure that any products, services or information available through the Website meet your specific requirements.</P> <P>(ao) We attempt to ensure that the information available on the Website is accurate. However, We do not guarantee the accuracy or completeness of material on this Website. We use all reasonable endeavours to correct errors and omissions as quickly as practicable after becoming aware or being notified of them. We make no commitment to ensure that such material is correct or up to date.</P> <P>(ap) All drawings, images, descriptive matter and specifications on the Website are for the sole purpose of giving an approximate description for your general information only and should be used only as a guide.</P> <P>(aq) The Website is provided on an &quot;as is&quot; and &quot;as available&quot; basis without any representation or endorsement made and We make no warranties or guarantees, whether express or implied unless otherwise expressly stated in these Terms of Use or required by law in relation to the information, materials, Content or services found or offered on the Website. </P> <P>(ar) We will not be responsible or liable to you for any loss of Content or material uploaded or transmitted through the Website and We accept no liability of any kind for any loss or damage from action taken in reliance on material or information contained on the Website.</P> <P>(as) You must bear the risk associated with the use of the internet. In particular, We will not be liable for any damage or loss caused by a distributed denial-of-service attack, any viruses, trojans, worms, logic bombs, keystroke loggers, spyware, adware or other material which is malicious or technologically harmful that may infect your computer, peripheral computer equipment, computer programs, data or other proprietary material as a result of your use of the Website or you downloading any material posted or sold on the Website or from any website linked to it. </P> <P>SUSPENDING OR TERMINATING YOUR ACCESS</P> <P>(at) We reserve the right to terminate or suspend your access to the Website or Service immediately and without notice to you if:&nbsp;</P> <P>(at.i) you fail to make any payment to Us when such payment is due; </P> <P>(at.ii) you breach any of the terms of these Terms of Use, Privacy Policy, Cookie Policy or other rules, conditions or restrictions posted on the Website (repeatedly or otherwise);</P> <P>(at.iii) you are impersonating any other person or entity;</P> <P>(at.iv) when requested by Us to do so, you fail to provide Us within a reasonable time with sufficient information to enable Us to determine the accuracy and validity of any information supplied by you, or your identity;&nbsp;</P> <P>(at.v) We suspect you have engaged, or are about to engage, or have in anyway been involved, in fraudulent or illegal activity on the Website; or</P> <P>(at.vi) if We otherwise determine to withdraw your access to the Website and/or the Service at our sole discretion for any reason.</P> <P>REVIEWS</P> <P>(au) You acknowledge that any review, feedback or rating which you leave may be published by Us on the Website and you agree that it may be displayed for as long as We consider appropriate and that the Content may be syndicated to Our other websites, publications or marketing materials.&nbsp;</P> <P>(av) You undertake that any review, feedback or rating that you write shall comply with the terms of these Terms of Use.</P> <P>(aw) You agree to indemnify and hold us harmless against any claim or action brought by third parties, arising out of or in connection with any review, feedback or rating posted by you on the Website, including, without limitation, the violation of their privacy, defamatory statements or infringement of intellectual property rights.&nbsp; </P> <P>(ax) You grant Us and Our affiliate companies a non-exclusive, royalty-free worldwide license to use or edit any reviews posted by you.&nbsp;</P> <P>(ay) We reserve the right to publish, edit or remove any reviews without notifying you.</P> <P>LINKING TO THE WEBSITE</P> <P>(az) You must not create a link to the Website from another website, document or any other source without first obtaining Our prior written consent and such consent if given may be subject to such conditions as We determine and such consent if given may be withdrawn at any time.</P> <P>(ba) We have not reviewed sites linked to the Website and is not responsible for the Content or accuracy of any off-Website pages or any other sites linked to the Website (including without limitation websites linked through advertisements or through any search engines).</P> <P>PERSONAL DATA AND COOKIES</P> <P>(bb) In using the Website you may provide Us with &quot;personal data&quot; as defined in the Data Protection Act 1998. You have certain rights in this personal data. By using this Website you grant us the consent to use your personal data in accordance with Our Privacy Policy.</P> <P>(bc) In using the Website you grant to Us the consent to undertake cross-border transfers of your personal data globally in accordance with Our Privacy Policy.</P> <P>(bd) Your use of the Website may be subject to use by Us of &quot;cookies&quot;, which are text files placed on your computer to temporarily store information. Our use of cookies is subject to Our Cookie Policy.</P> <P>(be) We may store and process your information on computers located in the United Kingdom that are protected by physical as well as technological security devices. For a complete description of how We use and protect your personal information, see Our Privacy Policy. If you object to your information being transferred or used in this way please do not use Our Services.</P> <P>(bf) We reserve the right to disclose such information to law enforcement authorities as We reasonably feel is necessary should you breach these Terms of Use.</P> <P>CANCELLATION of registration</P> <P>(bg) Where you are required to register with Us, you may cancel such registration at any time by notifying Us at <EMAIL>. Any fees paid by Users of the Website or Service are non-refundable (except those fees that are specifically expressed to be refundable under these Terms of Use). All provisions of these Terms of Use which by their nature should survive termination shall survive termination, including, without limitation, ownership provisions, warranty disclaimers, indemnity and limitations of liability.</P> <P>(bh) We may cancel your access to all or any part of the Service at any time, with or without cause, with or without notice, effective immediately, which may result in the forfeiture and destruction of all information associated with your membership.</P> <P>(bi) We may also cancel your registration if you do not visit the Website for an extended period of time, or if We reasonably believe that you have violated any Applicable Laws, acted inconsistently with the letter or spirit of these Terms of Use, or have violated Our rights or those of another party.</P> <P>(bj) Following cancellation We may retain any information you submitted as part of the registration process, and any transaction information arising from your use of this Website and Our Services, for such period as may be required by Applicable Laws.</P> <P>(bk) The provisions of these Terms of Use entitled &quot;Disclaimer&quot;, &quot;Limitation of Liability,&quot; and &quot;General Provisions&quot; will survive cancellation of your registration or termination of these Terms of Use.</P> <P>Non Attendance of classes And refunds</P> <P>(bl) Class Fees are non-refundable except in accordance with this section 13. </P> <P>(bm) If a Participant no longer wishes to attend a Class, he or she must contact us in writing to cancel his or her class attendance.</P> <P>(bn) If the Participant contacts Us in writing to cancel his or her class attendance:</P> <P>(bn.i) more than 5 days before the Class Date, We will refund an amount equivalent to 100% the Class Fee less any applicable Transaction Fees;</P> <P>(bn.ii) less than 5 days but more than 2 days before the Class Date, We will refund an amount equivalent to 50% the Class Fee less any applicable Transaction Fees;</P> <P>(bn.iii) less than 2 days before the Class Date, no refunds will be available. The full Class Fee will be charged regardless of whether the Participant attends the Class. </P> <P>(bo) Where the Participant cancels their class attendance, We will be entitled to retain 40% of the non-refunded Class Fee and transfer 60% of the non-refunded Class Fee (less any applicable Transaction Fees) to the Class Creator. </P> <P>(bp) Where the Participant attends a Class and is not satisfied that the Class matches the Class Plan, the Participant may contact our complaints team by email to <EMAIL>. We will endeavour to investigate your complaint and reply to you within 14 days. Where we find in favour of you, We will refund to you an amount equivalent to 100% the Class Fee less any applicable Transaction Fees. You acknowledge that you do not have an automatic right to a refund and that any refund is only available at Our sole discretion. </P> <P>(bq) All refunds paid to a Participant by Evercise will be in the form of Evercoins and will be paid to the Participant&rsquo;s Evercise Wallet. </P> <P>Cancellation of a class by a Class creator</P> <P>(br) Once a Class Creator has posted a Class Plan, the Class Creator may only cancel the Class if no Participants have accepted the Offer to join the Class. Once a Participant has joined a Class, the Class Creator is obliged to carry out the Class in accordance with the terms of the Class Plan.</P> <P>(bs) If a Class Creator is unable to carry out a class for reasons of illness or any other reason, he must contact Evercise in writing as soon as possible. Evercise may at its sole discretion allow a Class Creator to cancel a Class notwithstanding that a Participant has accepted the Offer to join a Class. In the event that such Class is cancels, Evercise will liaise between the Class Creator and any Participants to reschedule the Class and/or offer refunds to the Participants (as applicable).</P> <P>LIMITATION OF LIABILITY AND INDEMNITY</P> <P>(bt) Notwithstanding any other provision in these Terms of Use, nothing in these Terms of Use will exclude or limit Our liability for:</P> <P>(bt.i) death or personal injury resulting from Our negligence;</P> <P>(bt.ii) any other liability that cannot be excluded or limited by English law.</P> <P>(bu) We will not be liable, in contract or tort (including, without limitation, negligence), or in respect of pre-contract or other representations (other than fraudulent or negligent misrepresentations) or otherwise for the below mentioned losses which you have suffered or incurred arising out of or in connection with use of, or inability to use, Our Website or use of or reliance on any Content displayed on Our Website even if such losses are foreseeable or result from a deliberate breach by Us of these Terms of Use or as a result of any action We have taken in response to your breach of these Terms of Use:</P> <P>(bu.i) any economic losses (including without limitation loss of revenues, profits, contracts, business or anticipated savings);</P> <P>(bu.ii) any loss of goodwill or reputation; </P> <P>(bu.iii) any consequential or indirect losses; </P> <P>(bu.iv) any loss of data;</P> <P>(bu.v) wasted management or office time; or</P> <P>(bu.vi) any other loss or damage of any kind.</P> <P>(bv) Our total aggregate liability to you in contract, tort (including negligence or breach of statutory duty), misrepresentation, restitution or otherwise, arising in connection with:</P> <P>(bv.i) a Class, shall be limited to the proportion of the Class Fee paid by you and received by Us in respect of such Class; and</P> <P>(bv.ii) any other reason, shall be limited to the total amount of monies paid by you to us (less any proportion of such monies paid to any Class Creator and any applicable Transaction Fees) during the 12 months immediately preceding the date on which the claim arose.</P> <P>(bw) If you buy any goods or services from a third party seller through our Website, the seller&rsquo;s individual liability will be set out in their own terms and conditions.</P> <P>(bx) You agree to fully indemnify, defend and hold Us, and Our officers, directors, employees and suppliers, harmless immediately on demand, from and against all claims, including but not limited to losses (including loss of profit, revenue, goodwill or reputation), costs and expenses, including reasonable administrative and legal costs, arising out of any breach of these Terms of Use by you, or any other liabilities arising out of your use of this Website or any other person accessing the Website using your personal information with your authority.</P> <P>(by) This section 13 does not affect your statutory rights as a consumer.</P> <P>GENERAL</P> <P>(bz) If any provision of these Terms of Use is held by any competent authority to be invalid or unenforceable in whole or in part, the validity of the other provisions in these Terms of Use and the remainder of the provision in question will not be affected.</P> <P>(ca) All contracts are concluded and available in English only.</P> <P>(cb) If We fail, at any time to insist upon strict performance of any of your obligations under these Terms of Use, or if We fail to exercise any of the rights or remedies to which We are entitled under these Terms of Use, it shall not constitute a waiver of such rights or remedies and shall not relieve you from compliance with your obligations under these Terms of Use.</P> <P>(cc) A waiver by Us of any default shall not constitute a waiver of any other default.</P> <P>(cd) No waiver by Us of any of these Terms of Use shall be effective unless it is expressly stated to be a waiver and is communicated to you in writing.</P> <P>GOVERNING LAW AND JURISDICTION</P> <P>(ce) The Website is controlled and operated in the United Kingdom.</P> <P>(cf) These Terms of Use will be governed by the laws of England and Wales and you irrevocably agree to submit to the exclusive jurisdiction of the courts of England.</P> <P>DEFINITIONS</P> <P>(cg) &quot;Applicable Law&quot; in relation to any person, action or thing means the following in relation to that person, action or thing </P> <P>(cg.i) any law, rule or regulation of any country (or political sub-division of a country)</P> <P>(cg.ii) any obligation under any licence in any country (or political sub-division of a country); and/or</P> <P>(cg.iii) any lawful and binding determination, decision or direction of a regulator in any country (or political sub-division of a country).</P> <P>(ch) &quot;Class&quot; means the activity described and offered to Participants in a Class Plan.</P> <P>(ci) &ldquo;Class Creators&rdquo; shall have the meaning set out in section 1 of these Terms of Use. </P> <P>(cj) &quot;Class Fee&quot; means the fee payable by a Participant to a Class Creator for joining a Class.</P> <P>(ck) &quot;Class Plan&quot; means the plan posted by a Group CreatorClass Creator on the Website describing an activity offered to Users and how and when the activity will be delivered to Participants.</P> <P>(cl) &ldquo;Content&rdquo; shall have the meaning set out in section 1 of these Terms of Use. </P> <P>(cm) &ldquo;Contract&rdquo; shall have the meaning set out in section 5 of these Terms of Use.</P> <P>(cn) &ldquo;Evercise Wallet&rdquo; means the virtual wallet linked to a Participant or Class Creator&rsquo;s Evercise account which will store the amount of Evercoins and money standing to that Participant or Class Creator&rsquo;s Evercise account.</P> <P>(co) &ldquo;Evercoins&rdquo; means the virtual currency developed by Evercise and used on the Website to buy and sell services offered on the Website. 1 Evercoin is equal to 1 pound sterling.</P> <P>(cp) &quot;Intellectual Property Rights&quot; shall have the meaning as set out in section 6.1.</P> <P>(cq) &ldquo;Offer&rdquo; shall have the meaning set out in section 5 of these Terms of Use. </P> <P>(cr) &ldquo;Participants&rdquo; shall have the meaning set out in section 1 of these Terms of Use. </P> <P>(cs) &ldquo;Service&rdquo; shall have the meaning as set out in first paragraph of these Terms of Use.</P> <P>(ct) &ldquo;Terms of Use&rdquo; means these terms and conditions.</P> <P>(cu) &ldquo;Submit&rdquo; shall have the meaning set out in section 1 of these Terms of Use. </P> <P>(cv) &ldquo;Transaction Fee&rdquo; means any fees payable to Paypal or any other payment processing company (including any banks or credit card companies) for the processing of payments.</P> <P>(cw) &ldquo;User Submissions&rdquo; shall have the meaning set out in section 1 of these Terms of Use.</P> <P>(cx) &ldquo;Users&rdquo; shall have the meaning set out in section 1 of these Terms of Use.</P> <P>(cy) &quot;We&quot;/&quot;Us&quot;/&quot;Our&quot;/&quot;Evercise&quot;/&quot;Company&quot; means Qin Technology Ltd, a limited company, registered in England and Wales under company number: 08423324 and whose registered office at 13 Lock House, 35 Oval Road, London, NW1 7BF United Kingdom.</P> <P>(cz) &ldquo;Website&rdquo; means www.evercise.com.</P> <P>2 Contract between Class Creator and Participant</P> <P><BR><BR> </P> <P>3 Words defined in the Terms of Use shall have the same meaning in this Contract.</P> <P>4 Class Creators and Participants agree that as between them the Class Plan, and the Class shall be provided on the terms of this Contract and, where necessary the Terms of Use.</P> <P>5 Upon any one Participant accepting the relevant Offer the Class Creator shall be obliged to provide the activities set out and described in the Class Plan.</P> <P>6 Upon acceptance of an Offer the Participant shall Immediately pay the Class Fee to the Company.</P> <P>7 The Participant and the Class Creator authorises the Company to deduct its fees any applicable Transaction Fees from the Class Fee before transferring the relevant proportion of the Class Fee to the Class Creator.</P> <P>8 The Class Creator shall undertake the activities outlined in the Class Plan in accordance with the terms set out in the Class Plan.</P> <P>9 The Class Creator shall not be entitled to any Class Fees unless and until the Class Plan has been completed and the Company has received payment for all sums due to it under the Class Plan.</P> ', ];<file_sep>/app/controllers/widgets/locationController.php <?php namespace widgets; use Sentry, View, Geocoder, Exception, Request, Response, JavaScript, Input, Session; class LocationController extends \BaseController { public function getGeo() { } public function postGeo() { $ip = Request::getClientIp(); $address = array_values(Input::get()); $address = implode(',', $address); $geocoder = new \Geocoder\Geocoder(); $adapter = new \Geocoder\HttpAdapter\CurlHttpAdapter(); $provider = new \Geocoder\Provider\GoogleMapsProvider($adapter); $chain = new \Geocoder\Provider\ChainProvider(array( new \Geocoder\Provider\FreeGeoIpProvider($adapter), new \Geocoder\Provider\HostIpProvider($adapter), new \Geocoder\Provider\GoogleMapsProvider($adapter), )); $geocoder->registerProvider($chain); try { $geocode = $geocoder->geocode($address); JavaScript::put(array('latitude' => json_encode( $geocode->getLatitude()) , 'longitude' => json_encode( $geocode->getLongitude()) ) ); return Response::json(array('lat' => $geocode->getLatitude(), 'lng' => $geocode->getLongitude() )); } catch (Exception $e) { return Response::json(array('error' => $e->getMessage())); } } public function getMap() { return View::make('widgets/map'); } public static function addressToGeo($address) { $address = implode(',', $address); $geocoder = new \Geocoder\Geocoder(); $adapter = new \Geocoder\HttpAdapter\CurlHttpAdapter(); $provider = new \Geocoder\Provider\GoogleMapsProvider($adapter); $chain = new \Geocoder\Provider\ChainProvider(array( new \Geocoder\Provider\FreeGeoIpProvider($adapter), new \Geocoder\Provider\HostIpProvider($adapter), new \Geocoder\Provider\GoogleMapsProvider($adapter), )); $geocoder->registerProvider($chain); try { $geocode = $geocoder->geocode($address); JavaScript::put(array('latitude' => json_encode( $geocode->getLatitude()) , 'longitude' => json_encode( $geocode->getLongitude()) ) ); return ['lat' => $geocode->getLatitude(), 'lng' => $geocode->getLongitude() ]; } catch (Exception $e) { return ['error' => $e->getMessage()]; } } }<file_sep>/app/models/Speciality.php <?php /** * Class Speciality */ class Speciality extends Eloquent { /** * @var array */ protected $fillable = array('id', 'name', 'titles'); /** * The database table used by the model. * * @var string */ protected $table = 'specialities'; /** * Concatenate name and title * * @return string */ public function pluckSpecialityName() { return $this->attributes['name'] . ' ' . $this->attributes['titles']; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function Trainers() { return $this->belongsTo('Trainer'); } }<file_sep>/app/database/seeds/VenuesTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class VenuesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('venues')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Venue::create(array('user_id' => 1, 'name' => 'Greenlight', 'address' => 'Cally Road', 'town' => 'London', 'postcode' => 'h4', 'lat' => '51.50682494', 'lng' => '-0.15704746')); } }<file_sep>/app/composers/DistanceComposer.php <?php namespace composers; use Functions; class DistanceComposer { public function compose($view) { // get client location latlng $geocode = Functions::getPosition(); $viewdata= $view->getData(); $distanceMiles = 0; if (isset($viewdata['lat']) && isset($viewdata['lng'])) { $lat = $viewdata['lat']; $lng = $viewdata['lng']; //$lat = 51.50682494; //$lng = -0.15704746; $distance = Functions::getDistance( $geocode->getLatitude(), $geocode->getLongitude(), $lat, $lng); //$distance = Functions::getDistance( 50.01, -0.19, $lat, $lng); $distanceMiles = $distance->in('mi')->vincenty(); $view->with('distance', $distanceMiles); } } }<file_sep>/app/composers/ClassPurchaseComposer.php <?php namespace composers; use JavaScript; class ClassPurchaseComposer { public function compose($view) { JavaScript::put( [ 'overrideGaPageview' => json_encode(['pageview' => '/class-order']) ] ); } }<file_sep>/app/database/seeds/SessionsTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class SessionsTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('evercisesessions')->delete(); DB::table('migrate_sessions')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); $classdatetimes = DB::connection('mysql_import')->table('classdatetime')->get(); foreach ($classdatetimes as $classdatetime) { // classDatetimeId // classInfoId // classDatetimeSlot // classDatetimeParticipant // classDatetimeCreateTime // classDatetimeEmailedParticipantList // classDatetimeFeatured $classinfo = DB::connection('mysql_import')->table('classinfo')->where('classInfoId', $classdatetime->classInfoId)->first(); if($classinfo->classInfoPublished == 1) { $evercisegroupId = DB::table('migrate_groups')->where('classInfoId', $classdatetime->classInfoId)->pluck('evercisegroup_id'); $evercisegroup = Evercisegroup::find($evercisegroupId); if ($evercisegroup) { $session = Evercisesession::create(array( 'evercisegroup_id'=>$evercisegroupId, 'date_time'=>$classdatetime->classDatetimeSlot, 'price'=>$classinfo->classInfoPrice, 'duration'=>$classinfo->classInfoDuration )); $payment = Sessionpayment::create([ 'user_id'=>$evercisegroup->user_id, 'evercisesession_id'=>$session->id, 'total'=>0, 'total_after_fees'=>0, 'commission'=>0, 'processed'=>1, ]); $migrateGroups = DB::table('migrate_sessions')->insert(['classDatetimeId' => $classdatetime->classDatetimeId, 'evercisesession_id' => $session->id]); } else { $this->command->info('Cannot find evercisegroup. id: '.$evercisegroupId.', classinfo id: '.$classdatetime->classInfoId); } } } } }<file_sep>/app/composers/UserEditComposer.php <?php namespace composers; use JavaScript; use User; class UserEditComposer { public function compose($view) { $viewdata = $view->getData(); // grab all view data including shared $user = $viewdata['user']; $firstName = $user->first_name; $lastName = $user->last_name; $dob = $user->dob != '0000-00-00 00:00:00' ? $user->dob : ''; $email = $user->email; $gender = $user->gender; $area_code = $user->area_code; $phone = $user->phone; $markPref = User::find($user->id)->marketingpreferences()->where('name', 'newsletter')->first()['option']; JavaScript::put( [ 'initImage' => json_encode(['ratio' => 'user_ratio']) ] ); $view->with('firstName', $firstName) ->with('lastName', $lastName) ->with('dob', $dob) ->with('email', $email) ->with('gender', $gender) ->with('marketingPreference', $markPref) ->with('area_code', $area_code) ->with('phone', $phone); } }<file_sep>/app/controllers/PackagesController.php <?php class PackagesController extends \BaseController { public function index() { $packages = Packages::where('active', 1)->get(); $title = 'Fitness Packages | Evercise'; $desc = 'Get fit and stay active with an Evercise 5 class package and Save up to 30% and enjoy the VIP treatment with one of our 10 class packages.'; return View::make('v3.packages.index', compact('packages', 'title', 'desc')); } }<file_sep>/app/controllers/PagesController.php <?php /** * Class PagesController */ class PagesController extends \BaseController { /** * @var string */ protected $route_prefix_category = 'articles.category.'; /** * @var string */ protected $route_prefix_article = 'articles.article.'; private $articles; private $articleCategories; private $route; private $request; private $log; private $app; private $view; private $config; /** * @param Articles $articles * @param ArticleCategories $articleCategories * @param \Illuminate\Routing\Router $route * @param \Illuminate\Http\Request $request * @param \Illuminate\Log\Writer $log * @param \Illuminate\View\Factory $view * @param App $app */ public function __construct( Articles $articles, ArticleCategories $articleCategories, \Illuminate\Routing\Router $route, \Illuminate\Http\Request $request, \Illuminate\Log\Writer $log, \Illuminate\View\Factory $view, \Illuminate\Config\Repository $config, App $app ) { parent::__construct(); $this->articles = $articles; $this->articleCategories = $articleCategories; $this->route = $route; $this->request = $request; $this->log = $log; $this->app = $app; $this->view = $view; $this->config = $config; } /** CACHE THIS SUCKER */ public function generateRoutes() { /** Category Routes */ $categories = $this->articleCategories->all(); $cat = []; foreach ($categories as $c) { $cat[$c->id] = $c; if(is_null($c->permalink)) { continue; } $this->route->get($c->permalink, ['as' => $this->route_prefix_category . $c->id, 'uses' => 'PagesController@showCategory']); } /** Articles Routes */ $articles = $this->articles->all(); foreach ($articles as $a) { $this->route->get($this->articles->createUrl($a), ['as' => $this->route_prefix_article . $a->id, 'uses' => 'PagesController@showPage']); } } /** * @param $object * @return bool */ private function hasAccess($object) { if ($object instanceof Articles) { if ($object->status == 1) { return true; } if ($this->user && $this->user->hasAccess('admin')) { return true; } } if ($object instanceof ArticleCategories) { if ($object->status == 1) { return true; } if ($this->user && $this->user->hasAccess('admin')) { return true; } } return false; } /** * @param string $type * @return bool|\Illuminate\Support\Collection|static */ public function getObject($type = 'article') { $name = $this->route->currentRouteName(); $object = false; switch ($type) { case 'article': $article_id = str_replace($this->route_prefix_article, '', $name); $object = $this->articles->find($article_id); break; case 'category': $category_id = str_replace($this->route_prefix_category, '', $name); $object = $this->articleCategories->find($category_id); break; } if (!$object) { $this->log->error('NO URL FOUND ' . $this->request->url()); $this->app->abort(404); } return $object; } /** * */ public function index() { return $this->showBlog(); } /** * @return string */ public function showBlog() { $page = Input::get('page', 1); /** Articles */ $articles = $this->articles->where('status', 1)->where('page', 0)->orderBy('id', 'desc')->paginate(5); /** Articles Latest*/ $articles_latest = $this->articles->where('status', 1)->where('page', 0)->orderBy('id', 'desc')->limit(5)->get(); /** Categories */ $categories = $this->articleCategories->where('status', 1)->get(); $metaDescription = $this->config->get('evercise.blog.description'); $title = $this->config->get('evercise.blog.title'); $keywords = $this->config->get('evercise.blog.keywords'); return $this->view->make('v3.pages.index', compact('articles', 'categories', 'metaDescription', 'title', 'keywords', 'articles_latest'))->render(); } /** * @return \Illuminate\Http\RedirectResponse|string */ public function showCategory() { $category = $this->getObject('category'); if (!$this->hasAccess($category)) { /** Redirect Temporary to blog.. until we figure out what to do here */ return Redirect::route('blog', 307)->with('message', 'You don\'t have access to that page!'); } $articles = $this->articles->where('category_id', $category->id)->get(); /** Articles Latest*/ $articles_latest = $this->articles->where('status', 1)->where('page', 0)->orderBy('id', 'desc')->limit(5)->get(); /** Categories */ $categories = $this->articleCategories->where('status', 1)->get(); return $this->view->make('v3.pages.category', compact('articles', 'category', 'articles_latest', 'categories')); } /** * @return \Illuminate\View\View */ public function showPage() { $article = $this->getObject('article'); if (!$this->hasAccess($article)) { /** Redirect Temporary to blog.. until we figure out what to do here */ return Redirect::route('blog', 307)->with('message', 'You don\'t have access to that page!'); } $article->content = Shortcode::compile($article->content); $view = 'v3.pages.single'; if(!empty($article->template)) { $view = 'v3.pages.'.$article->template; } /** Articles Latest*/ $articles_latest = $this->articles->where('status', 1)->where('page', 0)->orderBy('id', 'desc')->limit(5)->get(); /** Categories */ $categories = $this->articleCategories->where('status', 1)->get(); $metaDescription = $article->description; $title = (!empty($article->meta_title) ? $article->meta_title : $article->title); $keywords = $article->keywords; $canonical = $this->articles->createUrl($article, true); return $this->view->make($view, compact('article', 'categories', 'metaDescription', 'title', 'keywords', 'articles_latest', 'categories', 'canonical')); } }<file_sep>/app/models/Token.php <?php /** * Class Token */ class Token extends \Eloquent { /** * @var array */ protected $fillable = array('id', 'user_id', 'facebook', 'twitter'); /** * The database table used by the model. * * @var string */ protected $table = 'tokens'; /** * Add Token * * @param $name * @param $token */ public function addToken($name, $token) { $tokenJSON = json_encode($token); if (!$this->attributes[$name]) { $milestone = Milestone::where('user_id', $this->attributes['user_id'])->first(); $milestone->add($name); } $this->update([$name => $tokenJSON]); } /** * Create Facebook Token * * @param $getUser * @return array */ public static function makeFacebookToken($getUser) { $facebookTokenArray = [ 'id' => $getUser['user_profile']['id'], 'access_token' => $getUser['access_token'] ]; return $facebookTokenArray; } public function hasValidFacebookToken() { return (!empty($this->facebook) ? true : false); } public function hasValidTwitterToken() { return (!empty($this->twitter) ? true : false); } public static function createIfDoesntExist($user_id) { if (static::where('user_id', $user_id)->first()) return false; $token = static::firstOrCreate([ 'user_id'=>$user_id, ]); return $token; } }<file_sep>/app/database/seeds/MilestonesTableSeeder.php <?php class MilestonesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('milestones')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Milestone::create(array('user_id' => '1')); } }<file_sep>/app/models/TransactionItems.php <?php class TransactionItems extends Eloquent { protected $table = 'transaction_items'; protected $fillable = ['id', 'user_id', 'transaction_id', 'type', 'sessionmember_id', 'package_id', 'amount', 'name', 'final_price']; /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function transaction() { return $this->belongsTo('Transactions', 'transaction_id'); } public function sessionmember() { return $this->belongsTo('Sessionmember', 'sessionmember_id'); } public function package() { return $this->belongsTo('Packages', 'package_id'); } }<file_sep>/app/controllers/ajax/UploadController.php <?php namespace ajax; use Sentry; use Illuminate\Http\Request; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; use Illuminate\Validation\Factory as Validator; use Intervention; use VenueImages; use Venue; use Illuminate\Config\Repository; use Illuminate\Support\Facades\Response; use Intervention\Image\ImageManager; class UploadController extends AjaxBaseController { private $config; private $file; private $request; private $string; private $response; private $validator; private $image; private $venue; private $venueImages; private $sentry; private $data = []; private $user; public function __construct( Filesystem $file, Request $request, VenueImages $venueImages, Venue $venue, Repository $config, Str $string, Response $response, Validator $validator, ImageManager $image ) { $this->file = $file; $this->request = $request; $this->venue = $venue; $this->venueImages = $venueImages; $this->image = $image; $this->config = $config; $this->string = $string; $this->response = $response; $this->validator = $validator; $this->user = Sentry::getUser(); } /** TO DO */ public function hasPermissions($object, $type = 'venue') { if ($this->user->hasAccess('admin')) { return true; } switch ($type) { case 'venue': if ($object->user_id == $this->user->id) { return true; } break; } return false; } /** * Upload Images for Venues * * @return string */ public function uploadVenueImage() { $id = $this->request->get('venue_id'); $venue = $this->venue->find($id); $user = $venue->user()->first(); if (!$this->hasPermissions($venue)) { $this->data = [ 'error' => true, 'messages' => 'You don\'t have permissions to upload photos for this venue' ]; return $this->response->json($this->data); } $file = $this->request->file('file'); $validator = $this->validator->make( $this->request->except('_token'), [ 'venue_id' => 'required|numeric', 'file' => 'mimes:jpeg,gif,png,bmp,tiff' ]); if ($validator->fails()) { $this->data = [ 'error' => true, 'messages' => $validator->messages() ]; /** Send back the Errors */ return $this->response->json($this->data); } else { /** Required Image Sizes */ $sizes = $this->config->get('evercise.venue_images'); /** HashDirectory of the new gallery */ $folder = $user->directory; /** New Slug for the Image */ $slug = $this->string->slug(implode(' ', [$venue->name, $venue->town, $venue->postcode, rand(1, 300)])); $file_name = $slug . '.' . $file->getClientOriginalExtension(); $thumb_file_name = $slug . '.' . 'thumb_' . $slug . '.' . $file->getClientOriginalExtension(); /** Save the files to the server */ $this->file->put($folder . '/' . $file_name, $this->image->make($file)->fit($sizes['regular']['width'], $sizes['regular']['height'])); $this->file->put($folder . '/' . $thumb_file_name, $this->image->make($file)->fit($sizes['thumb']['width'], $sizes['thumb']['height'])); $data = [ 'venue_id' => $venue->id, 'file' => $folder . '/' . $file_name, 'thumb' => $folder . '/' . $thumb_file_name ]; $image = $this->venueImages->create($data); return $image->toJson(); } } public function deleteVenueImage() { $image_id = $this->request->get('image_id'); $validator = $this->validator->make( $this->request->except('_token'), [ 'image_id' => 'required|numeric' ] ); if ($validator->fails()) { $this->data = [ 'error' => true, 'messages' => 'We need a Image ID' ]; return $this->response->json($this->data); } $venueImage = $this->venueImages->find($image_id); $venue = $this->venue->find($venueImage->venue_id); if (!$this->hasPermissions($venue)) { $this->data = [ 'error' => true, 'messages' => 'You don\'t have permissions to upload photos for this venue' ]; return $this->response->json($this->data); } if ($this->file->delete($venueImage->file)) { $this->file->delete($venueImage->thumb); $venueImage->delete(); return $this->response->json(['message' => 'Image deleted', 'id' => $image_id]); } $this->data = [ 'error' => true, 'messages' => 'We could not delete the image ' . $venueImage->file ]; return $this->response->json($this->data); } public function uploadCover() { return $this->upload('class_images'); } public function uploadProfilePicture() { return $this->upload('user_images'); } private function upload($type) { $validator = $this->validator->make( $this->request->except('_token'), [ 'x' => 'required|numeric', 'y' => 'required|numeric', 'width' => 'required|numeric', 'height' => 'required|numeric', 'box_width' => 'required|numeric', 'box_height' => 'required|numeric', 'file' => 'required|mimes:jpeg,gif,png' ] ); /** Did it faiL? */ if ($validator->fails()) { $this->data = [ 'error' => true, 'messages' => $validator->messages() ]; return $this->response->json($this->data); } $upload_file = $this->request->file('file'); $user_id = $this->request->get('user_id', $this->user->id); $user = Sentry::findUserById($user_id); $file = $this->image->make($upload_file->getRealPath()); $sizes = $this->config->get('evercise.'.$type); $folder = $user->directory; /**Calculate the crop ration based on the original image */ $crop_width = $this->request->get('width'); $crop_height = $this->request->get('height'); /**Crop locations calculate */ $crop_x = $this->request->get('x'); $crop_y = $this->request->get('y'); $image = $file->crop((int)$crop_width, (int)$crop_height, (int)$crop_x, (int)$crop_y); /** New Slug for the Image */ $slug = slugIt($user->display_name); $file_name = false; foreach($sizes as $s) { if(!$file_name) { $file_name = uniqueFile(public_path() . '/' . $folder . '/', $s['prefix'] . '_' . $slug, $upload_file->getClientOriginalExtension()); $real_name = str_replace($s['prefix'] . '_', '', $file_name); } $file_name = $s['prefix'].'_'.$real_name; $image->fit($s['width'], $s['height'])->save(public_path() . '/' . $folder . '/'.$file_name); } // If file has been temporarily uploaded with uploadWithoutCrop(), // then the name of the temporary upload will be sent through to be deleted here. $deleted = 'none'; if($this->request->has('deletion')) { $deletion = $this->request->get('deletion'); if( file_exists( $deletion ) ) { unlink( $deletion ); $deleted = $deletion; } } return $this->response->json(['file' => $folder . '/' . $real_name, 'filename' => $real_name, 'folder' => $folder, 'deleted' => $deleted]); } public function uploadWithoutCrop() { $validator = $this->validator->make( $this->request->except('_token'), [ 'file' => 'required|mimes:jpeg,gif,png' ] ); /** Did it faiL? */ if ($validator->fails()) { $this->data = [ 'error' => true, 'messages' => $validator->messages() ]; return $this->response->json($this->data); } $upload_file = $this->request->file('file'); $user_id = $this->request->get('user_id', $this->user->id); $user = Sentry::findUserById($user_id); $file = $this->image->make($upload_file->getRealPath()); $folder = $user->directory; /** New Slug for the Image */ $slug = slugIt($user->display_name); $file_name = uniqueFile(public_path() . '/' . $folder . '/', 'temp_'.$slug, $upload_file->getClientOriginalExtension()); //$image = $file->crop(100, 100, 0, 0); $file->save(public_path() . '/' . $folder . '/'.$file_name); return $this->response->json(['file' => $folder . '/' . $file_name, 'filename' => $file_name, 'folder' => $folder]); } /** * @param string $file * @param array $params * @return bool|string * * $ajax = App::make('ajax\UploadController'); die($ajax->renameFile('files/gallery/61/35/thumb_igor-matkovic-72.JPG', ['some'=> 'param', 'name' => 'what is this lololo', 'car'=>'tetstet'])); */ public function renameFile($file = '', array $params = []) { if (!empty($file) && count($params) > 0) { $new_file = substr(Str::slug(implode(' ', array_values($params))), 0, 40); $ext = pathinfo($file); if (!empty($ext['extension'])) { $new_file = $ext['dirname'] . '/' . $new_file . '.' . $ext['extension']; try { rename($file, $new_file); return $new_file; } catch (\Exception $e) { return false; } } } return false; } }<file_sep>/README.md # Evercise Setup ================================================== To set up Evercise on your local machine you need to do the following: Duplicate Example.env.php and name it: .env.php Update composer ```bash composer update --prefer-dist -vvv ``` Edit the contents of that file to match your setup! Reset your DB ```bash php artisan migrate:reset ``` When done open terminal and migrate Sentry ```bash php artisan migrate --package=cartalyst/sentry ``` When Sentry is migrated you can migrate and seed the rest of the DB ```bash php artisan migrate && php artisan db:seed ``` Set the correct permissions for your app (if you are in a local enviroment just 777 on it) ```bash chmod 777 -R app/storage/* ``` If you don't want to set 777 then just allow apache (or what ever user is running it) to be the $user:$group of the folder ```bash chmod apache:apache -R app/storage/* ``` # Evercise Vagrant ================================================== ## Dependencies https://www.virtualbox.org/wiki/Downloads http://www.vagrantup.com/downloads.html ## Setup In you local setup first update the .env.php to look like this: ```php return [ 'DEBUG_APP' => true, 'APP_URL' => 'http://dev.evercise.com/', 'ENCRYPTION_KEY' => '<KEY>', 'ASSETS_CACHE' => true, //DB LIVE 'DB_HOST' => 'localhost', 'DB_NAME' => 'evercise', 'DB_USER' => 'root', 'DB_PASS' => '', //DB MIGRATION 'DB_V1_HOST' => 'localhost', 'DB_V1_NAME' => 'evercise_v1', 'DB_V1_USER' => 'root', 'DB_V1_PASS' => '', //EMAIL SETUP 'EMAIL_DRIVER' => 'smtp', 'EMAIL_SMTP_HOST' => '127.0.0.1', 'EMAIL_SMTP_PORT' => 1025, 'EMAIL_FROM_ADDRESS' => '<EMAIL>', 'EMAIL_FROM_NAME' => 'Evercise', 'EMAIL_SMTP_ENCRYPTION' => '', 'EMAIL_SMTP_USERNAME' => '<EMAIL>', 'EMAIL_SMTP_PASSWORD' => '', 'EMAIL_SENDMAIL' => '/usr/sbin/sendmail -bs', 'EMAIL_PRETEND' => false, //For Production Set to False //Facebook Data 'FACEBOOK_ID' => '306418789525126', 'FACEBOOK_SECRET' => '<KEY>' ]; ``` Then Run: ```bash vagrant up ``` When the machine boots. And you notice the page is loading slowly. You should enable: I/O APIC Located in the Settings/System of the Virtual Machine that you are using ![Setup](https://www.dropbox.com/s/c9v36501zoqbc35/Screen%20Shot%202014-08-27%20at%209.46.26%201.png?dl=1) After that open your command line and go to the project root # How to ADD a new domain or site ================================================== ## Auto In the Server files you have a .sh file: scripts/server.sh For example we want to add a new site called dev.mysite.com and its located in the folder mysite First in your hosts file add the new domain and point to the machine IP In my case it would look like this: ```bash 192.168.10.10 dev.mysite.com ``` Log into the Vagrant server. Lets assume that your project files are located like this: ```bash /home/vagrant/html ``` and your new site is located: ```bash /home/vagrant/html/mysite ``` Now to set it up just run the command: ```bash sudo sh scripts/serve.sh dev.mysite.com /home/vagrant/html/mysite/public ``` Notice it has public at the end. Now the site will be created automatically in Nginx/Sites Available and linked to the enabled sites. Nginx and PHP will be restarted so it should work instantly <file_sep>/app/database/seeds/UsersTableSeeder.php <?php class UsersTableSeeder extends Seeder { public function run() { /* DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('users')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1');*/ $users = DB::connection('mysql_import')->table('user')->get(); foreach ($users as $user) { if( true/*strpos($user->Upassword, '$') === 0*/ ) { if($user->Ufullname) { $exn = explode(" ", $user->Ufullname); $fn = $exn[0]; $ln = explode($fn, $user->Ufullname)[1]; }else { $fn = $ln = null; } if(!User::where('email', $user->Uemail)->first()) { try { $displayName = str_replace(' ', '_', $user->Uname); $newUser = Sentry::getUserProvider()->create(array( 'email' => $user->Uemail, 'password' => $<PASSWORD>, 'activated' => 1, 'activation_code' => '', 'activated_at' => $user->UsignTime, 'last_login' => date('Y-m-d H:i:s'), 'persist_code' => null, 'reset_password_code' => null, 'first_name' => $fn, 'last_name' => $ln, 'display_name' => $displayName, 'gender' => $user->Usex ? $user->Usex : 0, 'dob' => $user->UDateOfBirth, 'area_code' => '', 'phone' => $user->Uphone, 'directory' => '', 'image' => '', )); $userGroup = Sentry::findGroupById(1); $newUser->addGroup($userGroup); } catch (UserExistsException $e) { $this->command->info('user exists'); } catch (Exception $e) { $this->command->info('Cannot make User in DB. '.$e); } try { $newUserRecord = User::find($newUser->id); $newUserRecord->makeUserDir(); $newUserRecord->save(); } catch (Exception $e) { $this->command->info('cannot make User Dir '.$e); exit; } try { /* $this->command->info($user->UheadImageAddress); exit;*/ if (strpos($user->UheadImageAddress,'https://graph.facebook.com') !== false) { $imageName = 'facebookimage.jpg'; $url = $user->UheadImageAddress .$user->UheadImageName; $newUserRecord->update(['image'=> $imageName]); $this->command->info('FACEBOOK IMAGE'); //exit; } else { $imageName = $user->UheadImageName; $url = 'http://evercise.com/'.$user->UheadImageAddress.'/'.$imageName; $newUserRecord->update(['image'=> $imageName]); } //$this->command->info('retrieving image: '.$url); $savePath = public_path().'/profiles/'.$newUserRecord->directory.'/'.$imageName; //$this->command->info('saving image: '.$savePath); try { $img = file_get_contents($url); file_put_contents($savePath, $img); }catch (Exception $e) { // This exception will happen from localhost, as pulling the file from facebook will not work $this->command->info('Cannot save image: '.$savePath); } Evercoin::create(['user_id'=>$newUserRecord->id, 'balance'=>0]); Milestone::create(['user_id'=>$newUserRecord->id]); Token::create(['user_id'=>$newUserRecord->id]); } catch (Exception $e) { $this->command->info('Cannot make User. '.$e); //exit; } } } } } }<file_sep>/app/database/migrations/2014_10_17_095107_create_articles.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateArticles extends Migration { /** * Run the migrations. * * @return void */ public function up() { self::down(); Schema::create( 'articles', function (Blueprint $table) { $table->increments('id'); $table->smallInteger('page')->default(0)->unsigned(); $table->integer('category_id')->default(0)->unsigned(); $table->string('title', 255); $table->string('main_image', 255); $table->string('description', 500); $table->string('intro', 500); $table->string('keywords', 500); $table->text('content'); $table->string('permalink', 255); $table->string('template', 255); $table->smallInteger('status')->default(0)->unsigned(); $table->timestamp('published_on'); $table->timestamps(); } ); Schema::create( 'article_categories', function (Blueprint $table) { $table->increments('id'); $table->integer('parent_id')->default(0)->unsigned(); $table->string('title', 255); $table->string('main_image', 255); $table->string('description', 500); $table->string('keywords', 500); $table->string('permalink', 255); $table->smallInteger('status')->default(1)->unsigned(); $table->timestamps(); } ); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('articles'); Schema::dropIfExists('article_categories'); } } <file_sep>/app/commands/CheckSessions.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; // php artisan check:sessions class CheckSessions extends Command { /** * The console command name. * * @var string */ protected $name = 'check:sessions'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $days = $this->option('days'); $this->info('checking for sessions in the last '.$days.' day'.($days!=1?'s':'')); $today = new DateTime('now'); $yesterday = (new DateTime('now'))->sub(new DateInterval('P'.$days.'D')); $sessions = Evercisesession::where('date_time', '<', $today) ->where('date_time', '>', $yesterday ) ->has('sessionpayment', 0) ->with('evercisegroup') ->with('sessionmembers') ->with('sessionpayment') ->get(); /*$session_ids = []; foreach ($sessions as $key => $session) { $session_ids[] = $session->id; }*/ //$sessionPayments = Sessionpayment::whereNotIn($session_ids)->get(); foreach ($sessions as $s_key => $session) { $this->info('session: group['.$session->evercisegroup_id.'] --> '. $session->id.' : '); $commission = 10.00; // In % $user = User::find($session->evercisegroup->user_id); if($user->custom_commission > 0) { $commission = $user->custom_commission; } //Adjust code for hte old percentage $commission = $commission/100; $total = count($session->sessionmembers) * $session->price; $totalAfterFees = $total * (1.00 - $commission); // If the session has members, and a sessionpayment has not already been created, create a sessionpayment if (count($session->sessionmembers) && count($session->sessionpayment)==0) { $this->info(' ... adding payment of '.$total.' minus '.($commission*100).'% commission = '.$totalAfterFees.', user: '.$session->evercisegroup->user_id); /* foreach ($session->sessionmembers as $m_key => $member) { $this->info(' ...member... '. $member->user_id); }*/ $payment = Sessionpayment::create([ 'user_id'=>$session->evercisegroup->user_id, 'evercisesession_id'=>$session->id, 'total'=>$total, 'total_after_fees'=>$totalAfterFees, 'commission'=>$commission, 'processed'=>0, ]); } } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('days', null, InputOption::VALUE_OPTIONAL, 'How many days to search back.', 1), ); } } <file_sep>/public/assets/jsdev/prototypes/8-cart.js function Cart(cart) { this.cart = cart; this.form = ''; this.maxQty = '2000'; this.addListeners(); if($('.checkout').length){ this.step = 0; this.viewPrice = VIEWPRICE; this.checkout(); } } Cart.prototype = { constructor: Cart, addListeners: function(){ $(document).on('submit', '#empty-cart', $.proxy(this.submit, this)); $(document).on('submit', '.remove-row', $.proxy(this.submit, this)); $(document).on('submit', '.add-to-class', $.proxy(this.submit, this)); $(document).on('change', '.btn-select', $.proxy(this.changeSelectDropdown, this)); $(document).on('click', '.toggle-select .switch a', $.proxy(this.switchQty, this)); $(document).on('click','#stripe-button' ,$.proxy(this.openStripe, this)); $(window).on('popstate', $.proxy(this.closeStripe, this)); $(document).on('change', 'select[name="quantity"]', $.proxy(this.selectQty, this)); }, changeSelectDropdown: function(e){ if($(e.target).hasClass('qty-select') ){ this.selectQty(e); } if($(e.target).hasClass('select-box') ){ $(e.target).closest('.add-to-class').trigger('submit'); } else if( $(e.target).val() ){ $(e.target).css('z-index', 1); $(e.target).closest('.add-to-class').trigger('submit'); }else{ $(e.target).css('z-index', 0); } }, switchQty: function(e){ e.preventDefault(); e.stopPropagation(); var toggle = $(e.target).closest('.toggle-select'); this.maxQty = $(toggle).data('qty'); var trigger = $(toggle).data('trigger'); var type = $(e.target).attr('href').substring(1); var currentQty = $(toggle).find('#toggle-quantity').val(); if(type == 'plus'){ if(currentQty < this.maxQty){ var qty = Math.max(parseInt(currentQty ) + 1) $(toggle).find('#toggle-quantity').val( qty ); $(toggle).find('#qty').text( qty ); } } else{ if(currentQty > 1){ var qty = Math.max(parseInt(currentQty ) - 1) $(toggle).find('#toggle-quantity').val( qty ); $(toggle).find('#qty').text( qty ); } } if(trigger){ $(e.target).closest('.add-to-class').trigger('submit'); } }, selectQty : function(e){ var qty = $(e.target).val(); $(e.target).closest('.qty-wrapper').find('.qty-select').val(qty); }, submit: function(e){ e.preventDefault(); e.stopPropagation(); this.form = $(e.target); this.ajaxSubmit(); }, ajaxSubmit: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { if(self.form.find('select[name="quantity"]') ){ self.form.find('select[name="quantity"]').parent().addClass('disabled'); } if(self.form.find('input[type="submit"]').hasClass('add-btn') ){ self.form.find("input[type='submit']").prop('disabled', true); } else{ self.form.find("input[type='submit']").replaceWith('<span id="cart-loading" class="icon icon-loading"></span>'); } console.log($('.checkout .mask').length); if($('.checkout .mask').length){ $('.mask').removeClass('hidden'); } self.form.find(".switch").addClass('disabled'); }, success: function (data) { if(data.view){ self.updateCart(data); if($('.checkout .mask').length){ $('.checkout .mask').addClass('hidden'); } } else if(data.refresh){ location.reload(); } else if(data.validation_failed == 1){ self.failedValidation(data); if($('.mask').length){ $('.mask').addClass('hidden'); } } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type=submit]").prop('disabled', false); $('#cart-loading').remove(); self.form.find(".switch").removeClass('disabled'); } }); }, updateCart: function(data){ $('.cart-dropdown:visible').addClass('open'); $('.cart-dropdown.open .dropdown-cart').replaceWith(data.view); $('.cart-items').html(data.items); }, failedValidation: function(data){ $('body').append('<div class="mt10 alert alert-danger alert-dismissible fixed" >'+data.errors.custom+'<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button></div>'); }, checkout: function(){ this.newUserForm = $('.checkout #new-user-form'); this.loginForm = $('.checkout .login-form'); this.userType = 'new'; var self = this; $('#step-2').on('shown.bs.collapse', function (e) { var t = $(e.target).attr('id'); $('a[href="#'+t+'"]').addClass('hidden'); $('#step-1').find('.switch-cart').addClass('hidden'); $('#step-1').find('.switch-back').removeClass('hidden'); $('.cart-progress').find('#progress-2').addClass('complete'); }); $(document).on('change', ':checkbox', function(e){ var name = $(e.target).attr('name'); $(':checkbox').prop("checked", false); $('input[name="'+name+'"]').prop("checked", true); self.userType = name; if(self.userType == 'ps'){ $('input[name="password"]').focus(); } }) $(document).on('keyup', self.loginForm.find('input[name="email"]') , function(e){ self.newUserForm.find('input[name="email"]').val($(e.target).val()) }) $(document).on('click', '#cart-account', function(e){ e.preventDefault(); if(self.userType == 'new'){ self.newUserForm.trigger('submit'); } else{ this self.loginForm.trigger('submit'); } }) $(document).on( 'submit','.checkout #new-user-form', $.proxy(this.newUser,this)); }, openStripe: function(e){ var self = this; // Open Checkout with further options handler.open({ name: 'Evercise', description: 'Checkout', amount: self.viewPrice }); e.preventDefault(); }, closeStripe: function(e){ handler.close(); }, newUser : function(e){ e.preventDefault(); var self = this; self.newUserForm.find('input[name="email"]').val( self.loginForm.find('input[name="email"]').val()); $.ajax(self.newUserForm.attr("action"), { type: "post", data: self.newUserForm.serialize(), dataType: 'json', beforeSend: function () { $('.has-error').removeClass('has-error'); $('.error-append').remove() self.newUserForm.find("input[type='submit']").prop('disabled', true); }, success: function (data) { if( data.validation_failed == 1 ){ self.failedValidation(data); } else{ location.reload(); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.newUserForm.find("input[type=submit]").prop('disabled', false); } }); }, failedValidation : function(data){ var self = this; var arr = data.errors; $.each(arr, function(index, value) { self.loginForm.find('input[name="' + index + '"]').parent().addClass('has-error').after('<div class="form-control input-lg input-group has-error error-append">' + value + '</div>'); }) } } <file_sep>/app/controllers/admin/AdminAjaxController.php <?php /** * Class AdminAjaxController * @property Elastic elastic */ class AdminAjaxController extends AdminController { /** * @var Evercisegroup */ private $evercisegroup; /** * @var \Illuminate\Http\Request */ private $input; /** * @var \Illuminate\Log\Writer */ private $log; /** * @var Es */ private $elasticsearch; /** * @var Geotools */ private $geotools; /** * @var */ private $elastic; /** * */ public function __construct( Evercisegroup $evercisegroup, Illuminate\Http\Request $input, Illuminate\Log\Writer $log, Es $elasticsearch, Geotools $geotools ) { parent::__construct(); $this->evercisegroup = $evercisegroup; $this->input = $input; $this->log = $log; $this->elasticsearch = $elasticsearch; $this->geotools = $geotools; } /** * @return \Illuminate\Http\JsonResponse */ public function searchStats() { $this->elastic = new Elastic( Geotools::getFacadeRoot(), $this->evercisegroup, Es::getFacadeRoot(), $this->log ); $response = ['draw' => $this->input->get('draw')]; $search = $this->input->get('search'); $from = $this->input->get('start', 0); $size = $this->input->get('lenght', 50); $results = $this->elastic->searchStats(['size' => $size, 'from' => $from, 'search' => $search['value']]); $response['recordsTotal'] = $results->total; $response['recordsFiltered'] = $results->total; foreach ($results->hits as $r) { $response['data'][] = [ $r->_source->search, $r->_source->size, $r->_source->results, $r->_source->radius, $r->_source->user_id, $r->_source->name, $r->_source->date ]; } return Response::json($response); } /** * @return \Illuminate\Http\JsonResponse */ public function downloadStats() { $this->elastic = new Elastic( Geotools::getFacadeRoot(), $this->evercisegroup, Es::getFacadeRoot(), $this->log ); $response = ['draw' => $this->input->get('draw')]; $search = $this->input->get('search'); $from = $this->input->get('start', 0); $size = $this->input->get('length', 200000); $results = $this->elastic->searchStats(['size' => $size, 'from' => $from, 'search' => $search['value']]); $response['recordsTotal'] = $results->total; $response['recordsFiltered'] = $results->total; $rows = []; foreach ($results->hits as $r) { $rows[] = [ 'search' => $r->_source->search, 'size' => $r->_source->size, 'results' => $r->_source->results, 'user_id' => $r->_source->user_id, 'name' => $r->_source->name, 'date' => $r->_source->date ]; } $this->download_send_headers("search_stats_" . date("Y-m-d") . ".csv"); return $this->array2csv($rows); } public function importStatsToDB() { $this->elastic = new Elastic( Geotools::getFacadeRoot(), $this->evercisegroup, Es::getFacadeRoot(), $this->log ); $search = $this->input->get('search'); $from = $this->input->get('start', 0); $size = $this->input->get('length', 200000); $results = $this->elastic->searchStats(['size' => $size, 'from' => $from]); $rows = []; $allowed = [ 'search', 'size', 'user_id', 'user_ip', 'radius', 'url', 'url_type', 'name', 'lat', 'lng', 'results' ]; StatsModel::truncate(); $split = 1000; foreach ($results->hits as $r) { $row = []; foreach ($allowed as $key) { $row[$key] = $r->_source->{$key}; } $row['created_at'] = $r->_source->date; $rows[] = $row; if(count($rows) == $split) { StatsModel::insert($rows); $rows = []; } } StatsModel::insert($rows); DB::select( DB::raw("UPDATE search_stats set search = replace(search, '?utm_source=Google', '') WHERE 1") ); return Redirect::to('/admin/search/stats'); } public function download_send_headers($filename) { // disable caching $now = gmdate("D, d M Y H:i:s"); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("Last-Modified: {$now} GMT"); // force download header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); // disposition / encoding on response body header("Content-Disposition: attachment;filename={$filename}"); header("Content-Transfer-Encoding: binary"); } public function array2csv(array &$array) { if (count($array) == 0) { return NULL; } ob_start(); $df = fopen("php://output", 'w'); fputcsv($df, array_keys(reset($array))); foreach ($array as $row) { fputcsv($df, $row); } fclose($df); return ob_get_clean(); } /** * @return \Illuminate\Http\JsonResponse */ public function resetPassword() { $user = Sentry::findUserById(Input::get('user_id')); $reset_code = $user->getResetPasswordCode(); $user->sendForgotPasswordEmail($reset_code); return Response::json([ 'callback' => 'adminPopupMessage', 'message' => 'Password reset. Email:' . $user->email ]); } /** * @return \Illuminate\Http\JsonResponse */ public function ajaxCheckUrl() { $this->beforeFilter('csrf', ['on' => 'post']); $url = $this->request->get('url'); /** CHeck if the URL is in the articles */ $check = Articles::where('permalink', $url)->count(); if ($check > 0) { return Response::json(['error' => TRUE]); } /** CHeck if the URL is in the ArticleCategories */ $check = ArticleCategories::where('permalink', $url)->count(); if ($check > 0) { return Response::json(['error' => TRUE]); } return Response::json(['error' => FALSE]); } /** * @return \Illuminate\Http\JsonResponse */ public function addRating() { $result = FakeRating::validateAndCreateRating(); if ($result['validation_failed']) { return Response::json($result); } else { return Response::json(['callback' => 'successAndRefresh']); } } /** * @return \Illuminate\Http\JsonResponse */ public function editSubcategories() { $assNumbers = explode(',', Input::get('update_associations')); $editsubcategoryIds = explode(',', Input::get('update_categories')); $subcategoryChanges = []; foreach($editsubcategoryIds as $subcatId) { $subcategoryChanges[$subcatId] = Input::get('categories_'.$subcatId); } //return $subcategoryChanges; $type = Input::get('type', ''); $associations = []; foreach ($assNumbers as $assId) { array_push($associations, [$assId => Input::get('associations_' . $assId)]); } Subcategory::editSubcategoryCategories($subcategoryChanges); Subcategory::editAssociations($associations); Subcategory::editTypes($type); //return Response::json(['callback' => 'adminPopupMessage', 'message' => count($associations).' : '.Input::get('associations_'.'3')]); return Response::json(['callback' => 'successAndRefresh']); } public function updateCategories() { $order = explode(',',Input::get('order')); $cats = Category::get(); foreach ($cats as $cat) { $cat->visible = Input::get('visible_'.$cat->id); $cat->save(); } $newOrder = []; $count=0; foreach($order as $id) { $count++; $newOrder[$id] = $count; } Category::editOrder($newOrder); //return $visibleSettings; return Response::json(['callback' => 'successAndRefresh']); } public function updateCategory() { $id = Input::get('id'); if(! $id) return false; $name = Input::get('name'); $description = Input::get('description'); $popularGroups = Input::get('popular_groups'); $popularSubcats = Input::get('popular_subcategories'); $popularGroupsCSV = $popularGroups ? implode(',', $popularGroups) : ''; $popularSubcatsCSV = $popularSubcats ? implode(',', $popularSubcats) : ''; $category = Category::find($id); $category->name = $name; $category->description = $description; $category->popular_classes = $popularGroupsCSV; $category->popular_subcategories = $popularSubcatsCSV; $category->save(); return Redirect::route('admin.categories'); } /** * @return \Illuminate\Http\JsonResponse */ public function addSubcategory() { $newCategoryName = Input::get('new_subcategory'); Subcategory::create(['name' => $newCategoryName]); return Response::json(['callback' => 'successAndRefresh']); } /** * @return \Illuminate\Http\JsonResponse */ public function unapproveTrainer() { $user = Sentry::findUserById(Input::get('user_id')); Trainer::unapprove($user); return Response::json(['callback' => 'successAndRefresh']); } /** * @return \Illuminate\Http\JsonResponse */ public function deleteSubcategory() { $id = Input::get('id', FALSE); if ($id) { $data = DB::table('evercisegroup_subcategories')->where('subcategory_id', $id)->delete(); DB::table('subcategories')->where('id', $id)->delete(); return Response::json(['success' => TRUE, 'id' => $id]); } return Response::json(['success' => FALSE, 'id' => $id]); } /** * @return \Illuminate\Http\JsonResponse */ public function editGroupSubcats() { $groupIds = explode(',', Input::get('update_categories')); $groupSubcats = []; foreach ($groupIds as $groupId) { array_push($groupSubcats, [$groupId => Input::get('categories_' . $groupId)]); if ($eg = Evercisegroup::find($groupId)) { $eg->adminMakeClassFeatured(Input::get('featured_' . $groupId)); } } Evercisegroup::editSubcats($groupSubcats); return Response::json(['callback' => 'successAndRefresh']); } /** * @return \Illuminate\Http\JsonResponse */ public function saveTags() { $tags = implode(',', Input::get('tags', [])); $id = Input::get('id'); Gallery::where('id', $id)->update(['keywords' => $tags]); return Response::json(['saved' => TRUE]); } /** * @return \Illuminate\Http\JsonResponse */ public function deleteGalleryImage() { $id = Input::get('id'); $gallery = Gallery::find($id); if (!empty($gallery->id)) { @unlink('files/gallery_defaults/' . $gallery->image); $gallery->delete(); } return Response::json(['deleted' => 'true', 'id' => $id]); } /** * @return bool|string */ public function galleryUploadFile() { if ($file = Request::file('file')) { if (!is_dir('files/gallery_defaults')) { mkdir('files/gallery_defaults'); } $name = 'g_' . rand(1, 1000) . '-' . $file->getClientOriginalName(); /** Save the image name without the Prefix to the DB */ $save = FALSE; foreach (Config::get('evercise.gallery.sizes') as $img) { $file_name = $img['prefix'] . '_' . $name; $image = Image::make($_FILES['file']['tmp_name'])->fit( $img['width'], $img['height'] )->save(public_path() . '/files/gallery_defaults/' . $file_name); if ($image) { $save = TRUE; } } if ($save) { Gallery::create(['image' => $name, 'counter' => Config::get('evercise.gallery.image_counter', 3)]); return '/files/gallery_defaults/thumb_' . $name; } } return FALSE; } /** * @return \Illuminate\Http\JsonResponse * @throws Exception */ public function featureClass() { $id = $this->input->get('id'); $class = $this->evercisegroup->find($id); if ($class->isFeatured()) { FeaturedClasses::where('evercisegroup_id', $id)->delete(); event('class.index.single', [$id]); return Response::json(['featured' => FALSE]); } FeaturedClasses::create(['evercisegroup_id' => $id]); event('class.index.single', [$id]); return Response::json(['featured' => TRUE]); } /** * */ public function sliderStatus() { $id = Input::get('id'); $checked = Input::get('checked', 'true'); $slider = Slider::where(['evercisegroup_id' => $id])->first(); if ($checked == 'true') { $slider->active = 1; } else { $slider->active = 0; } return $slider->save(); } public function setClassImage() { $class_id = Input::get('class_id'); $image_id = Input::get('image_id'); $class = Evercisegroup::find($class_id); $save_image = Gallery::selectImage($image_id, $class->user, $class->name); $class->image = $save_image; $class->save(); event('class.index.single', [$class->id]); return Response::json(['ok' => '1']); } public function deleteClass() { $id = Input::get('id'); $evercisegroup = Evercisegroup::with('evercisesession.sessionmembers')->find($id); if (!$evercisegroup) { return Response::json(['deleted' => FALSE, 'message' => 'No Evercise group found. Refresh page!']); } $deleted = $evercisegroup->adminDeleteIfNoSessions(); event('class.index.single', [$id]); return Response::json([ 'deleted' => $deleted, 'message' => ($deleted ? 'Class Deleted' : 'Please delete Class Sessions first and then you can delete classes') ]); } /** * @return \Illuminate\Http\RedirectResponse */ public function sliderUpload() { $class = Evercisegroup::find(Input::get('id')); if ($file = Request::file('file')) { if (!is_dir('files/slider')) { mkdir('files/slider'); } $image = Image::make($_FILES['file']['tmp_name']); $ext = $file->getClientOriginalExtension(); $name = slugIt([$class->id, $class->name]) . '.' . $ext; /** Save the image name without the Prefix to the DB */ $save = FALSE; foreach (Config::get('evercise.slider_images') as $img) { $file_name = $img['prefix'] . '_' . $name; $image = $image->fit( $img['width'], $img['height'] )->save(public_path() . '/files/slider/' . $file_name); if ($image) { $save = TRUE; } } if ($save) { $slide = Slider::firstOrNew(['evercisegroup_id' => $class->id]); $slide->image = $name; $slide->evercisegroup_id = $class->id; $slide->active = 1; $slide->save(); } } return Redirect::route('admin.listClasses'); } public function modalClassCategories($class_id = 0) { $evercisegroup = $this->evercisegroup->find($class_id); $subcategories_obj = $evercisegroup->subcategories()->get(); $subcategories = []; foreach ($subcategories_obj as $s) { $subcategories[$s->id] = TRUE; } $all_subs = Subcategory::orderBy('name', 'asc')->get(); $view = View::make('admin.modal.categories', compact('evercisegroup', 'subcategories', 'all_subs'))->render(); return Response::json(['view' => $view, 'error' => FALSE]); } public function saveClassCategories() { $class = $this->evercisegroup->find($this->input->get('class_id')); $categories = $this->input->get('cat'); if (strpos($categories, ',') !== FALSE) { $categories = explode(',', $categories); } else { $categories = [$categories]; } if ($class) { $class->subcategories()->detach(); if (count($categories) > 0) { $class->subcategories()->attach($categories); } } return Response::json(['res' => $class->subcategories()->get()->toArray(), 'error' => FALSE]); } public function runIndexer() { $indexer = App::make('events\Indexer'); return $indexer->indexAll(); } }<file_sep>/app/composers/PasswordComposer.php <?php namespace composers; class PasswordComposer { public function compose($view) { $view->with('confirmation', (isset($view->confirmation) ? $view->confirmation : false)); } }<file_sep>/app/lang/en/home.php <?php return [ 'main_header' => 'Lower your barrier to enjoy fitness classes', 'sub_header' => 'Flexible schedule and multiple options across London.', 'three_steps' => 'Get fit with Evercise in three simple steps:', 'featured_classes' => 'Featured Classes', 'register_text' => 'Join the Evercise community today and find<br>your way to a happier, fitter you...', ];<file_sep>/app/models/MilestoneRewards.php <?php /** * Class Milestone */ class MilestoneRewards extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'amount', 'message', 'status']; /** * @var string */ protected $table = 'milestone_rewards'; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } public static function clearUser($userId) { return static::where('user_id', $userId)->where('status', 0)->update(['status' => '1']); } public static function add($type, $amount, $user) { if (!$type || $amount == 0) { return FALSE; } $desc = FALSE; switch ($type) { case 'referral_signup': event('user.referral.signup', [$user, $amount, 'referralsignup']); $desc = 'Referral signup'; break; case 'ppc_signup': event('user.ppc.signup', [$user, $amount, 'ppcunique']); $desc = 'PPC Signup'; break; case 'static_ppc_signup': event('user.ppc.signup', [$user, $amount, 'ppcstatic']); $desc = 'Static PPC Signup'; break; case 'referral': event('user.referral.completed', [$user, $amount, 'referralcompleted']); $desc = 'Friend Referral'; break; case 'profile': $desc = 'Completed Profile'; break; case 'facebook': $desc = 'Connected Facebook account'; break; case 'twitter': $desc = 'Connected Twitter account'; break; case 'review': $desc = 'Wrote a review'; break; default: return FALSE; } if ($desc) { $reward = static::create([ 'amount' => round($amount, 2), 'message' => $desc, 'status' => 0, 'user_id' => $user->id ]); return TRUE; } return FALSE; } }<file_sep>/app/lang/en/how_it_works.php <?php return [ 'title' => 'How It Works', 'choose_user' => 'I am a participant', 'chooser_trainer' => 'I am a trainer', 'step_1_1' => 'Get fit with maximum flexibility', 'step_1_2' => 'Access a huge range of fitness classes', 'step_1_3' => 'Find a class wherever you are', 'step_1_4' => 'Join for FREE', 'step_2_1' => 'See reviews of a class before you join', 'step_2_2' => 'Review and join multiple timeslots', 'step_2_3' => 'View details about the venue and facilities', 'step_2_4' => 'Ask the trainer any questions you may have', 'step_3_1' => 'Train with like minded people', 'step_3_2' => 'Achieve your goals', 'step_3_3' => 'Receive a reminder well in advance', 'step_3_4' => 'Make new friends', 'step_4_1' => 'Make an impact with your review', 'step_4_2' => 'Tell users how you felt during the class', 'step_4_3' => 'Help like minded people with their fitness needs', 'tr_step_1_1' => 'No expensive monthly fees', 'tr_step_1_2' => 'Membership is FREE', 'tr_step_1_3' => 'Great exposure', 'tr_step_2_1' => 'Easily create a class', 'tr_step_2_2' => 'Reuse an edit venue details', 'tr_step_2_3' => 'View data on participants', 'tr_step_2_4' => 'Classes are promoted', 'tr_step_3_1' => 'Add sessions to a class with a click of a button', 'tr_step_3_2' => 'Directly message any participants', 'tr_step_3_3' => 'Get sent your participant list before each session', 'tr_step_4_1' => 'Withdraw money from you evercise wallet to your paypal account', 'tr_step_4_2' => 'View statistics on all classes', 'tr_step_4_3' => 'View your activity', 'tr_step_4_4' => 'Monitor your success', 'step_1_tab' => 'Step 1- Search Classes', 'step_1_title' => 'Search Classes', 'step_1_body' => '<p>Evercise is the perfect solution for those wanting to get fit with maximum flexibility. Access a huge range of fitness classes, trainers and locations on one website.</p> <br> <p>Whether your aim is to lose weight, bulk up or gain a skill, with Evercise you can find, compare and join classes, review trainers and join like minded people in your area to help you achieve your goals.</p>', 'step_2_tab' => 'Step 2- Join a class', 'step_2_title' => 'Join a class', 'step_2_body' => '<p>Not only does exercising in a group significantly reduce the cost per participant, many studies have proven that it also inspires willpower and discipline and therefore greater results!</p>', 'step_3_tab' => 'Step 3- Show Up and Shape Up', 'step_3_title' => 'Show Up and Shape Up', 'step_3_body' => '<p>Once you have purchased a class you can easily contact the trainer if you have any questions, Will will send you a reminder about the class the day before so all you have to do is show up and shape up.</p> <br> <p>If something comes up and you can&apos;t attend the class you can cancel, if you cancel more than 5 days in advance we will credit you evercoin account with the full amount of the class to spend on another class at a time that bests suits you. If you need to do a last minute cancellation we will credit you 50% of the cost up to 2 days before the class, unfortunately on closer to that we can not offer any credit </p>', 'step_4_tab' => 'Step 4- Rate and Review', 'step_4_title' => 'Rate and Review', 'step_4_body' => ' <p>Your evaluation has an impact on future classes. Tell users what happened during the class and how you felt with the group. You are more than welcome to join our community, let&apos;s inspire each other. </p>', 'tr_step_1_tab' => 'Step 1- Register', 'tr_step_1_title' => 'It&apos;s easy and FREE!', 'tr_step_1_body' => ' <p>We consider varying levels of expertise, class types and locations.Having a professional account and promoting classes is FREE.</p> <br> <p> <li> Click “register as trainer” on the nav bar, and follow the simple instructions.</li> <li> We aim to process your application in one working day!</li> <li>You can start creating classes straight away. These will become visible to the public as soon as we have processed your application.</li> </p>', 'tr_step_2_tab' => 'Step 2- Create a Class', 'tr_step_2_title' => 'They will be promoted by evercise on multiple platforms', 'tr_step_2_body' => ' <p>Easily create classes which will be linked to your profile and can be searched for and purchased online. Simply click “class hub” on the nav bar, then “create a new class”.</p> <br> <p> <li>Add your class name, photo and description. Specify its duration, size, price and whether it is gender specific. Choose a category so your class is easily searchable.</li> <li>Add venues and fill out details such as the facilities available. The venues you create will appear in a drop-down menu, so you only need to do this once per venue, not every time you create a class.</li> <li>If you run two similar classes with a small difference, you can “clone” a class you have already created, and simply change the relevant details.</li> <li> View participant lists and easily contact those who have joined. Evercise will send out handy reminders before each session.</li> </p>', 'tr_step_3_tab' => 'Step 3- Add Sessions', 'tr_step_3_title' => 'No need to start from scratch each time', 'tr_step_3_body' => ' <p>Once a class is created you can add multiple dates by simply clicking on the calendar.</p> <br> <p> <li>For each date added you can edit the time, price and duration.</li> <li>You can delete sessions until your first participant joins.</li> </p>', 'tr_step_4_tab' => 'Step 4- Manage Account', 'tr_step_4_title' => 'Managaging your accounts couldn&apos;t be easier', 'tr_step_4_body' => ' <p>Evercise has a variety of user-friendly features to help you manage your earnings and keep track of your activity.</p> <br> <p> <li>Getting paid through Evercise couldn’t be easier. Once a class is complete you can withdraw your money directly. You don&apos;t have to pay a penny until you start earning, and when you do, we only take a small commission of 10%!</li> <li>Evercise automatically creates a log of your activity. View your class statistics, e.g. total bookings and revenue, so you can monitor the progress and success of your class.</li> <li>Your Evercise Wallet will show a statement with all your incoming and outgoing funds. You can also view your earnings per month</li> </p>', '' => '', ];<file_sep>/app/database/seeds/SessionMembersTableSeeder.php <?php class SessionMembersTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('sessionmembers')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); $joingroups = DB::connection('mysql_import')->table('joingroup')->get(); foreach ($joingroups as $joingroup) { $user = DB::connection('mysql_import')->table('user')->where('Uid', $joingroup->Uid)->first(); if($user && $joingroup->groupToken !== '666') { $userEmail = $user->Uemail; $newUser = User::where('email', $userEmail)->first(); $evercisesessionId = DB::table('migrate_sessions')->where('classDatetimeId', $joingroup->groupId)->pluck('evercisesession_id'); if (Evercisesession::find($joingroup->groupId)) { $newUserId = $newUser->id; try { $newMember = Sessionmember::create([ 'user_id'=>$newUserId, 'evercisesession_id'=>$evercisesessionId, 'token'=>$joingroup->groupToken, 'transaction_id'=>$joingroup->groupTransactionId, 'payer_id'=>$joingroup->groupPaymentId, 'payment_method'=>'old' ]); } catch (Exception $e) { $this->command->info('Cannot make sessionmember. evercisesession_id: '.$evercisesessionId.', user id: '.$newUserId); //$this->command->info($e); //exit; } } } } } }<file_sep>/app/config/landing_pages.php <?php $base = 'assets/img/landings/'; return [ '/uk/london/bootcamp' => [ 'title' => 'Bootcamp Classes in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Bootcamp Trainers and Bootcamp classes all over London.', 'price' => '£10', 'category' => 'Bootcamp', 'category_id' => 7, 'total' => '100', 'main_image' => $base . 'bootcamp_assets/bootcamp_landing_img.jpg', 'popup_image' => $base . 'default_assets/bootcamp_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'bootcamp_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£6', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'bootcamp_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'bootcamp_assets/martial_arts_class_img.jpg', 'name' => 'MARTIAL ARTS', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ], [ 'image' => $base . 'bootcamp_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ], [ 'image' => $base . 'bootcamp_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ], [ 'image' => $base . 'bootcamp_assets/dance_class_img.jpg', 'name' => 'DANCE', 'from' => '£5', 'link' => 'uk/london?search=dance', 'total' => '50', ], ] ] ], '/uk/london/dance' => [ 'title' => 'Dance Classes in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Dance Trainers and Dance classes all over London.', 'price' => '£10', 'category' => 'Dance', 'category_id' => 1, 'total' => '100', 'main_image' => $base . 'dance_assets/dance_landing_img.jpg', 'popup_image' => $base . 'default_assets/dance_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'dance_assets/dance_class_img.jpg', 'name' => 'Dance', 'from' => '£6', 'link' => 'uk/london?search=dance', 'total' => '50', ], [ 'image' => $base . 'dance_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'dance_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ], [ 'image' => $base . 'dance_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ], [ 'image' => $base . 'dance_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£5', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'dance_assets/martial_arts_class_img.jpg', 'name' => '<NAME>', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ], ] ] ], '/uk/london/fitnessclasses' => [ 'title' => 'Fitness Classes in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Fitness Trainers and Fitness classes all over London.', 'price' => '£10', 'category' => 'Fitness', 'category_id' => 3, 'total' => '100', 'main_image' => $base . 'fitness_assets/fitness_landing_img.jpg', 'popup_image' => $base . 'default_assets/fitness_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'fitness_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ], [ 'image' => $base . 'fitness_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'fitness_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ], [ 'image' => $base . 'fitness_assets/dance_class_img.jpg', 'name' => 'Dance', 'from' => '£6', 'link' => 'uk/london?search=dance', 'total' => '50', ], [ 'image' => $base . 'fitness_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£5', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'fitness_assets/martial_arts_class_img.jpg', 'name' => '<NAME>', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ], ] ] ], '/uk/london/martialarts' => [ 'title' => 'Martial Arts in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Martial Arts Trainers and Martial Arts classes all over London.', 'price' => '£10', 'category' => 'Martial Arts', 'category_id' => 4, 'total' => '100', 'main_image' => $base . 'martial_arts_assets/martial_arts_landing_img.jpg', 'popup_image' => $base . 'default_assets/martial_arts_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'martial_arts_assets/martial_arts_class_img.jpg', 'name' => 'MARTIAL ARTS', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ], [ 'image' => $base . 'martial_arts_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'martial_arts_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£5', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'martial_arts_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ], [ 'image' => $base . 'martial_arts_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ], [ 'image' => $base . 'martial_arts_assets/dance_class_img.jpg', 'name' => 'Dance', 'from' => '£6', 'link' => 'uk/london?search=dance', 'total' => '50', ], ] ] ], '/uk/london/pilates' => [ 'title' => 'Pilates Classes in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Pilates Trainers and Pilates classes all over London.', 'price' => '£10', 'category' => 'Pilates', 'category_id' => 2, 'total' => '100', 'main_image' => $base . 'pilates_assets/pilates_class_landing.jpg', 'popup_image' => $base . 'default_assets/pilates_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'pilates_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ], [ 'image' => $base . 'pilates_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'pilates_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ], [ 'image' => $base . 'pilates_assets/dance_class_img.jpg', 'name' => 'Dance', 'from' => '£6', 'link' => 'uk/london?search=dance', 'total' => '50', ], [ 'image' => $base . 'pilates_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£5', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'pilates_assets/martial_arts_class_img.jpg', 'name' => '<NAME>', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ] ] ] ], '/uk/london/yoga' => [ 'title' => 'Yoga Classes in London | Evercise', 'description' => 'Evercise is an online platform that connects everyone wanting to exercise in a class with a wide array of Yoga Trainers and Yoga classes all over London.', 'price' => '£10', 'category' => 'Yoga', 'category_id' => 5, 'total' => '100', 'main_image' => $base . 'yoga_assets/yoga_landing_img.jpg', 'popup_image' => $base . 'default_assets/yoga_modal_img.jpg', 'blocks' => [ 'large' => [ [ 'image' => $base . 'yoga_assets/yoga_class_img.jpg', 'name' => 'YOGA', 'from' => '£5', 'link' => 'uk/london?search=yoga', 'total' => '50', ], [ 'image' => $base . 'yoga_assets/pilates_class_img.jpg', 'name' => 'PILATES', 'from' => '£5', 'link' => 'uk/london?search=pilates', 'total' => '50', ] ], 'small' => [ [ 'image' => $base . 'yoga_assets/fitness_class_img.jpg', 'name' => 'FITNESS', 'from' => '£5', 'link' => 'uk/london?search=fitness', 'total' => '50', ], [ 'image' => $base . 'yoga_assets/dance_class_img.jpg', 'name' => 'Dance', 'from' => '£6', 'link' => 'uk/london?search=dance', 'total' => '50', ], [ 'image' => $base . 'yoga_assets/bootcamp_class_img.jpg', 'name' => 'BOOTCAMP', 'from' => '£5', 'link' => 'uk/london?search=bootcamp', 'total' => '50', ], [ 'image' => $base . 'yoga_assets/martial_arts_class_img.jpg', 'name' => '<NAME>', 'from' => '£5', 'link' => 'uk/london?search=martial+arts', 'total' => '50', ] ] ] ] ];<file_sep>/app/models/Sessionmember.php <?php use Carbon\Carbon; /** * Class Sessionmember */ class Sessionmember extends \Eloquent { /** * @var array */ protected $fillable = ['user_id', 'evercisesession_id', 'token', 'transaction_id', 'payer_id', 'payment_method']; /** * The database table used by the model. * * @var string */ protected $table = 'sessionmembers'; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function Users() { return $this->belongsTo('User', 'user_id'); } public function rating() { return $this->hasOne('Rating'); } public static function todaysSales() { return count(DB::table('sessionmembers')->where('created_at', '>=', Carbon::now()->setTime(0, 0, 0))->get()); } public function session() { return $this->belongsTo('Evercisesession', 'evercisesession_id'); } }<file_sep>/app/composers/AccordionComposer.php <?php namespace composers; use JavaScript; class AccordionComposer { public function compose($view) { JavaScript::put(['InitAccordian' => 1, 'initSwitchView' => 1 ]); } }<file_sep>/app/database/migrations/2014_11_26_173143_create_coupons.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCoupons extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coupons', function(Blueprint $table) { $table->increments('id'); $table->integer('usage'); $table->string('coupon'); $table->string('description'); $table->enum('type', array('amount', 'package', 'percentage'))->default('amount'); $table->float('amount'); $table->integer('percentage'); $table->tinyInteger('package_id')->default('0'); $table->timestamp('active_from'); $table->timestamp('expires_at'); $table->timestamps(); }); $coupon = new Coupons(); $coupon->usage = 5; $coupon->coupon = 'ABCD'; $coupon->description = 'You got a shitty coupon for some amount'; $coupon->type = 'amount'; $coupon->amount = '9.99'; $coupon->percentage = '0'; $coupon->package_id = 0; $coupon->active_from = '2014-11-17 16:41:33'; $coupon->expires_at = '2014-12-17 16:41:33'; $coupon->save(); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('coupons'); } } <file_sep>/app/models/Milestone.php <?php /** * Class Milestone */ class Milestone extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'referrals', 'profile', 'facebook', 'twitter', 'reviews']; /** * @var string */ protected $table = 'milestones'; // //'milestones' => [ //'referral' => ['count'=>3, 'reward'=>5, 'recur'=>2, 'column'=>'referrals' ], //'profile' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'profile' ], //'facebook' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'facebook' ], //'twitter' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'twitter' ], //'review' => ['count'=>5, 'reward'=>5, 'recur'=>10, 'column'=>'reviews' ], //], /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } /** * * * @param $type */ public function add($type) { $milestones = Config::get('values')['milestones']; $column = $milestones[$type]['column']; $user = Sentry::findUserById($this->attributes['user_id']); $wallet = $user->getWallet(); if ($milestones[$type]['recur'] == 1) { if ($this->attributes[$column] == 0) { $this->attributes[$column] = 1; MilestoneRewards::add($type, $milestones[$type]['reward'], $user); $this->save(); Log::info('User ' .$user->id. ' has been awarded '. $milestones[$type]['reward']. 'for referring friends'); } } else { if ($milestones[$type]['recur'] > 1) { $this->attributes[$column] = $this->attributes[$column] + 1; if ($this->attributes[$column] <= ($milestones[$type]['recur'] * $milestones[$type]['count'])) { if (!($this->attributes[$column] % $milestones[$type]['count'])) { MilestoneRewards::add($type, $milestones[$type]['reward'], $user); Log::info('User ' .$user->id. ' has been awarded '. $milestones[$type]['reward']. 'for referring friends'); } } $this->save(); } } } /** * Assign Free coins to User * @param $type */ public function milestoneComplete($type) { $freeCoins = Config::get('values')['freeCoins']; if (isset($freeCoins[$type])) { MilestoneRewards::add($type, $freeCoins[$type], $this->user); } } public static function createIfDoesntExist($user_id) { if (static::where('user_id', $user_id)->first()) return false; $milestone = static::firstOrCreate([ 'user_id'=>$user_id, 'referrals'=>0, 'profile'=>0, 'facebook'=>0, 'twitter'=>0, 'reviews'=>0, ]); return $milestone; } public function showReferrals() { /* $total = ceil($this->referrals / Config::get('values')['milestones']['referral']['count']) * Config::get('values')['milestones']['referral']['count']; return $this->referrals .'/'. $total;*/ return $this->referrals; } }<file_sep>/app/commands/UpdateUserNewsletter.php <?php use Illuminate\Console\Command; class UpdateUserNewsletter extends Command { /** * The console command name. * * @var string */ protected $name = 'user:newsletter'; /** * The console command description. * * @var string */ protected $description = 'Subscribe all undecided users to the newsletter'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $done = 0; foreach (User::all() as $user) { if (is_null($user->newsletter) || $user->newsletter()->count() == 0) { $user->marketingpreferences()->sync([1]); $done++; } } $this->line('Added ' . $done . ' users to the newsletter'); } } <file_sep>/public/assets/jsdev/prototypes/33-list-accordion.js function listAccordion(accordion){ this.accordion = accordion; this.addListeners(); } listAccordion.prototype = { constructor : listAccordion, addListeners :function(){ this.accordion.on('shown.bs.collapse', function (e) { var link = $(e.target).attr('id'); $('a[href="#'+link+'"]').parent().addClass('active'); }) this.accordion.on('hidden.bs.collapse', function (e) { var link = $(e.target).attr('id'); $('a[href="#'+link+'"]').parent().removeClass('active'); }) } }<file_sep>/app/controllers/PdfController.php <?php class PdfController extends \BaseController { public function postPdf() { $sessionmembers = json_decode(Input::get('postMembers'), true); $evercisesession = Input::get('postEverciseSession'); $evercisegroup = Input::get('postEverciseGroup'); $timestamp = date("d-m-Y"); $pdfPage = PdfHelper::pdfView($evercisegroup, $evercisesession, $sessionmembers); return PDF::load($pdfPage, 'A4', 'portrait')->download($evercisegroup.'-'.$timestamp); } public function getPdf($session_id) { $evercisesession = Evercisesession::find($session_id); if(empty($evercisesession)) return null; $evercisegroup = Evercisegroup::find($evercisesession->evercisegroup_id); $sessionmembers = $evercisesession->users; if(empty($sessionmembers)) return null; $timestamp = date("d-m-Y"); $pdfPage = PdfHelper::pdfView($evercisegroup, $evercisesession, $sessionmembers); return PDF::load($pdfPage, 'A4', 'portrait')->download($evercisegroup->id.'-'.$timestamp); } }<file_sep>/app/database/migrations/2014_04_29_102623_create_evercisegroups_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateEvercisegroupsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('evercisegroups')) { Schema::create('evercisegroups', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('user_id')->unsigned();// Foreign key //$table->integer('category_id')->unsigned();// Foreign key $table->integer('venue_id')->unsigned();// Foreign key $table->string('name', 45); $table->string('title', 255); $table->string('description', 255); $table->tinyInteger('gender'); $table->string('image', 100); $table->integer('capacity'); $table->integer('default_duration'); $table->decimal('default_price', 6, 2)->default(0.00); $table->tinyInteger('published')->default(0); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('evercisegroups'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/controllers/ajax/CartController.php <?php namespace ajax; use Coupons; use Input, EverciseCart, Evercisesession, Response, View; use Packages; use Session; class CartController extends AjaxBaseController { /** * @return $this * * Add a product to the Cart. * POST variables: product-id, [quantity] * * product-id is currently the session-id with a capital 'S' slapped on the front. (to be replaced with a hash) */ public function add() { $productCode = Input::get('product-id', FALSE); $quantity = Input::get('quantity', 1); $force = Input::get('force', FALSE); $noCart = Input::get('noCart', FALSE); $refreshPage = Input::get('refresh-page', FALSE); $idArray = EverciseCart::fromProductCode($productCode); if ($idArray['type'] == 'session') { $sessionId = $idArray['id']; // needs fixing - this is grabbing the first class, couls of thought you need find in as the id is in a array $session = Evercisesession::find($sessionId); $evercisegroupId = $session->evercisegroup_id; $rowIds = EverciseCart::search(['id' => $productCode]); if ($rowIds[0]) // If product ID already exists in cart, then add to quantity. { $rowId = $rowIds[0]; $row = EverciseCart::get($rowId); $currentQuantity = $row->qty; $newQuantity = (!$force ? $currentQuantity + $quantity : $quantity); if ($newQuantity > $session->remainingTickets()) { return Response::json([ 'validation_failed' => 1, 'errors' => ['custom' => 'We only have ' . $session->remainingTickets() . ' ticket' . ($session->remainingTickets() > 1 ? 's' : '') . ' available for this class'] ]); } EverciseCart::update($rowId, $newQuantity); } else // Make a new entry in the cart, and link it to the session. { EverciseCart::associate('Evercisesession')->add($productCode, $session->evercisegroup->name, $quantity, $session->price, [ 'evercisegroupId' => $evercisegroupId, 'sessionId' => $sessionId, 'date_time' => $session->date_time, 'available' => $session->remainingTickets() ] ); } } else { if ($idArray['type'] == 'package') { // Package has been added $packageId = $idArray['id']; $package = Packages::find($packageId); $rowIds = EverciseCart::search(['id' => $productCode]); if ($rowIds[0]) // If product ID already exists in cart, then add to quantity. { $rowId = $rowIds[0]; $row = EverciseCart::get($rowId); $currentQuantity = $row->qty; $newQuantity = $currentQuantity + $quantity; EverciseCart::update($rowId, $newQuantity); } else // Make a new entry in the cart, and link it to the session. { EverciseCart::associate('Packages')->add($productCode, $package->name, $quantity, $package->price, ['style' => $package->style]); } } else { if ($idArray['type'] == 'topup') { $amount = Input::get('amount', 0); if ($amount < 1) { return Response::json([ 'validation_failed' => 1, 'errors' => ['custom' => 'Amount too small'] ]); } EverciseCart::clearTopup(); EverciseCart::instance('topup')->add($idArray['id'], 'top up', 1, $amount, []); } else { if ($idArray['type'] == 'wallet_payment') { $amount = Input::get('amount', 0); if ($amount > \Sentry::getUser()->wallet->balance) { // Not enough credit in wallet. } EverciseCart::instance('topup')->add($idArray['id'], 'top up', 1, $amount, []); } else { return 'code does not exist :' . $productCode; // Product code type does not exist } } } } if ($refreshPage) { return Response::json( [ 'refresh' => TRUE ] ); } else { return $this->getCart(); } } /** * @return $this * * Remove a specified quantity of a product from the Cart. If quantity is not set, one will be removed * POST variables: product-id, [quantity] */ public function remove() { $productCode = Input::get('product-id', FALSE); $rowId = EverciseCart::search(['id' => $productCode]); $refreshPage = Input::get('refresh-page', FALSE); if ($rowId) { $quantity = Input::get('quantity', 1); $currentQuantity = EverciseCart::get($rowId[0])->qty; $newQuantity = $currentQuantity - $quantity; if ($newQuantity > 0) { EverciseCart::update($rowId[0], $newQuantity); } else { EverciseCart::remove($rowId[0]); } } if ($refreshPage) { return Response::json( [ 'refresh' => TRUE ] ); } else { return $this->getCart(); } } /** * @return $this * * Remove a product from the Cart, regardless of quantity * POST variables: product-id */ public function delete() { $productCode = Input::get('product-id', FALSE); $rowId = EverciseCart::search(['id' => $productCode]); $refreshPage = Input::get('refresh-page', FALSE); $product = EverciseCart::fromProductCode($productCode); if ($rowId) { if ($product['type'] == 'package') { $currentQuantity = EverciseCart::get($rowId[0])->qty; $newQuantity = $currentQuantity - 1; if ($newQuantity > 0) { EverciseCart::update($rowId[0], $newQuantity); } else { EverciseCart::remove($rowId[0]); } } else { EverciseCart::remove($rowId[0]); } } if ($refreshPage) { return Response::json( [ 'refresh' => TRUE ] ); } else { return $this->getCart(); } } /** * @return $this * * Empty everything from Cart */ public function emptyCart() { EverciseCart::destroy(); return $this->getCart(); } /** * @return $this * * Return Cart data formatted as an array */ public function getCart() { $coupon = Session::get('coupon', FALSE); $data = EverciseCart::getCart($coupon); return Response::json([ 'view' => View::make('v3.cart.dropdown')->with($data)->render(), 'remaining' => $this->setRemaining($data), 'items' => count($data['sessions_grouped'])+ count($data['packages']) ]); } public function cartData() { $coupon = Session::get('coupon', FALSE); $data = EverciseCart::getCart($coupon); return Response::json( [ 'data' => $data ] ); } public function applyCoupon() { $coupon = Coupons::check(Input::get('coupon', FALSE)); $res = ['cart' => EverciseCart::getCart(), 'success' => FALSE]; if ($coupon) { Session::put('coupon', $coupon->coupon); $res['success'] = TRUE; $res['coupon'] = [ 'coupon' => $coupon->coupon, 'type' => $coupon->type, 'amount' => $coupon->amount, 'percentage' => $coupon->percentage, 'description' => $coupon->description ]; } return Response::json($res); } private function setRemaining($data) { $remaining = []; foreach ($data['sessions_grouped'] as $id => $val) { $remaining[$id] = $val['tickets_left']; } return $remaining; } }<file_sep>/app/lang/en/class_guidelines.php <?php return [ 'title' => 'Class Guidelines', 'subtitle' => 'Before setting up a class, please read and follow the guidelines below.', 'page_content' => ' <h3>Every class on Evercise must fit into one of the following categories:</h3> <br> <p>Workouts; Sports; Healthy lifestyle; Nutrition; Injury recovery</p> <hr> <h3>Rules</h3> <br> <p>You cannot use Evercise to sell physical products. You can only sell your own services; you cannot promote the services of others. You must be professionally qualified to perform the services that you offer on Evercise. No promotion of tobacco, drugs or drug paraphernalia. No contests, raffles, coupons or lifetime memberships.</p> <hr> <h3>About these guidelines</h3> <br> <p>Our goal is to provide everyone wanting to exercise with all the useful, relevant information they might need before making an informed decision to join a class. Providing accurate information will ensure your class fills with committed participants who are keen to get results. The Evercise Class Guidelines aim to be as open as possible while protecting the integrity of the instructor and the safety of the participant. Please contact us if you have any further questions before setting up a class on Evercise.</p> ', '' => '', ];<file_sep>/app/models/Landing.php <?php /** * Class Landing */ class Landing extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'email', 'code', 'category_id', 'location']; /** * @var string */ protected $table = 'landings'; /** * Check if the Landing code is correct * * @param $lc * @return int */ public static function checkLandingCode($lc) { $landingCode = 0; if (!is_null($lc)) { if (!is_null(Landing::where('code', $lc)->first())) { $landingCode = $lc; } } return $landingCode; } /** * Use Provided Landing Code * * @param $lc * @param $user_id * @return \Illuminate\Database\Eloquent\Model|int|null|static */ public static function useLandingCode($lc, $user_id) { $landing = 0; if (Landing::checkLandingCode($lc)) { $landing = Landing::where('code', $lc)->first(); $landing->update(['code' => '', 'user_id' => $user_id]); } return $landing; } }<file_sep>/app/composers.php <?php /* Dynamically load Composers from Config */ $composers = Config::get('composers'); foreach ($composers as $composer) { foreach ($composer as $name => $class) { View::composer($name, '\composers\\' . $class); } } <file_sep>/public/assets/jsdev/prototypes/37-withdrawel.js function Withdrawal(form){ this.form = form; this.modal = ''; this.addListeners(); } Withdrawal.prototype = { constructor : Withdrawal, addListeners: function(){ this.form.on('submit', $.proxy(this.submit, this)); $(document).on('submit', '#request-withdrawal-form', $.proxy(this.submit, this)); $(document).on('input', 'input[name="paypal"]', $.proxy(this.removeValidation, this)); $(document).on('input', 'input[name="amount"]', $.proxy(this.removeValidation, this)); }, submit : function(e){ e.preventDefault(); this.form = $(e.target); this.ajax(); }, ajax: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find('input[type="submit"]').prop('disabled', true); }, success: function (data) { if(data.view){ $('body').append(data.view); self.form.find('input[type="submit"]').replaceWith('<a href="#request-withdrawal" class="btn btn-default" data-toggle="modal" data-target="#request-withdrawal">Request Funds</a>') self.modal = $('#request-withdrawal'); self.modal.modal('show'); } else if(data.validation_failed == 1){ self.failedValidation(data); } else{ self.form.find('input[name="amount"]').addClass('mb40'); self.form.find('input[name="amount"]').after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="amount" data-bv-result="VALID">Withdrawel Successful, We are now refreshing this page for you.</small>'); location.reload(); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find('input[type="submit"]').prop('disabled', false); } }); }, removeValidation: function(e){ $(e.target).parent().removeClass('has-error mb40'); $(e.target).parent().find('.help-block:visible').remove(); }, failedValidation: function(data){ self = this; var arr = data.errors; $.each(arr, function(index, value) { self.form.find('input[name="' + index + '"]').parent().addClass('has-error mb40'); self.form.find('input[name="' + index + '"]').parent().find('.help-block:visible').remove(); self.form.find('input[name="' + index + '"]').after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); }) } }<file_sep>/app/database/migrations/2014_12_05_140643_update_packages_new.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class UpdatePackagesNew extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement('ALTER TABLE `packages` CHANGE `price` `price` DECIMAL( 8, 2 ) NOT NULL'); DB::statement('ALTER TABLE `packages` CHANGE `max_class_price` `max_class_price` DECIMAL( 8, 2 ) NOT NULL'); foreach(Packages::all() as $p) { switch($p->id) { case 1: case 4: $p->style = 'green'; break; case 2: case 5: $p->style = 'blue'; break; case 3: case 6: $p->style = 'pink'; break; } $p->save(); } } /** * Reverse the migrations. * * @return void */ public function down() { return true; } } <file_sep>/app/models/Slider.php <?php class Slider extends Eloquent { protected $table = 'slider'; protected $fillable = ['image', 'evercisegroup_id', 'date_end', 'active']; protected $hidden = ['created_at', 'updated_at']; protected $dates = ['date_end']; public function evercisegroup() { return $this->belongsTo('Evercisegroup', 'evercisegroup_id'); } public function getItems($limit = 5) { $items = []; $sliders = static::where('active', 1)->get(); $i = 0; foreach ($sliders as $slider) { $class = $slider->evercisegroup()->first(); if ($class) { $session = $class->evercisesession()->where('date_time', '>=', DB::raw('NOW()'))->orderBy( 'price', 'asc' )->first(); if ($session) { $items[] = $this->formatItem($slider, $session, $class); $i++; } if ($i == $limit) { break; } } } if (count($items) < $limit) { Log::error('Need more Slider ITEMS FAST!!!!'); } return $items; } public function formatItem($slider, $session, $class) { $item = $session->toArray(); $item['image'] = $slider->image; $item['name'] = $class->name; $item['description'] = $class->description; return $item; } }<file_sep>/app/composers/UpcomingTrainerSessionsComposer.php <?php namespace composers; use Evercisegroup; class UpcomingTrainerSessionsComposer { public function compose($view) { $viewdata = $view->getData(); $userTrainer = $viewdata['user']; $evercisegroups = Evercisegroup::with('Evercisesession.Sessionmembers.Users')->where('user_id', $userTrainer->id)->get(); $view->with('evercisegroups',$evercisegroups); } }<file_sep>/.version.php <?php return "hdub7bNdAQ"; <file_sep>/app/cronjobs/ReminderForPayments.php <?php namespace cronjobs; use events\Mail; use Illuminate\Log\Writer; class ReminderForPayments { private $log; private $mail; public function __construct(Writer $log, Mail $mail) { $this->log = $log; $this->mail = $mail; } function run() { $this->log->info('Sending Payments Reminder'); $payments = \Withdrawalrequest::where('processed', 0)->count(); if($payments > 0) { $this->mail->adminSendReminderForPayments($payments); } } }<file_sep>/app/controllers/admin/AdminGalleryController.php <?php class AdminGalleryController extends AdminController { public function __construct() { parent::__construct(); } public function index() { $this->data['images'] = Gallery::where('counter', '>', 0)->get(); $this->data['categories'] = []; foreach(Category::all() as $c) { $this->data['categories'][] = $c->name; } foreach(Subcategory::all() as $c) { $this->data['categories'][] = $c->name; } $this->data['categories'] = array_unique($this->data['categories']); return View::make('admin.gallery', $this->data)->render(); } } <file_sep>/app/database/migrations/2014_04_10_133144_create_sessions_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateSessionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('evercisesessions')) { Schema::create('evercisesessions', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->integer('evercisegroup_id')->unsigned();// Foreign key $table->timestamp('date_time'); $table->integer('members')->default(0); $table->decimal('price', 6, 2)->default(0.00); $table->integer('duration'); $table->boolean('members_emailed')->default(0); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('evercisesessions'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/config/shortcodes.php <?php /* * Configuration for ShortCodes * * * TAG => CLASS@FUNCTION */ return [ 'single_class' => 'Shortcodes@singleClass' ]; <file_sep>/app/database/migrations/2014_04_10_132455_create_users_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { //Artisan::call('migrate', ['--package' => 'cartalyst/sentry']); Schema::table('users', function($table) { if (!Schema::hasColumn('display_name', 'gender')) { $table->string('display_name', 45); $table->tinyInteger('gender'); $table->date('dob'); $table->string('area_code', 20); $table->string('phone', 20); $table->string('directory', 45)->default(''); $table->string('image', 45); $table->string('categories', 45); $table->string('remember_token', 100)->nullable(); } }); } /** * Reverse the migrations. * * @return void */ public function down() { /* DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('users'); DB::statement('SET FOREIGN_KEY_CHECKS = 1');*/ } } <file_sep>/app/config/homepage.php <?php return [ 'popular_searches' => [ 'Yoga', 'Dance', 'Workout', 'Bootcamp', 'Boxing' ], 'category_blocks' => [ [ 'title' => 'Yoga Classes', 'image' => '/img/home/yoga.jpg', 'link' => '/uk/london?search=yoga' ], [ 'title' => 'Martial Arts', 'image' => '/img/home/martial-arts.jpg', 'link' => '/uk/london?search=martial+arts' ], [ 'title' => 'Pilates Classes', 'image' => '/img/home/Pilates.jpg', 'link' => '/uk/london?search=pilates' ] ], 'category_tags' => [ 'Belly dance', 'Vinyasa yoga', 'Workout', 'Karate', 'Insanity', 'Pregnancy Yoga', 'Bootcamp', 'Tai Chi', 'Salsa', 'Pilates', 'Aqua cycling', 'Hiit', 'Boxing', 'Suspension training', 'Body conditioning', /* 'kettlebell', 'hiit', 'mma', 'workout', 'suspension training', 'belly dancing', 'pilates', 'pregnancy yoga', 'yoga', 'insanity', 'running', 'total body bootcamp', 'salsa', 'strength and conditioning', 'self defence', 'circuit', 'latin dance', 'balance', 'aerobics', 'hatha yoga', 'crossfit', 'zumba'*/ ], 'blocks' => [ [ 'title' => 'New This Week', 'link' => '/uk/london?sort=newest', 'link_title' => 'View all new this week', 'params' => [ 'size' => 4, 'radius' => '10mi', 'location' => 'London', 'sort' => 'newest' ] ], [ 'title' => 'Move your body for under £10', 'link' => '/uk/london?search=dance', 'link_title' => 'View all dance classes', 'params' => [ 'size' => 4, 'radius' => '10mi', 'location' => 'London', 'search' => 'dance', 'sort' => 'best', 'price' => [ 'under' => 10 ] ] ], [ 'title' => 'Get active, get fit, get inspired', 'link' => '/uk/london?search=fitness', 'link_title' => 'View all fitness classes', 'background' => '/img/home/fitness.jpg', 'params' => [ 'size' => 4, 'radius' => '10mi', 'location' => 'London', 'search' => 'fitness', 'sort' => 'best' ] ], ] ];<file_sep>/app/assets/javascripts/evercoin.js function initRedeemEvercoin(params) { evercoinParams = JSON.parse(params); var evercoinBalance = evercoinParams.balance; var priceInEvercoins = evercoinParams.priceInEvercoins; trace(priceInEvercoins); if (evercoinBalance > 0) { $(document).on('click' , '.redeem-btn.up', function(){ var redeem = parseInt($('#redeem').val()); if (redeem < evercoinBalance && redeem < priceInEvercoins) { $('#redeem').val(redeem + 10); }; } ) $(document).on('click' , '.redeem-btn.down', function(){ var redeem = parseInt($('#redeem').val()); if (redeem > 0) { $('#redeem').val(redeem - 10); } } ) $('#redeem').on('keyup', function(){ var redeem = parseInt($('#redeem').val()); if (redeem >= evercoinBalance && redeem < priceInEvercoins) { $('#redeem').val(evercoinBalance); } if (redeem >= priceInEvercoins && evercoinBalance >= priceInEvercoins){ $('#redeem').val(priceInEvercoins); } if (redeem >= priceInEvercoins && evercoinBalance < priceInEvercoins){ $('#redeem').val(evercoinBalance); } }) }; } registerInitFunction('initRedeemEvercoin'); function paidWithEvercoins(data) { $('.mask').hide(); trace('paidWithEvercoins : '+data.usecoins); trace('amountRemaining : '+data.amountRemaining); $('#evercoin-redeemed').html(data.usecoins); $('#balance-to-pay').html(data.amountRemaining); }<file_sep>/app/models/UserHelper.php <?php class UserHelper { /** * Generate the user default data * @param int $user_id */ public static function generateUserDefaults($user_id = 0) { if ($user_id < 1) { return false; } Wallet::createIfDoesntExist($user_id); Milestone::createIfDoesntExist($user_id); Token::createIfDoesntExist($user_id); } /** * Check referral code from session, if it exists and is valid, mark it as used and credit the new user the specified amount of Evercoins * * @param bool $referal_code * @param int $user_id */ public static function checkAndUseReferralCode($referral_code = false, $user_id = 0) { if ($referral = Referral::useReferralCode($referral_code, $user_id)) { Log::info('using referral code: ' . $referral_code. ' user id: '.$user_id); Milestone::where('user_id', $referral->user_id)->first()->add('referral'); Milestone::where('user_id', $user_id)->first()->milestoneComplete('referral_signup'); Session::forget('referralCode'); } } /** * Check PPC / Landing code from session, if it exists and is valid, mark it as used and credit the new user the specified amount of Evercoins * * @param bool $ppc_code * @param int $user_id */ public static function checkAndUseLandingCode($ppc_code = false, $user_id = 0) { if ($landing = Landing::useLandingCode($ppc_code, $user_id)) { $wallet = Wallet::where('user_id', $user_id)->first(); $type = 'ppc_signup'; $freeCoins = Config::get('values')['freeCoins']; if (isset($freeCoins[$type])) { $wallet->giveAmount($freeCoins[$type], $type); } } else if ($staticLanding = StaticLanding::useLandingCode($ppc_code, $user_id)) { $wallet = Wallet::where('user_id', $user_id)->first(); $wallet->giveAmount($staticLanding->amount, 'static_ppc_signup', $staticLanding->description); } Session::forget('ppcCode'); } } <file_sep>/app/models/VenueImport.php <?php class VenueImport extends \Eloquent { protected $fillable = array('id', 'user_id', 'name', 'address', 'town', 'postcode', 'lat', 'lng', 'image', 'source', 'external_id', 'venue_id'); /** * The database table used by the model. * * @var string */ protected $table = 'venue_import'; }<file_sep>/public/assets/jsdev/prototypes/38-trapezium.js function trapezium(wrapper){ this.wrapper = wrapper; this.btns = [] this.width = wrapper.outerWidth(); this.margin = parseInt(this.wrapper.find('.btn').css('margin-right')); this.init(); } trapezium.prototype = { constructor : trapezium, init : function(){ if($(window).width() > 990){ var self = this; var width = this.width; var btnWidth = 0; var row = 1; var col = 10; var offset = 1; var remaining = 0; var n = 0; this.wrapper.find('.trapezium-item').each(function(i, obj){ btnWidth = btnWidth + $(obj).outerWidth(true); if( btnWidth >= (width -20)){ remaining = btnWidth - width; var newMargin = (self.margin + (remaining / n)) +'px'; btnWidth = 0; row = ++row; self.wrapper.append('<div class="col-sm-'+col+' col-sm-offset-'+offset+' mb30" id="row-'+row+'"></div>'); width = self.wrapper.find('#row-'+row).outerWidth(); if(btnWidth < width){ btnWidth = btnWidth + $(obj).outerWidth(true); self.wrapper.find('#row-'+row).append(obj); col = col - 2; offset = ++offset; } } else{ ++n; self.wrapper.find('#row-'+row).append(obj); } }) } } }<file_sep>/app/cronjobs/SendExtraEmailsCron.php <?php namespace cronjobs; use Illuminate\Log\Writer; use Illuminate\Console\Application as Artisan; class SendExtraEmailsCron { private $log; /** * @var \Artisan */ private $artisan; public function __construct(Writer $log, Artisan $artisan) { $this->log = $log; $this->artisan = $artisan; } function run() { $this->log->info('Extra Email Command has Run!'); $this->artisan->call('email:extra'); } }<file_sep>/app/composers/DonutChartComposer.php <?php namespace composers; use Javascript; class DonutChartComposer { public function compose($view) { $rand = rand(1,10000000); // used for muliple instances of the same laracast JavaScript::put(array('initChart_'.$rand => json_encode(array('id' => $view->id )))); // Initialise chart JS. } }<file_sep>/app/lang/en/contact_us.php <?php return [ 'title' => 'Contact Us', 'subtitle' => 'There are several ways to get in contact depending on the nature of your enquiry.', 'please_contact' => 'please contact', // --------------------------------------------------------------------------------------------------------- 'general_title' => 'General enquiries', 'general_contact' => '<NAME> (participants) or <NAME> (trainers)', 'general_email' => '<EMAIL>', 'general_phone' => '+44(0)2033 266216', // --------------------------------------------------------------------------------------------------------- 'careers_title' => 'Careers', 'careers_contact' => '<NAME>', 'careers_email' => '<EMAIL>', 'careers_phone' => '+44(0)2033 266216', // --------------------------------------------------------------------------------------------------------- 'business_title' => 'Business collaboration', 'business_contact' => '<NAME>', 'business_email' => '<EMAIL>', 'business_phone' => '+44(0)2033 266216', ];<file_sep>/public/assets/jsdev/prototypes/40-my-location.js function myLocation(){ this.town = 'london'; this.btn; this.form; this.addListeners(); } myLocation.prototype = { constructor : myLocation, addListeners : function(){ $(document).on('click', '.locator', $.proxy(this.init, this)) //this.btn.on('click', $.proxy(this.init, this)); }, init: function(e){ this.btn = $(e.target); this.form = $(e.target).closest('form'); e.preventDefault(); e.stopPropagation(); navigator.geolocation.getCurrentPosition($.proxy(this.displayPosition, this), $.proxy(this.displayError, this)); }, displayPosition : function(position){ var lat = position.coords.latitude; var lng = position.coords.longitude; this.getLocation(lat,lng); }, displayError : function(error){ var errors = { 1: 'Permission denied', 2: 'Position unavailable', 3: 'Request timeout' }; alert("Error: " + errors[error.code]); }, getLocation: function(lat, lng){ geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(lat, lng); var self = this; geocoder.geocode({'latLng': latlng}, function(results, status) { if (results[0] && status == 'OK') { var address = results[0].formatted_address; self.form.find('input[name="location"]').val(address); self.getTown(results[0].address_components); self.form.find('input[name="city"]').val(self.town); if(self.btn.is('#mobile-sub')) { self.form.trigger('submit'); } } else{ console.log(status); } }) }, getTown : function(address_components){ var self = this; var result = address_components; for (var i = 0; i < result.length; ++i) { if (result[i].types[0] == "locality") { self.town = result[i].long_name ; } else if(result[i].types[0] == "political") { self.town = result[i].long_name ; } else if(result[i].types[0] == "postal_town"){ self.town = result[i].long_name ; } } } }<file_sep>/app/controllers/EvercisegroupsController.php <?php class EvercisegroupsController extends \BaseController { protected $evercisegroup; protected $input; protected $log; protected $elastic; public function __construct( Evercisegroup $evercisegroup, Illuminate\Http\Request $input, Illuminate\Log\Writer $log, Illuminate\Config\Repository $config, Es $elasticsearch, Geotools $geotools ) { parent::__construct(); $this->evercisegroup = $evercisegroup; $this->input = $input; $this->log = $log; $this->config = $config; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); } /** * Display a listing of the resource. * * @return Response */ public function index() { return Evercisegroup::getHub($this->user); } /** * Show the form for creating a new resource. * * @return Response */ public function create($clone_id = NULL) { // Get names of subcategories and sort alphabetically $subcategories = Subcategory::lists('name'); natsort($subcategories); $venues = Venue::usersVenues($this->user->id); $facilities = Facility::getLists(); if ($clone_id) { $cloneGroup = Evercisegroup::find($clone_id); if (!$cloneGroup->checkIfUserOwnsClass($this->user)) { return Redirect::route('evercisegroups.index')->with('errorNotification', 'You do not own this class'); } } return View::make('v3.classes.create') ->with('venues', $venues) ->with('facilities', $facilities) ->with('subcategories', $subcategories) ->with('cloneGroup', isset($cloneGroup) ? $cloneGroup : NULL); //return View::make('evercisegroups.create')->with('subcategories', $subcategories); } /** * @param $id * @return \Illuminate\Http\RedirectResponse */ public function cloneEG($id) { return Redirect::route('evercisegroups.create', [$id]); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id, $preview = NULL) { if (Request::segment(1) != 'classes') { return Redirect::to('classes/' . Request::segment(2), 301); } $data = $this->elastic->getSingle($id); if (!empty($data->hits[0]->_source)) { $class = $data->hits[0]->_source; if (is_numeric($id)) { return Redirect::route('class.show', [$id => $class->slug], 301); } $og = new OpenGraph(); /* try to create og if fails redirect to discover page */ try { $og->title($class->name) ->type('article') ->image( url() . '/' . $class->user->directory . '/thumb_' . $class->image, [ 'width' => 150, 'height' => 156 ] ) ->description($class->description) ->url(); $class->og = $og; } catch (Exception $e) { $class->og = []; } /** Overwrite Venue because of amenities */ $class->venue = Venue::with('facilities')->find($class->venue_id); $cats = array_map('trim', explode(',', $class->categories)); $subcats = Subcategory::whereIn('name', $cats)->get()->toArray(); $types = array_unique(array_values(array_map(function ($sub) { return $sub['type']; }, $subcats))); $class->next_session = FALSE; if (count($class->futuresessions) > 0) { $class->next_session = $class->futuresessions[0]; $i = 0; while ( $class->futuresessions[$i]->remaining == 0) { $i++; $class->next_session = $class->futuresessions[$i]; } } foreach ($class->futuresessions as $s) { if ($s->id == Input::get('t')) { $class->next_session = $s; } } $related = Subcategory::whereIn('type', $types)->orderByRaw("RAND()")->limit(6)->get(); if ($last = URL::previous()) { $breadcrumbs = ['SEARCH' => $last]; } else { $categories = array_map('trim', explode(',', $class->categories)); $breadcrumbs = [ ucfirst($categories[0]) => URL::route('search.parse', ['allsegments' => 'london', 'search' => $categories[0]]) ]; } $params = [ 'breadcrumbs' => $breadcrumbs, 'data' => (array)$class, 'related' => $related, 'title' => $class->name . ' - ' . trim($class->venue->town) . ' | Evercise', 'metaDescription' => $class->name . ' in activity that enhances and maintains overall health and wellness. ' . $class->name . ' Fitness Classes ' . trim($class->venue->town) ]; $params['canonical'] = URL::route('class.show', ['id' => $class->slug, 'preview' => '']); if (Sentry::check() && ($class->user_id == $this->user->id || $this->user->hasAccess('admin'))) // This Group belongs to this User/Trainer { event('class.viewed', [$class, $this->user]); $params['preview'] = 'preview'; return View::make('v3.classes.class_page', $params); } else { // This group does not belong to this user /** Check if this is active or not! */ if ($class->published == 0) { return Redirect::to('uk/london')->with('error', 'This class does not exist'); } event('class.viewed', [$class, $this->user]); return View::make('v3.classes.class_page', $params); } } else { //return View::make('errors.missing'); return Redirect::to('uk/london')->with('error', 'This class does not exist'); } } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { echo('edit'); exit; } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { echo('update'); exit; } /** * Remove the specified resource from storage. * * @param int $id * @return Route */ public function destroy() { $id = Input::get('id'); //return $id; $evercisegroup = Evercisegroup::with('evercisesession.sessionmembers')->find($id); if (!$evercisegroup) { return 'cannot find group ' . $id; } $delete = $evercisegroup->deleteGroup($this->user); event(' class.deleted', [$this->user, $evercisegroup]); return 'deleted ' . $id; } /** * Bring up delete view in window * * @param int $id * @return Route */ public function deleteEG($id) { $evercisegroup = Evercisegroup::with('evercisesession.sessionmembers')->find($id); $deletableStatus = 0; $deletableStatus = count($evercisegroup->sessionmember) ? 3 : ($evercisegroup->evercisesession->isEmpty() ? 1 : 2); return $deletableStatus ? View::make('evercisegroups.delete')->with('id', $id)->with( 'name', $evercisegroup->name )->with('evercisegroup', $evercisegroup)->with('deleteable', $deletableStatus) : Redirect::route('home'); } /* * query eg's based on location * * @return Response */ public function search($all_segments = []) { $search = Evercisegroup::parseSegments($all_segments); dd($search); /* check if search form posted otherwise set default for radius */ $radius = Input::get('radius', 10); $category = Input::get('category'); $locationString = Input::get('location'); return Evercisegroup::doSearch(['address' => $locationString], $category, $radius, $this->user); } public function search_C($country) { $location = $country; $radius = 25; $category = ''; return Evercisegroup::doSearch(['address' => $location], $category, $radius, $this->user); } }<file_sep>/app/composers/ClassHubComposer.php <?php namespace composers; use JavaScript; class ClassHubComposer { public function compose($view) { JavaScript::put( [ 'initPut' => json_encode(['selector' => '#newsession']), 'calendarSlide' => 1, 'initEvercisegroups' => 1, ] ); $view; } }<file_sep>/app/views/admin/yukonhtml/php/pages/pages-mailbox_message.php <div class="row"> <div class="col-md-3 col-lg-2"> <button class="btn btn-info btn-outline btn-sm">Compose</button> <hr/> <div class="list-group mailbox_menu"> <a href="pages-mailbox.html" class="list-group-item"> <span class="badge badge-danger">96</span> <span class="menu_icon icon_download"></span>Inbox </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_upload"></span>Sent </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="badge badge-danger">52</span> <span class="menu_icon icon_error-circle_alt"></span>Spam </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_pencil-edit"></span>Drafts </a> <a href="pages-mailbox.html" class="list-group-item"> <span class="menu_icon icon_trash_alt"></span>Trash </a> </div> </div> <div class="col-md-9 col-lg-10"> <div class="row"> <div class="col-md-4"> <div class="btn-group btn-group-sm"> <button type="button" class="btn btn-default">Reply</button> <button type="button" class="btn btn-default">Spam</button> <button type="button" class="btn btn-default text-danger">Delete</button> </div> </div> <div class="col-md-4 col-md-offset-4 text-right"> <div class="btn-group btn-group-sm"> <button type="button" class="btn btn-default bs_ttip" data-placement="bottom" title="Prev"><span class="el-icon-chevron-left"></span></button> <button type="button" class="btn btn-default bs_ttip" data-placement="bottom" title="Next"><span class="el-icon-chevron-right"></span></button> </div> </div> </div> <hr/> <div class="mail_details_top clearfix"> <div class="mail_date"> Thu 26.11.2015 </div> <div class="mail_user_image"> <img src="assets/img/avatars/avatar0<?php echo rand(1,9); ?>_tn.png" width="38" height="38" alt=""> </div> <div class="mail_user_info"> <h2><?php echo $faker->name; ?></h2> <span class="text-muted"><?php echo $faker->email; ?></span> </div> </div> <div class="mail_details_content"> <?php echo $faker->sentence(80); ?> </div> <div class="mail_details_send"> <textarea name="mail_reply" id="mail_reply" cols="30" rows="3" class="form-control" placeholder="Start typing here to replay or forward..."></textarea> </div> </div> </div> <file_sep>/app/assets/javascripts/trainers.js function initTrainerTitles(p) { var params = JSON.parse(p); titles = params.titles; title = params.title; $('#discipline').on('change', function () { var currentTitles = titles[this.value]; $("#title").empty(); for(var i=0; i<currentTitles.length; i++) { $("#title").append($("<option></option>").attr("value", currentTitles[i]).text(currentTitles[i])); } $("#title").val(title).attr("selected", "selected"); trace(title) }).change(); } registerInitFunction('initTrainerTitles'); function initCreateTrainer() { // create a new trainer $( '#trainer_create' ).on( 'submit', function() { $('.error-msg').remove(); $('input, select').removeClass('error'); loading(); // post to sontroller $.post( $( this ).prop( 'action' ), $( this ).serialize(), function( data ) { trace("about to win......."); loaded(); if (data.validation_failed == 1) { trace('validation failed: '); // show validation errors var arr = data.errors; trace(arr, true); var scroll = false; $.each(arr, function(index, value) { if (scroll == false) { //$('html, body').animate({ scrollTop: $("#" + index).offset().top }, 400); scroll = true; }; if (value.length != 0) { $("#" + index).addClass('error'); $("#" + index).after('<span class="error-msg">' + value + '</span>'); } }); $('#ajax-loading').hide(); }else{ // redirect to login page $('.success_msg').show(); setTimeout(function() { window.location.href = data; }, 100); //trace(data); } }, 'json' ); return false; }); } registerInitFunction('initCreateTrainer'); function initSessionNew() { // Open Create Session Window $( '#session_new' ).on( 'submit', function() { $('.error-msg').remove(); $('input').removeClass('error'); // post to sontroller $.post( $( this ).prop( 'action' ), { "evercisegroup": $( '#evercisegroup' ).val() }, function( data ) { trace("about to win......."); if (data.validation_failed == 1) { trace('loose'); var arr = data.errors; }else{ /*setTimeout(function() { window.location.href = data; }, 100);*/ trace(data); } }, 'json' ); return false; }); } //registerInitFunction(initSessionNew); <file_sep>/app/database/migrations/2014_12_05_094853_update_tickets.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class UpdateTickets extends Migration { /** * Run the migrations. * * @return void */ public function up() { $groups = Evercisegroup::all(); foreach($groups as $g) { DB::table('evercisesessions') ->where('evercisegroup_id', $g->id) ->update(array('tickets' => $g->capacity)); } } /** * Reverse the migrations. * * @return void */ public function down() { } } <file_sep>/public/assets/jsdev/prototypes/13-new-class.js function createClass(form){ this.form = form; this.validIcon = 'glyphicon glyphicon-ok'; this.invalidIcon = 'glyphicon glyphicon-remove'; this.validatingIcon = 'glyphicon glyphicon-refresh'; this.className = { validators: { notEmpty: { message: 'Your class name is required' }, stringLength: { min: 3, max: 50, message: 'Your class name must be more than 3 and less than 50 characters long' } } }; this.classDescription = { validators: { notEmpty: { message: 'Your class needs a description' }, stringLength: { min: 50, max: 500, message: 'Your class description must be more than 50 and less than 500 characters long' } } }; this.init(); } createClass.prototype = { constructor: createClass, init: function(){ this.validation(); this.addListener(); }, addListener: function(){ $(document).on('change', 'input[name="image"]', $.proxy(this.reValidate, this)) $(document).on('change', 'input[name="category_array[]"]', $.proxy(this.reValidate, this)); }, validation: function(){ var self = this; $(this.form) .on('init.form.bv', function(e, data) { data.bv.disableSubmitButtons(true); }) .bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: this.validIcon, invalid: this.invalidIcon, validating: this.validatingIcon }, fields: { class_name: this.className, class_description: this.classDescription } }) .on('success.field.bv', function(e, data) { if( !$("input[name='image']").val() && !$("input[name='category_array[]']").val()) { self.form.find("input[type='submit']").prop('disabled', true); } }) .on('success.form.bv', function(e) { e.preventDefault(); if( !$("input[name='image']").val() ) { self.form.find("input[type='submit']").parent().parent().before('<div data-dismiss="alert" class="alert alert-danger">You must add a cover image before you can proceed<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button></div>') } else if( !$("input[name='category_array[]']").val() ){ self.form.find("input[type='submit']").parent().parent().before('<div data-dismiss="alert" class="alert alert-danger">You must select at least one category before you can proceed<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button></div>') } else{ self.form.find("input[type='submit']").prop('disabled', false); self.ajaxUpload(); } }); }, ajaxUpload: function () { var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).after('<span id="class-loading" class="icon icon-loading ml10"></span>'); }, success: function (data) { if(data.validation_failed == 1){ self.failedValidation(data); console.log(data); } else{ window.location.href = data.url; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { $('#class-loading').remove(); } }); }, reValidate: function(){ if( $("input[name='image']").val() && $("input[name='category_array[]']").val()) { this.form.find("input[type='submit']").prop('disabled', false); } }, failedValidation: function(data){ var self = this; var arr = data.errors; $.each(arr, function(index, value) { if( index == 'venue_select'){ self.form.find('#venue_select').parent().parent().addClass('has-error'); self.form.find('#venue_select').parent().after('<small class="help-block custom-inline-error" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); } else if(self.form.find('input[name="' + index+ '"]').parent().hasClass('input-group')){ self.form.find('input[name="' + index + '"]').parent().parent().addClass('has-error'); self.form.find('input[name="' + index + '"]').parent().after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); self.form.find('input[name="' + index + '"]').parent().after('<i class="form-control-feedback glyphicon glyphicon-remove" data-bv-icon-for="' + index + '"></i>'); } else { self.form.find('input[name="' + index + '"]').parent().addClass('has-error'); self.form.find('input[name="' + index + '"]').parent().find('.glyphicon').remove(); self.form.find('input[name="' + index + '"]').parent().find('.help-block:visible').remove(); self.form.find('input[name="' + index + '"]').after('<small class="help-block" data-bv-validator="notEmpty" data-bv-for="' + index + '" data-bv-result="INVALID">' + value + '</small>'); self.form.find('input[name="' + index + '"]').after('<i class="form-control-feedback glyphicon glyphicon-remove" data-bv-icon-for="' + index + '"></i>'); } }) } }<file_sep>/app/config/values.php <?php return array( // count - How many to count to before a reward is given // reward - Amount rewarded in pounds // Recur - Number of times the award can be claimed 'milestones' => [ 'referral' => ['count'=>1, 'reward'=>5, 'recur'=>3, 'column'=>'referrals' ], 'profile' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'profile' ], 'facebook' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'facebook' ], 'twitter' => ['count'=>1, 'reward'=>.5, 'recur'=>1, 'column'=>'twitter' ], 'review' => ['count'=>5, 'reward'=>5, 'recur'=>10, 'column'=>'reviews' ], ], // Amount rewarded for signing up from a referral link in pounds 'freeCoins' => [ 'referral_signup' => 5, 'ppc_signup' => 5, 'static_ppc_signup' => 5, ], // Value of an evercoin in pounds 'evercoin' => 0.01, // category strings to load landing pages. the string is accpeted from a route, and mapped to these category id's in LandingsController::loadCategory 'ppc_categories' => ['dance'=>1, 'pilates'=>1, 'martialarts'=>4, 'yoga'=>5, 'bootcamp'=>7, 'personaltrainer'=>13], 'ppc_category_examples' => [ 1=> 'So you like to have a little music to your workouts? Look no further. We have Zumba, Salsa and many more class types available for those who want to move their muscles to a rhythmic beat.', 2=> 'So you&apos;re into a system that focuses on improving balance by stretching? Why not check out our intense Hot Pilates sessions, or our Post-natal classes for those looking to recover', 4=> 'Have an interest in Martial Arts? Why not punch your way through to our new range of classes, with choices from MMA to Kick-boxing. Check it out!', 5=> 'So you&apos;re into mind and body fitness? We have a range of classes that will get your legs stretching, from Vinyasa to Pilates. Pick your choice!', 7=> 'So you&apos;ve expressed an interest in exercising outdoors? Check out our boot camp classes all steered for those who love workouts in the fresh air!', 13=> 'So you&apos;re into a fitness regimes or routine workouts? There are one-to-one and group classes catered for all levels of expertise.', ], // dates 'min_age' => 16, 'max_age' => 120, // Refunds cut off dates (in number of days into the future) 'half_refund_cut_off' => 2, 'full_refund_cut_off' => 5, // price 'max_price' => 200 );<file_sep>/app/events/Sessions.php <?php namespace events; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Events\Dispatcher; use Illuminate\Routing\UrlGenerator; /** * Class Sessions * @package events */ class Sessions { /** * @var Repository */ protected $config; /** * @var Writer */ protected $log; /** * @var Dispatcher */ protected $event; /** * @var Activity */ protected $activity; /** * @var Indexer */ protected $indexer; /** * @var Mail */ protected $mail; /** * @var Tracking */ protected $track; /** * @var UrlGenerator */ private $url; /** * @param Activity $activity * @param Indexer $indexer * @param Mail $mail * @param Writer $log * @param Repository $config * @param Dispatcher $event * @param Tracking $track * @param UrlGenerator $url */ public function __construct( Activity $activity, Indexer $indexer, Mail $mail, Writer $log, Repository $config, Dispatcher $event, Tracking $track, UrlGenerator $url ) { $this->config = $config; $this->log = $log; $this->event = $event; $this->track = $track; $this->activity = $activity; $this->indexer = $indexer; $this->mail = $mail; $this->url = $url; } /** * @param $userList * @param $group * @param $location * @param $dateTime * @param $trainerName * @param $trainerEmail * @param $classId */ public function upcomingSessions($userList, $group, $location, $dateTime, $trainerName, $trainerEmail, $classId, $sessionId){ $this->log->info('Sending Upcomming Sessions email'); $this->mail->trainerSessionRemind($userList, $group, $location, $dateTime, $trainerName, $trainerEmail, $classId, $sessionId); $this->mail->usersSessionRemind($userList, $group, $location, $dateTime, $trainerName, $trainerEmail, $classId, $sessionId); } /** * @param $userList * @param $group * @param $session * @param $messageSubject * @param $messageBody */ public function mailAll($userList, $group, $session, $messageSubject, $messageBody){ $this->log->info('Trainer Emailing All'); $this->mail->trainerMailAll($userList, $group, $session, $messageSubject, $messageBody); } /** * @param $trainer * @param $user * @param $group * @param $dateTime * @param $messageSubject * @param $messageBody */ public function mailTrainer($trainer, $user, $evercisegroup, $session, $subject, $body) { $this->log->info('User '.$user->id.' Is Emailing Trainer '.$trainer->id); $this->mail->mailTrainer($trainer, $user, $evercisegroup, $session, $subject, $body); } /** * @param $user * @param $trainer * @param $everciseGroup * @param $sessionDate */ public function userLeaveSession($user, $trainer, $everciseGroup, $sessionDate){ $this->log->info('User left Session'); $this->mail->userLeaveSession($user, $trainer, $everciseGroup, $sessionDate); $this->mail->trainerLeaveSession($user, $trainer, $everciseGroup, $sessionDate); $this->indexer->indexSingle($everciseGroup->id); } /** * @param $user * @param $trainer * @param $session * @param $everciseGroup * @param $transactionId */ public function joinedClass($user, $trainer, $session, $evercisegroup, $transaction) { $this->track->registerUserSessionTracking($user, $session); $this->mail->trainerJoinSession($user, $trainer, $session, $evercisegroup, $transaction); $this->indexer->indexSingle($evercisegroup->id); } /** * @param $email * @param $userName * @param $userEmail * @param $group * @param $messageSubject * @param $messageBody */ public function refundRequest($email, $userName, $userEmail, $group, $messageSubject, $messageBody) { $this->mail->userRequestRefund($email, $userName, $userEmail, $group, $messageSubject, $messageBody); } /** * @param $user */ public function login($user) { $this->log->info('User ' . $user->id . ' has Logged In'); $this->track->userLogin($user); } }<file_sep>/app/commands/FixDisplayNames.php <?php use Illuminate\Console\Command; class FixDisplayNames extends Command { protected $name = 'fix:names'; protected $description = 'Fix User Display Names'; public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $users = User::all(); foreach ($users as $u) { $u->display_name = slugIt($u->display_name); $this->line(slugIt($u->display_name)); $u->save(); } $this->info('Done '.count($users)); $this->info('Indexing DB'); event('class.index.all'); $this->info('DONE Indexing DB'); } }<file_sep>/app/lang/en/discover.php <?php return array( 'search_box' => 'Search for Classes', 'location_box' => 'Location', 'radius_box' => 'Distance', 'zero_results' => 'Your search returned 0 results, please refine your search', 'classes_in_your_area' => 'Classes in your area', 'classes_near' => 'Classes near', 'recommended_classes' => 'Recommended Classes', '' => '', );<file_sep>/app/lang/en/trainers-about.php <?php return [ 'section1-title' => 'So you are looking at becoming a pro?', 'section1-subtitle' => 'Great choice!', 'section1-body' => ' <p>To become a Evercise Professional you must first be logged in as a user.</p> <br> <p>Click the link below to signup.</p> <p>Once signup you will be able to click the register as a trainer button to upgrade your account</p> ', 'section2-title' => 'What is Evercise to a fitness class instructor?', 'section2-subtitle' => 'Evercise brings you greater exposure!', 'section2-body' => ' <p>We offer a platform for health and fitness professionals to promote themselves,<br> their classes and their expertise to a large online community of potential participants. Create a professional profile viewable to the public,<br> add classes which will be linked to your profile and can be searched for and purchased online,<br> gain trust through our rating system.<br> Whether you want to generate interest in a new class you are trying out, or increase the number of participants at classes you teach already,<br> Evercise is the place to be.</p> ', 'section3-title' => 'What is an Evercise Instructor?', 'section3-subtitle' => 'Anyone who offers a professional group fitness service.', 'section3-body' => ' <p>You can be an Evercise Instructor if you are a qualified professional who runs or is looking to run group fitness classes in and around London. <br> We consider varying levels of expertise, class types and locations. <br> Potential participants can search through a wide range of instructors and classes on one website, <br> making Evercise highly appealing to the public and a great place for your online presence.</p> ', 'section3-image_url' => 'img/go_pro_icons.png', 'section3-image_alt' => 'what is evercise', 'section4-title' => 'Why should you join Evercise?', 'section4-subtitle' => 'In short, you can&apos;t lose, you can only win!', 'section4-body' => ' <p>Evercise provides access to a large targeted audience. <br> You become part of a keep-fit community, within which you can promote yourself for free, <br> gain exposure and boost the number of participants in your classes. <br> Evercise is also a great online base of operations in terms of organisation.</p> <p> <ul> <li>Set up classes at the click of a button (these classes will be automatically promoted)</li> <li>Manage payments through Evercise</li> <li>Download participant lists</li> <li>Evercise&apos;s events calendar sends out handy reminders to both you and your participants before a class.</li> </ul> </p> <p>You don’t have to pay a penny until you start earning, and when you do, <br> we offer a generous reward system so that the more you earn, <br> the smaller the rate of commission!</p> ', 'section4-image_url' => 'img/why_join.png', 'section4-image_alt' => 'why join evercise as a profesional trainer', 'section5-title' => 'What makes Evercise different?', 'section5-subtitle' => 'Evercise is not just another profile site.', 'section5-body' => ' <p>It is an ever expanding community of potential participants. <br> Due to busy, bustling, London lifestyles, it can be difficult to get individuals to commit to an entire course. <br> Through Evercise, participants can sign up on a class-by-class basis, <br> meaning all those wanting to get fit with maximum flexibility will come to Evercise first.</p> ', 'section5-image_url' => 'img/reputation_small.png', 'section5-image_alt' => 'gain a reputation on evercise', ];<file_sep>/public/assets/jsdev/prototypes/26.checkout.js function checkout(checkout){ this.checkout = checkout; this.viewPrice = viewPrice; this.addListeners(); } checkout.prototype ={ construstor: checkout, addListeners: function(){ this.checkout.find('#stripe-button').on('click', $.proxy(this.openStripe, this)) $(window).on('popstate', $.proxy(this.closeStripe, this)); }, openStripe: function(e){ var self = this; // Open Checkout with further options handler.open({ name: 'Evercise', description: 'Checkout', amount: self.viewPrice }); e.preventDefault(); }, closeStripe: function(e){ handler.close(); } }<file_sep>/app/lang/en/landing.php <?php /* ppc landing page content */ return[ 'header' => 'sign up today and receive up to <span class="highlight">&pound;8*</span>', 'terms' => '*&pound;8 of credit in evercoins that are not redeemable for cash and cannot be returned for a cash refund.', 'bodyHeader' => 'What is evercise?', 'whatIsEvercise' => 'At Evercise, we believe fitness should be fun, flexible, convenient and social. We offer classes of all types with no long term commitment, a variety of classes at different levels, reviews and a schedule that suits you. Search for classes in your area and book in less that 2 minutes!', 'whyEvercise' => '<li>Huge range of classes and class types</li><li>Choose classes near your location</li><li>No long term commitments</li><li>Earn money off with Evercoin</li><li>Get fit whilst having fun!</li>', 'testimonialHeader' => 'Don&apos;t just take our word for it...', 'testimonials' => [ [ 'name' => 'Gina', 'image' => 'Gina.png', 'location' => 'Islington, London', 'content' => 'Evercise has revolutionised the way I exercise. There is so much choice and I am saving a fortune. I find myself signing up for classes that I didn&apos;t even know existed!', ], [ 'name' => 'Sunita', 'image' => 'Sunita.png', 'location' => 'Southwark, London', 'content' => 'The flexibility that Eevercise offers is vital to my staying fit and healthy. The ability to workout when I have the time, with no financial commitment, really works for me.', ], ], ];<file_sep>/app/events/Indexer.php <?php namespace events; use Log, Geotools,Evercisegroup, Elastic; class Indexer { protected $elastic; public function load() { if (!isset($this->elastic)) { /** Load a partial instance of the Elastic thingy... no need for everything to be injected!*/ $this->elastic = new Elastic( Geotools::getFacadeRoot(), new Evercisegroup(), \Es::getFacadeRoot(), Log::getFacadeRoot() ); } } public function indexSingle($id) { $time_start = microtime(true); $this->load(); $total_indexed = $this->elastic->indexEvercisegroups($id); $time = microtime(true) - $time_start; Log::info('Indexed Classes id '.$id.' in ' . round($time, 2) . ' seconds'); } public function indexAll() { $time_start = microtime(true); $this->load(); $total_indexed = $this->elastic->indexEvercisegroups(); $time = microtime(true) - $time_start; $message = 'Index a total ' . $total_indexed . ' in ' . round($time, 2) . ' seconds'; Log::info($message); return $message; } }<file_sep>/app/controllers/ajax/CategoryController.php <?php namespace ajax; use Input, Sentry, Category,Response; class CategoryController extends AjaxBaseController { public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } public function getCategories() { $categories = \Category::with('subcategories')->get(); return $categories; //return var_dump($categories[0]->subcategories[0]); } /** return all categorys * - description * - popular classes (the chosen ones) * - subcategories (order by num classes, limit 15) * */ public function browse() { $results = Category::browse(); return Response::json($results); } }<file_sep>/app/controllers/admin/MainController.php <?php use Carbon\Carbon; /** * Class ArticlesController */ class MainController extends \BaseController { public function __construct() { parent::__construct(); } public function dashboard() { /** Stats */ $this->data['gallery_images_counter'] = Gallery::sum('counter'); $this->data['gallery_images_total'] = Gallery::where('counter', '>', 0)->count(); /** Users */ $this->data['total_users'] = User::all()->count(); $today = new DateTime(); $today->setTime(0, 0, 0); $this->data['users_today'] = User::where('created_at', '>', $today)->count(); $this->data['trainers_today'] = Trainer::where('created_at', '>', $today)->count(); $trainer = Sentry::findGroupByName('Trainer'); $this->data['total_trainers'] = Sentry::findAllUsersInGroup($trainer)->count(); $this->data['new_sessions_today'] = Evercisesession::where('created_at', '>', $today)->count(); $this->data['new_groups_today'] = Evercisegroup::where('created_at', '>', $today)->count(); $sevenDaysTime = new DateTime(); $sevenDaysTime->add(new DateInterval('P7D')); $this->data['upcoming_sessions_7'] = Evercisesession::where('date_time', '>', (new DateTime()))->where('date_time', '<', $sevenDaysTime)->count(); $thirtyDaysTime = new DateTime(); $thirtyDaysTime->add(new DateInterval('P30D')); $this->data['upcoming_sessions_30'] = Evercisesession::where('date_time', '>', (new DateTime()))->where('date_time', '<', $thirtyDaysTime)->count(); /** Sales */ $this->data['total_sales'] = Sessionpayment::where('created_at', '>=', Carbon::createFromDate(2015, 1, 1))->where('processed', 1)->sum('total'); $this->data['total_after_fees'] = Sessionpayment::where('created_at', '>=', Carbon::createFromDate(2015, 1, 1))->where('processed', 1)->sum('total_after_fees'); $this->data['total_commission'] = ($this->data['total_sales'] - $this->data['total_after_fees']); $this->data['session_sold_today'] = Sessionmember::todaysSales(); $this->data['transactions_today'] = DB::table('transactions')->where('created_at', '>=', Carbon::now()->setTime(0, 0, 0))->count(); $this->data['total_year'] = Sessionpayment::where('created_at', '>=', Carbon::now()->subYear()) ->where('processed', 1) ->groupBy('month') ->orderBy(DB::raw('year asc, month')) ->get([ DB::raw('YEAR(created_at) as year'), DB::raw('MONTH(created_at) as month'), DB::raw('SUM(total) as total'), DB::raw('SUM(total_after_fees) as total_after_fees') ]); $start = Carbon::now()->subYear(); $end = Carbon::now(); $interval = DateInterval::createFromDateString('1 month'); $period = new DatePeriod($start, $interval, $end); foreach ($period as $dt) { $this->data['total_months'][] = $dt->format("Y-m") . '-01'; $this->data['total_year_total'][(int)$dt->format("m")] = 0; $this->data['total_year_fee'][(int)$dt->format("m")] = 0; } foreach ($this->data['total_year'] as $m) { $this->data['total_year_total'][$m->month] = round($m->total, 0); $this->data['total_year_fee'][$m->month] = round($m->total - $m->total_after_fees, 0); } /** Classes Stats */ $this->data['total_classes'] = Evercisegroup::where('created_at', '>=', Carbon::now()->subYear()) ->groupBy('month') ->orderBy(DB::raw('year asc, month')) ->get([ DB::raw('YEAR(created_at) as year'), DB::raw('MONTH(created_at) as month'), DB::raw('COUNT(id) as total') ]); $this->data['total_sessions'] = Evercisesession::where('created_at', '>=', Carbon::now()->subYear()) ->groupBy('month') ->orderBy(DB::raw('year asc, month')) ->get([ DB::raw('YEAR(date_time) as year'), DB::raw('MONTH(date_time) as month'), DB::raw('COUNT(id) as total') ]); foreach ($period as $dt) { $this->data['total_classes_count'][(int)$dt->format("m")] = 0; $this->data['total_sessions_count'][(int)$dt->format("m")] = 0; } foreach ($this->data['total_classes'] as $m) { $this->data['total_classes_count'][$m->month] = round($m->total, 0); } foreach ($this->data['total_sessions'] as $m) { $this->data['total_sessions_count'][$m->month] = round($m->total, 0); } $this->data['complete_referrals'] = Referral::where('referee_id', '>', 0)->count(); $this->data['pending_referrals'] = Referral::where('referee_id', '=', 0)->count(); return View::make('admin.dashboard', $this->data)->render(); } public function expired($date = FALSE) { if (!$date) { $date = date('Y-m-d', strtotime('-1 month', time())); } $date = $date . ' 00:00:00'; $expired = DB::table('evercisesessions') ->select(DB::raw('evercisesessions.id, evercisesessions.date_time, evercisesessions.tickets as members, evercisesessions.price, evercisegroups.user_id, evercisegroups.name, users.email, users.first_name, users.last_name, users.phone')) ->leftJoin('evercisegroups', 'evercisegroups.id', '=', 'evercisesessions.evercisegroup_id') ->leftJoin('users', 'users.id', '=', 'evercisegroups.user_id') ->where('evercisesessions.date_time', '>', $date) ->whereNotIn('evercisesessions.evercisegroup_id', function ($query) { $query->select(DB::raw('evercisegroup_id')) ->from('evercisesessions') ->whereRaw('date_time > now()'); }) ->orderBy('evercisesessions.date_time', 'desc') ->get(); return View::make('admin.expired', compact('expired'))->render(); } public function users() { $users = User::all(); $trainerGroup = Sentry::findGroupByName('Trainer'); return View::make('admin.users', compact('users', 'trainerGroup'))->render(); } public function trainerCreate() { return View::make('admin.users.create')->render(); } public function trainerStore() { $validationRules = array_merge([ 'first_name' => 'required|max:15|min:2', 'last_name' => 'required|max:25|min:2', 'email' => 'required|unique:users,email', 'display_name' => 'required|unique:users,display_name', 'phone' => 'numeric', 'gender' => 'required', ], Trainer::$validationRules ); $validationRules['image'] = 'sometimes'; $inputs = Input::except(['_token', 'trainer']); $validator = Validator::make( $inputs, $validationRules ); if ($validator->fails()) { return Redirect::route('admin.users.trainerCreate') ->withErrors($validator) ->withInput(); } else { $inputs['display_name'] = str_replace(' ', '_', $inputs['display_name']); $inputs['dob'] = NULL; $inputs['password'] = Functions::randomPassword(8); $inputs['activated'] = TRUE; $inputs['gender'] = $inputs['gender'] == 'male' ? 1 : 2; $inputs['areacode'] = '+44'; try { // register user and add to user group $user = User::registerUser($inputs); $userGroup = Sentry::findGroupById(3); $user->addGroup($userGroup); if ($user) { UserHelper::generateUserDefaults($user->id); Session::forget('email'); if (FALSE) { User::subscribeMailchimpNewsletter( Config::get('mailchimp')['newsletter'], $user->email, $user->first_name, $user->last_name ); } User::makeUserDir($user); } } catch (Cartalyst\Sentry\Users\UserExistsException $e) { die($e->getMessage()); } try { event('user.registered', [$user]); } catch (Exception $e) { Log::error($e); } $trainer = ['confirmed' => 1, 'user_id' => $user->id]; $include = ['bio', 'phone', 'website', 'profession']; foreach ($inputs as $key => $val) { if (in_array($key, $include)) { $trainer[$key] = $val; } } if ($res = Trainer::createOrFail($trainer)) { event('trainer.registered', [$user,]); event('user.admin.trainerCreate', compact('user', 'trainer')); Session::flash('notification', 'Trainer Created'); return Redirect::route('admin.users'); } } } public function logInAs() { $user = Sentry::findUserById(Input::get('user_id')); Sentry::login($user); return Redirect::route('users.edit', ['id' => Input::get('user_id')]); } public function editCategories() { $cats = \Category::orderBy('order', 'asc')->get(); return View::make('admin.categories', compact('cats'))->render(); } public function subcategories() { $subcategories = \Subcategory::with('categories')->get(); $categories = \Category::all(); $category = []; $category[0] = ''; foreach ($categories as $c) { $category[$c->id] = $c->name; } return View::make('admin.subcategories', compact('categories', 'subcategories', 'category', 'subcatCats'))->render(); } /** * show all pending trainers. * * @return Response */ public function pendingTrainers() { return View::make('admin.pendingtrainers') ->with('trainers', Trainer::getUnconfirmedTrainers()); } /** * Approve trainers. * * @return Response */ public function approveTrainer() { $user = User::getUserByTrainerId(Input::get('trainer')); Trainer::approve($user); return Redirect::route('admin.pendingtrainers'); } /** * @return \Illuminate\View\View */ public function pendingWithdrawal() { $pendingWithdrawals = Withdrawalrequest::where('processed', 0)->with('user')->orderBy('created_at', 'desc')->get(); $processedWithdrawals = Withdrawalrequest::where('processed', 1)->with('user')->orderBy('created_at', 'desc')->get(); return View::make('admin.pendingwithdrawals') ->with('pendingWithdrawals', $pendingWithdrawals) ->with('processedWithdrawals', $processedWithdrawals); } public function processWithdrawalMulti() { $process = Input::get('process'); $payments = Withdrawalrequest::whereIn('id', array_keys($process))->get(); if ($payments->count() == 0) { return Redirect::route('admin.pending_withdrawal')->with('notification', 'You need to select somebody !!!'); } $paypal = App::make('WithdrawalPayment'); foreach ($payments as $p) { $paypal->addUser([ 'id' => $p->id, 'email' => $p->account, 'amount' => number_format($p->transaction_amount, 2) ]); } $res = $paypal->pay(); if ($res['ACK'] !== 'Success') { return Redirect::route('admin.pending_withdrawal')->with('notification', 'Check if all the emails are Correct!!!!!'); } foreach ($payments as $p) { $transaction = Transactions::create( [ 'user_id' => $p->user_id, 'total' => $p->transaction_amount, 'total_after_fees' => $p->transaction_amount, 'coupon_id' => 0, 'commission' => 0, 'token' => 0, 'transaction' => 0, 'payment_method' => 'paypal', 'payer_id' => $p->user_id ]); event('user.withdraw.completed', [User::find($p->user_id), $transaction, Wallet::where('user_id', $p->user_id)->pluck('balance')]); } foreach ($payments as $p) { $p->processed = 1; $p->save(); } return Redirect::route('admin.pending_withdrawal')->with('notification', 'Yaay.. you payed Somebody!!!'); } /** * @return \Illuminate\Http\RedirectResponse * * Same as function above, but no paypal payemt is attempted (bacause it doesn't work) */ public function processWithdrawalMultiManual() { $process = Input::get('process'); $payments = Withdrawalrequest::whereIn('id', array_keys($process))->get(); if ($payments->count() == 0) { return Redirect::route('admin.pending_withdrawal')->with('notification', 'You need to select somebody !!!'); } foreach ($payments as $p) { $transaction = Transactions::create( [ 'user_id' => $p->user_id, 'total' => $p->transaction_amount, 'total_after_fees' => $p->transaction_amount, 'coupon_id' => 0, 'commission' => 0, 'token' => 0, 'transaction' => 0, 'payment_method' => 'paypal', 'payer_id' => $p->user_id ]); event('user.withdraw.completed', [User::find($p->user_id), $transaction, Wallet::where('user_id', $p->user_id)->pluck('balance')]); } foreach ($payments as $p) { $p->processed = 1; $p->save(); } return Redirect::route('admin.pending_withdrawal')->with('notification', 'Make sure payments are made MANUALLY through PayPal !!!'); } /** * @return \Illuminate\Http\RedirectResponse */ public function processWithdrawal() { $withdrawal_id = Input::get('withdrawal_id'); Withdrawalrequest::find($withdrawal_id)->markProcessed(); return Redirect::route('admin.pending_withdrawal'); } /** * @return \Illuminate\View\View */ public function showLog() { $logFile = file_get_contents('../app/storage/logs/laravel.log', TRUE); $logFile = str_replace('[] []', '[] [] < br><br ><br > ', $logFile); $logFile = str_replace('#', '<br><span style="color:#c00; margin-left:20px">#</span>', $logFile); return View::make('admin.log') ->with('log', $logFile); } /** * @return \Illuminate\Http\RedirectResponse */ public function deleteLog() { $del = Input::get('del'); if ($del == 'delete_all') { file_put_contents('../app/storage/logs/laravel.log', ''); } return Redirect::to('admin/log'); } /** * @return \Illuminate\View\View */ public function showGroups() { $evercisegroups = Evercisegroup::with('subcategories')->with('featuredClasses')->get(); return View::make('admin.groups') ->with('evercisegroups', $evercisegroups); } /** * TODO - make this function (add categories to groups) * * @return \Illuminate\View\View */ public function addGroup() { return View::make('admin.groups'); } /** * @return \Illuminate\View\View|string */ public function showGroupRatings() { $fakeusers = Sentry::findGroupById(6); $fakeuserLoggedIn = $this->user ? $this->user->inGroup($fakeusers) : FALSE; if (!$fakeuserLoggedIn) { return 'please log in with a fake user'; } $evercisegroups = Evercisegroup::whereHas('futuresessions', function ($query) { $query->with('ratings'); $query->with('fakeRatings'); })->get(); return View::make('admin.fakeratings') ->with('evercisegroups', $evercisegroups); } public function yukon($page = 'dashboard') { //$users = User::with('evercisegroups')->where('display_name', 'LIKE', 'Peter_ATP')->get(); //return $page; //return $users; $unconfirmedTrainers = Trainer::getUnconfirmedTrainers(); $pendingWithdrawals = Withdrawalrequest::getPendingWithdrawals(); return View::make('admin.yukonhtml.index') ->with('admin_version', '1.0') ->with('sPage', '1') ->with('unconfirmedTrainers', $unconfirmedTrainers) ->with('pendingWithdrawals', $pendingWithdrawals) ->with('includePage', View::make('admin.' . $page)); } public function searchUsers() { $searchTerm = Input::get('search'); $sentryUsers = Sentry::findAllUsers(); $users = User::with('evercisegroups')->where('display_name', 'like', $searchTerm); return View::make('admin.users') ->with('users', $users) ->with('sentryUsers', $sentryUsers); } public function searchStats() { $from = Carbon::now()->subDays(30); $to = Carbon::now(); /** Top Searches The past Week */ $top_searches = StatsModel::select(DB::raw('count(*) as total, search, AVG(results) as avg')) ->whereBetween('created_at', array($from, $to)) ->groupBy('search') ->orderBy(DB::raw('count(*)'), 'desc') ->limit(20) ->get(); $top_cities = StatsModel::select(DB::raw('count(*) as total, name, AVG(results) as avg')) ->whereBetween('created_at', array($from, $to)) ->where('name', '!=', 'London') ->groupBy('name') ->orderBy(DB::raw('count(*)'), 'desc') ->limit(15) ->get(); $total_london = StatsModel::whereBetween('created_at', array($from, $to)) ->where('name', 'London') ->count(); $percentage_london = ($total_london / ($top_cities->count() + $total_london)) * 100; return View::make('admin.searchstats', compact('top_searches', 'top_cities', 'percentage_london')); } public function salesStats() { $sessionmembers = DB::table('sessionmembers')->orderBy('id', 'desc')->get(); $sales = []; foreach ($sessionmembers as $sm) { $session = Evercisesession::find($sm->evercisesession_id); $sales[] = [ 'id' => $sm->id, 'user_id' => $sm->user_id, 'user_name' => User::where('id', $sm->user_id)->pluck('display_name'), 'class_id' => $session->evercisegroup_id, 'class_name' => Evercisegroup::where('id', $session->evercisegroup_id)->pluck('name'), 'date' => $sm->created_at, 'amount' => $session->price, 'transaction_id' => $sm->transaction_id, 'payment_method' => $sm->payment_method, ]; } return View::make('admin.sales') ->with('sales', $sales); } public function transactions() { $transactions = Transactions::orderBy('id', 'desc')->get(); $userIds = []; foreach ($transactions as $tr) { $userIds[] = $tr->user_id; } $userNames = User::whereIn('id', $userIds)->lists('display_name', 'id'); //return var_dump($userNames); $trans = []; foreach ($transactions as $tr) { $trans[] = [ 'id' => $tr->id, 'user_id' => $tr->user_id, 'user_name' => $userNames[$tr->user_id], 'total' => $tr->total, 'total_after_fees' => $tr->total_after_fees, 'payment_method' => $tr->payment_method, 'token' => $tr->token, 'transaction' => $tr->transaction, 'processed' => $tr->processed, 'date_time' => $tr->created_at, ]; } return View::make('admin.transactions') ->with('transactions', $trans); } public function userPackages() { $userPackages = UserPackages::with('user') ->with('classes') ->get(); $packages = []; foreach ($userPackages as $up) { $numClassesUsed = count($up->classes); $packages[] = [ 'user_id' => $up->user_id, 'package_id' => $up->package_id, 'package_name' => $up->package->name, 'active' => ($numClassesUsed < $up->package->classes ? '1' : '0'), 'used' => $numClassesUsed, 'total' => $up->package->classes, ]; } return View::make('admin.packages') ->with('userPackages', $packages); } public function listClasses() { $classes = Evercisegroup::all(); $images = Gallery::where('counter', '>', 0)->get(); return View::make('admin.classes', compact('classes', 'images')); } public function landings() { $landings = LandingPages::all(); return View::make('admin.landings', compact('landings')); } public function landing($id) { $page = LandingPages::find($id); $categories = []; foreach (Subcategory::all() as $sub) { if (!in_array($sub->name, $categories)) { $categories[$sub->name] = $sub->name; } foreach ($sub->categories()->get() as $cat) { if (!in_array($cat->name, $categories)) { $categories[$cat->name] = $cat->name; } } } return View::make('admin.landing_manage', compact('page', 'categories')); } public function categoriesManage($id) { $category = Category::find($id); $groups = Evercisegroup::where('published', 1)->has('futuresessions') ->whereHas('subcategories', function ($query) use ($id) { $query->whereHas('categories', function ($query) use ($id) { $query->where('categories.id', $id); }); }) ->lists('name', 'id'); foreach ($groups as $id => $group) { $groups[$id] = $id.' - '.$group; } $subcategories = []; foreach ($category->subcategories as $subcat) { $subcategories[$subcat->id] = $subcat->name; } return View::make('admin.edit_category', compact('category', 'groups', 'subcategories')); } } <file_sep>/app/database/migrations/2014_08_28_151039_edit_columns_milestones.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EditColumnsMilestones extends Migration { /** * Run the migrations. * * @return void */ public function up() { // DB::statement('ALTER TABLE milestones MODIFY COLUMN referrals int(11)'); DB::statement('ALTER TABLE milestones MODIFY COLUMN profile int(11)'); DB::statement('ALTER TABLE milestones MODIFY COLUMN facebook int(11)'); DB::statement('ALTER TABLE milestones MODIFY COLUMN twitter int(11)'); DB::statement('ALTER TABLE milestones MODIFY COLUMN reviews int(11)'); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/views/admin/yukonhtml/php/pages/plugins-tables_footable.php <div class="row"> <div class="col-md-2"> <div class="list-group"> <a href="javascript:void(0)" class="active list-group-item">Footable</a> <a href="plugins-tables_datatable.html" class="list-group-item">Datatable</a> </div> </div> <div class="col-md-10"> <div class="row"> <div class="col-md-3"> <input id="textFilter" type="text" class="form-control input-sm"> <span class="help-block">Filter</span> </div> <div class="col-md-3"> <select class="form-control input-sm" id="userStatus"> <option></option> <option value="active">Active</option> <option value="disabled">Disabled</option> <option value="suspended">Suspended</option> </select> <span class="help-block">Status</span> </div> <div class="col-md-3"> <a class="btn btn-default btn-sm" id="clearFilters">Clear</a> </div> </div> <div class="row"> <div class="col-md-12"> <table class="table table-yuk2 toggle-arrow-tiny" id="footable_demo" data-filter="#textFilter" data-page-size="5"> <thead> <tr> <th data-toggle="true">First Name</th> <th> Last Name</th> <th data-hide="phone,tablet">Job Title</th> <th data-hide="phone,tablet" data-name="Date Of Birth"> DOB</th> <th data-hide="phone"> Status</th> </tr> </thead> <tbody> <tr> <td>Isidra</td> <td><a href="#">Boudreaux</a></td> <td>Traffic Court Referee</td> <td data-value="78025368997">22 Jun 1972</td> <td data-value="1"><span class="label label-success status-active" title="Active">Active</span></td> </tr> <tr> <td>Shona</td> <td>Woldt</td> <td><a href="#">Airline Transport Pilot</a></td> <td data-value="370961043292">3 Oct 1981</td> <td data-value="2"><span class="label label-default status-disabled" title="Disabled">Disabled</span></td> </tr> <tr> <td>Granville</td> <td>Leonardo</td> <td>Business Services Sales Representative</td> <td data-value="-22133780420">19 Apr 1969</td> <td data-value="3"><span class="label label-warning status-suspended" title="Suspended">Suspended</span> </td> </tr> <tr> <td>Easer</td> <td>Dragoo</td> <td>Drywall Stripper</td> <td data-value="250833505574">13 Dec 1977</td> <td data-value="1"><span class="label label-success status-active" title="Active">Active</span></td> </tr> <tr> <td>Maple</td> <td>Halladay</td> <td>Aviation Tactical Readiness Officer</td> <td data-value="694116650726">30 Dec 1991</td> <td data-value="3"><span class="label label-warning status-suspended" title="Suspended">Suspended</span> </td> </tr> <tr> <td>Maxine</td> <td><a href="#">Woldt</a></td> <td><a href="#">Business Services Sales Representative</a></td> <td data-value="561440464855">17 Oct 1987</td> <td data-value="2"><span class="label label-default status-disabled" title="Disabled">Disabled</span></td> </tr> <tr> <td>Lorraine</td> <td>Mcgaughy</td> <td>Hemodialysis Technician</td> <td data-value="437400551390">11 Nov 1983</td> <td data-value="2"><span class="label label-default status-disabled" title="Disabled">Disabled</span></td> </tr> <tr> <td>Lizzee</td> <td><a href="#">Goodlow</a></td> <td>Technical Services Librarian</td> <td data-value="-257733999319">1 Nov 1961</td> <td data-value="3"><span class="label label-warning status-suspended" title="Suspended">Suspended</span> </td> </tr> <tr> <td>Judi</td> <td>Badgett</td> <td>Electrical Lineworker</td> <td data-value="362134712000">23 Jun 1981</td> <td data-value="1"><span class="label label-success status-active" title="Active">Active</span></td> </tr> <tr> <td>Lauri</td> <td>Hyland</td> <td>Blackjack Supervisor</td> <td data-value="500874333932">15 Nov 1985</td> <td data-value="3"><span class="label label-warning status-suspended" title="Suspended">Suspended</span> </td> </tr> </tbody> <tfoot class="hide-if-no-paging"> <tr> <td colspan="5"> <ul class="pagination pagination-sm"></ul> </td> </tr> </tfoot> </table> </div> </div> </div> </div> <file_sep>/public/assets/jsdev/prototypes/17-fb-redirect.js function facebookRedirect(btn){ this.btn = btn; this.url = btn.attr('href'); this.redirect = ''; this.addListeners(); } facebookRedirect.prototype = { constructor : facebookRedirect, addListeners : function(){ $('input[name="trainer"]').on('change', $.proxy( this.changeFbUrl, this)); }, changeFbUrl : function(e){ var trainer = $(e.target).val(); if(trainer == 'yes'){ this.redirect = '/trainers.create'; if($('input[name="phone"]').length > 0){ $("label[for='phone']").find('small').text('(For Evercise to contact you)'); } } else{ this.redirect = ''; if($('input[name="phone"]').length > 0){ $("label[for='phone']").find('small').text('(Get alerts about your classes)'); } } this.btn.attr('href', this.url + this.redirect); } }<file_sep>/app/controllers/WalletsController.php <?php class WalletsController extends \BaseController { /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { return View::make('wallets.show'); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $result = Wallet::validWithdrawalRequest(Input::all(), $id); if ($result['validation_failed'] == 0) { return Response::json( [ 'callback' => 'openPopup', 'popup' => (string)(View::make('wallets.create')->with('withdrawal', $result['withdrawal'])->with( 'paypal', $result['paypal'] )) ] ); } return Response::json($result); } /** * Update the specified resource in storage. * @log info successful withdrawal request * @param int $id * @return Response */ public function update($id) { $valid_withrawal = Wallet::validWithdrawalRequest(Input::all(), $this->user->id); if ($valid_withrawal['validation_failed'] == 0) { $result = Withdrawalrequest::createWithdrawelRequest(Input::all(), $this->user->id); if ($result) { Log::info('successful withdrawal request'); Event::fire('wallet.request', [$this->user, Input::all()]); return Response::json($result); } } else { return Response::json($valid_withrawal); } } /** * Update users paypal details * * @param $userId * @return \Illuminate\Http\JsonResponse */ public function updatePaypal($userId) { Event::fire('wallet.updatePaypal', [$this->user, Input::all()]); return Response::json(Wallet::validPaypalUpdateRequest(Input::all(), $userId)); } }<file_sep>/app/composers/AdminShowUsersComposer.php <?php namespace composers; use User; use Sentry; use Input; class AdminShowUsersComposer { public function compose($view) { $sentryUsers = Sentry::findAllUsers(); $searchTerm = Input::get('search'); $users = User::with('evercisegroups')->where('display_name', 'LIKE', '%'.$searchTerm.'%')->whereHas('trainer', function($q){ //$q->where('confirmed', 1); })->get(); $view ->with('users', $users) ->with('sentryUsers', $sentryUsers); } }<file_sep>/public/assets/jsdev/prototypes/16-publish-class.js function publishClass(form){ this.form = form; this.addListeners(); } publishClass.prototype = { constructor: publishClass, addListeners: function(){ this.form.on("submit", $.proxy(this.submitForm, this)); }, submitForm: function(e) { e.preventDefault(); this.ajaxPost(); }, ajaxPost: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).after('<span id="publish-loading" class="icon icon-loading ml10"></span>'); }, success: function (data) { $('body').append(data.view); console.log(data.state); if(data.state == 1){ self.form.find("input[type='submit']").val('Un-publish'); self.form.find("input[name='publish']").val(0); } else { self.form.find("input[type='submit']").val('Publish'); self.form.find("input[name='publish']").val(1); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { //console.log('error'); console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false) $('#publish-loading').remove(); } }); } }<file_sep>/app/controllers/TokensController.php <?php class TokensController extends \BaseController { public function fb() { $application = Config::get('facebook'); $permissions = 'publish_stream'; $url_app = Request::root().'/tokens/fb'; // getInstance FacebookConnect::getFacebook($application); $getUser = FacebookConnect::getUser($permissions, $url_app); // Return facebook User data //return View::make('users/tokens')->with('accessToken', $facebookTokenJSON); if($getUser) { /* not working needs reviewing, not neccesary for now $fbUserProfile = $getUser['user_profile']; // grab the user profile from facebook connect $fbUserEmail = $fbUserProfile['email']; // grab the email address $checkForUser = User::where('email', $fbUserEmail)->first(); // check if a user already exists with this fb account if ($checkForUser) { return Redirect::to('users/'.$this->user->id.'/edit/evercoins')->with('errorNotification', 'This facebook account has already been redeemed'); } */ $token = Token::where('user_id', $this->user->id)->first(); $token->addToken('facebook', Token::makeFacebookToken($getUser)); event('user.facebook.connected', [$this->user]); } return Redirect::route('users.edit', [$this->user->display_name, 'wallet'])->with('success', 'Your facebook account has been linked successfully.'); } public function tw() { // Oauth token $oAuthToken = Input::get('oauth_token'); // Verifier token $verifier = Input::get('oauth_verifier'); // Request access token $accessToken = Twitter::oAuthAccessToken($oAuthToken, $verifier); // redirect URL in twitter app settings: http://dev.evercise.com/tokens/tw if($this->user) // This is just to stop it breaking from 127.0.0.1. { $userId = $this->user->id; if($accessToken) { $token = Token::where('user_id', $userId)->first(); $token->addToken('twitter', $accessToken); event('user.twitter.connected', [$this->user]); } } else { // Only from localhost because twitter redirects to 127.0.0.1 which buggers it up return View::make('users/tokens')->with('accessToken', $accessToken); } return Redirect::route('users.edit', [$this->user->display_name, 'wallet'])->with('success', 'Your twitter account has been linked successfully.'); } }<file_sep>/app/config/redirect.php <?php return [ 'what_is_evercise' => 'about_evercise', 'how_it_works' => 'about_evercise#how', 'style' => '/', 'img' => '/', 'class_guidelines' => 'fitness-class-guidelines', 'the_team' => 'leadership-team', 'packages' => 'fitness-packages', ];<file_sep>/app/lang/en/evercisegroups-trainer_index.php <?php return [ 'title' => ':name&apos;s class hub', 'subtitle' => 'You can add sessions, create new classes, clone classes and remove sessions from here', 'dates' => 'Dates', 'preview' => 'Preview', 'create_a_new_class' => 'Create a new class!', '' => '', ];<file_sep>/public/assets/jsdev/prototypes/15.preview-box.js function previewBox(box){ this.box = box; this.height = this.box.height(); this.init(); } previewBox.prototype ={ constructor: previewBox, init: function(){ $('#nav').css('margin-top', this.height); } }<file_sep>/app/composers/JoinSessionsComposer.php <?php namespace composers; use JavaScript; class JoinSessionsComposer { public function compose($view) { // get price and total frm view data $viewdata= $view->getData(); $sessionIds = $viewdata['sessionIds']; $total = isset($viewdata['total'])? $viewdata['total'] : 0; $price = isset($viewdata['price'])? $viewdata['price'] : 0; JavaScript::put( [ 'initJoinEvercisegroup' => json_encode(['sessions'=> $sessionIds,'total' => $total,'price' => $price]) ] ); } }<file_sep>/app/events/Milestone.php <?php namespace events; use Illuminate\Config\Repository; use Illuminate\Log\Writer; /** * Class Milestone * @package events */ class Milestone { /** * @var Dispatcher */ private $config; /** * @var Writer */ private $log; /** * @var Activity */ private $activity; /** * @param Writer $log * @param Repository $config * @param Activity $activity */ public function __construct( Writer $log, Repository $config, Activity $activity ) { $this->config = $config; $this->log = $log; $this->activity = $activity; } public function completed($user, $type, $title, $description) { $this->activity->milestoneCompleted($user, $type, $title, $description); } } <file_sep>/app/commands/IndexerGeo.php <?php use Illuminate\Console\Command; class IndexerGeo extends Command { /** * The console command name. * * @var string */ protected $name = 'indexer:geo'; /** * The console command description. * * @var string */ protected $description = 'Fix Issues with Geo location finding crap'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $time_start = microtime(true); $places = Place::where('lat', '<', 50)->get(); foreach ($places as $p) { $geo = Place::getGeo($p->name, true, true); $p->lat = $geo['lat']; $p->lng = $geo['lng']; $p->save(); } $places = Place::where('lat', '>', 55)->get(); foreach ($places as $p) { $geo = Place::getGeo($p->name, true, true); $p->lat = $geo['lat']; $p->lng = $geo['lng']; $p->save(); } $this->info('Geo fix Completed Completed'); $time = microtime(true) - $time_start; $this->info('Index a total of ' . round($time, 2) . ' seconds'); } } <file_sep>/app/composers/EvercisegroupCreateComposer.php <?php namespace composers; use JavaScript; use Config; class EvercisegroupCreateComposer { public function compose($view) { JavaScript::put( [ 'initSlider_price' => json_encode(['name'=>'price', 'min'=>1, 'max'=> Config::get('values')['max_price'], 'step'=>0.50, 'value'=>1, 'format'=>'dec']), 'initSlider_duration' => json_encode(['name'=>'duration', 'min'=>10, 'max'=>240, 'step'=>5, 'value'=>1]), 'initSlider_maxsize' => json_encode(['name'=>'maxsize', 'min'=>1, 'max'=>200, 'step'=>1, 'value'=>1]), 'initImage' => json_encode(['ratio' => 'group_ratio']), 'initPut' => json_encode(['selector' => '#evercisegroup_create']), 'initToolTip' => 1 ] ); $view; } }<file_sep>/app/events/Tracking.php <?php namespace events; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Http\Request; /** * Class Tracking * @package events */ class Tracking { /** * @var Repository */ protected $config; /** * @var Writer */ protected $log; /** * @param Writer $log * @param Repository $config * @param Request $request */ public function __construct(Writer $log, Repository $config, Request $request) { $this->config = $config; $this->log = $log; $this->request = $request; $this->enabled = (getenv('SALESFORCE_ENABLED') ?: FALSE); } /** * @param $user */ public function userRegistered($user) { $this->registerUserTracking($user, 'USER'); } /** * @param $user */ public function trainerRegistered($user) { $this->registerUserTracking($user, 'TRAINER'); } /** * @param $user */ public function userFacebookRegistered($user) { $this->registerUserTracking($user, 'FACEBOOK'); } /** * @param $user */ public function userLogin($user) { $this->registerUserTracking($user, 'USER', 'LOGIN'); } /** * @param $user */ public function userFacebookLogin($user) { $this->registerUserTracking($user, 'FACEBOOK', 'LOGIN'); } /** * @param $user */ public function userEdit($user) { $this->registerUserTracking($user, 'USER', 'EDIT'); } /** * @param $user */ public function trainerEdit($user) { $this->registerUserTracking($user, 'TRAINER', 'EDIT'); } /** * @param $user */ public function userChangedPassword($user) { } /** * @param $user */ public function userLogout($user) { } /** * @param $user * @param $session */ public function userClassSignup($user, $session) { return $this->registerUserSessionTracking($user, $session); } /** * @param $user * @param string $type * @param string $func */ public function registerUserTracking($user, $type = 'USER', $func = 'REGISTER') { $user_object = $this->formatUser($user, $type); if ($func != 'REGISTER') { if (empty($user->salesforce_id)) { $func = 'REGISTER'; } } if ($this->enabled) { switch ($func) { case "REGISTER": $this->log->info('CASE REGISTER'); $res = \Salesforce::create([$user_object], 'Contact'); $user->salesforce_id = $res[0]->id; $user->save(); case "EDIT": $user_object->id = $user->salesforce_id; $res = \Salesforce::update([$user_object], 'Contact'); break; case "LOGIN": $obj = new \stdClass(); $obj->id = $user->salesforce_id; $obj->Last_Login__c = gmdate("Y-m-d\TH:i:s\Z", time()); $res = \Salesforce::update([$obj], 'Contact'); break; } $this->log->info($res); $this->log->info($func); $this->log->info($type . ' ' . $user->id . ' ' . $user->salesforce_id . ' ' . $func . ' in SalesForce'); } return $user; } /** * @param $user * @param $session */ public function registerUserSessionTracking($user, $session) { $relation = new \stdClass(); /** Check if we dont have them in the DB and create them */ if (empty($session->salesforce_id)) { $session = $this->registerSessionTracking($session); } if (empty($user->salesforce_id)) { $user = $this->registerUserTracking($user, 'USER', 'REGISTER'); } $relation->Class__c = $session->salesforce_id; $relation->Registrant__c = $user->salesforce_id; if ($this->enabled) { $res = \Salesforce::create([$relation], 'Class_Registrant__c'); } $this->log->info('Relation Created in SalesForce ' . (implode(',', array_values((array)$relation)))); } /** * @param $user * @param string $type * @param string $func */ public function registerSessionTracking($session) { $this->log->info('REGISTERING USER TRACKING'); $class_obj = $this->formatSessionClass($session); if ($this->enabled) { $res = \Salesforce::create([$class_obj], 'Class__c'); $session->salesforce_id = $res[0]->id; $session->save(); } $this->log->info('New Session ' . $session->id . ' in SalesForce ' . $session->salesforce_id); return $session; } /** * @param $user * @param $type * @param $user_arr */ public function formatUser($user, $type) { $user_data = []; $user_data['RecordTypeId'] = '01220000000As0T'; $user_arr = $user->toArray(); $trainer = $user->trainer; if (!is_null($trainer)) { $user_data['RecordTypeId'] = '01220000000As0O'; $user_data['Profession__c'] = $trainer->profession; $user_data['Bio__c'] = substr($trainer->bio, 0, 499); $user_data['Website__c'] = $trainer->website; } $user_data['Gender__c'] = ($user_arr['gender'] == 1 ? 'Male' : 'Female'); $map = [ 'email' => 'Email', 'first_name' => 'FirstName', 'last_name' => 'LastName', 'phone' => 'Phone' ]; foreach ($map as $key => $val) { $user_data[$val] = $user_arr[$key]; } if(empty($user_data['LastName'])) { $user_data['LastName'] = 'none'; } if(empty($user_data['FirstName'])) { $user_data['FirstName'] = $user_arr['display_name']; } if (!empty($user_arr['dob']) && strtotime($user_arr['dob']) > 1000) { $user_data['Birthdate'] = gmdate("Y-m-d\TH:i:s\Z", strtotime($user_arr['dob'])); } if (!empty($user_arr['last_login']) && strtotime($user_arr['last_login']) > 1000) { $user_data['Last_Login__c'] = gmdate("Y-m-d\TH:i:s\Z", strtotime($user_arr['last_login'])); } $user_data['MailingCountry'] = 'United Kingdom'; unset($user_data['id']); return (object)$user_data; } /** * @param $session * @return \stdClass */ public function formatSessionClass($session) { $class = $session->evercisegroup; $user = $class->user; $venue = $class->venue; $categories = $class->subcategories; $main_categories = []; $categories_arr = []; foreach ($categories as $cat) { $categories_arr[] = $cat->name; $first = $cat->categories()->first(); if (!empty($first->name)) { $main_categories[$first->name] = TRUE; } } $class_obj = new \stdClass(); switch ($class->gender) { case "0": $target_gender = ''; break; case "1": $target_gender = 'Male'; break; case "2": $target_gender = 'Female'; break; } $this->log->info('SALESFORCE '.$user->salesforce_id); if(empty($user->salesforce_id)) { $this->log->info('SALESFORCE a'.$user->salesforce_id); $user_object = $this->formatUser($user, 'REGISTER'); $res = \Salesforce::create([$user_object], 'Contact'); $user->salesforce_id = $res[0]->id; $user->save(); } $class_obj->Name = $class->name . ' | ' . $session->id; $class_obj->Trainer__c = $user->salesforce_id; $class_obj->Description__c = $user->description; $class_obj->Category__c = implode(', ', array_keys($main_categories)); $class_obj->Category_1__c = (!empty($categories_arr[0]) ? $categories_arr[0] : ''); $class_obj->Category_2__c = (!empty($categories_arr[1]) ? $categories_arr[1] : ''); $class_obj->Category_3__c = (!empty($categories_arr[2]) ? $categories_arr[2] : ''); $class_obj->Venue_Name__c = $venue->name; $class_obj->Street_name_and_number__c = $venue->address; $class_obj->City__c = $venue->town; $class_obj->Postcode__c = $venue->postcode; $class_obj->Duration_mins__c = $session->duration; $class_obj->Maximum_Class_Size__c = $class->capacity; $class_obj->Price__c = $session->price; $class_obj->Target_Gender__c = $target_gender; $class_obj->Date_Time__c = gmdate("Y-m-d\TH:i:s\Z", strtotime($session->date_time)); return $class_obj; } }<file_sep>/app/models/Facility.php <?php /** * Class Facility */ class Facility extends Eloquent { /** * @var array */ protected $fillable = ['id', 'name', 'category', 'details', 'image']; /** * The database table used by the model. * * @var string */ protected $table = 'facilities'; /** * Get an array of facilities and an array of amenities. [id, name] * * @return array */ public static function getLists() { $amenities = Facility::where('category', 'amenity')->lists('name', 'id' ); $facilities = Facility::where('category', 'facility')->lists('name', 'id'); return ['facilities' => $facilities, 'amenities' => $amenities]; } }<file_sep>/app/models/Trainer.php <?php /** * Class Trainer */ class Trainer extends \Eloquent { /** * @var array */ protected $fillable = ['user_id', 'bio', 'website', 'specialities_id', 'gender', 'profession']; /** * The database table used by the model. * * @var string */ protected $table = 'trainers'; public static $validationRules = [ // validation for these fields upon update lies in User/validateUserEdit 'bio' => 'required|max:500|min:50', 'image' => 'required', 'website' => 'sometimes', 'profession' => 'required|max:50|min:2', ]; /** * @return \Illuminate\Database\Eloquent\Collection|static[] */ public static function getUnconfirmedTrainers() { $trainers = static::with('user')->where('confirmed', 0)->get(); return $trainers; } /** * @param $user */ public static function approve($user) { try { event('user.upgrade', [$user]); } catch (Exception $e) { return 'Cannot send email. Trainer NOT approved' . $e; } static::where('user_id', $user->id)->update(['confirmed' => 1]); } /** * @param $user */ public static function unapprove($user) { static::where('user_id', $user->id)->update(['confirmed' => 0]); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function speciality() //return $this; { return $this->hasOne('Speciality', 'id', 'specialities_id'); } /** * * * @param $params * @return bool|\Illuminate\Database\Eloquent\Model|static */ public static function createOrFail($params) { $user_id = $params['user_id']; if (count(Trainer::where('user_id', $user_id)->get()) < 1) { $newRecord = Trainer::create($params); return $newRecord; } else { return FALSE; } } public Static function isTrainerLoggedIn() { if (Sentry::check() ? (Sentry::getUser()->inGroup(Sentry::findGroupByName('trainer'))) : FALSE) { return TRUE; } else { return FALSE; } } /** * @return \Illuminate\Validation\Validator */ public static function validTrainerSignup($inputs) { $validator = self::validateTrainerSignup($inputs); return self::handleTrainerValidation($validator); } /** * @param $inputs * @return \Illuminate\Validation\Validator */ public static function validateTrainerSignup($inputs) { // validation rules for input field on register form $validator = Validator::make( $inputs, static::$validationRules ); return $validator; } public static function handleTrainerValidation($validator) { if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; } else { // if validation passes return validation_failed false $result = [ 'validation_failed' => 0 ]; } return $result; } public function updateTrainer($params) { $this->update(array_filter($params)); } }<file_sep>/public/assets/jsdev/helpers.js $.fn.exists = function(callback) { var args = [].slice.call(arguments, 1); if (this.length) { callback.call(this, args); } return this; }; function datepick(){ $('.date-picker').datepicker({ format: "yyyy-mm-dd", startDate: "+2d", autoclose: true, todayHighlight: true }); }<file_sep>/app/cronjobs/DailyIndexer.php <?php namespace cronjobs; use Illuminate\Log\Writer; use Illuminate\Console\Application as Artisan; class DailyIndexer { private $log; private $artisan; public function __construct(Writer $log, Artisan $artisan) { $this->log = $log; $this->artisan = $artisan; } function run() { $this->log->info('Running Daily Indexer'); $this->artisan->call('indexer:index'); } }<file_sep>/app/assets/javascripts/calendar.js //calendar.js function calendarSlide () { // create a array to store scrolling posistions class_top = new Array(); class_height = new Array(); class_id = new Array(); class_name = new Array(); class_duration = new Array(); // find top of each class and add it to the class top array // get the height of each class $('.hub-row').each(function(){ class_id.push($(this).data('id')); class_name.push($(this).data('name')); class_top.push($(this).offset().top); class_height.push($(this).height()); class_duration.push($(this).data('duration')); }) // set i var i = 0; var p = -1; mt = parseInt($('#calendar').css('marginTop')); topmt = mt; bottom = parseInt(class_height[class_height.length - 1] + mt); // get window position $(window).scroll(function(evt) { var y = $(this).scrollTop(); var calandar = $('#calendar'); if( y == 0 ){ calandar.css({ marginTop: topmt+ 'px', '-webkit-transition': 'all 0.5s ease', '-moz-transition': 'all 0.5s ease', '-o-transition': 'all 0.5s ease', 'transition': 'all 0.5s ease' }); $('#evercisegroupId').val(class_id[0]); $('#evercisegroupName').val(class_name[0]); $('#evercisegroupDuration').val(class_duration[0]); $('.hub-row').removeClass('selected'); $('div[data-id="'+class_id[0]+'"]').addClass('selected'); } else if (y >= class_top[i] && y < class_top[class_top.length - 1] ) { mt = parseInt(mt + class_height[i]); calandar.css({ marginTop: mt+'px', '-webkit-transition': 'all 0.5s ease', '-moz-transition': 'all 0.5s ease', '-o-transition': 'all 0.5s ease', 'transition': 'all 0.5s ease' }); i++; p++; $('#evercisegroupId').val(class_id[i]); $('#evercisegroupName').val(class_name[i]); $('#evercisegroupDuration').val(class_duration[i]); $('.hub-row').removeClass('selected'); $('div[data-id="'+class_id[i]+'"]').addClass('selected'); } else if( y < class_top[p] && p >= 0){ $('.hub-row').removeClass('selected'); $('div[data-id="'+class_id[p]+'"]').addClass('selected'); $('#evercisegroupId').val(class_id[p]); $('#evercisegroupName').val(class_name[p]); $('#evercisegroupDuration').val(class_duration[p]); i--; mt = parseInt(mt - class_height[i]); calandar.css({ marginTop: mt+'px', '-webkit-transition': 'all 0.5s ease', '-moz-transition': 'all 0.5s ease', '-o-transition': 'all 0.5s ease', 'transition': 'all 0.5s ease' }); p--; }; }); } registerInitFunction('calendarSlide'); <file_sep>/app/composers/TimeComposer.php <?php namespace composers; class TimeComposer { public function compose($view) { $hours = array(); for ($i = 0; $i < 24; $i ++) { $hours[sprintf("%02s", $i)] = sprintf("%02s", $i); } $minute_intervals = 15; $minutes = array(); for ($i = 0; $i < 60; $i += $minute_intervals) { $minutes[sprintf("%02s", $i)] = sprintf("%02s", $i); } $hourDefault = (isset($view->hourDefault) ? $view->hourDefault : '12'); $minuteDefault = (isset($view->minuteDefault) ? $view->minuteDefault : '00'); $view->with('hours', $hours)->with('minutes', $minutes)->with('hourDefault', $hourDefault)->with( 'minuteDefault', $minuteDefault ); } }<file_sep>/app/models/EmailStats.php <?php class EmailStats extends Eloquent { /** * @var array */ public $fillable = [ 'uid', 'status', 'sg_event_id', 'reason', 'event', 'purchase', 'email', 'timestamp', 'smtp-id', 'type', 'category' ]; protected $table = 'email_stats'; }<file_sep>/app/database/seeds/EvercoinsTableSeeder.php <?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class EvercoinsTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('evercoins')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Evercoin::create(array('user_id' => '1')); } }<file_sep>/app/controllers/ajax/VenuesController.php <?php namespace ajax; use Input, Response, Venue, Sentry, \widgets\LocationController; class VenuesController extends AjaxBaseController{ public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } /** * POST Params: * name * address * town * postcode * facilities_array (array of id's) * * @return \Illuminate\Http\JsonResponse */ public function store() { $inputs = Input::all(); $address = $inputs['address']; $town = $inputs['town']; $postcode = $inputs['postcode']; $geo = LocationController::addressToGeo([ $address, $town, $postcode ]); $result = Venue::validateAndStore( $this->user->id, $inputs, $geo, $this->user ); return Response::json($result); } public function edit() { $venue = Venue::find(Input::get('venue_id')); $res = ['error' => true, 'message' => '']; if(!isset($venue->id)) { $res['message'] = 'Venue Does not Exist'; return Response::json($res); } if($this->user->id != $venue->user_id) { $res['message'] = 'You dont have permissions to edit this class'; return Response::json($res); } $res['error'] = 'false'; $res['venue'] = $venue->toArray(); $facilities = $venue->getFacilities(); $amenities = $venue->getAmenities(); foreach($facilities as $f) { $res['facilities'][] = [ 'id' => $f->id, 'name' => $f->name, 'image' => $f->image, ]; } foreach($amenities as $f) { $res['amenities'][] = [ 'id' => $f->id, 'name' => $f->name, 'image' => $f->image, ]; } return Response::json($res); } /** * POST Params: * name * address * town * postcode * facilities_array (array of id's) * * @param $id * @return \Illuminate\Http\JsonResponse */ public function update($id) { $result = Venue::find($id)->validateAndUpdate( Input::all() , $this->user ); return Response::json($result); } }<file_sep>/app/database/migrations/2014_06_25_103829_create_areacodes_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAreacodesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('areacodes')) { Schema::create('areacodes', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string('area_code', 20); $table->string('area_covered', 200); $table->string('official_Ofcom', 200); $table->string('Previous_BT', 200); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); Schema::drop('areacodes'); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } } <file_sep>/app/database/seeds/MarketingpreferencesTableSeeder.php <?php class MarketingpreferencesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('marketingpreferences')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Marketingpreference::create(array('name' => 'newsletter', 'option' => 'yes')); Marketingpreference::create(array('name' => 'newsletter', 'option' => 'no')); } }<file_sep>/app/cronjobs/GenerateSalesforceSessionIds.php <?php namespace cronjobs; use events\Tracking; use Evercisesession; use Illuminate\Log\Writer; class GenerateSalesforceSessionIds { private $log; private $tracking; private $evercisesession; public function __construct(Writer $log, Tracking $tracking, Evercisesession $evercisesession) { $this->log = $log; $this->tracking = $tracking; $this->evercisesession = $evercisesession; } function run() { $this->log->info('Running Daily Indexer'); $sessions = $this->evercisesession->where('salesforce_id', '')->limit(30)->get(); foreach($sessions as $session) { $session = $this->tracking->registerSessionTracking($session); $this->log->info('Session Created '.$session->salesforce_id); } $this->log->info('Completed '.$sessions->count()); } }<file_sep>/app/models/PingElastic.php <?php /** * Class PingElastic */ class PingElastic { /** * @var Evercisegroup */ protected $evercisegroup; /** * @var \Illuminate\Log\Writer */ protected $log; /** * @var Elastic */ protected $elastic; /** * @var */ protected $search; /** * @param Evercisegroup $evercisegroup * @param \Illuminate\Log\Writer $log * @param Es $elasticsearch * @param Geotools $geotools */ public function __construct( Evercisegroup $evercisegroup, Illuminate\Log\Writer $log, Es $elasticsearch, Geotools $geotools ) { $this->evercisegroup = $evercisegroup; $this->log = $log; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); } /** * Ping ElasticSearch Instance * @return bool */ public function check() { return $this->elastic->ping(); } }<file_sep>/app/events/Activity.php <?php namespace events; use Activities; use Evercisesession; use Illuminate\Config\Repository; use Illuminate\Log\Writer; use Illuminate\Events\Dispatcher; /** * Class Activity * @package events */ class Activity { /** * @var Dispatcher */ private $config; /** * @var Writer */ private $log; /** * @var Dispatcher */ private $event; /** * @var Activities */ private $activities; /** * @var Evercisesession */ private $evercisesession; /** * @var Mail */ protected $mail; /** * @param Writer $log * @param Repository $config * @param Dispatcher $event * @param Activities $activities * @param Evercisesession $evercisesession * @param Mail $mail */ public function __construct( Writer $log, Repository $config, Dispatcher $event, Activities $activities, Evercisesession $evercisesession, Mail $mail ) { $this->config = $config; $this->log = $log; $this->event = $event; $this->activities = $activities; $this->evercisesession = $evercisesession; $this->mail = $mail; } /** * @param $id */ private function getSession($id) { return $this->evercisesession->find($id); } private function fixAmountDisplay($amount) { if (strpos($amount, '-') !== FALSE) { return str_replace('-', '-£', $amount); } return '£' . $amount; } /** * @param $class * @param $user */ public function payedClass($class, $user) { $trainer = $class->user()->first(); $this->activities->create([ 'title' => 'Joined class', 'description' => $class->name, 'link' => 'classes/' . $class->id, 'link_title' => 'View class', 'type' => 'payedclass', 'image' => $trainer->directory . '/' . $class->image, 'user_id' => $user->id, 'type_id' => $class->id ]); } /** * @param $class * @param $user */ public function canceledClass($class, $user) { $this->activities->create([ 'title' => 'Canceled class', 'description' => $class->name, 'type' => 'canceledclass', 'image' => $user->directory . '/' . $class->image, 'link' => 'classes/' . $class->id, 'user_id' => $user->id, 'type_id' => $class->id, ]); } /** * @param $class * @param $user */ public function unPublishedClass($class, $trainer) { $this->activities->create([ 'title' => 'Class unpublished', 'description' => $class->name, 'type' => 'classunpublished', 'image' => 'assets/img/activity/Activity_Class_Unpublished.png', 'link' => 'classes/' . $class->slug, 'link_title' => 'View', 'user_id' => $trainer->id, 'type_id' => $class->id, ]); } /** * @param $class * @param $user */ public function publishedClass($class, $trainer) { $this->activities->create([ 'title' => 'Class Published', 'description' => $class->name, 'type' => 'classpublished', 'image' => 'assets/img/activity/Activity_Class_Published.png', 'link' => 'classes/' . $class->slug, 'link_title' => 'View', 'user_id' => $trainer->id, 'type_id' => $class->id, ]); } /** * @param $user * @param $transaction */ public function walletToppup($user, $transaction) { $this->activities->create([ 'title' => 'Top Up', 'type' => 'wallettoppup', 'description' => $this->fixAmountDisplay($transaction->total) . ' credit to your account on ' . date('d/m/y'), 'user_id' => $user->id, 'type_id' => $transaction->id, 'link' => 'transactions/' . $transaction->id, 'link_title' => 'View', 'image' => 'assets/img/activity/Activity_Topped_Up.png', ]); } /** * @param $user * @param int $amount */ public function walletWithdraw($user, $amount = 0) { // $this->activities->create([ // 'description' => '£' . $amount . ' amount Withdrawn', // 'type' => 'walletwithdraw', // 'user_id' => $user->id // ]); $this->activities->create([ 'title' => 'Wallet Withdraw', 'type' => 'wallettoppup', 'description' => $this->fixAmountDisplay($amount) . ' amount Withdrawn', 'user_id' => $user->id, 'type_id' => $user->id, 'link' => 'profile/' . $user->id . '/wallet', 'link_title' => 'View', 'image' => 'assets/img/activity/Activity_Withdawal.png', ]); } /** * @param $user */ public function trainerRegistered($user) { $this->activities->create([ 'title' => 'Became a Instructor', 'type' => 'trainerregistered', 'description' => 'Welcome', 'user_id' => $user->id, 'type_id' => $user->id, 'link' => 'instructors/' . $user->display_name, 'link_title' => 'Page', 'image' => 'assets/img/activity/Activity_Joined_Evercise.png', ]); } /** * @param $user */ public function userRegistered($user) { $this->activities->create([ 'title' => 'Joined Evercise', 'type' => 'userregistered', 'description' => 'Welcome', 'user_id' => $user->id, 'type_id' => $user->id, 'link' => 'profile/' . $user->display_name, 'link_title' => 'Profile', 'image' => 'assets/img/activity/Activity_Joined_Evercise.png', ]); } /** * @param $user */ public function userEditProfile($user) { // $this->activities->create([ // 'description' => 'Edited your profile', // 'type' => 'editprofile', // 'user_id' => $user->id // ]); } /** * @param $user */ public function linkFacebook($user) { $this->activities->create([ 'title' => 'Facebook', 'type' => 'linkfacebook', 'description' => 'Linked account', 'user_id' => $user->id, 'type_id' => $user->id, 'link' => 'profile/' . $user->display_name, 'link_title' => 'Profile', 'image' => 'assets/img/activity/Activity_Facebook.png', ]); } /** * @param $user */ public function linkTwitter($user) { $this->activities->create([ 'title' => 'Twitter', 'type' => 'linkedtwitter', 'description' => 'Linked account', 'user_id' => $user->id, 'type_id' => $user->id, 'link' => 'profile/' . $user->display_name, 'link_title' => 'Profile', 'image' => 'assets/img/activity/Activity_Twitter.png', ]); } /** * @param $user * @param string $email */ public function invitedEmail($user, $email = '') { if ($email != '') { // // $this->activities->create([ // 'description' => 'Invited ' . $email . ' to join Evercise', // 'type' => 'invitedemail', // 'user_id' => $user->id // ]); } } /** * @param $class * @param $user */ public function createdClass($class, $user) { $this->activities->create([ 'title' => 'You created a class', 'type' => 'createclass', 'description' => $class->name, 'user_id' => $user->id, 'type_id' => $class->id, 'link' => 'classes/' . $class->id, 'link_title' => 'View', 'image' => $user->directory . '/search_' . $class->image, ]); } /** * @param $venue * @param $user */ public function createdVenue($venue, $user) { $this->activities->create([ 'title' => 'Venue Created', 'description' => $venue->name, 'type' => 'createvenue', 'description' => $venue->name, 'user_id' => $user->id, 'type_id' => $venue->id, 'link' => FALSE, 'link_title' => FALSE, 'image' => 'https://maps.googleapis.com/maps/api/staticmap?zoom=11&size=105x85&maptype=roadmap&markers=color:pink%7Clabel:e%7C' . $venue->lat . ',' . $venue->lng ]); } /** * @param $class * @param $user */ public function createdSessions($class, $user) { // $this->activities->create([ // 'description' => 'Created Multiple sessions for ' . $class->name, // 'type' => 'createdsessions', // 'user_id' => $user->id, // 'type_id' => $class->id // ]); } /** * @param $class * @param $user */ public function updatedClass($class, $user) { $this->activities->create([ 'title' => 'Updated a Class', 'type' => 'updatedclass', 'description' => $class->name, 'user_id' => $user->id, 'type_id' => $class->id, 'link' => 'classes/' . $class->id, 'link_title' => 'View', 'image' => 'updatedclass.png', ]); } /** * @param $venue * @param $user */ public function updatedVenue($venue, $user) { $this->activities->create([ 'title' => 'Venue Updated', 'description' => $venue->name, 'type' => 'updatevenue', 'user_id' => $user->id, 'type_id' => $venue->id, 'link' => FALSE, 'link_title' => FALSE, 'image' => 'https://maps.googleapis.com/maps/api/staticmap?zoom=11&size=105x85&maptype=roadmap&markers=color:pink%7Clabel:e%7C' . $venue->lat . ',' . $venue->lng ]); } /** * @param $class * @param $user */ public function updatedSessions($class, $user) { // $this->activities->create([ // 'description' => 'Created Sessions for ' . $class->name, // 'type' => 'updatedsessions', // 'user_id' => $user->id, // 'type_id' => $class->id // ]); } /** * @param $class * @param $user */ public function deletedClass($class, $user) { $this->activities->create([ 'title' => 'Deleted a Class', 'type' => 'deletedclass', 'description' => $class->name, 'user_id' => $user->id, 'type_id' => $class->id, 'link' => 'classes/' . $class->id, 'link_title' => 'View', 'image' => $user->directory . '/' . $class->image, ]); } /** * @param $venue * @param $user */ public function deletedVenue($venue, $user) { $this->activities->create([ 'description' => 'Deleted Venue ' . $venue->name, 'type' => 'deletedclass', 'user_id' => $user->id, 'type_id' => $venue->id ]); } /** * @param $class * @param $user */ public function deletedSessions($class, $user) { // $this->activities->create([ // 'description' => 'Deleted Sessions ' . $class->name, // 'type' => 'deletedsessions', // 'user_id' => $user->id, // 'type_id' => $class->id // ]); } /** * @param $user * @param $class */ public function userReviewedClass($user, $trainer, $rating, $session, $evercisegroup) { $this->activities->create([ 'title' => 'You recently reviewed', 'type' => 'classreviewed', 'description' => $evercisegroup->name, 'user_id' => $user->id, 'type_id' => $evercisegroup->id, 'link' => 'classes/' . $evercisegroup->id, 'link_title' => 'View', 'image' => 'assets/img/activity/Activity_Reviewed_Class.png', ]); $this->mail->userReviewedClass($user, $trainer, $rating, $session, $evercisegroup); $this->mail->thanksForReview($user, $trainer, $rating, $session, $evercisegroup); } /** * @param $coupon * @param $user */ public function usedCoupon($coupon, $user) { $this->activities->create([ 'title' => 'You used the coupon code: ' . $coupon->coupon, 'type' => 'couponused', 'description' => ($coupon->type == 'amount' ? 'Worth £' . round($coupon->amount, 2) : 'With ' . $coupon->percentage . '% discount'), 'user_id' => $user->id, 'type_id' => $coupon->id, 'link' => '', 'link_title' => '', 'image' => 'assets/img/activity/Activity_Coupon.png', ]); } /** * * Mark the purchase completed * @param $user * @param $cart * @param $transaction */ public function userCartCompleted($user, $cart, $transaction) { $title = 'You recently made a purchase'; $description = ''; if (count($cart['sessions']) > 0 && count($cart['packages']) > 0) { $description = 'Bought a total of ' . count($cart['sessions']) . ' ' . returnPlural('session', $cart['sessions']) . ' and ' . count($cart['packages']) . ' ' . returnPlural('package', $cart['packages']); } elseif (count($cart['sessions']) > 0 && count($cart['packages']) == 0) { $description = 'Bought a total of ' . count($cart['sessions']) . ' ' . returnPlural('session', $cart['sessions']); } elseif (count($cart['sessions']) == 0 && count($cart['packages']) > 0) { $description = 'Bought a total of ' . count($cart['packages']) . ' ' . returnPlural('package', $cart['packages']); } $description .= ' for ' . $this->fixAmountDisplay($cart['total']['final_cost']); $data = [ 'description' => $description, 'title' => $title, 'link' => 'transaction/' . $transaction->id, 'link_title' => 'View transaction', 'image' => 'assets/img/activity/Activity_Made_Purchase.png', 'type' => 'cartcompleted', 'user_id' => $user->id, 'type_id' => $transaction->id ]; $activity = $this->activities->create($data); } /** * @param $user * @param $transaction */ public function userTopupCompleted($user, $transaction, $type) { $title = 'Wallet top-up'; $description = 'With ' . $this->fixAmountDisplay($transaction->total); $data = [ 'description' => $description, 'title' => $title, 'link' => 'transaction/' . $transaction->id, 'link_title' => 'View transaction', 'image' => 'assets/img/activity/Activity_Topped_Up.png', 'type' => $type, 'user_id' => $user->id, 'type_id' => $transaction->id ]; $activity = $this->activities->create($data); } /** * @param $user * @param $transaction */ public function userReferralCompleted($user, $amount, $type) { $title = 'Referral completed'; $description = 'With ' . $this->fixAmountDisplay($amount); $data = [ 'description' => $description, 'title' => $title, 'link' => '', 'link_title' => '', 'image' => 'assets/img/activity/Activity_Refferal.png', 'type' => $type, 'user_id' => $user->id, 'type_id' => 0 ]; $activity = $this->activities->create($data); } /** * @param $user * @param $transaction */ public function userReferralSignup($user, $amount, $type) { $title = 'Signup from referral'; $description = 'With ' . $this->fixAmountDisplay($amount); $data = [ 'description' => $description, 'title' => $title, 'link' => '', 'link_title' => '', 'image' => 'assets/img/activity/Activity_Refferal.png', 'type' => $type, 'user_id' => $user->id, 'type_id' => 0 ]; $activity = $this->activities->create($data); } /** * @param $user * @param $transaction */ public function userWithdrawCompleted($user, $transaction) { $title = 'Wallet Withdrawal'; $description = 'With ' . $this->fixAmountDisplay($transaction->total); $data = [ 'description' => $description, 'title' => $title, 'link' => 'transaction/' . $transaction->id, 'link_title' => 'View transaction', 'image' => 'assets/img/activity/Activity_Withdrawal.png', 'type' => 'withdrawcompleted', 'user_id' => $user->id, 'type_id' => $transaction->id ]; $activity = $this->activities->create($data); } /** PACKAGES * * Deduct a item from a package * @param $user * @param $userpackage * @param $session */ public function packageUsed($user, $userpackage, $session) { $package = $userpackage->package()->first(); $class = $session->evercisegroup()->first(); $amountUsed = $userpackage->amountUsed($userpackage->id); $this->activities->create([ 'title' => $class->name . ' deducted from package', 'type' => 'packageused', 'description' => ($amountUsed > $package->classes ? 'You have ' . ($package->classes - $amountUsed) . ' left with this package' : 'You have used up all classes on this package'), 'user_id' => $user->id, 'type_id' => $userpackage->id, 'link' => ($amountUsed > $package->classes ? 'packages/' : ''), 'link_title' => ($amountUsed > $package->classes ? 'Buy more' : ''), 'image' => 'assets/img/activity/Activity_Package.png', ]); } public function milestoneCompleted($user, $type, $title, $description) { $this->activities->create([ 'title' => $title, 'description' => $description, 'link' => FALSE, 'link_title' => FALSE, 'type' => 'milestonecompleted', 'image' => 'assets/img/activity/Activity_Milestone.png', 'user_id' => $user->id, 'type_id' => $user->id ]); } public function ppcSignup($user, $amount, $type, $description = 0) { $this->activities->create([ 'title' => $description ? $description : 'Signup from PPC', 'description' => 'With ' . $this->fixAmountDisplay($amount), 'link' => FALSE, 'link_title' => FALSE, 'type' => $type, 'image' => 'assets/img/activity/Activity_Milestone.png', 'user_id' => $user->id, 'type_id' => 0 ]); } }<file_sep>/app/controllers/EmailGrabber.php <?php class EmailGrabber extends Controller { /** * @var EmailStats */ private $emailstats; public function __construct(EmailStats $emailstats) { $this->emailstats = $emailstats; } public function grab() { $all = Input::all(); foreach($all as $a) { $stat = []; foreach($this->emailstats->fillable as $key) { if($key == 'id') { continue; } if(!empty($a[$key])) { if($key == 'category') { $a[$key] = implode(', ', $a[$key]); } $stat[$key] = $a[$key]; } } if(count($stat) > 0) { $this->emailstats->create($stat); } } } }<file_sep>/app/models/Activities.php <?php /** * Class Areacodes */ class Activities extends Eloquent { /** * @var array */ protected $fillable = array('id', 'type', 'type_id', 'description', 'user_id', 'link', 'link_title', 'image', 'title'); /** * The database table used by the model. * * @var string */ protected $table = 'activity'; public static function getAll($user_id, $limit = 100){ return static::select(DB::raw('*, DATE_FORMAT(created_at,"%M %D %Y") as format_date'))->where('user_id', $user_id)->orderBy('id', 'desc')->limit($limit)->get(); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function transaction() { return $this->hasOne('Transactions', 'id', 'type_id'); } }<file_sep>/app/controllers/email/SessionMailer.php <?php namespace email; use HTML; class SessionMailer extends Mailer { /** * Outline all the events this class will be listening for. * @param [type] $events * @return void */ public function subscribe($events) { /** Removed */ } }<file_sep>/app/database/migrations/2014_09_05_100544_create_evercise_places_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEvercisePlacesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('places')) { Schema::create('places', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string ('name', 255); $table->tinyInteger('place_type', FALSE, TRUE)->default(1); $table->tinyInteger('zone', FALSE, TRUE)->default(1); $table->double('lat'); $table->double('lng'); $table->string('min_radius', 10); $table->text('poly_coordinates'); $table->enum('coordinate_type', array('radius', 'polygon'))->default('radius'); $table->timestamps(); //Indexes $table->index('place_type'); $table->index('name'); $table->index('coordinate_type'); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('places'); } } <file_sep>/app/database/seeds/ImportOldSeeder.php <?php class ImportOldSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('UsersTableSeeder'); $this->command->info('Users seeded!'); $this->call('TrainersTableSeeder'); $this->command->info('Trainers seeded!'); $this->call('EvercisegroupsTableSeeder'); $this->command->info('Evercisegroups seeded!'); $this->call('SessionsTableSeeder'); $this->command->info('Sessions seeded!'); $this->call('SessionMembersTableSeeder'); $this->command->info('SessionMembers seeded!'); } }<file_sep>/app/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ /* Show home page */ Route::get('/', ['as' => 'home', 'uses' => 'HomeController@showWelcome']); Route::get( 'popular', [ 'as' => 'popular', function () { return Redirect::to('uk/london'); } ] ); foreach (Config::get('redirect') as $old => $new) { Route::get( $old, [ function () use ($new) { return Redirect::to($new); } ] ); } Route::get('email', [ 'before' => 'admin', function () { $mail = App::make('events\Mail'); return $mail->sendEmailAgain(); } ] ); Route::get('ttt', [ 'before' => 'admin', function () { $user = Sentry::findUserById(323); $mindbody = new Mindbody($user); echo "<h4>addUserToClass</h4>"; d($mindbody->addUserToClass(24376, $user), FALSE); echo "<h4>getClasses</h4>"; d($mindbody->getClasses()); echo "<h4>getSchedules</h4>"; d($mindbody->getSchedules(), FALSE); echo "<h4>getEnrollments</h4>"; d($mindbody->getEnrollments(), FALSE); echo "<h4>getClassSchedules</h4>"; d($mindbody->getClassSchedules(), FALSE); } ] ); /** SEO URLS */ Route::get('/fitness-instructors/{id?}', ['as' => 'trainer.show', 'uses' => 'TrainersController@show']); Route::get('/classes/{id?}/{preview?}', ['as' => 'class.show', 'uses' => 'EvercisegroupsController@show']); /** Duplicate Name Added just because of the route URL */ Route::get('/classes/{id?}/{preview?}', ['as' => 'evercisegroups.show', 'uses' => 'EvercisegroupsController@show']); Route::get('/class/{id}/{preview?}', ['as' => 'evercisegroups.show.redirect', 'uses' => 'EvercisegroupsController@show']); // ajax prefix Route::group(['prefix' => 'ajax'], function () { // register Route::post('/users-store', ['as' => 'users.store', 'uses' => 'ajax\UsersController@store']); Route::post('/users-guest-store', ['as' => 'users.guest.store', 'uses' => 'ajax\UsersController@storeGuest']); Route::post('/users-update', ['as' => 'users.update', 'uses' => 'ajax\UsersController@update']); Route::post('/trainers/store', ['as' => 'trainers.store', 'uses' => 'ajax\TrainersController@store']); // Location Route::post('/users/getLocation', ['as' => 'users.location.get', 'uses' => 'ajax\UsersController@getLocation']); Route::post('/users/setLocation', ['as' => 'users.location.set', 'uses' => 'ajax\UsersController@setLocation']); // login // login Route::post('/auth/login', ['as' => 'auth.login.post', 'uses' => 'ajax\AuthController@postLogin']); // Search Route::post('/uk/{allsegments}', ['as' => 'ajax.search.parse', 'uses' => 'ajax\SearchController@parseUrl'])->where( 'allsegments', '(.*)?' ); Route::post('/uk/', ['as' => 'ajax.evercisegroups.search', 'uses' => 'ajax\SearchController@parseUrl']); Route::post('/map/uk/{allsegments}', ['as' => 'ajax.map.search.parse', 'uses' => 'ajax\SearchController@parseMapUrl'])->where( 'allsegments', '(.*)?' ); Route::post('/map/uk/', ['as' => 'ajax.map.evercisegroups.search', 'uses' => 'ajax\SearchController@parseMapUrl']); // cart // ajax prefix Route::group(['prefix' => 'cart'], function () { Route::post('add', ['as' => 'cart.add', 'uses' => 'ajax\CartController@add']); Route::post('remove', ['as' => 'cart.remove', 'uses' => 'ajax\CartController@remove']); Route::post('delete', ['as' => 'cart.delete', 'uses' => 'ajax\CartController@delete']); Route::post('empty', ['as' => 'cart.emptyCart', 'uses' => 'ajax\CartController@emptyCart']); Route::post('coupon', ['as' => 'cart.coupon', 'uses' => 'ajax\CartController@applyCoupon']); Route::post('wallet_payment', ['as' => 'cart.wallet.payment', 'uses' => 'CartController@walletPayment']); }); // sessions Route::post('/sessions/inline', ['as' => 'sessions.inline.groupId', 'uses' => 'ajax\SessionsController@getSessionsInline']); Route::put('/sessions/update', ['as' => 'sessions.update', 'uses' => 'ajax\SessionsController@update']); Route::post('sessions/store', ['as' => 'sessions.store', 'uses' => 'ajax\SessionsController@store']); Route::post('sessions/remove', ['as' => 'sessions.remove', 'uses' => 'ajax\SessionsController@destroy']); Route::post('sessions/getmembers', ['as' => 'session.get.members', 'uses' => 'ajax\SessionsController@getMembers']); Route::post('/sessions/getparticipants', ['as' => 'sessions.get.participants', 'uses' => 'ajax\SessionsController@getParticipants']); // venue Route::post('venues/store', ['as' => 'venue.store', 'uses' => 'ajax\VenuesController@store']); Route::post('venues/edit', ['as' => 'venue.edit', 'uses' => 'ajax\VenuesController@edit']); // evercise groups Route::post('evercisegroups', ['as' => 'evercisegroups.store', 'before' => 'trainer', 'uses' => 'ajax\EvercisegroupsController@store']); Route::post('publish', [ 'as' => 'evercisegroups.publish', 'before' => 'trainer', 'uses' => 'ajax\EvercisegroupsController@publish' ]); // uploads Route::post('upload/cover', ['as' => 'ajax.upload.cover', 'uses' => 'ajax\UploadController@uploadCover']); Route::post('upload/profile', ['as' => 'ajax.upload.profile', 'uses' => 'ajax\UploadController@uploadProfilePicture']); // Upload file only (no crop stuff) for the stupid Safari workaround Route::post('upload/basic', ['as' => 'ajax.upload.basic', 'uses' => 'ajax\UploadController@uploadWithoutCrop']); //Gallery Route::post('gallery/getDefaults', ['as' => 'ajax.gallery.getdefaults', 'uses' => 'ajax\GalleryController@getDefaults']); //Ratings Route::post('ratings/store', ['as' => 'ratings.store', 'uses' => 'ajax\RatingsController@store']); Route::get('wallet/sessions', ['as' => 'wallet.sessions', 'uses' => 'PaymentController@processWalletPaymentSessions']); Route::post('withdrawal/request', ['as' => 'ajax.request.withdrawal', 'uses' => 'ajax\UsersController@requestWithdrawal']); Route::post('withdrawal/process', ['as' => 'ajax.process.withdrawal', 'before' => 'trainer', 'uses' => 'ajax\UsersController@makeWithdrawal']); Route::post('categories', ['as' => 'ajax.categories', 'uses' => 'ajax\CategoryController@getCategories']); Route::post('categories/browse', ['as' => 'categories.browse', 'uses' => 'ajax\CategoryController@browse']); }); // auth / login Route::get( 'auth/login/{redirect_after_login_url}', [ 'as' => 'auth.login.redirect_after_login', function ($redirect_after_login_url) { return View::make('auth.login')->with('redirect_after_login', TRUE)->with( 'redirect_after_login_url', $redirect_after_login_url ); } ] ); Route::get( 'auth/login', [ 'as' => 'auth.login', function () { return View::make('auth.login')->with('redirect_after_login', FALSE)->with( 'redirect_after_login_url', FALSE ); } ] ); /*Route::get('login/fb/{redirect?}', ['as' => 'users.fb', function($redirect = 'no redirect') { return $redirect; }]);*/ Route::get('login/fb/{redirect?}/{param?}', ['as' => 'users.fb', 'uses' => 'UsersController@fb_login']); Route::post('auth/checkout', ['as' => 'auth.checkout', 'uses' => 'SessionsController@checkout']); Route::get('auth/logout', ['as' => 'auth.logout', 'uses' => 'UsersController@logout']); Route::get('auth/forgot', ['as' => 'auth.forgot', 'uses' => 'auth\AuthController@getForgot']); Route::post('auth/forgot', ['as' => 'auth.forgot.post', 'uses' => 'auth\AuthController@postForgot']); // Users Route::get('/register', ['as' => 'register', 'uses' => 'UsersController@create']); Route::get('/finished-user', [ 'as' => 'finished.user.registration', function () { new BaseController(); return View::make('v3.users.complete'); } ] ); Route::get('/profile/{id}/{tab?}', ['as' => 'users.edit', 'uses' => 'UsersController@edit', 'before' => 'user']); Route::get( '/users/{display_name}/activate/{code}', ['as' => 'users.activate', 'uses' => 'UsersController@activate'] ); Route::get( '/users/{display_name}/activate', ['as' => 'users.activatecodeless', 'uses' => 'UsersController@pleaseActivate'] ); Route::get( '/users/{display_name}/resetpassword/{code}', ['as' => 'users.resetpassword', 'uses' => 'UsersController@getResetPassword'] ); Route::post( '/users/resetpassword', ['as' => 'users.resetpassword.post', 'uses' => 'UsersController@postResetPassword'] ); Route::post( '/users/changepassword', ['as' => 'users.changepassword.post', 'before' => 'user', 'uses' => 'UsersController@postChangePassword'] ); Route::get('/users/{display_name}/logout', ['as' => 'users.logout', 'uses' => 'UsersController@logout']); // trainers Route::group(['prefix' => 'trainers'], function () { Route::get('/create', ['as' => 'trainers.create', 'uses' => 'TrainersController@create']); Route::get('/me', ['as' => 'trainer', 'uses' => 'TrainersController@show']); Route::get('/{id}/edit', ['as' => 'trainers.edit', 'uses' => 'TrainersController@edit']); Route::get('/{id}', ['as' => 'trainers.show', 'uses' => 'TrainersController@show']); Route::get('/{id}/edit/{tab}', ['as' => 'trainers.edit.tab', 'uses' => 'TrainersController@edit']); Route::put('/update/{id}', ['as' => 'trainers.update', 'uses' => 'TrainersController@update']); }); // evercisegroups (classes) Route::get( 'evercisegroups', ['as' => 'evercisegroups.index', 'before' => 'trainer', 'uses' => 'EvercisegroupsController@index'] ); Route::get( 'evercisegroups/create/{clone_id?}', ['as' => 'evercisegroups.create', 'before' => 'trainer', 'uses' => 'EvercisegroupsController@create'] ); Route::get( '/clone_class/{id}', ['as' => 'clone_class', 'uses' => 'EvercisegroupsController@cloneEG'] ); Route::post( '/evercisegroups/delete/{id}', ['as' => 'evercisegroups.delete', 'uses' => 'EvercisegroupsController@deleteEG'] ); /** Landing Pages */ foreach (Config::get('landing_pages') as $url => $params) { Route::get($url, ['as' => 'landing_page.' . str_replace('/', '.', $url), 'uses' => 'LandingsController@display'] ); } Route::get('/trainers', ['as' => 'landing.trainer.ppc', 'uses' => 'LandingsController@trainerPpc'] ); //Redirect All UK segments to the same function and we will go from there Route::any('/uk/{allsegments}', ['as' => 'search.parse', 'uses' => 'SearchController@parseUrl'])->where( 'allsegments', '(.*)?' ); Route::any('/uk/', ['as' => 'evercisegroups.search', 'uses' => 'SearchController@parseUrl']); // VenuesController Route::get('venues', 'VenuesController@index'); Route::get('venues/create', 'VenuesController@create'); Route::get('venues/edit/{id}', 'VenuesController@edit'); Route::post('venues/update/{id}', 'VenuesController@update'); Route::get('confo', [ 'as' => 'con', function () { return View::make('v3.cart.confirmation'); } ]); // Cart Route::group(['prefix' => 'cart'], function () { Route::get('checkout/{step?}', ['as' => 'cart.checkout', 'uses' => 'CartController@checkout']); Route::get('confirm', ['as' => 'cart.confirm', 'uses' => 'CartController@confirm']); Route::get('guest', ['as' => 'cart.guest', 'uses' => 'UsersController@guestCheckout']); Route::get('payment.error', ['as' => 'payment.error', 'uses' => 'CartController@paymentError']); Route::get('cartrow', [ 'as' => 'cart.row', function () { return View::make('v3.cart.cartrow'); } ]); }); Route::get('transaction/{id}', ['as' => 'transaction.show', 'uses' => 'TransactionController@show'] ); Route::get('transaction/{id}/download', ['as' => 'transaction.download', 'uses' => 'TransactionController@download'] ); // sessions Route::get( 'sessions/{evercisegroup_id}/index', ['as' => 'evercisegroups.trainer_show', 'uses' => 'SessionsController@index'] ); Route::get('sessions/add/{id}', ['as' => 'sessions.add', 'uses' => 'SessionsController@create']); Route::get('sessions/date_list', ['as' => 'sessions.date_list']); Route::post('sessions/join', ['as' => 'sessions.join', 'uses' => 'SessionsController@joinSessions']); Route::get('sessions/join/class', ['as' => 'sessions.join.get', 'uses' => 'SessionsController@joinSessions']); Route::get('/sessions/{id}', ['as' => 'sessions.show', 'uses' => 'SessionsController@show']); Route::get( '/sessions/{sessionId}/leave', ['as' => 'sessions.leave', 'uses' => 'SessionsController@getLeaveSession'] ); Route::post( '/sessions/{sessionId}/leave', ['as' => 'sessions.leave.post', 'uses' => 'SessionsController@postLeaveSession'] ); /* New Stripe payment */ Route::post('stripe/sessions', ['as' => 'stripe.sessions', 'uses' => 'PaymentController@processStripePaymentSessions']); Route::post('stripe/topup', ['as' => 'stripe.topup', 'uses' => 'PaymentController@processStripePaymentTopup']); Route::get('topup_confirmation', ['as' => 'topup_confirmation', 'uses' => 'PaymentController@topupConfirmation']); Route::get('topup', ['as' => 'topup', 'uses' => 'PaymentController@topup']); /* ------------------ */ /* Wallet only payment */ Route::get('wallet/sessions', ['as' => 'wallet.sessions', 'uses' => 'PaymentController@processWalletPaymentSessions']); /* ------------------ */ /* Show payment confirmation */ Route::get('checkout/confirmation', ['as' => 'checkout.confirmation', 'uses' => 'PaymentController@showConfirmation']); /* ------------------ */ Route::get('payment/error', ['as' => 'payment.error', 'uses' => 'PaymentController@paymentError']); Route::get('payment/proccess/paypal', ['as' => 'payment.process.paypal', 'uses' => 'PaymentController@processPaypalPaymentSessions']); Route::get('payment/request/paypal', ['as' => 'payment.request.paypal', 'uses' => 'PaymentController@requestPaypalPaymentSessions']); Route::get('payment/proccess/paypal/topup', ['as' => 'payment.process.paypal.topup', 'uses' => 'PaymentController@processPaypalPaymentTopUp']); Route::get('payment/request/paypal/topup', ['as' => 'payment.request.paypal.topup', 'uses' => 'PaymentController@requestPaypalPaymentTopUp']); Route::get('payment/cancelled', ['as' => 'payment.cancelled', 'uses' => 'PaymentController@cancelled']); // payment (old) Route::get( 'sessions/{evercisegroupId}/paywithstripe', ['as' => 'sessions.pay.stripe', 'uses' => 'SessionsController@payForSessionsStripe'] ); Route::post( 'wallets/{userId}/update_paypal', ['as' => 'wallets.updatepaypal', 'uses' => 'WalletsController@updatePaypal'] ); Route::post( '/sessions/{evercisegroupId}/redeemEvercoins', ['as' => 'sessions.redeemEvercoins.post', 'uses' => 'SessionsController@redeemEvercoins'] ); Route::get( '/sessions/{evercisegroupId}/paywithevercoins', function ($evercisegroupId) { return Redirect::to('evercisegroups/' . $evercisegroupId); } ); Route::post( '/sessions/{evercisegroupId}/paywithevercoins', ['as' => 'sessions.paywithevercoins.post', 'uses' => 'SessionsController@postPayWithEvercoins'] ); Route::get('/sessions/{sessionId}/refund', ['as' => 'sessions.refund', 'uses' => 'SessionsController@getRefund']); Route::post( '/sessions/{sessionId}/refund', ['as' => 'sessions.refund.post', 'uses' => 'SessionsController@postRefund'] ); // mail Route::get('/sessions/{sessionId}/mail_all', ['as' => 'sessions.mail_all', 'uses' => 'SessionsController@getMailAll']); Route::post( '/sessions/{sessionId}/mail_all', ['as' => 'sessions.mail_all.post', 'uses' => 'SessionsController@postMailAll'] ); Route::get('/sessions/{sessionId}/mail_one/{userId}', ['as' => 'sessions.mail_one', 'uses' => 'SessionsController@getMailOne'] ); Route::post('/sessions/{sessionId}/mail_one/{userId}', ['as' => 'sessions.mail_one.post', 'uses' => 'SessionsController@postMailOne'] ); Route::get('/sessions/{sessionId}/mail_trainer/{trainerId}', ['as' => 'sessions.mail_trainer', 'uses' => 'SessionsController@getMailTrainer'] ); Route::post('/sessions/{sessionId}/mail_trainer/{trainerId}', ['as' => 'sessions.mail_trainer.post', 'uses' => 'SessionsController@postMailTrainer'] ); Route::get('/conversation/{displayName}', ['as' => 'conversation', 'uses' => 'MessageController@getConversation', 'before' => 'user'] ); Route::post('/conversation/{displayName}', ['as' => 'conversation.post', 'uses' => 'MessageController@postMessage'] ); Route::get('/fitness-packages', ['as' => 'packages', 'uses' => 'PackagesController@index']); // widgets Route::group(['prefix' => 'widgets'], function () { Route::get('upload', ['as' => 'widgets.upload', 'uses' => 'widgets\ImageController@getUploadForm']); Route::post('upload', ['as' => 'widgets.upload.post', 'uses' => 'widgets\ImageController@postUpload']); Route::get('crop', ['as' => 'widgets.crop', 'uses' => 'widgets\ImageController@getCrop']); Route::post('crop', ['as' => 'widgets.crop.post', 'uses' => 'widgets\ImageController@postCrop']); Route::get('map', ['as' => 'widgets.map', 'uses' => 'widgets\LocationController@getMap']); Route::get('mapForm', ['as' => 'widgets.map-form', 'uses' => 'widgets\LocationController@getGeo']); Route::post('postGeo', ['as' => 'widgets.postGeo', 'uses' => 'widgets\LocationController@postGeo']); Route::get('calendar', ['as' => 'widgets.calendar', 'uses' => 'widgets\CalendarController@getCalendar']); Route::post('calendar', ['as' => 'widgets.calendar', 'uses' => 'widgets\CalendarController@postCalendar']); }); // layouts and static pages Route::get('blog', ['as' => 'blog', 'uses' => 'PagesController@showBlog']); Route::get('about-evercise', [ 'as' => 'general.about', function () { return View::make('v3.pages.about'); } ]); Route::get('terms-of-use', [ 'as' => 'general.terms', function () { return View::make('v3.pages.terms'); } ]); Route::get('privacy', ['as' => 'static.privacy', 'uses' => 'StaticController@show']); Route::get('leadership-team', ['as' => 'static.the_team', 'uses' => 'StaticController@show']); Route::get('faq', ['as' => 'static.faq', 'uses' => 'StaticController@dickface']); Route::get('careers', ['as' => 'static.careers', 'uses' => 'StaticController@show']); Route::get('fitness-class-guidelines', ['as' => 'static.class_guidelines', 'uses' => 'StaticController@show']); Route::get('contact_us', ['as' => 'static.contact_us', 'uses' => 'StaticController@show']); Route::get('how_it_works', ['as' => 'static.how_it_works', 'uses' => 'StaticController@show']); Route::post('/postPdf', ['as' => 'postPdf', 'uses' => 'PdfController@postPdf']); Route::get('/download_user_list/{session_id}', ['as' => 'getPdf', 'uses' => 'PdfController@getPdf']); Route::get('video/create', ['as' => 'video', 'uses' => 'VideoController@create']); // marketing Route::get('refer_a_friend/{code}', ['as' => 'referral', 'uses' => 'ReferralsController@submitCode']); Route::get('ppc/{category}/{code}', ['as' => 'landing.category.code', 'uses' => 'LandingsController@submitPpc']); Route::get('ppc_fb/{category}', ['as' => 'ppc_fb.category', 'uses' => 'LandingsController@facebookPpc']); Route::post('landing/send', ['as' => 'landings.send', 'uses' => 'LandingsController@landingSend']); Route::post('landing/enquiry', ['as' => 'landings.enquiry', 'uses' => 'LandingsController@trainerEnquiry']); Route::post('new_referral', ['as' => 'new_referral', 'uses' => 'ReferralsController@store']); Route::group(['prefix' => 'tokens'], function () { Route::get('/fb', ['as' => 'tokens.fbtoken', 'uses' => 'TokensController@fb']); Route::get('/tw', ['as' => 'tokens.twtoken', 'uses' => 'TokensController@tw']); }); Route::get( '/twitter', [ 'as' => 'twitter', 'uses' => function () { // Reqest tokens $tokens = Twitter::oAuthRequestToken(); // Redirect to twitter Twitter::oAuthAuthenticate(array_get($tokens, 'oauth_token')); exit; } ] ); /** ARTICLES */ if (Schema::hasTable('articles')) { $pagesController = App::make('PagesController'); $pagesController->generateRoutes(); } $landings = ['dance', 'pilates', 'martialarts', 'yoga', 'bootcamp', 'personaltrainer']; foreach ($landings as $land) { Route::get($land, [ 'as' => 'landing.bootcamp', 'uses' => function () use ($land) { $lc = App::make('LandingsController'); return $lc->landCategory($land); } ]); } // ------------- ADMIN STUFF --------------- // ------------- ADMIN SECTION --------------- Route::get('/admin/', ['as' => 'admin.page', 'uses' => 'AdminController@dashboard', 'before' => 'admin']); Route::get('/admin/', ['as' => 'admin.dashboard', 'uses' => 'AdminController@dashboard', 'before' => 'admin']); Route::get('/admin/', ['as' => 'users.create', 'uses' => 'AdminController@dashboard', 'before' => 'admin']); Route::group(['prefix' => 'ajax/admin', 'before' => 'admin'], function () { Route::post('check_url', ['as' => 'admin.ajax.check_url', 'uses' => 'AdminAjaxController@ajaxCheckUrl']); Route::post('/reset_password', ['as' => 'admin.reset_password', 'uses' => 'AdminAjaxController@resetPassword']); Route::post('/fakeratings', ['as' => 'admin.fakeratings.addrating', 'uses' => 'AdminAjaxController@addRating']); Route::post('/update_categories', ['as' => 'admin.update_categories', 'uses' => 'AdminAjaxController@updateCategories']); Route::post('/update_category', ['as' => 'admin.update_category', 'uses' => 'AdminAjaxController@updateCategory']); Route::post('/edit_subcategories', ['as' => 'admin.edit_subcategories', 'uses' => 'AdminAjaxController@editSubcategories']); Route::post('/add_subcategory', ['as' => 'admin.add_subcategory', 'uses' => 'AdminAjaxController@addSubcategory']); Route::post('/edit_group_subcats', ['as' => 'admin.edit_group_subcats', 'uses' => 'AdminAjaxController@editGroupSubcats']); Route::post('/subcategory/delete', ['as' => 'ajax.admin.subcategory.delete', 'uses' => 'AdminAjaxController@deleteSubcategory']); Route::post('/unapprove_trainer', ['as' => 'admin.unapprove_trainer', 'uses' => 'AdminAjaxController@unapproveTrainer']); Route::get('/search/stats', ['as' => 'admin.ajax.searchstats', 'uses' => 'AdminAjaxController@searchStats']); Route::post('/search/stats/download', ['as' => 'admin.ajax.searchstats.download', 'uses' => 'AdminAjaxController@downloadStats']); Route::post('galleryImageUpload', ['as' => 'admin.ajax.gallery_upload', 'uses' => 'AdminAjaxController@galleryUploadFile']); Route::post('saveTags', ['as' => 'admin.ajax.saveTags', 'uses' => 'AdminAjaxController@saveTags']); Route::post('deleteGalleryImage', ['as' => 'admin.ajax.gallery_delete', 'uses' => 'AdminAjaxController@deleteGalleryImage']); Route::post('set_class_image', ['as' => 'admin.ajax.set_image', 'uses' => 'AdminAjaxController@setClassImage']); Route::post('featureClass', ['as' => 'admin.ajax.featureClass', 'uses' => 'AdminAjaxController@featureClass']); Route::post('sliderUpload', ['as' => 'admin.ajax.slider_upload', 'uses' => 'AdminAjaxController@sliderUpload']); Route::post('sliderStatus', ['as' => 'admin.ajax.sliderStatus', 'uses' => 'AdminAjaxController@sliderStatus']); Route::delete( '/evercisegroups/delete', ['as' => 'admin.ajax.delete.class', 'before' => 'admin', 'uses' => 'AdminAjaxController@deleteClass'] ); Route::get('modal/categories/{id?}', ['as' => 'ajax.admin.modal.categories', 'uses' => 'AdminAjaxController@modalClassCategories']); Route::get('/importStatsToDB', ['as' => 'ajax.admin.import.stats', 'uses' => 'AdminAjaxController@importStatsToDB']); Route::put('modal/categories', ['as' => 'ajax.admin.modal.categories.save', 'uses' => 'AdminAjaxController@saveClassCategories']); Route::post('runindexer', ['as' => 'ajax.admin.indexall', 'uses' => 'AdminAjaxController@runIndexer']); }); Route::group( ['prefix' => 'admin', 'before' => 'admin'], function () { Route::get('/dashboard', ['as' => 'admin.dashboard', 'uses' => 'MainController@dashboard']); /** USERS */ Route::get('/users', ['as' => 'admin.users', 'uses' => 'MainController@users']); Route::get('/users/trainer', ['as' => 'admin.users.trainerCreate', 'uses' => 'MainController@trainerCreate']); Route::post('/users/trainer', ['as' => 'admin.users.trainerStore', 'uses' => 'MainController@trainerStore']); Route::post('/log_in_as', ['as' => 'admin.log_in_as', 'uses' => 'MainController@logInAs']); Route::get('/pendingtrainers', ['as' => 'admin.pendingtrainers', 'uses' => 'MainController@pendingTrainers']); Route::post('/approve_trainer', ['as' => 'admin.approve_trainer', 'uses' => 'MainController@approveTrainer']); Route::get('/pending_withdrawal', ['as' => 'admin.pending_withdrawal', 'uses' => 'MainController@pendingWithdrawal']); Route::post('/pending_withdrawal_multi', ['as' => 'admin.pending.process', 'uses' => 'MainController@processWithdrawalMulti']); Route::post('/pending_withdrawal_multi_manual', ['as' => 'admin.pending.process.manual', 'uses' => 'MainController@processWithdrawalMultiManual']); Route::post('/process_withdrawal', ['as' => 'admin.process_withdrawal', 'uses' => 'MainController@processWithdrawal']); Route::get('/categories', ['as' => 'admin.categories', 'uses' => 'MainController@editCategories']); Route::get('categories/{id?}', ['as' => 'admin.categories.manage', 'uses' => 'MainController@categoriesManage']); Route::get('/subcategories', ['as' => 'admin.subcategories', 'uses' => 'MainController@subcategories']); Route::get('/listclasses', ['as' => 'admin.listClasses', 'uses' => 'MainController@listClasses']); Route::get('articles', ['as' => 'admin.articles', 'uses' => 'ArticlesController@articles']); Route::get('article/delete/{id?}', ['as' => 'admin.article.delete', 'uses' => 'ArticlesController@deleteArticle']); Route::match(['GET', 'POST'], 'article/manage/{id?}', ['as' => 'admin.article.manage', 'uses' => 'ArticlesController@manage']); Route::get('article/categories', ['as' => 'admin.article.categories', 'uses' => 'ArticlesController@categories']); Route::get('article/categories/{id?}', ['as' => 'admin.article.categories.manage', 'uses' => 'ArticlesController@categoriesManage']); Route::match(['GET', 'POST'], 'article/categories/{id?}', ['as' => 'admin.article.categories.manage', 'uses' => 'ArticlesController@categoriesManage']); Route::get('/search/stats', ['as' => 'admin.searchstats', 'uses' => 'MainController@searchStats']); Route::get('/sales', ['as' => 'admin.sales', 'uses' => 'MainController@salesStats']); Route::get('/transactions', ['as' => 'admin.transactions', 'uses' => 'MainController@transactions']); Route::get('/packages', ['as' => 'admin.packages', 'uses' => 'MainController@userPackages']); Route::get('/gallery', ['as' => 'admin.gallery', 'uses' => 'AdminGalleryController@index']); /** TO DOOO */ Route::get('log', ['as' => 'admin.log', 'uses' => 'MainController@showLog']); Route::post('/log', ['as' => 'admin.log.delete', 'uses' => 'MainController@deleteLog']); Route::get('/fakeratings', ['as' => 'admin.fakeratings', 'uses' => 'MainController@showGroupRatings']); Route::post('/edit_classes/{id}', ['as' => 'admin.edit_classes', 'uses' => 'MainController@editClasses']); Route::post('/groups', ['as' => 'admin.groups.addcat', 'uses' => 'MainController@addCategory']); Route::get('/fakeratings', ['as' => 'admin.fakeratings', 'uses' => 'MainController@showGroupRatings']); Route::get('expired/{date?}', ['as' => 'admin.expired', 'uses' => 'MainController@expired']); Route::get('landings', ['as' => 'admin.landings', 'uses' => 'MainController@landings']); Route::get('landing/{id?}', ['as' => 'admin.landing.manage', 'uses' => 'MainController@landing']); } ); /* Route::get('makestaticlandingcode', function(){ StaticLanding::create(['code'=>'89o7645v68h6345']); }); Route::get('generatestaticlandingemail', function(){ // Make sure line '$this->log->info($view);' in Mail/send is uncommented, to get generated email in log $code = StaticLanding::find(1)->code; //return View::make('v3.emails.user.static_landing_email')->with('ppcCode', StaticLanding::find(1)->code); event('generate.static.landing.email', [$code, 0]); return 'generated. code: '.$code; }); */ Route::get('ping', ['as' => 'ping.me', 'uses' => 'PingController@check']); Route::get('/evercisegroups/{id?}/{preview?}', ['as' => 'class.show.eg', 'uses' => 'EvercisegroupsController@show']); Route::any('emailgrab', ['as' => 'email.grab', 'uses' => 'EmailGrabber@grab']); Route::get('cleansubcategoriesup', function () { $subcategories = Subcategory::get(); foreach ($subcategories as $sc) { $n = $sc['name']; //return var_dump($n); //if ($n != 'dance' && $n != 'belly dancing') //return ucfirst($n); $sc->name = ucfirst($n); $sc->save(); } }); Route::get('test1', function () { $trainer = User::find('169'); event('trainer.registered_ppc', [$trainer]); return 'event fired : ' . $trainer->display_name; }); Route::get('test2', function () { $transaction = \Transactions::find(5318091); $hashes = $transaction->makeBookingHashBySession('1479'); $output = ''; foreach ($hashes as $hash) { $output .= $hash . ','; } return $output; }); Route::get('test3', function () { $cart = EverciseCart::getCart(); $upperPrice = round($cart['packages'][0]['max_class_price'], 2) + 0.01; //Log::live() /* $everciseGroups = Evercisegroup::whereHas('futuresessions', function($query) use($packagePrice) { $query->where('price', '<', $packagePrice); })->take(3)->get();*/ $searchController = App::make('SearchController'); $everciseGroups = $searchController->getClasses([ 'sort' => 'price_desc', 'price' => ['under' => round($upperPrice, 2), 'over' => round(($upperPrice - 10))], 'size' => '3' ]); return var_dump($everciseGroups); }); Route::get('test4/{term}', function ($term) { return Subcategory::getRelatedFromSearch($term); }); Route::get('test5', function () { return d(Category::browse()); }); <file_sep>/app/database/migrations/2014_08_27_090947_create_fakeuser_data.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFakeuserData extends Migration { /** * Create the * * @return void */ public function up() { //Check if Fake Group Exists $fake_group = DB::select('select * from groups where name = ?', array('Fakeuser')); if (count($fake_group) == 0) { Sentry::getGroupProvider()->create( array( 'name' => 'Fakeuser', 'permissions' => array('fakeuser' => 1), ) ); } // Find the Fakeuser group $fake_user_group = Sentry::findGroupByName('Fakeuser'); //HardCoded Users IDS from the current DB $user_ids = [450,449,448,447,446,445,444,443,442,441,438,437,436,435,434,433,432,431,430,429,428,427,426,425,424,423,422,421,420,419,418,417,416,415,414,413,412,411,410,409,407,406,405,402,401,400,399,398,397,394]; //Modify users to be fakeusers foreach ($user_ids as $id) { try { // Find the user using the user id $user = Sentry::findUserByID($id); // Check if the user is in the fake user group.. if not add him if (!$user->inGroup($fake_user_group)) { $user->addGroup($fake_user_group); } } catch (\Exception $e) { //Looks like he is in group allready echo $e->getMessage(); } } } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/public/assets/jsdev/prototypes/4-toggle-switch.js var ToggleSwitch = function (toggle) { this.toggle = toggle; this.originalClass = toggle.data('removeclass'); this.switchClass = toggle.data('switchclass'); this.originalText = toggle.text(); this.switchText = toggle.data('switchtext'); this.init(); } ToggleSwitch.prototype = { constructor: ToggleSwitch, init: function(){ this.toggle.text(this.switchText); this.toggle.addClass(this.switchClass); this.toggle.removeClass(this.originalClass); this.toggle.data('switchtext', this.originalText); this.toggle.data('removeclass', this.switchClass); this.toggle.data('switchclass', this.originalClass); } }<file_sep>/app/database/migrations/2014_11_11_141709_add_columns_wallethistory.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddColumnsWallethistory extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('wallethistory', function($table) { $table->dropColumn('sessionpayment_id'); $table->integer('sessionmember_id')->unsigned();// Foreign key; $table->string('description', 500); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('wallethistory', function($table) { $table->integer('sessionpayment_id')->unsigned(); $table->dropColumn('sessionmember_id'); $table->dropColumn('description'); }); } } <file_sep>/app/models/Wallet.php <?php class Wallet extends \Eloquent { protected $fillable = ['id', 'user_id', 'balance', 'previous_balance']; protected $table = 'wallets'; /** * checks if the withdrawel request is valid * @logs info: valid request * @log notci: invalid request * @return array|\Illuminate\Http\JsonResponse */ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } public static function validWithdrawalRequest($inputs, $id) { $validator = Validator::make( $inputs, [ 'withdrawal' => 'required|max:1000|min:1|numeric', 'paypal' => 'required|max:255|min:5', ] ); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; Log::notice('Invalid wthdrawal request, failed validation'); } else { $wallet = static::where('user_id', $id)->first(); $withdrawal = $inputs['withdrawal']; $paypal = $inputs['paypal']; if ($withdrawal <= $wallet->balance) { $result = [ 'validation_failed' => 0, 'withdrawal' => $withdrawal, 'paypal' => $paypal ]; Log::info('valid withdrawal request'); } else { $result = [ 'validation_failed' => 1, 'errors' => ['withdrawal' => 'You don`t have that much in your wallet. '] ]; Log::notice('Invalid withdrawal request, not enough money in wallet'); } } return $result; } /** * @return \Illuminate\Validation\Validator */ public static function validPaypalUpdateRequest($inputs, $id) { $validator = Validator::make( $inputs, [ 'updatepaypal' => 'required|max:255|min:5|email', ] ); if ($validator->fails()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; } else { $paypal = $inputs['updatepaypal']; $wallet = static::userWallet($id); $wallet->updatePaypal($paypal); $result = [ 'callback' => 'gotoUrl', 'url' => route('trainers.edit.tab', [$id, 'wallet']), ]; } return $result; } public function deposit($amount, $description, $type = 'deposit', $sessionmember_id = 0, $token = 0, $transactionId = 0, $paymentMethod = 0, $payer_id = 0) { return $this->transaction($amount, $description, $type, $sessionmember_id, $token, $transactionId, $paymentMethod, $payer_id ); } public function withdraw($amount, $description, $type = 'withdraw', $sessionmember_id = 0, $token = 0, $transactionId = 0, $paymentMethod = 0, $payer_id = 0) { return $this->transaction(-$amount, $description, $type, $sessionmember_id, $token, $transactionId, $paymentMethod, $payer_id); } protected function transaction($amount, $walletHistoryDescription, $type, $sessionmember_id = 0, $token = 0, $transactionId = 0, $paymentMethod = 0, $payer_id = 0) { $user_id = $this->attributes['user_id']; /*$transaction = Transactions::create( [ 'user_id' => $user_id, 'total' => $amount, 'total_after_fees' => $amount, 'coupon_id' => 0, 'commission' => 0, 'token' => $token, 'transaction' => $transactionId, 'payment_method' => $paymentMethod, 'payer_id' => $payer_id ]);*/ $newBalance = $this->attributes['balance'] + $amount; /* if(!$type instanceof \User) { switch ($type) { case 'deposit': event('user.topup.completed', [$this->user, $transaction, $newBalance]); break; case 'withdraw': event('user.withdraw.completed', [$this->user, $transaction, $newBalance]); break; case 'referral': event('user.referral.completed', [$this->user, $transaction, $newBalance]); break; case 'referral_signup': event('user.referral.signup', [$this->user, $transaction, $newBalance]); break; case 'full_payment': break; case 'part_payment': break; } } else { Log::error('----- WE MISSED THIS ONE!!!!!!!-----'); Log::error($type); }*/ $user_id = $this->attributes['user_id']; $this->attributes['previous_balance'] = $this->attributes['balance']; $this->attributes['balance'] = $newBalance; $this->save(); Wallethistory::create( [ 'user_id' => $user_id, 'sessionmember_id' => $sessionmember_id, 'transaction_amount' => $amount, 'new_balance' => $this->attributes['balance'], 'description' => $walletHistoryDescription, ] ); return $newBalance; } public function recordedSave(array $params) { //$transaction_amount = $params['balance'] - $params['previous_balance']; Wallethistory::create( [ 'user_id' => $params['user_id'], 'transaction_amount' => $params['transaction_amount'], 'new_balance' => $params['new_balance'], 'sessionmember_id' => $params['sessionmember_id'], 'description' => $params['description'], ] ); parent::save(); } public function updatePaypal($newPaypal) { $this->attributes['paypal'] = $newPaypal; $this->save(); } public function giveAmount($amount = 0, $type, $description = 0) { if(!$type || $amount == 0) return false; $newBalance = $this->attributes['balance'] + $amount; $transaction = Transactions::create( [ 'user_id' => $this->user->id, 'total' => $amount, 'total_after_fees' => $amount, 'coupon_id' => 0, 'commission' => 0, 'token' => 0, 'transaction' => 0, 'payment_method' => $type, 'payer_id' => 0 ]); switch($type) { case 'referral_signup': event('user.referral.signup', [$this->user, $transaction, $newBalance]); $walletHistoryDescription = 'You received £'.$amount.' for referral sign up'; break; case 'ppc_signup': event('user.ppc.signup', [$this->user, $transaction, 'ppcunique']); $walletHistoryDescription = 'You received £'.$amount.' for ppc sign up'; break; case 'static_ppc_signup': event('user.ppc.signup', [$this->user, $transaction, 'ppcstatic', $description ]); $walletHistoryDescription = 'You received £'.$amount.' for ppc sign up'; break; case 'referral': event('user.referral.completed', [$this->user, $transaction, $newBalance]); $walletHistoryDescription = 'You received £'.$amount.' for referring your friends'; break; case 'profile': $walletHistoryDescription = 'You received £'.$amount.' for completing your profile'; break; case 'facebook': $walletHistoryDescription = 'You received £'.$amount.' for connecting your Facebook account'; break; case 'twitter': $walletHistoryDescription = 'You received £'.$amount.' for connecting your Twitter account'; break; case 'review': $walletHistoryDescription = 'You received £'.$amount.' for writing a review'; break; default: return false; } $this->deposit($amount, $walletHistoryDescription, $type); //event('milestone.completed', [$user, $type, $title, $walletHistoryDescription, $amount]); } public static function userWallet($user_id) { return Wallet::where('user_id', $user_id)->first(); } public function getBalance() { return sprintf('%0.2f', $this->balance); } public static function createIfDoesntExist($user_id) { if (static::where('user_id', $user_id)->first()) return false; $wallet = static::firstOrCreate([ 'user_id'=>$user_id, 'balance'=>0, 'previous_balance'=>0 ]); return $wallet; } }<file_sep>/app/database/seeds/TrainersTableSeeder.php <?php class TrainersTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('trainers')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); $bodyinfos = DB::connection('mysql_import')->table('bodyinfo')->get(); foreach ($bodyinfos as $bodyinfo) { $user = DB::connection('mysql_import')->table('user')->where('Uid', $bodyinfo->Uid)->first(); if($user) { $userEmail = $user->Uemail; $newUser = User::where('email', $userEmail)->first(); if($newUser) { $newTrainer = Trainer::firstOrCreate([ 'user_id'=>$newUser->id, 'bio'=>$bodyinfo->bodyInfoBio, 'website'=>$bodyinfo->bodyInfoWebsite, 'confirmed'=>1,//$user->UproApplication == 2 ? 1 : 0, 'profession'=>$bodyinfo->bodyInfoJobTitle ]); try { $sentryUser = Sentry::getUserProvider()->findById($newUser->id); $userGroup = Sentry::findGroupById(3); $sentryUser->addGroup($userGroup); } catch (Exception $e) { $this->command->info('Cannot add trainer to group '.$e); } $wallet = Wallet::firstOrCreate(['user_id'=>$newUser->id, 'balance'=>0, 'previous_balance'=>0]); } else { $this->command->info('Could not find new user: '.$userEmail); } } else { $this->command->info('Could not find old user: '.$bodyinfo->Uid); } } } }<file_sep>/app/composers/RecommendedClassesComposer.php <?php namespace composers; use Evercisegroup; use Sentry; class RecommendedClassesComposer { public function compose($view) { $sentryUser = Sentry::getUser(); $testers = Sentry::findGroupById(5); $testerLoggedIn = $sentryUser ? $sentryUser->inGroup($testers) : false; $evercisegroups = Evercisegroup::has('futuresessions') ->has('featuredClasses') ->has('confirmed') ->has('tester', '<', $testerLoggedIn ? 5 : 1) // testing to make sure class does not belong to the tester ->with('user') ->with('venue') ->with('ratings') ->take(4) ->get(); $ratings = []; foreach ($evercisegroups as $key => $evercisegroup) { $stars = 0; foreach ($evercisegroup->ratings as $k => $rating) { $ratings[$rating->evercisegroup_id] = $stars + $rating->stars; $stars = $stars + $rating->stars; } } $view->with('evercisegroups', $evercisegroups) ->with('ratings', $ratings); } }<file_sep>/app/controllers/ajax/RatingsController.php <?php namespace ajax; use Input, Response, Sentry, Evercisegroup, Validator, View, Redirect, Sessionmember, Evercisesession, Rating, Trainerhistory, Milestone, Event; class RatingsController extends AjaxBaseController{ public function __construct() { parent::__construct(); $this->user = Sentry::getUser(); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $validator = Validator::make( Input::all(), array( 'sessionmember_id' => 'unique:ratings,sessionmember_id', 'feedback_text' => 'required', ) ); if($validator->fails()) { $result = [ 'validation_failed' => 1,'sessionmember_id' => Input::get('sessionmember_id'), 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { $sessionmember_id = Input::get('sessionmember_id'); $user_created_id = $this->user->id; $stars = Input::get('stars'); $comment = Input::get('feedback_text'); //$user_id = $this->user->id; $sessionmember = Sessionmember::find($sessionmember_id); $session_id = $sessionmember->evercisesession_id; $session = Evercisesession::find($session_id); $evercisegroup_id = $session->evercisegroup_id; $group = Evercisegroup::find($evercisegroup_id); $trainer = $group->user; // Check integrity of id's if (!$sessionmember) return [ 'validation_failed' => 1, 'errors' => ['message' => 'no sessionmember'] ]; elseif ( $sessionmember->user_id != $user_created_id ) return [ 'validation_failed' => 1, 'errors' => ['message' => $sessionmember_id .' ids do not match '.$sessionmember->user_id .'!='. $user_created_id] ]; // Check group is in past elseif (strtotime($session->date_time) >= strtotime( date('Y-m-d H:i:s') ) ) return [ 'validation_failed' => 1, 'errors' => ['message' => 'Cannot rate a session in the future'] ]; $rating = Rating::create([ 'user_id' => $trainer->id, 'sessionmember_id' => $sessionmember_id, 'session_id' => $session_id, 'evercisegroup_id' => $evercisegroup_id, 'user_created_id' => $user_created_id, 'stars' => $stars, 'comment' => $comment ]); $timestamp = strtotime($session->date_time); $niceTime = date('h:ia', $timestamp); $niceDate = date('dS F Y', $timestamp); Trainerhistory::create(array('user_id'=> $trainer->id, 'type'=>'rated_session', 'display_name'=>$this->user->display_name, 'name'=>$group->name, 'time'=>$niceTime, 'date'=>$niceDate)); Milestone::where('user_id', $this->user->id)->first()->add('review'); event('activity.user.reviewed.class', [$this->user, $trainer, $rating, $session, $group]); } return Response::json( [ 'url' => route('users.edit', [ $this->user->display_name, 'attended']) ] ); } } <file_sep>/app/config/backups/facebook.php <?php // app/config/facebook.php // Facebook app Config if (App::environment('local')) { // The environment is local return array( 'appId' => '306418789525126', 'secret' => '<KEY>' ); } elseif (App::environment('staging')) { // The environment is donkey return array( 'appId' => '247621532113217', // donkey 'secret' => '762e0e54c435804033d7ece1d4b50122' // donkey ); } elseif (App::environment('production')) { // The environment is VS10319 return array( 'appId' => '425004847609443', // VS10319 'secret' => 'cef796862987836c8bb175e4304de6da' // VS10319 ); } elseif (App::environment('amazonsandbox')) { // The environment is VS10319 return array( 'appId' => '', // 'secret' => '' // ); }<file_sep>/app/models/Pardot.php <?php use HGG\Pardot\Connector; use HGG\Pardot\Exception\PardotException; /** * Class Pardot */ class Pardot { /** * Construct */ public function __construct() { $connectorParameters = [ 'email' => getenv('PARDOT_EMAIL'), 'user-key' => getenv('PARDOT_KEY'), 'password' => getenv('<PASSWORD>'), 'format' => getenv('PARDOT_FORMAT') ?: 'json', 'output' => getenv('PARDOT_OUTPUT') ?: 'full', ]; $this->connector = new Connector($connectorParameters); } public function createUnregisteredUser($email) { $params = [ 'email' => $email, 'first_name' => 'Invited', 'last_name' => 'Invited', 'country' => 'United Kingdom' ]; $create = $this->connector->post('prospect', 'create', $params); return $create; } public function createUser($user) { $params = [ 'email' => $user->email, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'country' => 'United Kingdom', 'phone' => $user->phone, 'Birthdate' => $user->dob ]; $create = $this->connector->post('prospect', 'create', $params); return $create; } /** * @param $email * @return \Cartalyst\Sentry\Users\UserInterface * @internal param $user */ public function getUser($email) { try { $user = Sentry::findUserByLogin($email); } catch (Exception $e) { try { $pardot_user = $this->connector->post('prospect', 'read', ['email' => $email]); } catch (\Exception $e) { $pardot_user = $this->createUnregisteredUser($email); } return $pardot_user['id']; } if (empty($user->salesforce_id)) { $events = App::make('events\Tracking'); $user = $events->registerUserTracking($user, ($user->isTrainer() ? 'TRAINER' : 'USER')); } if (empty($user->pardot_id)) { try { $pardot_user = $this->connector->post('prospect', 'read', ['email' => $user->email]); } catch (\Exception $e) { \Log::info($e->getMessage()); $pardot_user = $this->createUser($user); } if (!empty($pardot_user['id'])) { $user->pardot_id = $pardot_user['id']; $user->save(); } } return $user; } /** * @param $user_email * @param $campaign_id * @param PardotEmail $mail */ public function send($user_email, $campaign_id, PardotEmail $mail) { $user = $this->getUser($user_email); $pardot_id = FALSE; if (!empty($user->pardot_id) && $user->pardot_id > 0) { $pardot_id = $user->pardot_id; } else { if (!empty($user)) { $pardot_id = $user; } } if ($pardot_id) { $params = [ 'campaign_id' => $campaign_id, 'prospect_id' => $pardot_id, 'name' => $mail->subject, 'subject' => $mail->subject, 'text_content' => $mail->plainText, 'html_content' => $mail->content, 'from_email' => $mail->from, 'from_name' => $mail->fromName ]; $send = $this->connector->post('email', 'send', $params); if (!empty($send['id'])) { Log::info('Pardot Campaign ' . $campaign_id . ' : ' . $send['id'] . ' Sent to user ' . $user_email); return TRUE; } } Log::error('No Message Sent ' . $user_email . ' ' . $campaign_id); throw new Exception('No Message Sent'); } }<file_sep>/app/lang/en/evercisegroups-show.php <?php return [ 'tab_description' => 'Description', 'tab_reviews' => 'Reviews/Participants', 'sessions_head_1' => 'Class Date', 'sessions_head_2' => 'Start Time', 'sessions_head_3' => 'End Time', 'sessions_head_4' => 'Price <small>(Per Person)</small>', 'sessions_head_5' => 'Tickets Left', 'sessions_head_6' => 'Join', 'join_session' => 'Join Session', 'checkout' => 'Checkout', 'total_sessions' => 'Total Sessions', 'total_price' => 'Total Price', 'show_more' => '-- Click to view more --', 'hide_more' => '-- Click to hide extra --', 'venue_facilities' => 'Venue Facilities', 'venue_amenities' => 'Venue Amenities', 'reviews_participants' => 'Reviews / Participants', 'overall_rating' => 'Overall Rating', 'overall_rating' => 'Overall Rating', 'class_full' => 'class full', '' => '', '' => '', '' => '', '' => '', ];<file_sep>/app/models/Messages.php <?php class Messages extends TBMsg { public static function sendMessage($senderId, $receiverId, $content) { /* $convId = static::getConversationByTwoUsers($senderId, $receiverId); if(! ($convId > 0)) $convId = static::createConversation([$senderId, $receiverId])->id; static::addMessageToConversation($convId, $senderId, $content);*/ //Oh look this method already exists static::sendMessageBetweenTwoUsers($senderId, $receiverId, $content); } /** * @param $currentUserId * @param $displayName * @return int conversation_id */ public static function getConversationIdByDisplayName($currentUserId, $displayName) { return static::getConversationByTwoUsers($currentUserId, User::getIdFromDisplayName($displayName)); } /** * @param $convId * @param $userId * @return Tzookbstatic\Entities\Conversation */ public static function getMessages($currentUserId, $convId) { return static::getConversationMessages($convId, $currentUserId); } public static function sendMessageByDisplayName($currentUserId, $displayName, $content) { $convId = Messages::getConversationIdByDisplayName($currentUserId, $displayName); static::sendMessage($currentUserId, User::getIdFromDisplayName($displayName), $content); } public static function unread($userId) { return static::getNumOfUnreadMsgs($userId); } public static function getLastMessageDisplayName($userId) { $convs = TBMsg::getUserConversations($userId); foreach ($convs as $conv) { foreach ($conv->getAllParticipants() as $p){ if($p != $userId){ /** Return display_name of first conversation buddy found */ return User::where('id', $p)->pluck('display_name'); } } } return ''; } public static function markRead($userId, $convId) { static::markReadAllMessagesInConversation($convId, $userId); } public static function getConversations($userId) { $convs = TBMsg::getUserConversations($userId); $ids = []; foreach($convs as $conv){ foreach ($conv->getAllParticipants() as $p) { if ($p != $userId) { $ids[] = $p; } } } return User::whereIn('id', $ids)->lists('display_name'); } public function unreadMessagesInConversation($userId, $convId) { /** TODO - Put a little number next to each conversation in the list */ return 0; } }<file_sep>/app/models/Areacodes.php <?php /** * Class Areacodes */ class Areacodes extends Eloquent { /** * @var array */ protected $fillable = array('id', 'area_code', 'area_covered', 'official_Ofcom', 'Previous_BT'); /** * The database table used by the model. * * @var string */ protected $table = 'areacodes'; }<file_sep>/public/testing_helpers/evercise.sql -- phpMyAdmin SQL Dump -- version 3.5.2.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Aug 22, 2014 at 05:08 PM -- Server version: 5.5.28 -- PHP Version: 5.5.13 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 */; -- -- Database: `evercise` -- -- -------------------------------------------------------- -- -- Table structure for table `areacodes` -- CREATE TABLE IF NOT EXISTS `areacodes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `area_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `area_covered` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `official_Ofcom` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `Previous_BT` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `evercisegroups` -- CREATE TABLE IF NOT EXISTS `evercisegroups` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `venue_id` int(10) unsigned NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(5000) COLLATE utf8_unicode_ci NOT NULL, `gender` tinyint(4) NOT NULL, `image` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `capacity` int(11) NOT NULL, `default_duration` int(11) NOT NULL, `default_price` decimal(6,2) NOT NULL DEFAULT '0.00', `published` tinyint(4) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercisegroups_user_id_foreign` (`user_id`), KEY `evercisegroups_venue_id_foreign` (`venue_id`), KEY `evercisegroups_published_index` (`published`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `evercisegroup_subcategories` -- CREATE TABLE IF NOT EXISTS `evercisegroup_subcategories` ( `evercisegroup_id` int(10) unsigned NOT NULL, `subcategory_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `evercisegroup_id` (`evercisegroup_id`), KEY `subcategory_id` (`subcategory_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `evercisesessions` -- CREATE TABLE IF NOT EXISTS `evercisesessions` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `evercisegroup_id` int(10) unsigned NOT NULL, `date_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `members` int(11) NOT NULL DEFAULT '0', `price` decimal(6,2) NOT NULL DEFAULT '0.00', `duration` int(11) NOT NULL, `members_emailed` tinyint(1) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercisesessions_evercisegroup_id_foreign` (`evercisegroup_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `evercoinhistory` -- CREATE TABLE IF NOT EXISTS `evercoinhistory` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `transaction_amount` decimal(8,2) NOT NULL, `new_balance` decimal(8,2) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercoinhistory_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `evercoins` -- CREATE TABLE IF NOT EXISTS `evercoins` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `balance` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercoins_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `facilities` -- CREATE TABLE IF NOT EXISTS `facilities` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `category` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `groups` -- CREATE TABLE IF NOT EXISTS `groups` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `permissions` text COLLATE utf8_unicode_ci, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `groups_name_unique` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `historytypes` -- CREATE TABLE IF NOT EXISTS `historytypes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `landings` -- CREATE TABLE IF NOT EXISTS `landings` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user_id` int(11) NOT NULL, `category_id` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `landings_user_id_index` (`user_id`), KEY `landings_category_id_index` (`category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `marketingpreferences` -- CREATE TABLE IF NOT EXISTS `marketingpreferences` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `option` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'yes', `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `migrate_groups` -- CREATE TABLE IF NOT EXISTS `migrate_groups` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `classInfoId` int(10) unsigned NOT NULL, `evercisegroup_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `migrate_sessions` -- CREATE TABLE IF NOT EXISTS `migrate_sessions` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `classDatetimeId` int(10) unsigned NOT NULL, `evercisesession_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE IF NOT EXISTS `migrations` ( `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `milestones` -- CREATE TABLE IF NOT EXISTS `milestones` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `referrals` int(11) NOT NULL, `profile` int(11) NOT NULL, `facebook` int(11) NOT NULL, `twitter` int(11) NOT NULL, `reviews` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `milestones_user_id_foreign` (`user_id`), KEY `milestones_facebook_index` (`facebook`), KEY `milestones_twitter_index` (`twitter`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `ratings` -- CREATE TABLE IF NOT EXISTS `ratings` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `sessionmember_id` int(10) unsigned NOT NULL, `session_id` int(10) unsigned NOT NULL, `evercisegroup_id` int(10) unsigned NOT NULL, `user_created_id` int(10) unsigned NOT NULL, `stars` tinyint(4) NOT NULL, `comment` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `ratings_user_id_foreign` (`user_id`), KEY `ratings_sessionmember_id_foreign` (`sessionmember_id`), KEY `ratings_session_id_foreign` (`session_id`), KEY `ratings_evercisegroup_id_foreign` (`evercisegroup_id`), KEY `ratings_user_created_id_foreign` (`user_created_id`), KEY `ratings_sessionmember_id_index` (`sessionmember_id`), KEY `ratings_session_id_index` (`session_id`), KEY `ratings_evercisegroup_id_index` (`evercisegroup_id`), KEY `ratings_user_created_id_index` (`user_created_id`), KEY `ratings_stars_index` (`stars`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `referrals` -- CREATE TABLE IF NOT EXISTS `referrals` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `referee_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `referrals_user_id_foreign` (`user_id`), KEY `referrals_referee_id_index` (`referee_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `sessionmembers` -- CREATE TABLE IF NOT EXISTS `sessionmembers` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `evercisesession_id` int(10) unsigned NOT NULL, `token` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `transaction_id` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `payer_id` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `payment_method` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `sessionmembers_user_id_foreign` (`user_id`), KEY `sessionmembers_evercisesession_id_foreign` (`evercisesession_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `sessionpayments` -- CREATE TABLE IF NOT EXISTS `sessionpayments` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `evercisesession_id` int(10) unsigned NOT NULL, `total` decimal(19,4) NOT NULL, `total_after_fees` decimal(19,4) NOT NULL, `commission` decimal(19,4) NOT NULL, `processed` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `evercisesession_id` (`evercisesession_id`), KEY `sessionpayments_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `specialities` -- CREATE TABLE IF NOT EXISTS `specialities` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `titles` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `subcategories` -- CREATE TABLE IF NOT EXISTS `subcategories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `subcategory_categories` -- CREATE TABLE IF NOT EXISTS `subcategory_categories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `subcategory_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `subcategory_id` (`subcategory_id`), KEY `category_id` (`category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `throttle` -- CREATE TABLE IF NOT EXISTS `throttle` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned DEFAULT NULL, `ip_address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `attempts` int(11) NOT NULL DEFAULT '0', `suspended` tinyint(1) NOT NULL DEFAULT '0', `banned` tinyint(1) NOT NULL DEFAULT '0', `last_attempt_at` timestamp NULL DEFAULT NULL, `suspended_at` timestamp NULL DEFAULT NULL, `banned_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `throttle_user_id_index` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `tokens` -- CREATE TABLE IF NOT EXISTS `tokens` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `facebook` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `twitter` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `tokens_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `trainerhistory` -- CREATE TABLE IF NOT EXISTS `trainerhistory` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `historytype_id` int(10) unsigned NOT NULL, `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `trainerhistory_user_id_foreign` (`user_id`), KEY `trainerhistory_historytype_id_foreign` (`historytype_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `trainers` -- CREATE TABLE IF NOT EXISTS `trainers` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `bio` varchar(500) COLLATE utf8_unicode_ci NOT NULL, `website` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `confirmed` tinyint(1) NOT NULL DEFAULT '0', `specialities_id` int(10) unsigned NOT NULL, `profession` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `trainers_user_id_foreign` (`user_id`), KEY `trainers_confirmed_index` (`confirmed`), KEY `trainers_specialities_id_index` (`specialities_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `permissions` text COLLATE utf8_unicode_ci, `activated` tinyint(1) NOT NULL DEFAULT '0', `activation_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `activated_at` timestamp NULL DEFAULT NULL, `last_login` timestamp NULL DEFAULT NULL, `persist_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `reset_password_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `first_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `last_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `display_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `gender` tinyint(4) NOT NULL, `dob` date NOT NULL, `area_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `directory` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `categories` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `users_email_unique` (`email`), KEY `users_activation_code_index` (`activation_code`), KEY `users_reset_password_code_index` (`reset_password_code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `users_groups` -- CREATE TABLE IF NOT EXISTS `users_groups` ( `user_id` int(10) unsigned NOT NULL, `group_id` int(10) unsigned NOT NULL, PRIMARY KEY (`user_id`,`group_id`), KEY `users_groups_group_id_foreign` (`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `user_has_categories` -- CREATE TABLE IF NOT EXISTS `user_has_categories` ( `user_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `user_has_categories_user_id_foreign` (`user_id`), KEY `user_has_categories_category_id_foreign` (`category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `user_marketingpreferences` -- CREATE TABLE IF NOT EXISTS `user_marketingpreferences` ( `user_id` int(10) unsigned NOT NULL, `marketingpreference_id` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `user_marketingpreferences_user_id_foreign` (`user_id`), KEY `user_marketingpreferences_marketingpreference_id_foreign` (`marketingpreference_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `venues` -- CREATE TABLE IF NOT EXISTS `venues` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `address` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `town` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `postcode` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `lat` decimal(10,8) NOT NULL, `lng` decimal(11,8) NOT NULL, `image` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `venues_user_id_foreign` (`user_id`), KEY `venues_lat_index` (`lat`), KEY `venues_lng_index` (`lng`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `venue_facilities` -- CREATE TABLE IF NOT EXISTS `venue_facilities` ( `venue_facilities_id` int(11) NOT NULL AUTO_INCREMENT, `venue_id` int(10) unsigned NOT NULL, `facility_id` int(10) unsigned NOT NULL, `details` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`venue_facilities_id`), KEY `venue_facilities_venue_id_foreign` (`venue_id`), KEY `venue_facilities_facility_id_foreign` (`facility_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `wallethistory` -- CREATE TABLE IF NOT EXISTS `wallethistory` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `sessionpayment_id` int(10) unsigned NOT NULL, `transaction_amount` decimal(8,2) NOT NULL, `new_balance` decimal(8,2) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `wallethistory_user_id_foreign` (`user_id`), KEY `wallethistory_sessionpayment_id_index` (`sessionpayment_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `wallets` -- CREATE TABLE IF NOT EXISTS `wallets` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `balance` decimal(19,4) NOT NULL, `previous_balance` decimal(19,4) NOT NULL, `paypal` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `wallets_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1; -- -------------------------------------------------------- -- -- Table structure for table `withdrawalrequests` -- CREATE TABLE IF NOT EXISTS `withdrawalrequests` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `transaction_amount` decimal(19,4) NOT NULL, `account` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `acc_type` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `processed` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `withdrawalrequests_user_id_foreign` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -- Constraints for dumped tables -- -- -- Constraints for table `evercisegroups` -- ALTER TABLE `evercisegroups` ADD CONSTRAINT `evercisegroups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `evercisegroups_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`); -- -- Constraints for table `evercisesessions` -- ALTER TABLE `evercisesessions` ADD CONSTRAINT `evercisesessions_evercisegroup_id_foreign` FOREIGN KEY (`evercisegroup_id`) REFERENCES `evercisegroups` (`id`); -- -- Constraints for table `evercoinhistory` -- ALTER TABLE `evercoinhistory` ADD CONSTRAINT `evercoinhistory_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `evercoins` -- ALTER TABLE `evercoins` ADD CONSTRAINT `evercoins_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `milestones` -- ALTER TABLE `milestones` ADD CONSTRAINT `milestones_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `ratings` -- ALTER TABLE `ratings` ADD CONSTRAINT `ratings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `referrals` -- ALTER TABLE `referrals` ADD CONSTRAINT `referrals_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `sessionmembers` -- ALTER TABLE `sessionmembers` ADD CONSTRAINT `sessionmembers_evercisesession_id_foreign` FOREIGN KEY (`evercisesession_id`) REFERENCES `evercisesessions` (`id`), ADD CONSTRAINT `sessionmembers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `sessionpayments` -- ALTER TABLE `sessionpayments` ADD CONSTRAINT `sessionpayments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `tokens` -- ALTER TABLE `tokens` ADD CONSTRAINT `tokens_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainerhistory` -- ALTER TABLE `trainerhistory` ADD CONSTRAINT `trainerhistory_historytype_id_foreign` FOREIGN KEY (`historytype_id`) REFERENCES `historytypes` (`id`), ADD CONSTRAINT `trainerhistory_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `trainers` -- ALTER TABLE `trainers` ADD CONSTRAINT `trainers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `users_groups` -- ALTER TABLE `users_groups` ADD CONSTRAINT `users_groups_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`), ADD CONSTRAINT `users_groups_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_has_categories` -- ALTER TABLE `user_has_categories` ADD CONSTRAINT `user_has_categories_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`), ADD CONSTRAINT `user_has_categories_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `user_marketingpreferences` -- ALTER TABLE `user_marketingpreferences` ADD CONSTRAINT `user_marketingpreferences_marketingpreference_id_foreign` FOREIGN KEY (`marketingpreference_id`) REFERENCES `marketingpreferences` (`id`), ADD CONSTRAINT `user_marketingpreferences_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venues` -- ALTER TABLE `venues` ADD CONSTRAINT `venues_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `venue_facilities` -- ALTER TABLE `venue_facilities` ADD CONSTRAINT `venue_facilities_facility_id_foreign` FOREIGN KEY (`facility_id`) REFERENCES `facilities` (`id`), ADD CONSTRAINT `venue_facilities_venue_id_foreign` FOREIGN KEY (`venue_id`) REFERENCES `venues` (`id`); -- -- Constraints for table `wallethistory` -- ALTER TABLE `wallethistory` ADD CONSTRAINT `wallethistory_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `wallets` -- ALTER TABLE `wallets` ADD CONSTRAINT `wallets_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `withdrawalrequests` -- ALTER TABLE `withdrawalrequests` ADD CONSTRAINT `withdrawalrequests_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); /*!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>/app/composers/AdminPendingTrainersComposer.php <?php namespace composers; use Trainer; class AdminPendingTrainersComposer { public function compose($view) { $view ->with('trainers', Trainer::getUnconfirmedTrainers()); } }<file_sep>/app/models/Evercoin.php <?php /** * Class Evercoin */ class Evercoin extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'user_id', 'balance']; /** * The database table used by the model. * * @var string */ protected $table = 'evercoins'; /** * @param $amount */ public function deposit($amount) { $this->transaction($amount); } /** * @param $amount * @return mixed */ public function withdraw($amount) { $this->transaction(- $amount); return $this->balance; } /** * Convert Pounds To Evercoins * * @param $amountInPounds * @return float */ public static function poundsToEvercoins($amountInPounds) { return $amountInPounds * 1 / Config::get('values')['evercoin']; } /** * Convert Evercoins to Pounds * * @param $amountInEvercoins * @return mixed */ public static function evercoinsToPounds($amountInEvercoins) { return $amountInEvercoins * Config::get('values')['evercoin']; } /** * Generate a new Transaction * * @param $amount */ protected function transaction($amount) { $user_id = $this->attributes['user_id']; $oldBalance = $this->attributes['balance']; $newBalance = $oldBalance + $amount; $this->attributes['balance'] = $newBalance; $this->save(); Evercoinhistory::create( [ 'user_id' => $user_id, 'transaction_amount' => $amount, 'new_balance' => $newBalance ] ); } }<file_sep>/app/composers/AutocompleteCategoryComposer.php <?php namespace composers; use Subcategory; use JavaScript; class AutocompleteCategoryComposer { public function compose($view) { $force = isset($view->force) ? $view->force : 0; $subcategories = Subcategory::lists('name'); sort($subcategories); JavaScript::put(array('initAutocompleteCategory' => ['force'=>$force, 'list'=>$subcategories])); } }<file_sep>/app/widgets/Shortcodes.php <?php class Shortcodes { protected $elastic; protected $search; protected $evercisegroup; protected $input; protected $log; protected $redirect; protected $paginator; protected $config; public function __construct() { $this->evercisegroup = new Evercisegroup; $this->input = Request::getFacadeRoot(); $this->log = Log::getFacadeRoot(); $this->link = new Link; $this->view = View::getFacadeRoot(); $this->place = new Place; $this->redirect = Redirect::getFacadeRoot(); $this->config = Config::getFacadeRoot(); $this->elastic = new Elastic( Geotools::getFacadeRoot(), $this->evercisegroup, Es::getFacadeRoot(), $this->log ); $this->search = new Search($this->elastic, $this->evercisegroup, $this->log); } public function singleClass($attr, $content = null, $name = null) { $class = false; $area = false; $params = [ 'from' => 0, 'size' => 1 ]; if(!empty($attr['area'])) { /** AreaID is defined. So get that */ $area = $this->place->find($attr['area']); } else { /** Area is not defined. Is the NearMe option defined? */ if(!empty($attr['nearme'])) { $place = Place::getLocation($this->input->ip(), true, true); $zip = $place->getZipcode(); $params['radius'] = '3mi'; $area = $this->place->getByLocation($zip); } } if(!$area) { $area = $this->link->where('permalink', '=', 'london')->first()->getArea; } switch($attr['type']) { case 'id': if(!empty($result = $this->search->cleanSingleResults($this->search->getSingle($attr['param'])))) { $class = $result[0]; } break; case 'search': $params['search'] = $attr['param']; if(!empty($result = $this->search->cleanSingleResults($this->search->getResults($area, $params)))) { $class = $result[0]; } break; } if (!$class) { /** Get a random one */ if(!empty($result = $this->search->cleanSingleResults($this->search->getSingle(0)))) { $class = $result[0]; } } return $this->view->make('widgets/cms_single_class', (array)$class)->render(); } }<file_sep>/app/controllers/email/UserMailer.php <?php namespace email; use HTML; class UserMailer extends Mailer { /** * Outline all the events this class will be listening for. * @param [type] $events * @return void */ public function subscribe($events) { /** ALL SUBS REMOVED TO config/events */ } } <file_sep>/app/models/Place.php <?php /** * Class Place */ class Place extends \Eloquent { protected $fillable = [ 'name', 'place_type', 'lng', 'lat', 'min_radius', 'zone', 'poly_coordinates', 'coordinate_type' ]; protected $table = 'places'; public function link() { return $this->hasOne('Link', 'parent_id', 'id'); } public static function getByGoogleLocation($params = []) { if (count($params) == 0) { return FALSE; } $location = []; $type = 'AREA'; switch ($params['type']) { case 'postal_code': $type = 'ZIP'; $location = ['postcode', $params['postcode']]; break; case 'administrative_area_level_3': $type = 'BOROUGH'; $location = [$params['city'], $params['neighborhood']]; break; case 'neighborhood': $type = 'BOROUGH'; $location = [$params['city'], $params['neighborhood']]; break; case 'train_station': case 'subway_station': $type = 'STATION'; $location = [ $params['city'], (!empty($params['point']) ? $params['point'] : $params['station'] . ' Station') ]; break; case 'park': $location = [$params['city'], $params['establishment']]; break; case 'route': $location = [$params['city'], $params['route']]; break; default: $location = [$params['formatted']]; if (!empty($params['establishment']) && !empty($params['city'])) { $location = [$params['city'], $params['establishment']]; } } $name = $params['formatted']; $location = implode('/', array_map('slugIt', $location)); return self::checkGoogleLocation($location, $name, $type, $params); } public static function getByLocation($location = '', $city = 'London') { /** First Check the Location if it exists */ if (!empty($location)) { /** We now have to create a lot of shit to get this working */ $is_city = TRUE; $is_area = TRUE; $zip_code = FALSE; if (strpos($location, ',') !== FALSE) { $location = explode(',', $location); } else { $location = [$location]; } /** Remove London and united kingdom from Googles Crap */ foreach ($location as $i => $val) { if (trim($val) == 'United Kingdom') { unset($location[$i]); } elseif (stripos($val, 'United Kingdom') !== FALSE) { $location[$i] = trim(str_ireplace('United Kingdom', '', $val)); } if (trim($val) == $city) { $is_city = TRUE; unset($location[$i]); } elseif (stripos($val, $city) !== FALSE) { /** London Sometimes at the front of the row London N1 0QH, Kingdom */ $is_city = TRUE; $location[$i] = trim(str_ireplace($city, '', $val)); if ($location[$i] == '') { unset($location[$i]); } } if (!empty($location[$i]) && stripos($val, 'station') !== FALSE) { $is_area = FALSE; $location[$i] = trim(str_ireplace('station', '', $location[$i])); if ($location[$i] == '') { unset($location[$i]); } } /** Check for a zip Code */ if (!empty($location[$i]) && preg_match( '#^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$#', trim(strtoupper($location[$i])) ) ) { $zip_code = strtoupper(trim($location[$i])); unset($location[$i]); } } $name = implode(' ', $location); $location = Str::slug($name); $name .= ($is_city && strpos($name, $city) === FALSE ? ' ' . ucfirst($city) : ''); $name .= (!$is_area && strpos($name, 'station') === FALSE ? ' Station' : ''); $return = []; $type = 'AREA'; if ($is_city) { $return[] = strtolower($city); } if ($is_area && !$zip_code && $city == 'London') { $return[] = 'area'; } if (!$is_area && $city == 'London') { $return[] = 'station'; $type = 'STATION'; } if ($zip_code) { $type = 'ZIP'; $return = ['postcode', Str::slug($zip_code)]; $name = $zip_code; } if (!$zip_code) { $return[] = $location; } /** @var $return REMOVE EMPTY Array fields */ $return = array_filter($return); $location_url = implode('/', $return); if (substr($location_url, -4) == 'area') { $location_url = str_replace('/area', '', $location_url); } return self::checkLocation($location_url, $name, $type, ($is_city ? $city : FALSE), $zip_code); } } public static function checkGoogleLocation($url, $name, $type, $params = []) { $url = rtrim((string)$url, '/'); $link = Link::where('permalink', $url)->first(); if (count($link) == 0) { $link = new Link(['permalink' => $url, 'type' => $type]); $data = [ 'name' => (string)$name, 'place_type' => 1, 'lng' => $params['lng'], 'lat' => $params['lat'], 'zone' => 0, 'poly_coordinates' => '', 'coordinate_type' => 'radious' ]; $place = static::create($data)->link()->save($link)->getArea; } else { $place = $link->getArea; } return $place; } public static function checkLocation($url, $name, $type, $is_city = FALSE, $is_zip = FALSE) { $url = rtrim((string)$url, '/'); $link = Link::where('permalink', $url)->first(); if (count($link) == 0) { /** This crap is new.. so lets add it and figure out where the f* is it */ if ($is_zip) { $min_radius = '1mi'; } $geo = self::getGeo($name, $is_city, $is_zip); $link = new Link(['permalink' => $url, 'type' => $type]); $data = [ 'name' => (string)$name, 'place_type' => 1, 'lng' => $geo['lng'], 'lat' => $geo['lat'], 'zone' => 0, 'poly_coordinates' => '', 'coordinate_type' => 'Radious' ]; $place = static::create($data)->link()->save($link)->getArea; } else { $place = $link->getArea; } return $place; } public static function getGeo($location, $is_city, $is_zip) { $geocode = self::getLocation($location, $is_city, $is_zip); if ($geocode) { return ['lat' => $geocode->getLatitude(), 'lng' => $geocode->getLongitude()]; } else { /** Since this will return a 0 0 in the middle of the ocean. */ /** Lets set london */ return ['lat' => 51.517961, 'lng' => -0.126318]; } } public static function getLocation($location, $is_city, $is_zip) { $geocoder = new \Geocoder\Geocoder(); $adapter = new \Geocoder\HttpAdapter\CurlHttpAdapter(); $chain = new \Geocoder\Provider\ChainProvider( [ new \Geocoder\Provider\FreeGeoIpProvider($adapter), new \Geocoder\Provider\HostIpProvider($adapter), new \Geocoder\Provider\GoogleMapsProvider($adapter) ] ); $geocoder->registerProvider($chain); try { $addition = $location . ($is_zip ? ' UK' : '') . ($is_city ? ' ' . $is_city : ''); $geocode = $geocoder->geocode($addition); return $geocode; } catch (Exception $e) { return FALSE; } } public static function moveAreaPermalinks() { die('NOT FOR USE RIGHT NOW'); $areas = Place::all(); foreach ($areas as $area) { $url = ''; if ($area->permalink != 'COMPLETED') { //Generate URL if ($area->place_type == 'station') { $url = 'london/station/' . $area->permalink; } if ($area->place_type == 'area') { $url = 'london/area/' . $area->permalink; } $url = self::checkDuplicate($url); $link = new Link(['type' => $area->place_type, 'parent_id' => $area->id, 'permalink' => $url]); $save = $area->link()->save($link); } } } public static function checkDuplicate($url) { do { $check = Link::where('permalink', $url)->count() > 0; if ($check) { if (strpos($url, '_') === FALSE) { $url .= '_0'; } $url = ++$url; } } while ($check); return $url; } }<file_sep>/app/models/SessionPayment.php <?php /** * Class Sessionpayment * * Sessionpayment is a holding table to process payments from past classes into a trainers wallet. * Accessed only by the commands (CheckPayments and CheckSessions), which are run on a cron * CheckSessions will pick up a session which took place over 1 day ago, and make an entry in Sessionpayment * CheckPayments will pick this up from Sessionpayment after 3 days, mark it processed, and credit the trainers wallet. */ class Sessionpayment extends \Eloquent { /** * @var array */ protected $fillable = ['user_id', 'evercisesession_id', 'total', 'total_after_fees', 'commission', 'processed']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('User'); } public function evercisesession() { return $this->belongsTo('Evercisesession'); } /** * Convert Pounds to Pennies * * @param $pounds * @return mixed */ public static function poundsToPennies($pounds) { return ($pounds * 100); } /** * Convert Pennies to Pounds * * @param $pennies * @return float */ public static function penniesToPounds($pennies) { return ($pennies / 100); } } <file_sep>/app/config/searchindex.php <?php /** Simple Search Index */ return [ 'name' => 5, 'title' => 3, 'categories' => 4, 'description' => 3 ];<file_sep>/app/commands/GenerateUrls.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; class GenerateUrls extends Command { /** * The console command name. * * @var string */ protected $name = 'classes:url'; /** * The console command description. * * @var string */ protected $description = 'Generate a new hash for the classes'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $classes = Evercisegroup::all(); foreach ($classes as $class) { $class->slug = Evercisegroup::uniqueSlug($class); $class->save(); } $this->line("Completed ".$classes->count()); $this->line("Indexing"); event('class.index.all'); $this->line("DONE"); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('days', null, InputOption::VALUE_OPTIONAL, 'How many days old records should be before processing.', 3), ); } } <file_sep>/app/models/User.php <?php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel; /** * Class User */ class User extends SentryUserModel implements UserInterface, RemindableInterface { /** * @var array */ protected $fillable = [ 'display_name', 'password', 'first_name', 'last_name', 'activated', 'reset_password_code', 'remember_token', 'persist_code', 'activated_at', 'permissions', 'email', 'gender', 'activation_code', 'dob', 'area_code', 'phone', 'directory', 'image', 'custom_commission' ]; public static $validationRules = [ 'first_name' => 'required|alpha|max:15|min:2', 'last_name' => 'required|alpha|max:15|min:2', 'phone' => 'numeric', 'password' => '<PASSWORD>', 'email' => 'email', ]; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password']; /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function packages() { return $this->hasMany('UserPackages', 'user_id'); } public function mindbody() { return $this->hasOne('ExternalService')->where('service', 'mindbody'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function trainer() { return $this->hasOne('Trainer'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function rewards() { return $this->hasMany('MilestoneRewards'); } public function isAdmin() { } public function isTrainer() { return (count($this->trainer) == 1); } /* public function user_has_marketingpreference() { return $this->hasManyThrough('User_has_marketingpreference', 'Marketingpreference'); } public function Marketingpreferences() { return $this->belongsToMany('MarketingPreference', 'user_has_marketingpreferences', 'marketingpreferences_id', 'user_id'); }*/ /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function marketingpreferences() { return $this->belongsToMany( 'Marketingpreference', 'user_marketingpreferences', 'user_id', 'marketingpreference_id' )->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function newsletter() { return $this->belongsToMany( 'Marketingpreference', 'user_marketingpreferences', 'user_id', 'marketingpreference_id' ) ->where('name', 'newsletter') ->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function sessions() { return $this->belongsToMany('Evercisesession', 'sessionmembers', 'user_id', 'evercisesession_id') ->withPivot('token', 'transaction_id', 'payer_id', 'payment_method')->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function pastsessions() { return $this->belongsToMany('Evercisesession', 'sessionmembers', 'user_id', 'evercisesession_id') ->withPivot('token', 'transaction_id', 'payer_id', 'payment_method') ->where('date_time', '<', DB::raw('NOW()')) ->orderBy('date_time', 'asc') ->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function futuresessions() { return $this->belongsToMany('Evercisesession', 'sessionmembers', 'user_id', 'evercisesession_id') ->withPivot('token', 'transaction_id', 'payer_id', 'payment_method') ->where('date_time', '>=', DB::raw('NOW()')) ->orderBy('date_time', 'asc') ->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function evercisegroups() { return $this->hasMany('Evercisegroup'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function pendingWithdrawals() { return $this->hasMany('Withdrawalrequest')->where('withdrawalrequests.processed', 0); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function emailOut() { return $this->hasMany('EmailOut'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function wallet() { return $this->hasOne('Wallet'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function wallethistory() { return $this->hasMany('Wallethistory'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function evercoin() { return $this->hasOne('Evercoin'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function milestone() { return $this->hasOne('Milestone'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function token() { return $this->hasOne('Token'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function referrals() { return $this->hasMany('Referral'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function transactions() { return $this->hasMany('Transaction'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function activities() { return $this->hasMany('Activities') ->orderBy('created_at', 'desc'); } /** * @param $trainer_id * @return \Illuminate\Database\Eloquent\Model|null|static */ public static function getUserByTrainerId($trainer_id) { $user = Static::whereHas('trainer', function ($query) use (&$trainer_id) { $query->where('id', $trainer_id); })->first(); return $user; } /** * @return array */ public static function validDatesUserDob() { // dates for validation $dt = new DateTime(); $before = $dt->sub(new DateInterval('P' . Config::get('values')['min_age'] . 'Y')); $dateBefore = $before->format('Y-m-d'); $dt = new DateTime(); $after = $dt->sub(new DateInterval('P' . Config::get('values')['max_age'] . 'Y')); $dateAfter = $after->format('Y-m-d'); return [$dateBefore, $dateAfter]; } /** * @param $inputs * @param $dateAfter * @param $dateBefore * @return \Illuminate\Validation\Validator */ public static function validateUserSignup($inputs/*, $dateAfter, $dateBefore*/) { // validation rules for input field on register form $validator = Validator::make( $inputs, array_merge( static::$validationRules, [ 'display_name' => 'required|max:20|min:5|unique:users', 'email' => 'required|email|unique:users', ] ) ); return $validator; } /** * @param $inputs * @param $validator * @return array */ public static function handleUserValidation($inputs, $validator) { // if fails add errors to results if ($validator->fails()) { $result = [ 'callback' => 'error', 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; // log errors Log::notice($validator->errors()->toArray()); } elseif ($inputs['phone'] != '' && $inputs['areacode'] == '') { // is user has filled in the area code but no number fail validation $result = [ 'callback' => 'error', 'validation_failed' => 1, 'errors' => ['areacode' => 'Please select a country'] ]; Log::notice('Please select a country'); } else { // if validation passes return validation_failed false $result = [ 'validation_failed' => 0 ]; } return $result; } /** * @param $inputs * @param $dateAfter * @param $dateBefore * @param $isTrainer * @return \Illuminate\Validation\Validator */ public static function validateUserEdit($inputs, $dateAfter, $dateBefore, $isTrainer) { if ($isTrainer) { $validationRules = array_merge( static::$validationRules, Trainer::$validationRules ); } $validationRules['image'] = 'sometimes'; $validationRules['dob'] = 'date_format:Y-m-d|after:' . $dateAfter . '|before:' . $dateBefore; $validator = Validator::make( $inputs, $validationRules ); return $validator; } /** * @param $first_name * @param $last_name * @param $dob * @param $gender * @param $image * @param $area_code * @param $phone */ public function updateUser($params) { $this->update(array_filter($params)); } public function checkProfileMilestones() { if ( $this->gender && $this->dob && $this->phone && $this->image ) { event('user.fullProfile', [$this]); Milestone::where('user_id', $this->id)->first()->add('profile'); } } /** * @param $user */ public static function addToUserGroup($user) { try { // find the user group $userGroup = Sentry::findGroupById(1); // add the user to this group $user->addGroup($userGroup); } catch (Exception $e) { Log::error('cannot add to user group: ' . $e); } } /** * @param $user */ public static function addToFbGroup($user) { try { $userGroup = Sentry::findGroupById(2); $user->addGroup($userGroup); } catch (Exception $e) { Log::error('cannot add to facebook group: ' . $e); } } public static function getFacebookUser($redirect_url, $params = '') { try { // Use a single object of a class throughout the lifetime of an application. $application = Config::get('facebook'); $permissions = 'publish_stream,email,user_birthday,read_stream'; if ($redirect_url != NULL) { $url_app = Request::root() . '/login/fb/' . $redirect_url.'/'.$params; } else { $url_app = Request::root() . '/login/fb'; } // getInstance FacebookConnect::getFacebook($application); $getUser = FacebookConnect::getUser($permissions, $url_app); // Return facebook User data return $getUser; } catch (Exception $e) { Log::error('There was an error communicating with Facebook' . $e); } } /** * @param $user * @param $me */ public static function grabFacebookImage($user, $me) { $image = 'http://graph.facebook.com/' . $me['id'] . '/picture?width=300&height=300'; try { $img = file_get_contents($image); return self::createImage($user, $image); } catch (Exception $e) { // This exception will happen from localhost, as pulling the file from facebook will not work Log::error('no facebook image :' . $e); return self::createImage($user); } } /** * @param $redirect * @param $user * @return \Illuminate\Http\RedirectResponse */ public static function facebookRedirectHandler($redirect = NULL, $user, $message = NULL, $params = '') { if (!empty($params)) { $data = explode(':', $params); $params = []; if (!empty($data[1])) { $params[$data[0]] = $data[1]; } } else { $params = []; } if ($redirect != NULL) { if ($redirect == 'trainers.create') // Used when the 'i want to list classes' button is clicked in the register page { $result = Redirect::route($redirect, $params)->with( 'notification', $message ); } else // Used when logging in before hitting the checkout { $result = Redirect::route($redirect, $params); } } else { $result = Redirect::route('finished.user.registration'); } return $result; } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this-><PASSWORD>; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } public function getRememberToken() { return $this->remember_token; } public function setRememberToken($value) { $this->remember_token = $value; } public function getRememberTokenName() { return 'remember_token'; } /** * @return \Illuminate\Validation\Validator */ public static function validUserSignup($inputs) { /* date of birth not been used in v3 * list($dateBefore, $dateAfter) = self::validDatesUserDob(); */ $validator = self::validateUserSignup($inputs/*, $dateAfter, $dateBefore*/); return self::handleUserValidation($inputs, $validator); } /** * @return \Illuminate\Validation\Validator */ public static function validUserEdit($inputs, $isTrainer) { list($dateBefore, $dateAfter) = self::validDatesUserDob(); $validator = self::validateUserEdit($inputs, $dateAfter, $dateBefore, $isTrainer); return self::handleUserValidation($inputs, $validator); } /** * @return \Cartalyst\Sentry\Users\UserInterface * * Store */ public static function registerUser($inputs) { $display_name = $inputs['display_name']; $first_name = $inputs['first_name']; $last_name = $inputs['last_name']; $email = $inputs['email']; $password = $inputs['password']; $area_code = isset($inputs['areacode']) ? $inputs['areacode'] : '+44'; $phone = isset($inputs['phone']) ? $inputs['phone'] : ''; $gender = isset($inputs['gender']) ? ($inputs['gender'] == 'male' ? 1 : ($inputs['gender'] == 'female' ? 2 : 0)) : 0; $user = Sentry::register( [ 'display_name' => $display_name, 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, 'area_code' => $area_code, 'phone' => $phone, 'password' => <PASSWORD>, 'gender' => $gender, 'activated' => TRUE, 'directory' => '', 'image' => '', 'categories' => '' ] ); self::addToUserGroup($user); Log::info('new user created called ' . $display_name); return $user; } /** * @param $user */ public static function sendGuestWelcomeEmail($user) { event('user.guest.signup', [$user]); } public static function sendWelcomeEmail($user) { event('user.signup', [$user]); } /** * @param $user * @param $inputs */ public static function sendFacebookWelcomEmail($user, $inputs) { event('user.facebook.signup', [$user]); } public function sendForgotPasswordEmail($reset_code) { event('user.forgot.password', [$this, $reset_code]); } /** * @param $newsletter * @param $list_id * @param $email_address */ public static function subscribeMailchimpNewsletter($list_id, $email_address, $first_name, $last_name) { try { MailchimpWrapper::lists()->subscribe($list_id, ['email' => $email_address], ['FNAME' => $first_name, 'LNAME' => $last_name]); Log::info('user added to mailchimp'); } catch (Mailchimp_Error $e) { if ($e->getMessage()) { $error = 'Code:' . $e->getCode() . ': ' . $e->getMessage(); Log::error($error); } } } /** * @param $newsletter * @param $list_id * @param $email_address */ public static function unSubscribeMailchimpNewsletter($list_id, $email_address) { try { MailchimpWrapper::lists()->unsubscribe($list_id, ['email' => $email_address]); Log::info('user removed from mailchimp'); } catch (Mailchimp_Error $e) { if ($e->getMessage()) { $error = 'Code:' . $e->getCode() . ': ' . $e->getMessage(); Log::error($error); } } } /** * Get full name from either User object or a user id * * @param $id * @return string */ public static function getName($userOrId) { if (!is_a($userOrId, 'Eloquent')) // parameter passed in is id { $user = static::select('first_name', 'last_name')->where('id', $userOrId)->firstOrFail(); } else // parameter passed in is User { $user = $userOrId; } return static::getFullName($user); } /** * Get full name and email from either User object or a user id * * @param $id * @return string */ public static function getNameAndEmail($userOrId) { if (!is_a($userOrId, 'Eloquent')) { $user = User::select('first_name', 'last_name', 'email')->where('id', $userOrId)->firstOrFail(); } else { $user = $userOrId; } return ['name' => static::getFullName($user), 'email' => $user->email]; } /** * Concatenate first and last names from User object * * @param $user * @return string */ public static function getFullName($user) { return $user->first_name . ' ' . $user->last_name; } public function getWallet() { if (!isset($this->wallet)) { Wallet::createIfDoesntExist($this->id); } return $this->wallet; } /* foreign keys */ /** * */ public static function makeUserDir($user) { $dir = hashDir($user->id, 'u'); Log::info('User dir ' . $dir); $user->directory = $dir; $user->save(); return; } public function resetPassword() { $newPassword = Functions::randomPassword(7); $resetPasswordCode = $this->getResetPasswordCode(); $this->attemptResetPassword($resetPasswordCode, $newPassword); return $newPassword; } public function getGender() { return ($this->gender == 1 ? 'male' : ($this->gender == 2 ? 'female' : '')); } public function hasTwitter() { if ($this->token) { return $this->token->hasValidTwitterToken(); } else { return FALSE; } } public function hasFacebook() { if ($this->token) { return $this->token->hasValidFacebookToken(); } else { return FALSE; } } public function getFacebookId() { if ($this->token) { if ($this->token->hasValidFacebookToken()) { $facebookToken = json_decode($this->token->facebook); if ($facebookToken) { if (isset($facebookToken->id)) { return $facebookToken->id; } } } } return NULL; } public function getTwitterId() { if ($this->token) { if ($this->token->hasValidTwitterToken()) { $twitterToken = json_decode($this->token->twitter); if ($twitterToken) { if (isset($twitterToken->screen_name)) { return $twitterToken->screen_name; } } } } return NULL; } public static function createImage($user, $image = FALSE) { $sizes = Config::get('evercise.user_images'); $dir = hashDir($user->id, 'u'); if (!$image) { $image = Image::make(file_get_contents('http://robohash.org/' . slugIt($user->display_name) . '/bgset_bg1/2.2' . slugIt($user->display_name) . '.png?size=300x300')); } else { $image = Image::make(file_get_contents($image)); } $user_file_name = slugIt(implode(' ', [$user->display_name, rand(1, 10)])) . '.png'; foreach ($sizes as $s) { $file_name = $s['prefix'] . '_' . $user_file_name; try { $image->fit($s['width'], $s['height'])->save($dir . '/' . $file_name); } catch (Exception $e) { continue; } } $user->image = $user_file_name; $user->save(); return $user; } public static function uniqueDisplayName($display_name) { $next_display_name = $display_name; do { $unique = static::where('display_name', $next_display_name)->first(); $next_display_name = $display_name . rand(1, 10); } while (!is_null($unique)); return $next_display_name; } public function numGroups() { return count($this->evercisegroups); } public function pendingReferrals() { return $this->hasMany('Referral') ->where('referee_id', 0); } public function countPendingReferrals() { return count($this->pendingReferrals); } public static function getIdFromDisplayName($displayName) { return static::where('display_name', $displayName)->pluck('id'); } public static function getDisplayNameFromId($id) { return static::where('id', $id)->pluck('display_name'); } } <file_sep>/app/composers/EvercisegroupsSearchComposer.php <?php namespace composers; use JavaScript; class EvercisegroupsSearchComposer { public function compose($view) { JavaScript::put( [ 'MapWidgetloadScript' => json_encode(['discover'=> true]), 'initSwitchView' => 1 , 'InitSearchForm' => 1 , 'initClassBlock' => 1 , 'zero_results' =>trans('discover.zero_results') ] ); $view; } }<file_sep>/app/composers/TrainerShowComposer.php <?php namespace composers; use JavaScript; class TrainerShowComposer { public function compose($view) { JavaScript::put( [ 'mailAll' => 1, 'initSessionListDropdown' => 1, 'initEvercisegroupsShow' => 1 ] ); } }<file_sep>/app/controllers/StaticController.php <?php class StaticController extends \BaseController { /** * Display a listing of the resource. * * @return Response */ // FAQ is loaded from database, editable in Admin. Articles > How it works public function show() { $page = Route::getCurrentRoute()->getPath(); return View::make('static.'.$page); } }<file_sep>/app/commands/CheckPayments.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; // php artisan check:payments class CheckPayments extends Command { /** * The console command name. * * @var string */ protected $name = 'check:payments'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $days = $this->option('days'); $this->info('checking for unprocessed payments older than '.$days.' day'.($days!=1?'s':'')); $cutOffDate = (new DateTime('now'))->sub(new DateInterval('P'.$days.'D')); $payments = Sessionpayment::where('created_at', '<', $cutOffDate) ->where('processed', 0) ->with('user.wallet') ->get(); foreach ($payments as $p_key => $payment) { //$payment->user points to the user who bought the class NOT the trainer to be paid! $trainer = $payment->evercisesession->evercisegroup->user; $currentBalance = $trainer->wallet->balance; $newBalance = $currentBalance + $payment->total_after_fees; $this->info('processing payment. id: '.$payment->id.', total after fees: '.$payment->total_after_fees.', new balance: '.$newBalance); $trainer->wallet->find($trainer->wallet->id)->deposit($payment->total_after_fees, $payment->id, 'trainer_payment'); $payment->update(['processed'=>1]); } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('days', null, InputOption::VALUE_OPTIONAL, 'How many days old records should be before processing.', 3), ); } } <file_sep>/app/Functions.php <?php use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Symfony\Component\VarDumper\Cloner\VarCloner; if (!function_exists('ga')) { /* * Google Event * */ function ga($url) { $track = " <script> if (typeof ga == 'function') { ga('send', 'pageview', '".$url."'); } </script> "; return $track; } } if (!function_exists('uniqueFile')) { /* * Wrap event class * */ function uniqueFile($path, $name, $extension) { do { $next_file = $name.'-'.rand(1,50).'.'.$extension; } while (is_file($path.$next_file)); return $next_file; } } if (!function_exists('formatDuration')) { /* * Wrap event class * */ function formatDuration($duration = 0) { $hours = floor($duration / 60); $minutes = $duration % 60; return ($hours ? $hours . ' hours ' : '') . ( $minutes . ' minutes'); } } if (!function_exists('event')) { /* * Wrap event class * */ function event($name, $params = []) { Event::fire($name, $params); } } if (!function_exists('d')) { /* * nice print of vardump without the xdebug * */ function d($var, $die = true) { $dumper = 'cli' === PHP_SAPI ? new CliDumper : new HtmlDumper; $dumper->dump((new VarCloner)->cloneVar($var)); if ($die) { die(); } } } if (!function_exists('returnPlural')) { /* * nice print of vardump without the xdebug * */ function returnPlural($string, $count = 1) { if (is_array($count)) { $count = count($count); } if ($count == 1) { return str_singular($string); } return str_plural($string); } } if (!function_exists('image')) { /* * nice print of vardump without the xdebug * */ function image($image, $alt = 'image', $params = []) { /* * return html image tag */ return HTML::image($image, $alt, $params); } } if (!function_exists('generateImage')) { function generateImage($size = 200) { $hash = str_random(); /* parse hash string */ $csh = hexdec(substr($hash, 0, 1)); // corner sprite shape $ssh = hexdec(substr($hash, 1, 1)); // side sprite shape $xsh = hexdec(substr($hash, 2, 1)) & 7; // center sprite shape $cro = hexdec(substr($hash, 3, 1)) & 3; // corner sprite rotation $sro = hexdec(substr($hash, 4, 1)) & 3; // side sprite rotation $xbg = hexdec(substr($hash, 5, 1)) % 2; // center sprite background /* corner sprite foreground color */ $cfr = hexdec(substr($hash, 6, 2)); $cfg = hexdec(substr($hash, 8, 2)); $cfb = hexdec(substr($hash, 10, 2)); /* side sprite foreground color */ $sfr = hexdec(substr($hash, 12, 2)); $sfg = hexdec(substr($hash, 14, 2)); $sfb = hexdec(substr($hash, 16, 2)); /* final angle of rotation */ $angle = hexdec(substr($hash, 18, 2)); /* size of each sprite */ $spriteZ = 128; /* start with blank 3x3 identicon */ $identicon = imagecreatetruecolor($spriteZ * 3, $spriteZ * 3); imageantialias($identicon, TRUE); /* assign white as background */ $bg = imagecolorallocate($identicon, 255, 255, 255); imagefilledrectangle($identicon, 0, 0, $spriteZ, $spriteZ, $bg); /* generate corner sprites */ $corner = getsprite($csh, $cfr, $cfg, $cfb, $cro); imagecopy($identicon, $corner, 0, 0, 0, 0, $spriteZ, $spriteZ); $corner = imagerotate($corner, 90, $bg); imagecopy($identicon, $corner, 0, $spriteZ * 2, 0, 0, $spriteZ, $spriteZ); $corner = imagerotate($corner, 90, $bg); imagecopy($identicon, $corner, $spriteZ * 2, $spriteZ * 2, 0, 0, $spriteZ, $spriteZ); $corner = imagerotate($corner, 90, $bg); imagecopy($identicon, $corner, $spriteZ * 2, 0, 0, 0, $spriteZ, $spriteZ); /* generate side sprites */ $side = getsprite($ssh, $sfr, $sfg, $sfb, $sro); imagecopy($identicon, $side, $spriteZ, 0, 0, 0, $spriteZ, $spriteZ); $side = imagerotate($side, 90, $bg); imagecopy($identicon, $side, 0, $spriteZ, 0, 0, $spriteZ, $spriteZ); $side = imagerotate($side, 90, $bg); imagecopy($identicon, $side, $spriteZ, $spriteZ * 2, 0, 0, $spriteZ, $spriteZ); $side = imagerotate($side, 90, $bg); imagecopy($identicon, $side, $spriteZ * 2, $spriteZ, 0, 0, $spriteZ, $spriteZ); /* generate center sprite */ $center = getcenter($xsh, $cfr, $cfg, $cfb, $sfr, $sfg, $sfb, $xbg); imagecopy($identicon, $center, $spriteZ, $spriteZ, 0, 0, $spriteZ, $spriteZ); // $identicon=imagerotate($identicon,$angle,$bg); /* make white transparent */ imagecolortransparent($identicon, $bg); /* create blank image according to specified dimensions */ $resized = imagecreatetruecolor($size, $size); imageantialias($resized, TRUE); /* assign white as background */ $bg = imagecolorallocate($resized, 255, 255, 255); imagefilledrectangle($resized, 0, 0, $size, $size, $bg); /* resize identicon according to specification */ imagecopyresampled($resized, $identicon, 0, 0, (imagesx($identicon) - $spriteZ * 3) / 2, (imagesx($identicon) - $spriteZ * 3) / 2, $size, $size, $spriteZ * 3, $spriteZ * 3); /* make white transparent */ imagecolortransparent($resized, $bg); return $resized; } /* generate sprite for corners and sides */ function getsprite($shape, $R, $G, $B, $rotation) { global $spriteZ; $sprite = imagecreatetruecolor($spriteZ, $spriteZ); imageantialias($sprite, TRUE); $fg = imagecolorallocate($sprite, $R, $G, $B); $bg = imagecolorallocate($sprite, 255, 255, 255); imagefilledrectangle($sprite, 0, 0, $spriteZ, $spriteZ, $bg); switch ($shape) { case 0: // triangle $shape = [ 0.5, 1, 1, 0, 1, 1 ]; break; case 1: // parallelogram $shape = [ 0.5, 0, 1, 0, 0.5, 1, 0, 1 ]; break; case 2: // mouse ears $shape = [ 0.5, 0, 1, 0, 1, 1, 0.5, 1, 1, 0.5 ]; break; case 3: // ribbon $shape = [ 0, 0.5, 0.5, 0, 1, 0.5, 0.5, 1, 0.5, 0.5 ]; break; case 4: // sails $shape = [ 0, 0.5, 1, 0, 1, 1, 0, 1, 1, 0.5 ]; break; case 5: // fins $shape = [ 1, 0, 1, 1, 0.5, 1, 1, 0.5, 0.5, 0.5 ]; break; case 6: // beak $shape = [ 0, 0, 1, 0, 1, 0.5, 0, 0, 0.5, 1, 0, 1 ]; break; case 7: // chevron $shape = [ 0, 0, 0.5, 0, 1, 0.5, 0.5, 1, 0, 1, 0.5, 0.5 ]; break; case 8: // fish $shape = [ 0.5, 0, 0.5, 0.5, 1, 0.5, 1, 1, 0.5, 1, 0.5, 0.5, 0, 0.5 ]; break; case 9: // kite $shape = [ 0, 0, 1, 0, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 0, 1 ]; break; case 10: // trough $shape = [ 0, 0.5, 0.5, 1, 1, 0.5, 0.5, 0, 1, 0, 1, 1, 0, 1 ]; break; case 11: // rays $shape = [ 0.5, 0, 1, 0, 1, 1, 0.5, 1, 1, 0.75, 0.5, 0.5, 1, 0.25 ]; break; case 12: // double rhombus $shape = [ 0, 0.5, 0.5, 0, 0.5, 0.5, 1, 0, 1, 0.5, 0.5, 1, 0.5, 0.5, 0, 1 ]; break; case 13: // crown $shape = [ 0, 0, 1, 0, 1, 1, 0, 1, 1, 0.5, 0.5, 0.25, 0.5, 0.75, 0, 0.5, 0.5, 0.25 ]; break; case 14: // radioactive $shape = [ 0, 0.5, 0.5, 0.5, 0.5, 0, 1, 0, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 0, 1 ]; break; default: // tiles $shape = [ 0, 0, 1, 0, 0.5, 0.5, 0.5, 0, 0, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 0, 1 ]; break; } /* apply ratios */ for ($i = 0; $i < count($shape); $i++) $shape[$i] = $shape[$i] * $spriteZ; imagefilledpolygon($sprite, $shape, count($shape) / 2, $fg); /* rotate the sprite */ for ($i = 0; $i < $rotation; $i++) $sprite = imagerotate($sprite, 90, $bg); return $sprite; } /* generate sprite for center block */ function getcenter($shape, $fR, $fG, $fB, $bR, $bG, $bB, $usebg) { global $spriteZ; $sprite = imagecreatetruecolor($spriteZ, $spriteZ); imageantialias($sprite, TRUE); $fg = imagecolorallocate($sprite, $fR, $fG, $fB); /* make sure there's enough contrast before we use background color of side sprite */ if ($usebg > 0 && (abs($fR - $bR) > 127 || abs($fG - $bG) > 127 || abs($fB - $bB) > 127)) $bg = imagecolorallocate($sprite, $bR, $bG, $bB); else $bg = imagecolorallocate($sprite, 255, 255, 255); imagefilledrectangle($sprite, 0, 0, $spriteZ, $spriteZ, $bg); switch ($shape) { case 0: // empty $shape = []; break; case 1: // fill $shape = [ 0, 0, 1, 0, 1, 1, 0, 1 ]; break; case 2: // diamond $shape = [ 0.5, 0, 1, 0.5, 0.5, 1, 0, 0.5 ]; break; case 3: // reverse diamond $shape = [ 0, 0, 1, 0, 1, 1, 0, 1, 0, 0.5, 0.5, 1, 1, 0.5, 0.5, 0, 0, 0.5 ]; break; case 4: // cross $shape = [ 0.25, 0, 0.75, 0, 0.5, 0.5, 1, 0.25, 1, 0.75, 0.5, 0.5, 0.75, 1, 0.25, 1, 0.5, 0.5, 0, 0.75, 0, 0.25, 0.5, 0.5 ]; break; case 5: // morning star $shape = [ 0, 0, 0.5, 0.25, 1, 0, 0.75, 0.5, 1, 1, 0.5, 0.75, 0, 1, 0.25, 0.5 ]; break; case 6: // small square $shape = [ 0.33, 0.33, 0.67, 0.33, 0.67, 0.67, 0.33, 0.67 ]; break; case 7: // checkerboard $shape = [ 0, 0, 0.33, 0, 0.33, 0.33, 0.66, 0.33, 0.67, 0, 1, 0, 1, 0.33, 0.67, 0.33, 0.67, 0.67, 1, 0.67, 1, 1, 0.67, 1, 0.67, 0.67, 0.33, 0.67, 0.33, 1, 0, 1, 0, 0.67, 0.33, 0.67, 0.33, 0.33, 0, 0.33 ]; break; } /* apply ratios */ for ($i = 0; $i < count($shape); $i++) $shape[$i] = $shape[$i] * $spriteZ; if (count($shape) > 0) imagefilledpolygon($sprite, $shape, count($shape) / 2, $fg); return $sprite; } } if (!function_exists('slugIt')) { /* * Slug the string and convert all non latin characters into similar letters * * Example: * ć => c * Ể => E * */ function slugIt($str, $slug = true, $separator = '-') { $foreign_chars = Config::get('foreign_chars'); $array_from = array_keys($foreign_chars); $array_to = array_values($foreign_chars); if (is_array($str) || is_object($str)) { $str = implode(' ', (array)$str); } $str = preg_replace($array_from, $array_to, $str); if ($slug) { return Str::slug($str, $separator); } return $str; } } if (!function_exists('hashDir')) { function hashDir($id, $folder = 'gallery') { $id = abs($id + 20000); $public = ''; if (App::runningInConsole()) { $public = 'public/'; } $path = 'files/' . $folder; if (!is_dir($public . $path)) { mkdir($public . $path); } $h = $id % 4096; $maindir = floor($h / 64); $subdir = $h % 64; if (!is_dir($public . $path)) { mkdir($public . $path); } if (!is_dir($public . $path . '/' . $maindir)) { mkdir($public . $path . '/' . $maindir); } if (!is_dir($public . $path . '/' . $maindir . '/' . $subdir)) { mkdir($public . $path . '/' . $maindir . '/' . $subdir); } return $path . '/' . $maindir . '/' . $subdir; } } if (!function_exists('isTesting')) { function isTesting() { if (isset($_GET['test'])) { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $allowed_ips = Config::get('evercise.testing_ips'); foreach ($allowed_ips as $i) { if (strpos($ip, $i) !== false) { return true; } } } return false; } } class Functions { public static function getPosition($address = null) { if (is_null($address)) { $query = Request::getClientIp(); if ($query == '127.0.0.1' || $query == null) { $query = '172.16.58.3'; /* london office? */ } } else { $query = $address; } $geocoder = new \Geocoder\Geocoder(); $adapter = new \Geocoder\HttpAdapter\CurlHttpAdapter(); $chain = new \Geocoder\Provider\ChainProvider([ new \Geocoder\Provider\FreeGeoIpProvider($adapter), new \Geocoder\Provider\HostIpProvider($adapter), new \Geocoder\Provider\IpGeoBaseProvider($adapter), new \Geocoder\Provider\GoogleMapsProvider($adapter), ]); $geocoder->registerProvider($chain); try { $geocode = $geocoder->geocode($query); } catch (Exception $e) { $geocode = $geocoder->geocode('london'); } /* catch should pick this up if ($geocode->getLatitude() == 0 && $geocode->getLongitude() == 0) { $geocode = $geocoder->geocode('london'); }*/ return $geocode; } public static function getDistance($clientLat, $clientLng, $lat, $lng) { $geotools = new \League\Geotools\Geotools(); $coordA = new \League\Geotools\Coordinate\Coordinate([$clientLat, $clientLng]); $coordB = new \League\Geotools\Coordinate\Coordinate([$lat, $lng]); $distance = $geotools->distance()->setFrom($coordA)->setTo($coordB); return $distance; } public static function getCalendarTemplate() { $template = ' {table_open}<table border="0" cellpadding="0" cellspacing="0" id="calendar" class="calendar">{/table_open} {heading_row_start}<tr class="calendar-head">{/heading_row_start} {heading_previous_cell}<th><a href="#" id="month_{previous_url}" class="text-left"><span class="icon icon-grey-left-arrow hover"></span></a></th>{/heading_previous_cell} {heading_title_cell}<th colspan="{colspan}"><strong class="text-center">{heading}</strong></th>{/heading_title_cell} {heading_next_cell}<th><a href="#" id="month_{next_url}" class="text-right"><span class="icon icon-grey-right-arrow hover"></span></a></th>{/heading_next_cell} {heading_row_end}</tr>{/heading_row_end} {week_row_start}<tr class="calendar-days">{/week_row_start} {week_day_cell}<td><a class="active" href="{week_day}">{week_day}</a></td>{/week_day_cell} {week_row_end}</tr>{/week_row_end} {cal_row_start}<tr class="calendar-row">{/cal_row_start} {cal_cell_start}<td>{/cal_cell_start} {cal_cell_content}<a class="active" href="{content}">{day}</a>{/cal_cell_content} {cal_cell_content_today}<div class="calendarHighlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today} {cal_cell_no_content}{day}{/cal_cell_no_content} {cal_cell_no_content_today}<div class="calendarHighlight">{day}</div>{/cal_cell_no_content_today} {cal_cell_blank}&nbsp;{/cal_cell_blank} {cal_cell_end}</td>{/cal_cell_end} {cal_row_end}</tr>{/cal_row_end} {table_close}</table>{/table_close} '; return $template; } public static function randomPassword($charachters) { $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789"; $pass = []; //remember to declare $pass as an array $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache for ($i = 0; $i < $charachters; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } return implode($pass); //turn the array into a string } public static function arrayDate($array, $format = 'h:ia M-dS') { $dateTime = []; foreach ($array as $key => $value) { $dateTime[$key] = date($format, strtotime($value)); } return $dateTime; } }<file_sep>/app/database/seeds/CategoriesTableSeeder.php <?php class CategoriesTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('categories')->truncate(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); Category::create(array('name' => 'Dance', 'image' => 'dance.png')); Category::create(array('name' => 'Pilates', 'image' => 'pilates.png')); Category::create(array('name' => 'Workout', 'image' => 'workout.png')); Category::create(array('name' => 'Martial Arts', 'image' => 'martialarts.png')); Category::create(array('name' => 'Yoga', 'image' => 'yoga.png')); Category::create(array('name' => 'Sport', 'image' => 'sport.png')); Category::create(array('name' => 'Bootcamp', 'image' => 'bootcamp.png')); Category::create(array('name' => 'Aerobic', 'image' => 'aerobic.png')); Category::create(array('name' => 'Cycling', 'image' => 'cycling.png')); Category::create(array('name' => 'Aqua', 'image' => 'aqua.png')); Category::create(array('name' => 'Health', 'image' => 'health.png')); Category::create(array('name' => 'Injury', 'image' => 'injury.png')); Category::create(array('name' => 'Personal Training', 'image' => 'injury.png')); } }<file_sep>/app/models/EvercisegroupImport.php <?php use Carbon\Carbon; /** * Class Evercisegroup */ class EvercisegroupImport extends \Eloquent { /** * @var array */ protected $fillable = [ 'user_id', 'evercisegroup_id', 'external_id', 'external_venue_id', 'source', 'slug', 'name', 'description', 'image' ]; protected $editable = [ 'name', 'venue_id', 'description', 'image', 'category1', 'category2', 'category3', ]; /** * The database table used by the model. * * @var string */ protected $table = 'evercisegroup_import'; }<file_sep>/public/assets/jsdev/prototypes/32-remove-session.js function RemoveSession(form){ this.form = form; this.id =''; this.addListeners(); } RemoveSession.prototype = { constructor : RemoveSession, addListeners: function(){ this.form.on('submit', $.proxy(this.submit, this)); }, submit: function(e){ e.preventDefault(); this.form = $(e.target); this.id = this.form.find('input[name="id"]').val(); this.ajax(); }, ajax: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true); $('#hub-edit-row-'+self.id).addClass('bg-danger'); }, success: function (data) { self.remove(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false); $('#hub-edit-row-'+self.id).removeClass('bg-info'); } }); }, remove: function(data){ $('#hub-edit-row-'+data.id).fadeOut(400); } }<file_sep>/docs/evercise_2_0.sql -- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Apr 11, 2014 at 09:12 AM -- Server version: 5.6.12-log -- PHP Version: 5.4.12 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 */; -- -- Database: `evercise_2_0` -- CREATE DATABASE IF NOT EXISTS `evercise_2_0` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `evercise_2_0`; -- -------------------------------------------------------- -- -- Table structure for table `activity` -- CREATE TABLE IF NOT EXISTS `activity` ( `activityId` int(11) NOT NULL AUTO_INCREMENT, `activityName` varchar(45) DEFAULT NULL, `activityTitles` varchar(255) DEFAULT NULL, PRIMARY KEY (`activityId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `category` -- CREATE TABLE IF NOT EXISTS `category` ( `categoryId` int(11) NOT NULL AUTO_INCREMENT, `categoryName` varchar(45) DEFAULT NULL, `categoryDescription` varchar(45) DEFAULT NULL, PRIMARY KEY (`categoryId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `featuredgymgroup` -- CREATE TABLE IF NOT EXISTS `featuredgymgroup` ( `featuredGroupId` int(11) NOT NULL AUTO_INCREMENT, `gym_gymId` int(11) NOT NULL, `group_groupId` int(11) NOT NULL, PRIMARY KEY (`featuredGroupId`,`gym_gymId`,`group_groupId`), KEY `fk_featuredGroup_gym1_idx` (`gym_gymId`), KEY `fk_featuredGroup_group1_idx` (`group_groupId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `group` -- CREATE TABLE IF NOT EXISTS `group` ( `groupId` int(11) NOT NULL AUTO_INCREMENT, `user_userId` int(11) NOT NULL, `category_categoryId` int(11) NOT NULL, `groupName` varchar(45) DEFAULT NULL, `groupTitle` varchar(45) DEFAULT NULL, `groupDescription` varchar(255) DEFAULT NULL, `groupAddress` varchar(45) DEFAULT NULL, `groupTown` varchar(45) DEFAULT NULL, `groupPostcode` varchar(45) DEFAULT NULL, `groupLat` int(11) DEFAULT NULL, `groupLong` int(11) DEFAULT NULL, `groupImage` varchar(45) DEFAULT NULL, `groupCapacity` int(11) DEFAULT NULL, `groupDefaultDuration` int(11) DEFAULT NULL, `groupcol` varchar(45) DEFAULT NULL, `groupDefaultPrice` double DEFAULT NULL, `groupPublished` tinyint(4) DEFAULT NULL, `groupDatesAdded` varchar(45) DEFAULT NULL, `groupCreated` timestamp NULL DEFAULT NULL, PRIMARY KEY (`groupId`,`user_userId`,`category_categoryId`), KEY `fk_group_user1_idx` (`user_userId`), KEY `fk_group_category1_idx` (`category_categoryId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `gym` -- CREATE TABLE IF NOT EXISTS `gym` ( `gymId` int(11) NOT NULL AUTO_INCREMENT, `user_userId` int(11) NOT NULL, `gymName` varchar(45) DEFAULT NULL, `gymTitle` varchar(45) DEFAULT NULL, `gymDescription` varchar(45) DEFAULT NULL, `gymDirectory` varchar(45) DEFAULT NULL, `gymLogoImage` varchar(45) DEFAULT NULL, `gymBackgroundImage` varchar(45) DEFAULT NULL, `gymCreated` timestamp NULL DEFAULT NULL, PRIMARY KEY (`gymId`,`user_userId`), KEY `fk_gym_user1_idx` (`user_userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `gymtrainer` -- CREATE TABLE IF NOT EXISTS `gymtrainer` ( `gymTrainerId` int(11) NOT NULL AUTO_INCREMENT, `user_userId` int(11) NOT NULL, `gym_gymId` int(11) NOT NULL, `gymtrainerStatus` int(11) DEFAULT NULL, PRIMARY KEY (`gymTrainerId`,`user_userId`,`gym_gymId`), KEY `fk_user_has_gym_gym1_idx` (`gym_gymId`,`gymTrainerId`), KEY `fk_user_has_gym_user1_idx` (`user_userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `rating` -- CREATE TABLE IF NOT EXISTS `rating` ( `ratingId` int(11) NOT NULL AUTO_INCREMENT, `user_userId` int(11) NOT NULL, `ratingStars` tinyint(4) DEFAULT NULL, `ratingComment` varchar(255) DEFAULT NULL, `sessionmember_sessionmemberId` int(11) NOT NULL, `session_sessionId` int(11) NOT NULL, `group_groupId` int(11) NOT NULL, `user_createdUserId` int(11) NOT NULL, PRIMARY KEY (`ratingId`,`user_userId`,`sessionmember_sessionmemberId`,`session_sessionId`,`group_groupId`,`user_createdUserId`), KEY `fk_rating_user1_idx` (`user_userId`), KEY `fk_rating_sessionmember1_idx` (`sessionmember_sessionmemberId`), KEY `fk_rating_session1_idx` (`session_sessionId`), KEY `fk_rating_group1_idx` (`group_groupId`), KEY `fk_rating_user2_idx` (`user_createdUserId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `session` -- CREATE TABLE IF NOT EXISTS `session` ( `sessionId` int(11) NOT NULL AUTO_INCREMENT, `group_groupId` int(11) NOT NULL, `sessionTime` timestamp NULL DEFAULT NULL, `sessionMembers` int(11) DEFAULT NULL, `sessionCreated` timestamp NULL DEFAULT NULL, `sessionMembersEmailed` int(11) DEFAULT NULL, PRIMARY KEY (`sessionId`,`group_groupId`), KEY `fk_session_group1_idx` (`group_groupId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `sessionmember` -- CREATE TABLE IF NOT EXISTS `sessionmember` ( `sessionmemberId` int(11) NOT NULL AUTO_INCREMENT, `sessionId` int(11) NOT NULL, `user_userId` int(11) NOT NULL, `sessionmemberPrice` double DEFAULT NULL, `sessionmemberCreated` timestamp NULL DEFAULT NULL, `sessionmemberReviewed` tinyint(4) DEFAULT NULL, PRIMARY KEY (`sessionmemberId`,`user_userId`,`sessionId`), KEY `fk_sessionmember_user1_idx` (`user_userId`), KEY `fk_sessionmember_session1_idx` (`sessionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `trainer` -- CREATE TABLE IF NOT EXISTS `trainer` ( `trainerId` int(11) NOT NULL AUTO_INCREMENT, `user_userId` int(11) NOT NULL, `trainerCreated` timestamp NULL DEFAULT NULL, `trainerBio` varchar(1024) DEFAULT NULL, `trainerWebsite` varchar(45) DEFAULT NULL, `trainerProfession` varchar(45) DEFAULT NULL, PRIMARY KEY (`trainerId`,`user_userId`), KEY `fk_trainer_user1_idx` (`user_userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' ' AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `trainerhistory` -- CREATE TABLE IF NOT EXISTS `trainerhistory` ( `trainerHistoryId` int(11) NOT NULL AUTO_INCREMENT, `trainerHistoryTypeId` int(11) DEFAULT NULL, `trainerHistoryGroupId` int(11) DEFAULT NULL, `trainerHistoryGymId` int(11) DEFAULT NULL, `trainerHistoryUserId` int(11) DEFAULT NULL, `user_userId` int(11) NOT NULL, PRIMARY KEY (`trainerHistoryId`,`user_userId`), KEY `fk_trainerHistory_user1_idx` (`user_userId`) ) ENGINE=InnoDB DEFAULT CHARSET=big5 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE IF NOT EXISTS `user` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userType` tinyint(4) DEFAULT '1', `userName` varchar(15) DEFAULT NULL, `userEmail` varchar(100) DEFAULT NULL, `userPassword` varchar(255) DEFAULT NULL, `userSex` tinyint(4) DEFAULT NULL, `userDob` timestamp NULL DEFAULT NULL, `userPhone` int(11) DEFAULT NULL, `userCreated` timestamp NULL DEFAULT NULL, `userLastLogin` timestamp NULL DEFAULT NULL, `userDirectory` varchar(45) DEFAULT NULL, `userImage` varchar(45) DEFAULT NULL, `userCategories` varchar(45) DEFAULT NULL, `userHash` varchar(45) DEFAULT NULL, `userVerified` varchar(45) DEFAULT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; -- -- Dumping data for table `user` -- INSERT INTO `user` (`userId`, `userType`, `userName`, `userEmail`, `userPassword`, `userSex`, `userDob`, `userPhone`, `userCreated`, `userLastLogin`, `userDirectory`, `userImage`, `userCategories`, `userHash`, `userVerified`) VALUES (1, 1, 'Tris', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); -- -- Constraints for dumped tables -- -- -- Constraints for table `featuredgymgroup` -- ALTER TABLE `featuredgymgroup` ADD CONSTRAINT `fk_featuredGroup_group1` FOREIGN KEY (`group_groupId`) REFERENCES `group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_featuredGroup_gym1` FOREIGN KEY (`gym_gymId`) REFERENCES `gym` (`gymId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `group` -- ALTER TABLE `group` ADD CONSTRAINT `fk_group_category1` FOREIGN KEY (`category_categoryId`) REFERENCES `category` (`categoryId`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_group_user` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `gym` -- ALTER TABLE `gym` ADD CONSTRAINT `fk_gym_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `gymtrainer` -- ALTER TABLE `gymtrainer` ADD CONSTRAINT `fk_user_has_gym_gym1` FOREIGN KEY (`gym_gymId`, `gymTrainerId`) REFERENCES `gym` (`gymId`, `user_userId`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_user_has_gym_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `rating` -- ALTER TABLE `rating` ADD CONSTRAINT `fk_rating_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`), ADD CONSTRAINT `fk_rating_sessionmember1` FOREIGN KEY (`sessionmember_sessionmemberId`) REFERENCES `sessionmember` (`sessionmemberId`), ADD CONSTRAINT `fk_rating_session1` FOREIGN KEY (`session_sessionId`) REFERENCES `session` (`sessionId`), ADD CONSTRAINT `fk_rating_group1` FOREIGN KEY (`group_groupId`) REFERENCES `group` (`groupId`), ADD CONSTRAINT `fk_rating_user2` FOREIGN KEY (`user_createdUserId`) REFERENCES `user` (`userId`); -- -- Constraints for table `session` -- ALTER TABLE `session` ADD CONSTRAINT `fk_session_group1` FOREIGN KEY (`group_groupId`) REFERENCES `group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `sessionmember` -- ALTER TABLE `sessionmember` ADD CONSTRAINT `fk_sessionmember_session1` FOREIGN KEY (`sessionId`) REFERENCES `session` (`sessionId`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_sessionmember_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `trainer` -- ALTER TABLE `trainer` ADD CONSTRAINT `fk_trainer_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `trainerhistory` -- ALTER TABLE `trainerhistory` ADD CONSTRAINT `fk_trainerHistory_user1` FOREIGN KEY (`user_userId`) REFERENCES `user` (`userId`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!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>/app/controllers/LandingsController.php <?php class LandingsController extends \BaseController { protected $evercisegroup; protected $sentry; protected $link; protected $input; protected $log; protected $session; protected $redirect; protected $paginator; protected $place; protected $elastic; protected $search; public function __construct( Evercisegroup $evercisegroup, Sentry $sentry, Link $link, Illuminate\Http\Request $input, Illuminate\Log\Writer $log, Illuminate\Session\Store $session, Illuminate\Routing\Redirector $redirect, Illuminate\Pagination\Factory $paginator, Illuminate\Config\Repository $config, Es $elasticsearch, Geotools $geotools, Place $place ) { parent::__construct(); $this->evercisegroup = $evercisegroup; $this->sentry = $sentry; $this->link = $link; $this->input = $input; $this->log = $log; $this->place = $place; $this->session = $session; $this->redirect = $redirect; $this->paginator = $paginator; $this->config = $config; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); $this->search = new Search($this->elastic, $this->evercisegroup, $this->log); } /** * Display a listing of the resource. * * @return Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return View::make('landings.create'); } public function display() { $url = str_replace(URL::to('/'), '', Request::url()); $item = Config::get('landing_pages.' . $url); if (!isset($item['category'])) { return Redirect::route('home'); } $params = [ 'size' => 10, 'from' => 0, 'radius' => '10mi', 'search' => $item['category'] ]; $item['number_sessions'] = 0; $area = $this->place->where('name', 'London')->first(); $i = 0; foreach ($item['blocks']['large'] as $block) { $params['search'] = $block['name']; $searchResults = $this->search->getResults($area, $params); $total = 0; if ($searchResults->total > 0) { $price = 0; foreach ($searchResults->hits as $evercisegroup) { $total += count($evercisegroup->futuresessions); foreach ($evercisegroup->futuresessions as $session) { if ($price == 0 || $price > $session->price) { $price = $session->price; } } } $item['blocks']['large'][$i]['from'] = '£' . $price; } $item['blocks']['large'][$i]['total'] = $total; $item['number_sessions'] += $total; $i++; } $i = 0; foreach ($item['blocks']['small'] as $block) { $params['search'] = $block['name']; $searchResults = $this->search->getResults($area, $params); $total = 0; if ($searchResults->total > 0) { $price = 0; foreach ($searchResults->hits as $evercisegroup) { $total += count($evercisegroup->futuresessions); foreach ($evercisegroup->futuresessions as $session) { if ($price == 0 || $price > $session->price) { $price = $session->price; } } } $item['blocks']['small'][$i]['from'] = '£' . $price; } $item['blocks']['small'][$i]['total'] = $total; $item['number_sessions'] += $total; $i++; } return View::make('v3.landing.user-categories', $item)->render(); } public function trainerPpc() { return View::make('v3.landing.trainer'); } public function landingSend() { $email = Input::get('email'); $location = Input::get('location'); $categoryId = Input::get('category_id'); $validator = Validator::make( Input::all(), [ 'email' => 'required|email', 'category_id' => 'required' ] ); if ($validator->fails()) { return Redirect::back(); } $ppcCode = Functions::randomPassword(20); $ppc = Landing::create([ 'email' => $email, 'code' => $ppcCode, 'location' => $location, 'category_id' => $categoryId ]); if ($ppc) { event('landing.user', [ 'email' => $email, 'categoryId' => $categoryId, 'ppcCode' => $ppcCode, 'location' => $location ]); Session::flash('success', 'Discover your first class. Remember to check your email for the offer!'); } //return $this->submitPpc($categoryId, $ppcCode, $email); $category = Category::find($categoryId); return Redirect::to('uk/london?search='.$category->name)->with('email', $email); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $validator = Validator::make( Input::all(), [ 'email' => 'required|email|unique:users,email', 'category' => '', ] ); if ($validator->fails()) { if (Request::ajax()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { return Redirect::route('landing.category', ['category' => Input::get('category')]) ->withErrors($validator) ->withInput(); } } else { $email = Input::get('email'); $categoryId = Input::get('category'); $ppcCode = Functions::randomPassword(20); $ppc = Landing::create(['email' => $email, 'code' => $ppcCode, 'category_id' => $categoryId]); Session::put('ppcCode', $ppcCode); Session::put('email', $email); $category = Category::find($categoryId)->pluck('name'); if ($ppc) { Event::fire('landing.ppc', [ 'email' => $email, 'categoryId' => $categoryId, 'ppcCode' => $ppcCode ]); } //return Redirect::to('users/create'); return Response::json(['callback' => 'gotoUrl', 'url' => route('users.create')]); } } // Facebook link on landing page clicked public function facebookPpc($categoryId) { $ppcCode = Functions::randomPassword(20); $ppc = Landing::create(['email' => 'facebook', 'code' => $ppcCode, 'category_id' => $categoryId]); Session::put('ppcCategory', $categoryId); Session::put('ppcCode', $ppcCode); return Redirect::to('login/fb'); } // Accept code from a pay-per-click generated email. public function submitPpc($categoryId, $ppcCode) { Session::put('ppcCategory', $categoryId); Session::put('ppcCode', $ppcCode); return Redirect::route('register'); //$category = Category::find($categoryId); //return Redirect::to('uk/london?search='.$category->name)->with('email', $email); } public function loadCategory($category) { if (array_key_exists($category, Config::get('values')['ppc_categories'])) { $categoryId = Config::get('values')['ppc_categories'][$category]; $category = Category::find($categoryId); return View::make('landings.create') ->with('category', $category); } else { return Redirect::to('/'); } } public function landCategory($cat) { return $this->loadCategory($cat); } public function categoryLanding($cat) { } public function trainerEnquiry() { $validator = Validator::make( Input::all(), [ 'email' => 'required|email|unique:users,email', 'name' => 'required', ] ); if ($validator->fails()) { if (Request::ajax()) { $result = [ 'validation_failed' => 1, 'errors' => $validator->errors()->toArray() ]; return Response::json($result); } else { return Redirect::route('landing.trainer.ppc') ->withErrors($validator) ->withInput(); } } else { return 'good'; } } }<file_sep>/app/tests/StripePaymentTest.php <?php namespace app\tests; use Mockery as m; use StripePaymentController, Cart; class StripePaymentTest extends TestCase { public function tearDown() { m::close(); } public function setUp() { parent::setUp(); } /** @test */ public function process_payment() { $productCode = 'S136'; $groupName = 'INSANITY'; $quantity = 1; $price = 10; $evercisegroupId = 136; $sessionId = 1231; $date_time = '2014-11-17 21:30:00'; /* Cart::associate('Evercisesession')->add( $productCode, $groupName, $quantity, $price, [ 'evercisegroupId' => $evercisegroupId, 'sessionId' => $sessionId, 'date_time' => $date_time ] ); $response = $this->action('POST', 'StripePaymentController@store'); */ } }<file_sep>/app/composers/TrainerHistoryComposer.php <?php namespace composers; use Trainerhistory; class TrainerHistoryComposer { public function compose($view) { $viewdata = $view->getData(); $userTrainer = $viewdata['user']; $historys = Trainerhistory::where('user_id', $userTrainer->id)->orderBy('created_at', 'desc')->paginate(15); $view->with('historys', $historys); } }<file_sep>/app/models/StatsModel.php <?php /** * Articles Models */ class StatsModel extends Eloquent { /** * @var array */ protected $fillable = array('*'); /** * The database table used by the model. * * @var string */ protected $table = 'search_stats'; }<file_sep>/app/assets/javascripts/rating.js function initAddRating() { var base = this; this.checkButton = function(id){ if ($('#classlist_'+id+' #stars').val() > 0 && $('#classlist_'+id+' #feedback_text').val().length > 0 ) { $('#classlist_'+id+' form#feedback input.btn').removeClass('disabled'); } else { $('#classlist_'+id+' form#feedback input.btn').addClass('disabled'); } }; $(".class-list-box").on({ keyup: function () { var id = $(this).find('.list-staradd span').data('id'); base.checkButton(id); }, mousedown: function () { var id = $(this).find('.list-staradd span').data('id'); base.checkButton(id); } }); $(".list-staradd span").on({ mouseenter: function () { var id = $(this).data('id'); if ($('#classlist_'+id+' #stars').val() == 0) { //trace($(this).data('id')); var rating = $(this).data('rating'); for (var i = 0; i <= rating ; i++) { $('#classlist_'+id+' span[data-rating='+i+']').addClass('full'); } } }, mouseleave: function () { var id = $(this).data('id'); if ($('#classlist_'+id+' #stars').val() == 0) { $('#classlist_'+id+' .list-staradd span').removeClass('full'); } }, mousedown: function () { var id = $(this).data('id'); if ($('#classlist_'+id+' #stars').val() == 0) { var rating = $(this).data('rating'); $('#classlist_'+id+' #stars').val(rating); //base.checkButton(id); } else { $('#classlist_'+id+' .list-staradd span').removeClass('full'); var rating = $(this).data('rating'); for (var i = 0; i <= rating ; i++) { $('#classlist_'+id+' span[data-rating='+i+']').addClass('full'); } $('#classlist_'+id+' #stars').val(0); //base.checkButton(id); } } }); //this.checkButton(2); } registerInitFunction('initAddRating'); <file_sep>/app/composers/HomePageComposer.php <?php namespace composers; use JavaScript; class HomePageComposer { public function compose($view) { JavaScript::put( [ 'initPlayVideo' => 1, ] ); } }<file_sep>/app/controllers/widgets/imageController.php <?php namespace widgets; use Auth, BaseController, Input, Sentry, View, Response, Validator, Image, Config, Trainer; class ImageController extends \BaseController { protected $layout = 'widgets.upload-form'; public function getUploadForm() { return View::make('widgets/upload-form'); } public function postUpload() { //return Response::json('woo'); $file = Input::file('image'); $input = array('image' => $file); $rules = array( 'image' => 'image' ); if (!isset($file)) return Response::json(['success' => false, 'errors' => ['image'=>'Image exceeds the limit of 2Mb']]); if ($file->getSize() > Config::get('image')['max_size']) return Response::json(['success' => false, 'errors' => ['image'=>'Image exceeds the limit of 2Mb']]); if ($file->getMimeType() == 'image/x-ms-bmp') return Response::json(['success' => false, 'errors' => ['image'=>'The image format is not supported.']]); $validator = Validator::make($input, $rules); if ( $validator->fails() ) { return Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]); } else { $destinationPath = 'profiles/'.Sentry::getUser()->directory; // change file name $filename = Sentry::getUser()->display_name; $ext = $file->getClientOriginalExtension(); $filename = pathinfo($filename, PATHINFO_FILENAME); $increment = 0; while(file_exists($destinationPath.'/'.$filename . $increment . '.' . $ext)) { $increment++; } $filename = $filename.'-'.$increment.'.'.$ext; $file->move($destinationPath, $filename); $viewString = View::make('widgets/crop')->__toString(); $imgSrc = url('/') .'/'. $destinationPath . '/' . $filename; $postCrop = url('/').'/widgets/crop'; return Response::json(array('crop'=>$viewString, 'image_url' => $imgSrc , 'postCrop' => $postCrop)); } } public function getCrop() { /******* ASPECT RATIO = (2.35 : 1) *******/ //Don't forget to initialise the JS (initImage) from the containing controller return View::make('widgets/crop'); } public function postCrop() { $pos_x = Input::get('pos_x'); $pos_y = Input::get('pos_y'); $width = Input::get('width'); $height = Input::get('height'); $img_url = Input::get('img_url'); $img_height = Input::get('img_height'); $label = Input::get('label'); $fieldtext = Input::get('fieldtext'); $user = Sentry::getUser(); $save_location = $user->directory; $img_name = basename($img_url); // open file a image resource $img_path = public_path() . '/profiles/' . $save_location . '/' .$img_name; $img = Image::make($img_path); $true_height = $img->height(); $factor = $true_height / $img_height; $scaledCoords = $this->scale($factor, array('width'=>$width, 'height'=>$height, 'pos_x'=>$pos_x, 'pos_y'=>$pos_y)); // crop image $img->crop($scaledCoords['width'], $scaledCoords['height'], $scaledCoords['pos_x'], $scaledCoords['pos_y']); $thumbFilename = (Trainer::isTrainerLoggedIn() ? 'trainers' : 'users').'-'.$img_name; $fileNameWithPath = '/profiles/' . $save_location . '/'.$thumbFilename; $img->save(public_path() . $fileNameWithPath); $viewString = View::make('widgets/upload-form')->with('uploadImage',$fileNameWithPath )->with('label',$label )->with('fieldtext',$fieldtext )->__toString(); $newImage = url('/') . $fileNameWithPath; return Response::json(array('uploadView'=>$viewString,'newImage' => $newImage, 'thumbFilename' => $thumbFilename )); } public function scale($factor, $params) { $scaledParams = array(); foreach ($params as $key => $value) { $scaledParams[$key] = (int) round($value * $factor); } return $scaledParams; } }<file_sep>/server/setup.sh echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;" | mysql -u root echo "FLUSH PRIVILEGES;" | mysql -u root echo "Moving Config Files" sudo \cp -r /var/www/html/server/my.cnf /etc/my.cnf sudo \cp -r /var/www/html/server/php.ini /etc/php.ini sudo service httpd restart sudo service mysqld restart echo "START MAILCATCHER" mailcatcher --ip=0.0.0.0 echo "Seting PERMISSIONS" cd /var/www/html php artisan clear-compiled php artisan ide-helper:generate php artisan optimize php artisan assets:clean<file_sep>/app/lang/en/evercisegroups-create.php <?php return [ 'title' => 'Add the information about your class', 'subtitle' => 'Make it as relevant and interesting as possible', 'choose_class_image' => 'Choose a suitable image to represent your class', 'upload_image' => 'Upload your class image', '' => '', ];<file_sep>/app/database/migrations/2015_02_04_113513_update_categories_popular.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class UpdateCategoriesPopular extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement('ALTER TABLE categories CHANGE COLUMN popular popular_classes TEXT;'); Schema::table('categories', function(Blueprint $table) { $table->text('popular_subcategories'); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('ALTER TABLE categories CHANGE COLUMN popular_classes popular TEXT;'); Schema::table('categories', function(Blueprint $table) { $table->dropColumn('popular_subcategories'); }); } } <file_sep>/app/commands/SendExtraEmails.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class SendExtraEmails extends Command { /** * The console command name. * * @var string */ protected $name = 'email:extra'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; protected $cutOff; /** * Create a new command instance. * */ public function __construct() { parent::__construct(); $cutOffDate = Config::get('pardot.reminders.usercutoff'); $this->cutOff = new DateTime(); $this->cutOff->setDate($cutOffDate['year'], $cutOffDate['month'], $cutOffDate['day']); } /** * Execute the console command. * * @return mixed */ public function fire() { //$this->whyNotRefer(); //$this->notReturned(); //$this->notReturnedTrainer(); } public function whyNotRefer() { $numDays = Config::get('pardot.reminders.whynotreferafriend.dayssinceclass'); $this->info('whyNotRefer - Searching for users who have not been registered through a PPC, and have bought a class which took place '.$numDays.' days ago'); $afewdaysago = (new DateTime())->sub(new DateInterval('P'.$numDays.'D')); $users = User::whereHas('sessions', function($query) use (&$afewdaysago){ $query->where('date_time', '<', $afewdaysago); }) ->with(['activities' => function($query){ $query->where('type', 'ppcstatic')->orWhere('type', 'ppcunique'); }]) ->where('created_at', '>', $this->cutOff) ->with(['emailOut' => function($query){ $query->where('type', '=', 'mail.rateclass'); }]) ->get(); $emailsSent = 0; foreach($users as $user) { if(! count($user->emailOut)) { if (! count($user->activities)) { $emailsSent++; $this->info('user: ' . $user->id); event('user.why_not_refer', [$user]); } } } $this->info('user count: '.$emailsSent); } /** * check for users who: * have not logged in for 10 days * have an activity of type ppcstatic or ppcunique (signed up through PPC) * have > 5 credit in wallet * have never bought a class * does not have an entry in 'email_out' matching type 'whynotusefreecredit' * signed up after 01/12/14 * * @return mixed */ public function notReturned() { $numDays = Config::get('pardot.reminders.whynotusefreecredit.daysinactive'); // How many days user must be inactive before email is fired. should be 10 $this->info('whyNoUseFreeCreditEh Searching for users who have not used their free credit, and have been inactive for '.$numDays.' days'); $afewdaysago = (new DateTime())->sub(new DateInterval('P'.$numDays.'D')); $users = User::where('last_login', '<', $afewdaysago) ->whereHas('activities', function($query){ $query->where('type', 'ppcstatic')->orWhere('type', 'ppcunique'); }) ->whereHas('wallet', function($query){ $query->where('balance', '>=', '5'); }) ->has('sessions', '<', 1) ->where('created_at', '>', $this->cutOff) ->with(['emailOut' => function($query){ $query->where('type', '=', 'mail.notreturned'); }]) ->get(); $everciseGroups = Evercisegroup::whereHas('featuredClasses', function($query){}) ->get(); $this->info('featured group count: '.count($everciseGroups)); $groups = []; foreach($everciseGroups as $group) $groups[] = $group; $emailsSent = 0; foreach($users as $user) { if(! count($user->emailOut)) { $emailsSent++; $randomGroups = []; foreach (array_rand($groups, 3) as $key) $randomGroups[] = $groups[$key]; if (count($randomGroups) > 2) $this->info('user: ' . $user->id . ' | featured groups: ' . $randomGroups[0]->id . ', ' . $randomGroups[1]->id . ', ' . $randomGroups[2]->id); event('user.not_returned', [$user, $randomGroups]); } } $this->info('user count: '.$emailsSent); } public function notReturnedTrainer() { // email trainer if he hasn't been back for 10 days or something } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( //array('example', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( //array('days', null, InputOption::VALUE_OPTIONAL, 'How many days to search back.', 1), ); } } <file_sep>/app/commands/FixLocation.php <?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Debug\Exception\FatalErrorException; class FixLocation extends Command { protected $name = 'location:fix'; protected $description = 'Fix Messed Up Locations'; public function __construct() { parent::__construct(); } public function fire() { $id = $this->option('id'); $places = Place::where('id', '>', $id)->limit(500)->get(); foreach($places as $place) { $name = $place->name; if($place->link->type == 'STATION') { $name .= ' station'; } $geo = Place::getLocation($name, 'London', false); $this->line($name); $this->line($geo['latitude'].', '.$geo['longitude']); if(!empty($geo['latitude'])) { $place->lat = $geo['latitude']; $place->lng = $geo['longitude']; $place->save(); } else{ $this->line('MISSING '.$name.' '.$place->id); } $this->line($place->id); if($place->id%100 == 0) { $this->line('SLEEP'); sleep(3); } } } protected function getOptions() { return [ ['id', null, InputOption::VALUE_OPTIONAL, 'Start from ID', 1], ]; } }<file_sep>/app/views/admin/yukonhtml/php/pages/partials/side_menu.php <!-- main menu --> <nav id="main_menu"> <ul> <li class="first_level"> <a href="dashboard"> <span class="icon_house_alt first_level_icon"></span> <span class="menu-title">Dashboard</span> </a> </li> <li class="first_level"> <a href="javascript:void(0)"> <span class="icon_document_alt first_level_icon"></span> <span class="menu-title">Admin Tools</span> </a> <ul> <li class="submenu-title">Admin tools</li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="pendingwithdrawals">Pending Withdrawals</a></li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="users">Users</a></li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="pendingtrainers">Pending Trainers</a></li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="log">Log</a></li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="categories">Categories</a></li> <li><a <?php if($sPage == "forms-regular_elements") { echo 'class="act_nav" '; }; ?>href="groups">Classes</a></li> </ul> </li> </ul> <div class="menu_toggle"> <span class="icon_menu_toggle"> <i class="arrow_carrot-2left toggle_left"></i> <i class="arrow_carrot-2right toggle_right" style="display:none"></i> </span> </div> </nav><file_sep>/app/config/events.php <?php /* * Configuration for Event Listeners and Triggers * * The logic is: * * [ * 'PRIORITY' => [EVENT NAME => EVENT FUNCTION UNDER THE events Namespace] * ] */ /** AVAILABLE EVENT NAMES */ /* * Event::fire('user.registeredFacebook', [$user]); * * user.registered => After the User has Registered * user.registeredFacebook => After User Signs up with facebook * user.edit => User edited there profile * user.changedPassword => User has changed there password * user.login => User has changed there password * user.logout => User has changed there password * user.loginFacebook => User has changed there password * user.fullProfile => User has completed there profile * trainer.registered => trainer has registered * trainer.edit => trainer has edited there user details * trainer.editTrainerDetails => trainer has edited there user details * evecisegroup.created => trainer created a new class * evecisegroup.delete => trainer deleted a class * session.create => Trainer added a nnew session to a class * session.delete => Trainer removed a session * session.joined => User joined a class * session.left => User left a class * rating.create => User left a rating for a class * wallet.request => Trainer has requested a withdrawel from there wallet * wallet.updatePaypal => User has updated there paypal details * * * class.index.single => Index a Single Class * class.index.all => Index all Classes * * user.admin.trainerCreate => ($user, $trainer) when a admin creates a trainer * *activity.class.payed => $class, $user *activity.class.canceled $class, $user *activity.class.create $class, $user *activity.class.update $class, $user *activity.class.delete $class, $user *activity.venue.create $venue, $user *activity.venue.update $venue, $user *activity.venue.delete $venue, $user *activity.session.create $class, $user *activity.session.update $class, $user *activity.session.delete $class, $user *activity.wallet.topup $user, $amount *activity.wallet.withdraw $user, $amount *activity.user.editprofile $user *activity.user.facebook $user *activity.user.twitter $user *activity.user.invite $user, $email */ return [ '10' => [ ['user.registered' => 'User@hasRegistered'], // $user ['user.registeredFacebook' => 'User@facebookRegistered'], // $user // ∑ ['user.signup' => 'User@welcome'], // $user // ∑ ['user.guest.signup' => 'User@welcomeGuest'], // $user // ∑ ['user.facebook.signup' => 'User@facebookWelcome'], // $user // ∑ ['user.forgot.password' => '<PASSWORD>'], // $user // ∑ ['user.changedPassword' => '<PASSWORD>'], // $user, $link // ∑ ['user.upgrade' => 'User@userUpgrade'], // $user // ∑ ['user.login' => 'User@login'], // $user ['user.logout' => 'User@logout'], // $user ['user.loginFacebook' => 'User@facebookLogin'], ['user.edit' => 'User@edit'], ['user.cart.completed' => 'User@cartCompleted'], // $user, $cart, $transaction // ∑ ['user.topup.completed' => 'User@topupCompleted'], // $user, $transaction, $balance // ∑ ['user.message.reply' => 'User@messageReply'], // $sender, $recipient, $body ['user.withdraw.completed' => 'User@withdrawCompleted'], // $user, $transaction, $balance // ∑ ['user.referral.completed' => 'User@referralCompleted'], // $user, $transaction, $balance // ∑ ['user.referral.signup' => 'User@referralSignup'], // $user, $transaction, $balance // ∑ ['user.class.rate' => 'User@rateClass'], // $user // ∑ ['user.class.rate.haspackage' => 'User@rateClassHasPackage'], // $user // ∑ ['user.ppc.signup' => 'User@ppcSignup'], // $user, $transaction, $type // ∑ ['user.not_returned' => 'User@notReturned'], // $user, $everciseGroups ['user.why_not_refer' => 'User@whyNotRefer'], // $user ['trainer.edit' => 'Trainer@edit'], ['trainer.session.joined' => 'Trainer@sessionsJoined'], // $user, $trainer, $session, $everciseGroup, $transactionId, tickets ['trainer.registered' => 'Trainer@<EMAIL>'], //$trainer ['trainer.registered_ppc' => 'Trainer@registeredPpc'], //$trainer ['trainer.complete_profile' => 'Trainer@whyNotCompleteProfile'], //$trainer ['trainer.create_first_class' => 'Trainer@whyNotCreateFirstClass'], //$trainer ['trainer.not_returned' => 'Trainer@notReturnedTrainer'], //$trainer ['class.created' => 'Classes@classCreated'], // $class, $trainer ['class.deleted' => 'Classes@classDeleted'], // $class, $trainer ['class.updated' => 'Classes@classUpdated'], // $class, $trainer ['class.published' => 'Classes@classPublished'], // $class, $trainer ['class.unpublished' => 'Classes@classUnPublished'], // $class, $trainer ['session.joined' => 'Sessions@joinedClass'], // $user, $trainer, $session, $everciseGroup, $transactionId ['session.upcoming_session' => 'Sessions@upcomingSessions'], ['session.mail_all' => 'Sessions@mailAll'], ['session.mail_trainer' => 'Sessions@mailTrainer'], ['session.userLeft' => 'Sessions@userLeaveSession'], ['session.trainerLeft' => 'Sessions@trainerLeaveSession'], ['session.refund' => 'Sessions@refundRequest'], ['venue.create' => 'Classes@venueCreated'], ['venue.update' => 'Classes@venueUpdated'], ['user.facebook.connected' => 'User@connectedFacebook'], // $user ['user.twitter.connected' => 'User@connectedTwitter'], // $user ['marketing.newYear' => 'User@newYear'], // $user ['marketing.relaunch' => 'Trainer@relaunch'], // $user ], '5' => [ ['referral.invite' => 'User@invite'], // $email, $referralCode, $referrerName, $referrerEmail, $balanceWithBonus // ∑ ['landing.ppc' => 'User@ppc'], // $email, $categoryId, $ppcCode ['landing.user' => 'User@userLanding'], // $email, $categoryId, $ppcCode, $location ['generate.static.landing.email' => 'User@generateStaticLanding<EMAIL>'], ], '0' => [ //All Tracking is Low Priority ['stats.class.counter' => 'Stats@classViewed'], ['class.viewed' => 'Classes@classViewed'], // $class, $user = false ['user.admin.trainerCreate' => 'Admin@hasCreatedTrainer'], ['class.index.single' => 'Indexer@indexSingle'], ['class.index.all' => 'Indexer@indexAll'], // ['user.edit' => 'Tracking@userEdit'], // ['trainer.edit' => 'Tracking@trainerEdit'], // ['user.changedPassword' => '<PASSWORD>'], // ['user.package.used' => 'Tracking@userChangePassword'], // ['session.create' => 'Tracking@registerSessionTracking'], /** * THIS IS REALLY LOW PRIORITY * MOST OF THE FUNCTIONS HERE ARE ALREADY TRIGGERED BY OTHER EVENTS * BUT JUST IN CASE WE NEED THEM */ ['activity.class.payed' => 'Activity@payedClass'], // $class, $user ['activity.class.canceled' => 'Activity@canceledClass'], // $class, $user ['activity.class.create' => 'Activity@createdClass'], // $class, $user ['activity.class.update' => 'Activity@updatedClass'], // $class, $user ['activity.class.delete' => 'Activity@deletedClass'], // $class, $user ['activity.venue.create' => 'Activity@createdVenue'], // $venue, $user ['activity.venue.update' => 'Activity@updatedVenue'], // $venue, $user ['activity.venue.delete' => 'Activity@deletedVenue'], // $venue, $user ['activity.session.create' => 'Activity@createdSessions'], // $class, $user ['activity.session.update' => 'Activity@updatedSessions'], // $class, $user ['activity.session.delete' => 'Activity@deletedSessions'], // $class, $user ['activity.wallet.topup' => 'Activity@walletToppup'], // $user, $amount ['activity.wallet.withdraw' => 'Activity@walletWithdraw'], // $user, $amount ['activity.user.coupon' => 'Activity@usedCoupon'], // $coupon, $user ['activity.user.editprofile' => 'Activity@userEditProfile'], // $user ['activity.user.facebook' => 'Activity@linkFacebook'], // $user ['activity.user.twitter' => 'Activity@linkTwitter'], // $user ['activity.user.invite' => 'Activity@invitedEmail'], // $user, $email ['activity.user.package.used' => 'Activity@packageUsed'], // $user, $userpackage, $package, $session √ ['activity.user.cart.completed' => 'Activity@userCartCompleted'], // $user, $cart, $transaction √ ['activity.user.reviewed.class' => 'Activity@userReviewedClass'], // $user, $trainer, $review, $class ] ]; <file_sep>/app/database/seeds/EvercisegroupsTableSeeder.php <?php class EvercisegroupsTableSeeder extends Seeder { public function run() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('evercisegroups')->delete(); DB::table('migrate_groups')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); $classinfos = DB::connection('mysql_import')->table('classinfo')->where('classInfoPublished', 1)->get(); foreach ($classinfos as $classinfo) { $user = DB::connection('mysql_import')->table('user')->where('Uid', $classinfo->Uid)->first(); $this->command->info('Creating Venue. user_id: '. $classinfo->Uid); if($user) { $userEmail = $user->Uemail; $newUser = User::where('email', $userEmail)->first(); if ($newUser) { $address = explode(',',$classinfo->classInfoAddress); try { $venue = Venue::create([ 'user_id' => $newUser->id, 'name' => $address[0], 'address' => $address[0], 'town' => count($address) > 1 ? $address[1] : '', 'postcode' => count($address) > 2 ? $address[2] : '', 'lat' => $classinfo->classInfoLatitude, 'lng' => $classinfo->classInfoLongitude, 'image' => $classinfo->classInfoImageName, ]); $venueId = $venue->id; } catch (Exception $e) { $this->command->info('Cannot make venue. '.$e); exit; } try { $evercisegroup = Evercisegroup::create([ 'user_id' => $newUser->id, //'category_id' => $classinfo->classInfoCategory, 'venue_id' => $venueId, 'name' => $classinfo->classInfoName, 'title' => $classinfo->classInfoSubtitle, 'description' => $classinfo->classInfoDescription, 'gender' => 0, 'image' => $classinfo->classInfoImageName, 'capacity' => $classinfo->classInfoMax, 'default_duration' => $classinfo->classInfoDuration, 'default_price' => $classinfo->classInfoPrice, 'published' => 1, ]); $migrateGroups = DB::table('migrate_groups')->insert(['classInfoId' => $classinfo->classInfoId, 'evercisegroup_id' => $evercisegroup->id]); } catch (Exception $e) { $this->command->info('Cannot make evercisegroup. '.$e); exit; } $url = 'http://evercise.com/'.$classinfo->classInfoImageAddress.'/'.$classinfo->classInfoImageName; //$this->command->info('retrieving image: '.$url); $savePath = public_path().'/profiles/'.$newUser->directory.'/'.$classinfo->classInfoImageName; $this->command->info('saving image: '.$savePath); try { $img = file_get_contents($url); file_put_contents($savePath, $img); }catch (Exception $e) { // This exception will happen from localhost, as pulling the file from facebook will not work $this->command->info('Cannot save image: '.$savePath); } } } } } }<file_sep>/app/views/hello.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><style>h1 {font-family: helvetica, arial, sans-serif; text-transform: uppercase; font-size: 26px; line-height: 30px; font-weight: 500; color:#768690; margin: 0} h3 {font-family: helvetica, arial, sans-serif; text-transform: uppercase; font-size: 18px; line-height: 26px; font-weight: 500; color:#768690; margin: 0} p { font-family: helvetica, arial, sans-serif; font-size: 14px; line-height: 26px; font-weight: normal; color:#768690; } b { font-weight: bold; color:#768690; } table{ max-width: 640px; width: 100%; table-layout: fixed} th{border-bottom: 1px solid #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; line-height: 26px; font-weight: 500; color:#768690; margin: 0} strong{ font-family: helvetica, arial, sans-serif; font-size: 18px; line-height: 26px; font-weight: 500; color:#768690; margin: 0} .container{ } .pink-text{ color: #ff1b7e} .blue-text{ color: #5ECDE8} .white-text{ color: #ffffff} .text-right{ text-align: right} .text-center{ text-align: center} img{ width: 100%} .img-original{width: auto} .image-left{ float: left; margin-right: 25px} .image-right{ float: right; margin-left: 25px} .footer { font-size: 12px; text-align: left;} .mt5{ margin-top: 5px;} .mb30{ width: 100%; margin-bottom: 30px; float: left;} .btn{line-height: 5px; border-radius:3px;color:#ffffff;display:inline-block;font-family:helvetica, arial, sans-serif;font-size:14px;font-weight:bold;text-align:center;text-decoration:none;-webkit-text-size-adjust:none; } .btn-blue{ background: #5ecde8} .btn-pink{ background: #ff1b7e} .btn-grey{ background: #768690;} .bottom-border{ border-bottom: 1px solid #f2f2f2} @media only screen and (max-device-width: 320px) and (max-device-height: 568px) { table{ width: 100%} h1 { font-family: helvetica, arial, sans-serif; text-transform: uppercase; font-size: 30px; line-height: 42px; font-weight: 500; color:#768690; margin: 0 } p { font-family: helvetica, arial, sans-serif; font-size: 26px; line-height: 38px; font-weight: normal; color:#768690; } b { font-weight: bold; color:#768690; } img { max-width: 640px; width: 100%} .footer { font-size: 13px; text-align: left;} .sm-hidden{ display: none} } @media screen and (max-device-width: 375px) and (max-device-height: 667px) { table{ width: 100%} h1 { font-family: helvetica, arial, sans-serif; text-transform: uppercase; font-size: 30px; line-height: 42px; font-weight: normal; color:#768690; } p { font-family: helvetica, arial, sans-serif; font-size: 26px; line-height: 38px; font-weight: normal; color:#768690; } b { font-weight: bold; color:#768690; } img { max-width: 640px; width: 100%} .footer { font-size: 13px; text-align: left;} .sm-hidden{ display: none} }</style></head><body bgcolor="#bfbfbf"> <!-- Opening main --> <table bgcolor="#FFFFFF" border="0" align="center" cellspacing="0" cellpadding="0" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> <table width="100%" height="auto" bgcolor="#FFFFFF" border="0" align="center" cellspacing="0" cellpadding="0" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> <!-- Main image --> <table width="100%" height="auto" border="0" cellspacing="0" cellpadding="0" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> <a href="http://evercise.dev/uk/london" title="Confirmation of booking"> <img src="http://evercise.dev/assets/img/email/user_booking_confirmation.jpg" alt="booking confirmation" style="width: 100%;"></a> </td> </tr></table></td></tr></table><table width="100%" height="auto" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" align="center" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> <!-- Messaging --> <table width="100%" height="20" align="left" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> </td> </tr></table><table width="100%" height="auto" align="left" cellspacing="30" cellpadding="0" bgcolor="#FFFFFF" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td align="left"> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">Dear lewis_mewis</p> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">Thank for your Evercise booking! Please take note of your unique booking code (below). Your trainer will require this and another form of ID.</p> <strong style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;"><p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">Transaction ID: 5318084</p></strong> </td> </tr></table><table class="table" width="100%" height="auto" align="left" cellspacing="0" cellpadding="30" bgcolor="#FFFFFF" style="max-width: 640px; table-layout: fixed; width: 100%;"><tbody><tr><td> <table class="table" width="100%" height="20" align="left" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" style="max-width: 640px; table-layout: fixed; width: 100%;"><tbody><tr align="left"><th colspan="2" style="border-bottom: 1px solid #768690; color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;"> Name </th> <th colspan="3" style="border-bottom: 1px solid #768690; color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;"> Date </th> <th style="border-bottom: 1px solid #768690; color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;"> Price </th> </tr><tr align="left"><td colspan="2"> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">WARM UP</p> </td> <td colspan="3"> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">5 classes</p> </td> <td> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">£27.99</p> </td> </tr><tr><td colspan="7" align="left"> <br><br><strong style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;">Sub-total <span class="blue-text" style="color: #5ECDE8;">£27.99</span></strong> <br><br></td> </tr><tr><td colspan="7" align="left"> <strong style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 18px; font-weight: 500; line-height: 26px; margin: 0;">Total <span class="blue-text" style="color: #5ECDE8;">£27.99</span></strong> </td> </tr></tbody></table></td> </tr></tbody></table><table width="100%" height="auto" align="center" cellspacing="0" cellpadding="20" bgcolor="#f2f2f2" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td width="100%"> <table width="100%" height="auto" align="center" cellspacing="0" cellpadding="10" bgcolor="#f2f2f2" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">Here are a few classes you could attend using your new package</p> </td> </tr></table><table width="100%" height="auto" align="center" cellspacing="0" cellpadding="10" bgcolor="#f2f2f2" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td></td></tr></table></td> </tr></table><!-- Footer --><table width="100%" height="85" cellspacing="0" cellpadding="0" bgcolor="#ffffff" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td class="sm-hidden" width="30" height="85"></td> <td class="sm-hidden" height="50"> <p class="footer" style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 12px; font-weight: normal; line-height: 26px; text-align: left;">© Copyright 2014 Evercise</p> </td> <td width="100" height="40" align="center"> <p style="color: #768690; font-family: helvetica, arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 26px;">Follow us on</p> </td> <td width="40" height="40" align="center"> <a href="http://facebook.com/evercise"><img src="http://evercise.com/img/email-campaign/facebook.png" width="40" height="40" border="0" alt="Facebook" style="width: 100%;"></a> </td> <td width="40" height="40" align="center"> <a href="http://twitter.com/evercise"><img src="http://evercise.com/img/email-campaign/twitter.png" width="40" height="40" border="0" alt="Twitter" style="width: 100%;"></a> </td> <td width="40" height="40" align="center"> <a href="http://instagram.com/evercisefitness"><img src="http://evercise.com/img/email-campaign/instagram.png" width="40" height="40" border="0" alt="Instagram" style="width: 100%;"></a> </td> <td class="sm-hidden" width="30" height="85"></td> </tr></table><table width="100%" height="20" cellspacing="0" cellpadding="30" bgcolor="#ffffff" style="max-width: 640px; table-layout: fixed; width: 100%;"><tr><td> </td> </tr></table><!-- Closing main --></td> </tr></table></td> </tr></table></body></html> <file_sep>/app/composers/CalendarComposer.php <?php namespace composers; use JavaScript; use Calendar; use Functions; class CalendarComposer { public function compose($view) { if (isset($view->month)){ $month = $view->month; $year = $view->year; } else{ $month = date('m'); $year = date('Y'); } $calendarData = []; $startDay = $month == date('m') ? date('d')+1 : 1; if ($month >= date('m') || $year >= date('Y')) for ($i=$startDay; $i<=cal_days_in_month(CAL_GREGORIAN,$month,$year); $i++) $calendarData[$i] = 'day_'.$i; $template = Functions::getCalendarTemplate(); JavaScript::put(array('initEverciseGroups' => 1 )); Calendar::initialize(array('template' => $template, 'show_next_prev' => true)); $view->with('calendarData', $calendarData); } }<file_sep>/app/models/Withdrawalrequest.php <?php class Withdrawalrequest extends \Eloquent { protected $fillable = ['user_id', 'transaction_amount', 'account', 'acc_type', 'processed']; protected $table = 'withdrawalrequests'; /** * @param $inputs , $id * @return array */ public static function createWithdrawelRequest($inputs, $id) { $withdrawalAmount = $inputs['withdrawal']; $paypal = $inputs['paypal']; $wallet = Wallet::where('user_id', $id)->first(); $withdrawal = Withdrawalrequest::create( [ 'user_id' => $id, 'transaction_amount' => $withdrawalAmount, 'account' => $paypal, 'acc_type' => 'paypal', 'processed' => 0 ] ); if ($withdrawal) { $wallet->withdraw($withdrawalAmount, 'Withdrawal request', Sentry::getUser()); $result = [ 'callback' => 'openConfirmPopup', 'url' => route('trainers.edit.tab', [$id, 'wallet']), 'popup' => (string)(View::make('wallets.confirm') ->with('withdrawal', $withdrawalAmount) ->with('paypal', $paypal)) ]; } else { $result = [ 'callback' => 'refreshpage' ]; } return $result; } public function user() { return $this->belongsTo('User', 'user_id'); } public function markProcessed() { $this->attributes['processed'] = 1; $this->save(); } public static function getPendingWithdrawals() { return Withdrawalrequest::where('processed', 0)->with('user')->get(); } public static function getProcessedWithdrawals() { return Withdrawalrequest::where('processed', 1)->with('user')->get(); } }<file_sep>/app/database/migrations/2014_09_01_153435_populate_featured_classes.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class PopulateFeaturedClasses extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::table('featured_evercisegroups')->insert( [ ['evercisegroup_id' => 181 ], ['evercisegroup_id' => 189 ], ['evercisegroup_id' => 21 ], ['evercisegroup_id' => 191 ] ] ); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/lang/en/trainers-create.php <?php return [ 'title' => 'You&apos;re almost there', 'subtitle' => 'We have created a user account for you, please fill in the details below to updgrade to a trainer.', 'upload_image' => 'Upload your user image', '' => '', ];<file_sep>/app/composers/AdminPendingWithdrawalComposer.php <?php namespace composers; use Withdrawalrequest; class AdminPendingWithdrawalComposer { public function compose($view) { $pendingWithdrawals = Withdrawalrequest::getPendingWithdrawals(); $processedWithdrawals = Withdrawalrequest::getProcessedWithdrawals(); $view ->with('pendingWithdrawals', $pendingWithdrawals) ->with('processedWithdrawals', $processedWithdrawals); } }<file_sep>/ExampleEnviroment.php <?php /** * This is a Example Enviroment file * * Make a copy of this file and name it .env.php * * After your copied it just edit the contents of it to match your setup */ return [ 'DEBUG_APP' => true, 'APP_URL' => 'http://evercise.dev/', 'ENCRYPTION_KEY' => '<KEY>', 'ASSETS_CACHE' => false, //To Enable set TRUE //DB LIVE 'DB_HOST' => 'localhost', 'DB_NAME' => 'evercise', 'DB_USER' => 'evercise', 'DB_PASS' => '<PASSWORD>', //DB MIGRATION 'DB_V1_HOST' => 'localhost', 'DB_V1_NAME' => 'evercise', 'DB_V1_USER' => 'evercise', 'DB_V1_PASS' => '<PASSWORD>', //EMAIL SETUP 'EMAIL_DRIVER' => 'smtp', 'EMAIL_SMTP_HOST' => 'smtp.gmail.com', 'EMAIL_SMTP_PORT' => 587, 'EMAIL_FROM_ADDRESS' => '<EMAIL>', 'EMAIL_FROM_NAME' => 'Evercise', 'EMAIL_SMTP_ENCRYPTION' => 'tls', 'EMAIL_SMTP_USERNAME' => '<EMAIL>', 'EMAIL_SMTP_PASSWORD' => '<PASSWORD>', 'EMAIL_SENDMAIL' => '/usr/sbin/sendmail -bs', 'EMAIL_PRETEND' => true, //For Production Set to False //Facebook Data 'FACEBOOK_ID' => '306418789525126', 'FACEBOOK_SECRET' => '<KEY>', //ELASTIC SEARCH 'ELASTIC_HOST' => 'ec2-54-72-203-163.eu-west-1.compute.amazonaws.com:9200', 'ELASTIC_INDEX' => 'evercise_CHANGE_ME_TO_SOMETHING_UNIQUE', 'ELASTIC_TYPE' => 'evercise', // Pardot Example 'PARDOT_ACTIVE' => true, 'PARDOT_EMAIL' => '<EMAIL>', 'PARDOT_KEY' => '85d82e88f97a0159f312d6a6be6a19f4', 'PARDOT_PASSWORD' => '<PASSWORD>!', 'PARDOT_FORMAT' => 'json', 'PARDOT_OUTPUT' => 'full' ];<file_sep>/app/commands/IndexerCreate.php <?php use Illuminate\Console\Command; class IndexerCreate extends Command { /** * The console command name. * * @var string */ protected $name = 'indexer:create'; /** * The console command description. * * @var string */ protected $description = 'Create the needed Index For Elastic To work'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); /** Load a partial instance of the Elastic thingy... no need for everything to be injected!*/ $this->elastic = new Elastic([], [], Es::getFacadeRoot(), []); $this->elastic_index = getenv('ELASTIC_INDEX'); $this->elastic_type = getenv('ELASTIC_TYPE'); return; } /** * Execute the console command. * * @return mixed */ public function fire() { if(!$this->elastic_index) { $this->error('YOU NEED TO UPDATE YOUR .env.php file.'); $this->error('Please check Example.env.php'); return; } $this->info('Checking if the Index exits. And deleting it!'); $this->elastic->deleteIndex($this->elastic_index); $this->info('Creating a new Index '.$this->elastic_index); $this->elastic->createIndex($this->elastic_index); $this->info('Setting all the required mappings for the Index'); $this->elastic->resetIndex($this->elastic_index, $this->elastic_type); $this->info('Completed'); } } <file_sep>/app/database/migrations/2014_10_22_095199_seed_categories.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class SeedCategories extends Migration { /** * Run the migrations. * * @return void */ public function up() { $categories = [ ['parent_id' => 0, 'title' => 'Information', 'main_image' => '', 'description' => 'Evercise Info', 'keywords' => 'evercise.com, evercise, information', 'permalink' => 'information', ], ['parent_id' => 0, 'title' => 'Fitness', 'main_image' => '', 'description' => 'All About Fitnes', 'keywords' => 'fitness', 'permalink' => 'fitness', ], ['parent_id' => 0, 'title' => 'Lifestyle', 'main_image' => '', 'description' => 'All about lifestyle', 'keywords' => 'Lifestyle', 'permalink' => 'lifestyle', ], ]; foreach($categories as $cat) { ArticleCategories::create($cat); } } /** * Reverse the migrations. * * @return void */ public function down() { DB::table('article_categories')->truncate(); } } <file_sep>/app/controllers/SearchController.php <?php class SearchController extends \BaseController { protected $evercisegroup; protected $sentry; protected $link; protected $input; protected $log; protected $session; protected $redirect; protected $paginator; protected $place; protected $elastic; protected $search; public function __construct( Evercisegroup $evercisegroup, Sentry $sentry, Link $link, Illuminate\Http\Request $input, Illuminate\Log\Writer $log, Illuminate\Session\Store $session, Illuminate\Routing\Redirector $redirect, Illuminate\Pagination\Factory $paginator, Illuminate\Config\Repository $config, Es $elasticsearch, Geotools $geotools, Place $place, SearchModel $searchModel ) { parent::__construct(); $this->evercisegroup = $evercisegroup; $this->sentry = $sentry; $this->link = $link; $this->input = $input; $this->log = $log; $this->place = $place; $this->session = $session; $this->redirect = $redirect; $this->paginator = $paginator; $this->config = $config; $this->elastic = new Elastic( $geotools::getFacadeRoot(), $this->evercisegroup, $elasticsearch::getFacadeRoot(), $this->log ); $this->search = new Search($this->elastic, $this->evercisegroup, $this->log); $this->searchmodel = $searchModel; } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { if ($evercisegroup = $this->evercisegroup->with('Evercisesession.Sessionmembers.Users') ->with('evercisesession.sessionpayment') ->with('subcategories.categories') ->find($id) ) { if ($this->sentry->check() && $evercisegroup->user_id == $this->user->id) // This Group belongs to this User/Trainer { return $evercisegroup->showAsOwner($this->user); } else // This group does not belong to this user { return $evercisegroup->showAsNonOwner($this->user); } } else { return View::make('errors.missing'); } } /** * Parse All Params and forward it to the right function * @param array $all_segments */ public function parseUrl($all_segments = '') { $link = false; $fullLocation = $this->input->get('fullLocation', FALSE); if(!$fullLocation) { $link = $this->link->checkLink($all_segments, $this->input->get('area', FALSE)); } if ($link && !$this->input->get('area', FALSE)) { return $this->search($link->getArea); } elseif ($link && $this->input->get('area', FALSE)) { $input = array_filter($this->input->except(['area', '_token', 'location'])); $input['allsegments'] = $link->permalink; return $this->redirect->route( 'search.parse', $input ); } elseif (!$link && !$this->input->get('location', FALSE) && $all_segments != '') { $this->log->info('Somebody tried to access a missing URL ' . $this->input->url()); $input['allsegments'] = ''; $input = array_filter(array_except($input, ['area'])); return $this->redirect->route( 'search.parse', $input ); } return $this->search(); } /** * query eg's based on location * * * search * location * city * per_page * page * from * distance * venue_id * * * @return Response */ public function search($area = FALSE) { $input = array_filter($this->input->all()); $dates = $this->searchmodel->search($area, $input, $this->user, TRUE); $input['date'] = $this->searchmodel->getSearchDate($dates, $input); $results = $this->searchmodel->search($area, $input, $this->user); $results['selected_date'] = $input['date']; $results['available_dates'] = $dates; if (!empty($results['redirect'])) { return $results['redirect']; } $results['related_categories'] = \Subcategory::getRelatedFromSearch(!empty($input['search']) ? $input['search'] : FALSE); JavaScript::put(['results' => $results]); return View::make('v3.classes.discover.search') ->with($results); } public function getClasses($params) { return $this->searchmodel->getClasses($params); } }<file_sep>/public/assets/jsdev/prototypes/12-category-select.js function categorySelect(form){ this.form = form; this.select = this.form.find('.select2'); this.keywordSelect = this.form.find('input[name="keywords"]'); this.keywords = []; this.keys = []; this.gallery = ''; this.maximumSelectionSize = 3; this.minimumResultsForSearch = 1; this.placeholder = 'Choose upto 3 categories'; this.dropdownCssClass = 'select2-hidden'; this.init(); } categorySelect.prototype = { constructor: categorySelect, init: function(){ this.select.select2({ maximumSelectionSize: this.maximumSelectionSize, minimumResultsForSearch: this.minimumResultsForSearch, placeholder: this.placeholder, closeOnSelect: true, openOnEnter: false, formatNoMatches: function() { return ''; }, dropdownCssClass: this.dropdownCssClass }); this.addListener(); }, addListener: function () { this.form.on("submit", $.proxy(this.submitForm, this)); this.select.on("select2-selecting", $.proxy(this.addToKeywords, this)) this.select.on("select2-removing", $.proxy(this.removeFromKeywords, this)) $(document).on('swiperight', '#image-carousel', function(){ $(this).carousel('next'); }) $(document).on('swipeleft', '#image-carousel', function(){ $(this).carousel('prev'); }) }, submitForm: function(e){ e.preventDefault(); this.ajaxUpload(); }, ajaxUpload: function () { var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { $('#gallery-row').after('<div id="gallery-loading" class="alert alert-success text-center"><span class="icon icon-loading ml10"></span> Loading gallery based on your selected categories...</div>'); }, success: function (data) { self.gallery = data.view; $('#gallery-row').html(self.gallery).trigger('change'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.select.prop('disabled', false); $('#gallery-loading').remove(); } }); }, addToKeywords: function(e){ this.keys.push(e.choice.id); this.keywords.push(e.choice.text); this.keywordSelect.val(this.keywords); this.updateCategoriesInput(); this.form.submit(); }, removeFromKeywords: function(e){ this.keywords = $.grep(this.keywords, function(value) { return value != e.choice.text; }); this.keys = $.grep(this.keys, function(value) { return value != e.choice.id; }); this.updateCategoriesInput(); }, updateCategoriesInput: function(){ $('input[name="category_array[]"]').val(this.keywords).trigger('change'); } }<file_sep>/app/controllers/widgets/calendarController.php <?php namespace widgets; use Auth, BaseController, Form, Input, Redirect, Sentry, View, Request, Response, Validator, Image, Calendar, Functions; class CalendarController extends \BaseController { protected $layout = 'widgets.calendar'; /** * Display a listing of the resource. * * @return Response */ public function getCalendar() { // Look in CalendarComposer } public function postCalendar() { $month = Input::get('month'); $year = Input::get('year'); return View::make('widgets.calendar')->with('year', $year)->with('month', $month); } }<file_sep>/app/lang/en/header.php <?php return array( 'how_it_works' => 'How it works', 'discover_classes' => 'Discover classes', 'login' => 'Login', 'register' => 'Register', );<file_sep>/app/views/v3/classes/class_page.blade.BACKUP.php @extends('v3.layouts.master') <?php View::share('og', $data['og']) ?> @section('body') @if(isset($preview)) <nav class="navbar navbar-inverse navbar-fixed-top" id="preview"> <div class="container mt10"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> {{ Form::open(['route' => 'evercisegroups.publish', 'method' => 'post', 'id' =>'publish-class']) }} <span class="text-white">This is what your class will look like when published</span> {{ Html::linkRoute('sessions.add', 'Edit Sessions', $data['evercisegroup']->id, ['class' => 'btn btn-default text-right ml20 mr20'] ) }} {{ Form::hidden('id', $data['evercisegroup']->id ) }} {{ Form::hidden('publish', $data['evercisegroup']->published == 1 ? 0 : 1) }} {{Form::submit( $data['evercisegroup']->published == 1 ? 'Un-publish' : 'Publish',['class'=>'btn btn-primary'])}} {{ Form::close() }} </div> </div> </div> </nav> @endif <div class="hero no-nav-change" style="background-image: url('{{url().'/'.$data['trainer']->user->directory.'/cover_'.$data['evercisegroup']->image}}')"> <nav class="navbar navbar-inverse nav-bar-bottom" role="navigation"> <div class="container"> <ul class="nav navbar-nav nav-justified nav-no-float" id="scroll-to"> <li class="active"><a href="#about">About</a></li> <li class="{{ count($data['evercisegroup']->futuresessions) == 0 ? 'disabled' : null}}"><a href="#schedule">Schedule</a></li> <li class="{{ count($data['venue']->facilities) == 0 ? 'disabled' : null}}"><a href="#facilities">Facilities & Amenities</a></li> <li class="{{ count($data['allRatings']) == 0 ? 'disabled' : null}}"><a href="#ratings" >Reviews</a></li> <li class="text-center"> <span> <a href="{{ Share::load(Request::url() , $data['evercisegroup']->name)->facebook() }}" target="_blank"><span class="icon icon-fb-white mr20 hover"></span> </a> <a href="{{ Share::load(Request::url() , $data['evercisegroup']->name)->twitter() }}" target="_blank"><span class="icon icon-twitter-white mr20 hover"></span> </a> <a href="{{ Share::load(Request::url() , $data['evercisegroup']->name)->gplus() }}" target="_blank"><span class="icon icon-google-white hover"></span> </a> </span> </li> </ul> </div> </nav> </div> <div class="container mt30 mb40"> <div class="row" id="about"> <div class="col-sm-6"> <h1 class="mb5">{{ $data['evercisegroup']->name }}</h1> <div class="mb30"> @if (isset($data['allRatings'])) @include('v3.classes.ratings.stars', array('rating' => $data['allRatings'])) @endif </div> <p>{{ $data['evercisegroup']->description }}</p> <div class="row"> <div class="col-sm-11"> <div class="row mt20"> <div class="col-sm-3"> {{ image($data['trainer']->user->directory.'/small_'.$data['trainer']->user->image, $data['trainer']->user->first_name, ['class' => 'img-responsive img-circle']) }} </div> <div class="col-sm-9 mt25"> <div class="condensed"> <strong>This class is presented by</strong> </div> <span>{{ Html::linkRoute('trainer.show', $data['trainer']->user->display_name, $data['trainer']->user->display_name) }}</span> </div> </div> </div> </div> </div> <div class="col-sm-6"> <h1 class="mb5">Location</h1> <span><span class="icon icon-pink-pointer"></span>{{ $data['venue']->address }}</span> <div id="map_canvas" class="map_canvas mt10" data-zoom="12" data-lat="{{ $data['venue']->lat }}" data-lng="{{ $data['venue']->lng }}"></div> </div> </div> <hr> <div id="schedule" class="row"> <div class="col-sm-12"> <h1>Upcoming sessions</h1> </div> <div class="col-sm-12"> <ul class="nav navbar-nav nav-carousel hide-by-class-wrapper"> <li><a class="hide-by-class disabled" href="#Mon">MON</a></li> <li><a class="hide-by-class disabled" href="#Tue">TUE</a></li> <li><a class="hide-by-class disabled" href="#Wed">WED</a></li> <li><a class="hide-by-class disabled" href="#Thu">THU</a></li> <li><a class="hide-by-class disabled" href="#Fri">FRI</a></li> <li><a class="hide-by-class disabled" href="#Sat">SAT</a></li> <li><a class="hide-by-class disabled" href="#Sun">SUN</a></li> </ul> <div class="table-responsive center-block"> <table class="table table-hover pull-left"> <tbody> @foreach($data['evercisegroup']->futuresessions as $futuresession) <tr class="{{date('D' , strtotime($futuresession->date_time))}} hide-by-class-element hide"> <td><span class="icon icon-calendar mr5"></span><span>{{ date('M jS Y' , strtotime($futuresession->date_time))}}</span></td> <td><span class="icon icon-clock mr5"></span><span>{{ (date('g:ia' , strtotime($futuresession->date_time))) .' - '. (date('g:ia' , strtotime($futuresession->date_time) + ( $futuresession->duration * 60))) }}</span></td> <td> @if($futuresession->remainingTickets() > 0) <span class="icon icon-ticket mr10"></span><span>x {{$futuresession->remainingTickets() }} tickets left</span> @else <span class="text-danger">Class Full</span> @endif </td> <td><span class="icon icon-watch mr5"></span><span>{{ $futuresession->formattedDuration() }}</span></td> <td> <span> <strong class="text-primary mr25 lead">&pound;{{ $futuresession->price }} </strong> </span> </td> <td> @if($futuresession->remainingTickets() > 0) {{ Form::open(['route'=> 'cart.add','method' => 'post', 'id' => 'add-to-class'. $futuresession->id, 'class' => 'add-to-class']) }} <div class="btn-group pull-right"> {{ Form::submit('Join class', ['class'=> 'btn btn-primary add-btn']) }} {{ Form::hidden('product-id', EverciseCart::toProductCode('session', $futuresession->id)) }} {{ Form::hidden('force', true) }} <select name="quantity" id="quantity" class="btn btn-primary btn-select"> @for($i=1; $i<($futuresession->remainingTickets() + 1 ); $i++) <option value="{{$i}}" {{ (!empty($cart_items[$futuresession->id]) && $cart_items[$futuresession->id] == $i ? 'selected="selected"' : '') }}>{{$i}}</option> @endfor </select> </div> {{ Form::close() }} @else <span class="text-danger">Class Full</span> @endif </td> </tr> @endforeach </tbody> </table> </div> </div> </div> <hr> @if(count($facilities = $data['venue']->getFacilities()) || count($amenities = $data['venue']->getAmenities())) <div id="facilities" class="row"> <div class="col-sm-12"> @if(count($facilities = $data['venue']->getFacilities())) <div class="page-header"> <h1>Venue Facilities</h1> </div> <ul class="row custom-list"> @foreach($facilities as $facility) <div class="col-sm-3"> <li>{{ $facility->name}}</li> </div> @endforeach </ul> @endif @if(count($amenities = $data['venue']->getAmenities())) <div class="page-header"> <h1>Venue Amenties</h1> </div> <ul class="row custom-list"> @foreach($amenities as $amenity) <div class="col-sm-3"> <li>{{ $amenity->name}}</li> </div> @endforeach </ul> @endif </div> </div> @endif @if(count($data['allRatings']) > 0) <hr> <div id="ratings" class="row"> <div class="col-sm-12"> <div class="page-header"> <h1>Reviews</h1> </div> </div> @foreach ($data['allRatings'] as $rating) <div class="col-sm-6"> @include('v3.users.rating_block') </div> @endforeach </div> @endif </div> @stop <file_sep>/app/filters.php <?php /* |-------------------------------------------------------------------------- | Application & Route Filters |-------------------------------------------------------------------------- | | Below you will find the "before" and "after" events for the application | which may be used to do any work before or after a request into your | application. Here you may also register your custom route filters. | */ App::before(function ($request) { // }); App::after(function ($request, $response) { // }); /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. | */ Route::filter('auth', function () { if (!Sentry::check()) { return Redirect::route('home'); } }); Route::filter('auth.basic', function () { return Auth::basic(); }); Route::filter('admin', function () { if (!App::environment('local')) { // Find the user using the user id if ($user = Sentry::getUser()) { // Find the Administrator group $admin = Sentry::findGroupByName('Admin'); // Check if the user is in the administrator group if (!$user->inGroup($admin)) { return Redirect::route('home')->with('notification', 'You do not have the correct privileges to view this page'); } } else { return Redirect::route('home')->with('notification', 'You do not have the correct privileges to view this page'); } } }); Route::filter('user', function () { // Kick out if not logged in if (!Sentry::check()) { return Redirect::route('home')->with('notification', 'You do not have the correct privileges to view this page. Please Log In'); } }); Route::filter('trainer', function () { // Kick out if not a trainer - send to trainer sign up page if (!Trainer::isTrainerLoggedIn()) { return Redirect::route('trainers.create'); } }); /* |-------------------------------------------------------------------------- | Guest Filter |-------------------------------------------------------------------------- | | The "guest" filter is the counterpart of the authentication filters as | it simply checks that the current user is not logged in. A redirect | response will be issued if they are, which you may freely change. | */ Route::filter('guest', function () { if (Auth::check()) { return Redirect::to('/'); } }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function () { $token = Input::header('X-CSRF-Token', Input::input('_token')); if (Session::token() !== $token) { throw new Illuminate\Session\TokenMismatchException; } }); /* 404 handler */ App::missing(function ($exception) { //Since we have a fuckup here.. we need to do this one manually if (Request::is('trainer/*')) { return Redirect::to(str_replace('trainer/', 'trainers/', Request::url()), 301); } $redirects = Config::get('evercise.301_REDIRECTS'); $current_url = ltrim($_SERVER['REQUEST_URI'], '/'); if ($redirects) { foreach ($redirects as $url => $route) { if ($url == $current_url) { return Redirect::route($route, [], 301); } } } return Response::view('v3.errors.missing', ['title' => 'Whoops | 404 Page Not Found'], 404); }); View::composer('*', function ($view) { // Share the name of the view, to be passed to the locatlisations (it's used to load the correct localisation file) View::share('view_name', $view->getName()); });<file_sep>/public/assets/jsdev/prototypes/3-masonry.js var Masonry = function (masonry) { this.masonry = masonry; this.init(); } Masonry.prototype = { constructor: Masonry, init: function(){ var $container = this.masonry; $container.masonry({ itemSelector: '.masonry-item', isInitLayout: true, transitionDuration: 0 }); $container.masonry; } }<file_sep>/app/lang/en/about.php <?php return [ 'section1-title' => 'What is Evercise?', 'section1-body' => ' <p>Evercise is an online network that gives <br> <b>everyone</b> wanting to <b>exercise</b> access to fitness instructors and classes across London.<br> We understand that if you have a busy lifestyle,<br> you can&apost necessarily commit to a rigid fitness regime. That&aposs what makes Evercise different.<br> You can choose your class by location, trainer or type, and you don&apost need to sign up for a whole course at once, you can join on a class-by-class basis.<br> Your fitness: your terms. After joining a class, you will receive a booking confirmation with all the useful details<br> (you will also receive a handy reminder the day before the class).<br> With Evercise, organising your fitness is easy, fun and flexible.</p> ', 'section1-image_url' => '/img/WIE_1.jpg', 'section1-image_alt' => 'potato', 'section2-title' => 'Community', 'section2-body' => ' <p>At Evercise we don&apost underestimate the motivational power of camaraderie. <br> Exercising in a group inspires greater willpower and discipline, and therefore greater results! <br> It significantly reduces the cost of the class per participant,<br> and because there are so many people wanting so many different things, <br> there is a huge variety of classes to choose from.<br>Use our Evercise community to find people with similar fitness requirements, <br> and a trainer to suit those requirements. <br> From the moment you book a class you can talk to other members of the class <br> and the trainer through the <i>Community Thread.</i> Share your experiences, write reviews and club together to request more classes from the same trainer.</p> ', 'section2-image_url' => '/img/WIE_2.jpg', 'section2-image_alt' => 'potato fitness idea', 'section3-title' => 'Evercise for the Instructor', 'section3-body' => ' <p>If you are a professional trainer teaching any fitness class indoors or outdoors, <br> Evercise can help you achieve your goals. By setting up a professional account <br> (which is free by the way), <br> you can advertise your services to a wide range of potential participants.<br> Increase the number of participants in a class you run, <br> or create interest in a new class you are developing. Promote your services, showcase your skills, and create unique events. <br> Evercise is a great platform for organisation, too. <br> Setting up and getting paid for classes through Evercise couldn&apos;t be easier. <br> <b>To find out more, visit our &apos;'. HTML::linkRoute('trainers.create', 'Be a pro') .'&apos; page</b></p> ', 'section3-image_url' => '/img/WIE_3.jpg', 'section3-image_alt' => 'potato group fitness class', 'section4-title' => 'Understanding the Class Panels', 'section4-body' => ' <p>When a trainer organises a class, it will be displayed as a panel (please see example above) on your user dashboard Each panel shows the class description and basic information. You can click on the panel to view further information about the specific class. <br>The yellow bar, or <i>joining percentage,</i> represents the class availability, showing how many people have joined and how many spaces are left. <br>The star rating represents the feedback that the trainer has received from previous classes. <br>Once you have joined a class we cannot offer a refund if you pull out, but you will receive a full refund if the class is cancelled. </p> ', 'section4-image_url' => '/img/boxdes1.png', 'section4-image_alt' => 'evercise fitness class box', ];<file_sep>/public/assets/jsdev/prototypes/9-add-sessions.js // unused at the moment see addSessionsToCalendar /* function AddSessions(form){ this.form = form; this.calendar = this.form.find('#calendar'); this.daysOfWeek = ''; this.dates = []; this.submitDates = []; this.index = ''; this.recur = 'no'; this.recurring = 6; this.recurringFor = this.form.find('#recurring-days').val(); this.originalDates = []; this.rows = []; this.currentDates = []; this.init(); } AddSessions.prototype = { constructor: AddSessions, init: function () { this.calendar.datepicker({ format: "yyyy-mm-dd", startDate: "+1d", todayHighlight: true, multidate: true }) .on('changeDate', $.proxy(this.getCurrentDates, this) ); this.daysOfWeek = this.calendar.find('.dow'); this.addListener(); }, addListener: function () { this.daysOfWeek.on("click", $.proxy(this.dayOfWeek, this) ); $('input[name="recurring"]').on('change', $.proxy(this.recurringCheck, this)); this.form.on("submit", $.proxy(this.submitForm, this)); this.form.find('#recurring-days').on("change", $.proxy(this.changeRecurringFor, this)); }, dayOfWeek: function(e){ this.index = ($(e.target).index()); this.rows = []; this.setdayOfWeeks(); }, getCurrentDates: function(e){ var self = this; this.currentDates = e.dates; this.dates = []; // keep original dates intact $.each(this.currentDates , function(i,v){ self.dates.push({ 'key': v.valueOf(), 'dates': v }) }) }, setdayOfWeeks: function(){ var d = new Date(), month = d.getMonth(), self = this; d.setDate(1); // Get the first nth in the month while (d.getDay() !== this.index) { d.setDate(d.getDate() + 1); } // Get all the other nth in the month while (d.getMonth() === month) { var recurringDate = new Date( d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) ); var resultFound = $.grep(self.dates, function(e){ return e.key == recurringDate.valueOf(); }); if (resultFound.length == 0) { self.dates.push({ 'key' : recurringDate.valueOf(), 'dates' : recurringDate } ); } else{ self.dates = self.dates.filter(function(el){ return el.key !== recurringDate.valueOf(); }) } d.setDate(d.getDate() + 7); } this.setCalendarDates(); }, recurringDates: function(){ //this.currentDates = this.calendar.datepicker('getDates'); var self = this; $.each(this.currentDates , function(i, val){ self.dates.push({ 'key' : val.valueOf(), 'dates' : val }); self.originalDates.push( val ); var weekOfMonth = Math.ceil(val.getDate() / 7 ); var dayOfWeek = val.getDay(); var monthOfYear = val.getMonth() + 1; self.setRecurringDays(dayOfWeek, monthOfYear, weekOfMonth); }) }, submitForm: function(e){ e.preventDefault(); var self =this; $.each(this.calendar.datepicker('getDates') , function(i,v){ var day = v.getDate(); var month = (v.getMonth() + 1); var year = v.getFullYear(); self.submitDates.push(year + '-'+ month + '-' + day); }) $('input[name="session_array"]').val( this.submitDates ); this.ajaxUpload(); }, ajaxUpload: function () { var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true).parent().after('<span id="session-loading" class="icon icon-loading ml10 mt10"></span>'); }, success: function (data) { $('#update-session').html(data.view); $('input[name="recurring"][value="no"]').click(); self.dates = []; self.submitDates = []; self.originalDates = []; self.setCalendarDates(); $("html, body").animate({scrollTop: $('#update-container').offset().top -20 }, 1000); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log('error'); //console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false) $('#session-loading').remove(); } }); }, setRecurringDays: function(day, month, week) { var self = this; for( var i = 0; i < self.recurringFor; i++){ var d = new Date(), formatedDate; d.setMonth(month + i); d.setDate(1); // Get the first nth in the month while (d.getDay() !== day) { d.setDate(d.getDate() + 1); } // Get the nth week in the month while ( Math.ceil(d.getDate() / 7 ) !== week) { d.setDate(d.getDate() + 7); } var formatedDate = new Date( d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) ); self.dates.push( { 'key' : formatedDate.valueOf(), 'dates' : formatedDate } ); } this.setCalendarDates(); }, recurringCheck: function(e){ if($(e.target).val() == 'yes'){ this.recur = 'yes'; this.recurringDates(); } else{ this.recur = 'no'; this.resetCalendarDates(); } }, setCalendarDates: function(){ var dates = []; var dateValues ={}; $.each(this.dates , function (index, value) { // check for duplicates if ( ! dateValues[ value.key ]){ dateValues[value.key] = true; dates.push(value.dates); } }); this.calendar.datepicker('setDates', dates ); }, resetCalendarDates: function(){ console.log(this.originalDates); this.calendar.datepicker('setDates', this.originalDates ); }, changeRecurringFor : function(e){ this.recurringFor = $(e.target).val(); if(this.recur == 'yes'){ this.calendar.datepicker('setDates', this.currentDates ); } $('input[name="recurring"][value="'+this.recur+'"]').trigger('change'); } } */<file_sep>/app/composers/AdminCategoriesComposer.php <?php namespace composers; use JavaScript; class AdminCategoriesComposer { public function compose($view) { $categories = \Category::get(); return $view->with('categories', $categories); } }<file_sep>/app/models/Subcategory.php <?php /** * Class Subcategory */ class Subcategory extends Eloquent { /** * @var array */ protected $fillable = ['id', 'name', 'description', 'associations', 'type']; /** * The database table used by the model. * * @var string */ protected $table = 'subcategories'; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function categories() { return $this->belongsToMany( 'Category', 'subcategory_categories', 'subcategory_id', 'category_id' )->withTimestamps(); } /** * @param $categoryChanges * @return bool */ public static function editSubcategoryCategories($categoryChanges) { foreach ($categoryChanges as $subcategoryId => $change) { $subcategory = Subcategory::find($subcategoryId); if($subcategory && is_array($change)) { $subcategory->categories()->detach(); $catArray = []; foreach ($change as $cat) { if (!in_array($cat, $catArray)) array_push($catArray, $cat); } $subcategory->categories()->attach($catArray); } } return 1; } public static function editAssociations($associationChanges) { foreach($associationChanges as $ass) { foreach($ass as $key => $assData) { if ($subcategory = Subcategory::find($key)) $subcategory->update(['associations' => $assData]); } } return true; } public static function editTypes($changes) { foreach($changes as $sub_id => $type) { if ($subcategory = Subcategory::find($sub_id)) $subcategory->update(['type' => $type]); } return true; } public static function namesToIds($names) { return static::whereIn('name', $names)->lists('id'); } public static function getRelated($type) { return static::where('type', $type)->lists('name'); } public function evercisegroups() { return $this->belongsToMany('Evercisegroup', 'evercisegroup_subcategories', 'subcategory_id', 'evercisegroup_id'); } /** * Takes the search term and returns a collection of up to 10 classes which: * - share a category * - Have future sessions * - Ordered by number of future sessions * * @param $searchTerm * @return $this|string */ public static function getRelatedFromSearch($searchTerm = false) { $cacheId = 'category_' . ($searchTerm ?: 'nosearch'); if(Cache::has($cacheId)) { $subcategoryNames = Cache::get($cacheId); } else { $subcategory = static::where('name', 'LIKE', '%' . $searchTerm . '%') ->first(); //return $subcategory->name; if ($subcategory) { $catIds = []; foreach ($subcategory->categories as $category) { $catIds[] = $category->id; } } else { $catIds = Category::lists('id'); } $subcategories = static:: whereHas('categories', function ($query) use ($catIds) { $query->whereIn('categories.id', $catIds); }) ->whereHas('evercisegroups', function ($query) { $query->whereHas('futuresessions', function ($query) { }); }) ->take(10) ->get() ->sortBy(function ($subcats) { return $subcats->evercisegroups->count(); }); $subcategoryNames = []; foreach($subcategories as $subcat){ $subcategoryNames[] = $subcat->name; } Cache::put($cacheId, $subcategoryNames, 180); /** ---------- prepare output for testing --------- */ /* $subcategoryName = $subcategory ? $subcategory->name : 'no Subcategory. Categories: ' . implode(',', $catIds); $subcategoryCategories = $subcategory ? $subcategory->categories : []; $output = '<strong>Subcategory: '.$subcategoryName.'</strong>'; $output .= '<br><br><strong>Categories: '.count($subcategoryCategories).'</strong>'; foreach ($subcategoryCategories as $cat) { $output .= '<br>'.$cat->name; } $output .= '<br><br><strong>Subcategories: '.count($subcategories).'</strong>'; foreach ($subcategories as $subcat) { $output .= '<br>'.$subcat->id.' - '.$subcat->name; } return $output;*/ /** ------------------------------------------------ */ } return $subcategoryNames; } public function getCategoriesString() { $output = ''; foreach ($this->categories as $cat) { $output .= $cat->name . ', '; } return $output; } }<file_sep>/app/database/migrations/2014_07_16_180535_create_migrate_groups_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateMigrateGroupsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (! Schema::hasTable('migrate_groups')) { Schema::create('migrate_groups', function(Blueprint $table) { $table->engine = "InnoDB"; $table->increments('id')->unsigned();// Foreign key; $table->integer('classInfoId')->unsigned(); $table->integer('evercisegroup_id')->unsigned(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('migrate_groups'); } } <file_sep>/public/assets/jsdev/prototypes/29-edit-class.js function EditClass(form){ this.form = form; this.addListeners(); } EditClass.prototype = { constructor: EditClass, addListeners: function(){ this.form.on('submit', $.proxy(this.submit, this)); }, submit: function(e){ e.preventDefault(); this.form = $(e.target); this.ajax(); }, ajax: function(){ var self = this; $.ajax(self.form.attr("action"), { type: "post", data: self.form.serialize(), dataType: 'json', beforeSend: function () { self.form.find("input[type='submit']").prop('disabled', true); self.form.find(".btn-toggle-down").prop('disabled', true); }, success: function (data) { self.edit(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown); }, complete: function () { self.form.find("input[type='submit']").prop('disabled', false) } }); }, edit: function(data){ $('#'+ data.id).html(data.view); $('#edit-'+ data.id).removeClass('disabled'); $('#submit-'+ data.id).hide(); $('#'+ data.id).parent().collapse('show'); $('#infoToggle-'+data.id).removeClass('hide'); datepick(); new UpdateSession($('.update-session')); new RemoveSession($('.remove-session')); new GetMembers($('.get-members')); $('.mail-popup').exists(function(){ new MailPopup(this); }) } }<file_sep>/app/models/Packages.php <?php use Carbon\Carbon; /** * Class Milestone */ class Packages extends \Eloquent { /** * @var array */ protected $fillable = ['id', 'name', 'description', 'price', 'bullets', 'classes', 'style', 'max_class_price']; /** * @var string */ protected $table = 'packages'; public function savings() { return round(100-($this->price / ($this->max_class_price * $this->classes) * 100), 0); } public function availableClasses() { return Evercisegroup::where('default_price', '<=', $this->max_class_price)->where('published', 1)->count(); } }
157bb4f6a874af7cd9ef928cefd6434ff8c037a8
[ "SQL", "JavaScript", "Markdown", "PHP", "Shell" ]
370
PHP
Evercise/evercise
90ae836d9359e3338240c062c1012fb1062661d0
f19289764dde6408dbdabd3f753d7d71a38b2b15
refs/heads/master
<file_sep># Default Theme # if patched_font_in_use; then # TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="⮂" # TMUX_POWERLINE_SEPARATOR_LEFT_THIN="⮃" # TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="⮀" # TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="⮁" # else TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="||" TMUX_POWERLINE_SEPARATOR_LEFT_THIN="|" TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="||" TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="|" #fi TMUX_POWERLINE_DEFAULT_BACKGROUND_COLOR=${TMUX_POWERLINE_DEFAULT_BACKGROUND_COLOR:-'235'} TMUX_POWERLINE_DEFAULT_FOREGROUND_COLOR=${TMUX_POWERLINE_DEFAULT_FOREGROUND_COLOR:-'255'} TMUX_POWERLINE_DEFAULT_LEFTSIDE_SEPARATOR=${TMUX_POWERLINE_DEFAULT_LEFTSIDE_SEPARATOR:-$TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD} TMUX_POWERLINE_DEFAULT_RIGHTSIDE_SEPARATOR=${TMUX_POWERLINE_DEFAULT_RIGHTSIDE_SEPARATOR:-$TMUX_POWERLINE_SEPARATOR_LEFT_BOLD} # Format: segment_name background_color foreground_color [non_default_separator] if [ -z $TMUX_POWERLINE_LEFT_STATUS_SEGMENTS ]; then TMUX_POWERLINE_LEFT_STATUS_SEGMENTS=( # "tmux_session_info 148 234" \ "hostname 232 251" \ "weather 232 14" \ "battery 232 127" \ # "vcs_branch 232 226" \ # "vcs_dirty 232 220" \ # "vcs_compare 232 220" \ # "vcs_staged 232 220" \ # "vcs_modified 232 220" \ # "vcs_others 232 0" \ ) fi if [ -z $TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS ]; then TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS=( #"earthquake 3 0" \ # "pwd <PASSWORD>" \ # "mailcount 9 255" \ # "now_playing 234 37" \ # "cpu 240 136" \ # "load 237 167" \ # "ifstat_sys 232 34" \ "ifstat 232 34" \ # "lan_ip 232 87" \ # "wan_ip 232 87" \ "tmux_mem_cpu_load 232 226" \ "time 232 136" \ # "rainbarf 232 0" \ #"xkb_layout 125 117" \ # "date_day 235 136" \ # "date 235 136 ${TMUX_POWERLINE_SEPARATOR_LEFT_THIN}" \ ) fi
769aeeff73cccde069ed63315b0f53864b5566e6
[ "Shell" ]
1
Shell
DarthNerdus/tmux-powerline
0c6c39ad80ca73fce1b83288ec2c80beeab4390e
58f75e94b738bae3bd3a8eb8e72699acbc6b8e75
refs/heads/master
<repo_name>vardhanapoorv/React<file_sep>/spy/dist/pageTwo.bundle.js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var margin = { top: 20, right: 20, bottom: 70, left: 40 }, width = 600 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); var xAxis = d3.svg.axis().scale(x).orient("bottom"); var yAxis = d3.svg.axis().scale(y).orient("left").ticks(10); var svg = d3.select("body").append("svg").attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var formatDate = d3.time.format("%Y-%m-%d"); var len; d3.json("datz.json", function (error, data) { len = data.length; data.forEach(function (d) { d.Date = formatDate.parse(d.Date); d.ans = d.ans; }); x.domain(d3.extent(data, function (d) { return d.Date; })); y.domain(d3.extent(data, function (d) { return d.ans; })); svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis).selectAll("text").style("text-anchor", "end").attr("dx", "-.8em").attr("dy", "-.55em").attr("transform", "rotate(-90)"); svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 5).attr("dy", ".71em").style("text-anchor", "end").text("Value"); svg.selectAll("bar").data(data).enter().append("rect").attr("class", "bar").attr("x", function (d) { return x(d.Date) - width / len / 2; }).attr("width", width / len).attr("y", function (d) { return y(d.ans); }).attr("height", function (d) { return height - y(d.ans); }); }); /***/ }) /******/ ]);<file_sep>/README.md Download the zip folder. Type the command "npm run watch" on terminal, this will give you the localhost address with port Run it on safari spy->dist->comb.html (Main html file to run) <file_sep>/spy/webpack.config.js const path = require('path') const config = { entry: { pageOne:'./src/chart.js', pageTwo:'./src/hist.js' } , output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] } } module.exports = config<file_sep>/spy/dist/pageOne.bundle.js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; 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; }; }(); 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; } function getChartSize(el) { var width = .9 * parseInt(el.style('width')); var height = .7 * parseInt(width * 7 / 9); return [width, height]; } var AxisX = function (_React$Component) { _inherits(AxisX, _React$Component); function AxisX() { _classCallCheck(this, AxisX); return _possibleConstructorReturn(this, (AxisX.__proto__ || Object.getPrototypeOf(AxisX)).apply(this, arguments)); } _createClass(AxisX, [{ key: "render", value: function render() { var data = this.props.data; var margin = this.props.margin; var height = this.props.height - margin.top - margin.bottom; var width = this.props.width - margin.left - margin.right; var x = d3.time.scale().range([0, width]); var xAxis = d3.svg.axis().scale(x).orient("bottom"); x.domain(d3.extent(data, function (d) { return d.date; })); d3.select(".x").attr("transform", "translate(0," + height + ")").call(xAxis).append("text").attr("transform", "translate(" + width / 2 + " ," + (height + margin.bottom) + ")").attr("x", 6).attr("dx", ".71em").style("text-anchor", "middle").text("Date"); return React.createElement("g", { className: "x axis" }); } }]); return AxisX; }(React.Component); ; var AxisY = function (_React$Component2) { _inherits(AxisY, _React$Component2); function AxisY() { _classCallCheck(this, AxisY); return _possibleConstructorReturn(this, (AxisY.__proto__ || Object.getPrototypeOf(AxisY)).apply(this, arguments)); } _createClass(AxisY, [{ key: "render", value: function render() { var data = this.props.data; var margin = this.props.margin; var height = this.props.height - margin.top - margin.bottom; var width = this.props.width - margin.left - margin.right; var y = d3.scale.linear().range([height, 0]); var yAxis = d3.svg.axis().scale(y).orient("left"); y.domain([0, d3.max(data, function (d) { return d.close; })]); d3.select(".y").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end").text("Price ($)"); return React.createElement("g", { className: "y axis" }); } }]); return AxisY; }(React.Component); ; var Line = function (_React$Component3) { _inherits(Line, _React$Component3); function Line() { _classCallCheck(this, Line); return _possibleConstructorReturn(this, (Line.__proto__ || Object.getPrototypeOf(Line)).apply(this, arguments)); } _createClass(Line, [{ key: "render", value: function render() { var data = this.props.data; var margin = this.props.margin; var height = this.props.height - margin.top - margin.bottom; var width = this.props.width - margin.left - margin.right; var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); var line = d3.svg.line().x(function (d) { return x(d.date); }).y(function (d) { return y(d.close); }); data.forEach(function (d) { x.domain(d3.extent(data, function (d) { return d.date; })); y.domain([0, d3.max(data, function (d) { return d.close; })]); }); var newline = line(data); console.log(newline); return React.createElement("path", { className: "line", d: newline }); } }]); return Line; }(React.Component); ; var Chart = function (_React$Component4) { _inherits(Chart, _React$Component4); function Chart(props) { _classCallCheck(this, Chart); var _this5 = _possibleConstructorReturn(this, (Chart.__proto__ || Object.getPrototypeOf(Chart)).call(this, props)); _this5.state = { chartWidth: 0, chartHeight: 0, x: NaN, y: NaN, data: [], margin: {} }; return _this5; } _createClass(Chart, [{ key: "componentDidMount", value: function componentDidMount() { var container = d3.select("#graphic"); var margin = { top: 20, right: 20, bottom: 30, left: 50 }; var chartWidth = getChartSize(container)[0]; var chartHeight = getChartSize(container)[1]; var _this = this; var formatDate = d3.time.format("%Y-%m-%d"); function type(d) { d.date = formatDate.parse(d.date); d.close = +d.close; return d; } d3.tsv("stk.tsv", type, function (error, data) { if (error) throw error; _this.setState({ chartWidth: chartWidth, chartHeight: chartHeight, data: data, margin: margin }); }); } }, { key: "render", value: function render() { var width = this.state.chartWidth; var height = this.state.chartHeight; var margin = this.state.margin; var data = this.state.data; return React.createElement( "div", { id: "chart" }, React.createElement( "svg", { height: height, width: width }, React.createElement( "g", { transform: "translate(50,20)" }, React.createElement(AxisX, { width: width, height: height, margin: margin, data: data }), React.createElement(AxisY, { width: width, height: height, margin: margin, data: data }), React.createElement(Line, { width: width, height: height, margin: margin, data: data }) ) ) ); } }]); return Chart; }(React.Component); ; ReactDOM.render(React.createElement(Chart, null), document.getElementById('graphic')); /***/ }) /******/ ]);
e768c528bf4f3f2c86384661804c0645bcc19fc2
[ "JavaScript", "Markdown" ]
4
JavaScript
vardhanapoorv/React
2220c6e61b31fcbc61d046dda7df024447884875
c9bedc7e777ad1148e0bf5bde8197c50e2d9f5f8
refs/heads/master
<file_sep>''' 读取test目录下所有文件,并将所有图片传入模型函数,并将图片名及判断结果写入csv文件的两列。 ''' # USAGE # python classify.py --model pokedex.model --labelbin lb.pickle --image examples/charmander_counter.png # python classify.py -m model.model -l lb.pickle -i img.jpg # import the necessary packages from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np import argparse import imutils import pickle import cv2 import csv import os # construct the argument parse and parse the arguments # ap = argparse.ArgumentParser() # ap.add_argument("-m", "--model", required=True, # help="path to trained model model") # ap.add_argument("-l", "--labelbin", required=True, # help="path to label binarizer") # ap.add_argument("-i", "--image", required=True, # help="path to input image") # args = vars(ap.parse_args()) model = load_model("1vgg1000.model") lb = pickle.loads(open("1vgg1000.pickle", "rb").read()) def write_csv(filename, label): path = "11.csv" with open(path,'a+', newline = '') as f: #单纯a+会每个一行一个空行 csv_write = csv.writer(f) data_row = [filename,label] csv_write.writerow(data_row) def listdir(path, list_name): #传入存储的list for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append(file_path) #file_path[5:]将前面的路径去掉,只保留文件名 #print(list_name) def predict_cnn(image, model, lb): ''' 将预测部分整合为函数,并将结果的标签1/2/3/4/5写入csv文件。 ''' # pre-process the image for classification filename = str(image) model = model lb = lb image = cv2.imread(image) image = cv2.resize(image, (300, 300)) image = image.astype("float") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) proba = model.predict(image)[0] idx = np.argmax(proba) label = lb.classes_[idx] label = "{}: {:.2f}% ".format(label, proba[idx] * 100) print("[label]", label) # [:1]就是标签位 print(label[0]) write_csv(filename[12:], label[0]) filelist = [] listdir('test_224224/', filelist) print(len(filelist)) #print(filelist) #pbar = ProgressBar().start() for image_file in filelist: #args["image"] = image_file print(image_file) predict_cnn(image_file, model, lb) #os.system("python classify4.py --model model200.model --label lb200.pickle -i " + image_file) <file_sep> ''' 读取CSV标签文件,并将图片目录下的所有图片移到对应标签文件名的目录下。 ''' import os import re import csv import shutil csv_file = "train.csv" def listdir(path, list_name): for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append(file_path[5:]) #print(list_name) filename = [] listdir('data/',filename) with open(csv_file) as file: reader = csv.reader(file) #print(list(reader)) for row in reader: #print(reader.line_num, row) #print(row) #print(row[0]) #print(row[1]) if row[0] in filename: #print(row[0]) #y验证 if row[1] == '1': #print(row[0]+"1_GAOJI") shutil.copy('data/'+row[0],'1_GAOJI/') if row[1] == '2': shutil.copy('data/'+row[0],'2_JUAN') if row[1] == '3': shutil.copy('data/'+row[0],'3_CENGJI') if row[1] == '4': shutil.copy('data/'+row[0],'4_JI') if row[1] == '5': shutil.copy('data/'+row[0],'5_JIAZHUANG') <file_sep># -*- coding: utf-8 -*- import os def listdir(path, list_name): for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append(file_path[9:]) print(list_name) listdir('data_ext/',[]) <file_sep># KerasBase_Cloud_Recognition Recognize Clouds for five classes with keras base neural network. <file_sep># import the necessary packages from keras.models import Sequential from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.layers.core import Activation from keras.layers.core import Flatten from keras.layers.core import Dropout from keras.layers.core import Dense from keras import backend as K class CNN: @staticmethod def build(width, height, depth, classes): # initialize the model along with the input shape to be # "channels last" and the channels dimension itself model = Sequential() inputShape = (height, width, depth) chanDim = -1 # if we are using "channels first", update the input shape # and channels dimension if K.image_data_format() == "channels_first": inputShape = (depth, height, width) chanDim = 1 nb_filters = 32 # size of pooling area for max pooling pool_size = (2, 2) # convolution kernel size kernel_size = (3, 3) model = Sequential() """ model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same', input_shape=input_shape)) """ model.add(Conv2D(nb_filters, (kernel_size[0], kernel_size[1]), padding='same', input_shape=inputShape)) # 卷积层1 model.add(Activation('relu')) # 激活层 model.add(Conv2D(nb_filters, (kernel_size[0], kernel_size[1]))) # 卷积层2 model.add(Activation('relu')) # 激活层 model.add(BatchNormalization(axis=chanDim)) model.add(MaxPooling2D(pool_size=pool_size)) # 池化层 model.add(Dropout(0.25)) # 神经元随机失活 model.add(Flatten()) # 拉成一维数据 model.add(Dense(128)) # 全连接层1 model.add(Activation('relu')) # 激活层 model.add(Dropout(0.5)) # 随机失活 model.add(Dense(classes)) # 全连接层2 model.add(Activation('softmax')) # Softmax评分 # return the constructed network architecture return model<file_sep># coding=utf-8 from PIL import Image import os import re ''' 读取目录下的所有图片,并将每个图片调用转换尺寸函数,并将缩小尺寸的每个图片保存到另一个目录下 ''' def fixed_size(infile, width, height, outfile): """按照固定尺寸处理图片""" im = Image.open(infile) #im = im.convert('RGB') out = im.resize((width, height), Image.ANTIALIAS) out.save(outfile) def dirlist(path, allfile): filelist = os.listdir(path) for filename in filelist: filepath = os.path.join(path, filename) if os.path.isdir(filepath): dirlist(filepath, allfile) else: allfile.append(filepath) #print(allfile) return allfile def load_files(rootdir): allfile=dirlist(rootdir,[]) for file in allfile: fixed_size(file, 300, 300, file) print("=========================Convert Finished: " + str(file) + "============================") #dirlist("train/mid/",[]) load_files("test_300300/")
0b1ac9e974916172a7d48777fe55bc571e0a5b66
[ "Markdown", "Python" ]
6
Python
Henry3II/KerasBase_Cloud_Recognition
5cf175e88c914fa48560cb4014a3df3bfe083fe5
c01f5ba4151f835579eb87f9e306f6053a986131
refs/heads/master
<repo_name>danielmititelu/Remi<file_sep>/TestChat/UserControls/MainUC.xaml.cs using Game; using MessageControl; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace UserControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainUC : UserControl { static MainUC _instance; public MainUC() { InitializeComponent(); _instance=this; } private void send_KeyDown(object sender, KeyEventArgs e) { if(e.Key==Key.Enter) { Client.GetInstance().WriteLine("MESSAGE_CHAT:"+send.Text); send.Text=""; } } public void SetText(string message) { this.Dispatcher.Invoke((Action) ( () => { received.AppendText(message+"\n"); received.ScrollToEnd(); } )); } public void AddPlayer(string message) { this.Dispatcher.Invoke((Action) ( () => { listBox1.Items.Clear(); foreach(String user in message.Split(':')) { listBox1.Items.Add(user); } } )); } public void AddRoom(string message) { this.Dispatcher.Invoke((Action) ( () => { rooms.Items.Clear(); if(!message.Equals("")) { foreach(String room in message.Split(':')) { rooms.Items.Add(room); } } } )); } private void NewRoom(object sender, RoutedEventArgs e) { CreateRoom newRoom=new CreateRoom(); newRoom.Owner=MainWindow.GetInstance(); newRoom.ShowDialog(); } private void JoinRoom(object sender, RoutedEventArgs e) { if(!( rooms.SelectedItem==null )) { MainWindow.GetInstance().Switch(new RoomUC(""+rooms.SelectedItem)); Client.GetInstance().WriteLine("JOIN_ROOM:"+rooms.SelectedItem); } } public static MainUC GetInstance() { return _instance; } } } <file_sep>/TestChat/MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using UserControls; namespace Game { /// <summary> /// Interaction logic for Login.xaml /// </summary> public partial class MainWindow : Window { public bool _inGame=false; static MainWindow _instance; public MainWindow() { InitializeComponent(); Switch(new LoginUC()); _instance=this; } public MainWindow(string roomName) { InitializeComponent(); Switch(new RoomUC(roomName)); _instance=this; this.Show(); Client.GetInstance().WriteLine("REJOIN_ROOM:"+roomName); } public void Switch(UserControl content) { this.Content=content; } public void Login() { this.Dispatcher.Invoke((Action) ( () => { this.Content=new MainUC(); } )); } public static MainWindow GetInstance() { return _instance; } public static bool Exists() { if(_instance==null) { return false; } else return true; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if(Client.Exists()) { if(!RoomUC.Exists()) { Client.GetInstance().WriteLine("EXIT_FROM_CHAT:Am iesit din chat server"); } else { Client.GetInstance().WriteLine("EXIT_FROM_CHAT:"+RoomUC.GetInstance().getRoomName()+":"+_inGame); } if(!GameWindow.Exists()) Client.GetInstance().Close(); } } } } <file_sep>/Server/UniqueRandom.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server { class UniqueRandom { private readonly List<int> _currentList; private readonly Random _random=new Random(); public UniqueRandom(IEnumerable<int> seed) { _currentList=new List<int>(seed); } public int Next() { if(_currentList.Count==0) { throw new ApplicationException("No more numbers"); } int i=_random.Next (_currentList.Count); int result=_currentList[i]; _currentList.RemoveAt(i); return result; } public IEnumerable<int> Next14() { for(int i=0 ; i<=13 ;i++ ) { yield return Next(); } } } } <file_sep>/TestChat/GameWindow.xaml.cs using CanvasItems; using Handlers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Threading; using UserControls; namespace Game { /// <summary> /// Interaction logic for Game.xaml /// </summary> public partial class GameWindow : Window { private Point mouseClick; private double canvasLeft; private double canvasTop; bool formatie=false; int[] selectedImages=null; bool drawFromBoard=false; int n=0; public Image temp_img; String client_to_add; private string _roomName; DispatcherTimer timer=new DispatcherTimer(); int time=3; bool etalat=false; static GameWindow _instance; public GameWindow() { InitializeComponent(); _instance=this; this.Show(); timer.Interval=new TimeSpan(0, 0, 1); timer.Tick+=timerTick; } public GameWindow(string roomName) { InitializeComponent(); _instance=this; this.Show(); _roomName=roomName; timer.Interval=new TimeSpan(0, 0, 1); timer.Tick+=timerTick; } private void timerTick(object sender, EventArgs e) { time--; if(time==0) { timer.Stop(); this.Dispatcher.Invoke((Action) ( () => { error.Content=""; } )); } } public static GameWindow GetInstance() { return _instance; } public static bool Exists() { if(_instance==null) return false; else return true; } public void SetText(string message) { this.Dispatcher.Invoke((Action) ( () => { received.AppendText(message+"\n"); received.ScrollToEnd(); } )); } public void ErrorText(string message) { this.Dispatcher.Invoke((Action) ( () => { error.Content=message; time=3; timer.Start(); } )); } public void NewUser(string readData) { this.Dispatcher.Invoke((Action) ( () => { String[] users=readData.Split(':'); player1.Content="[empty]"; player2.Content="[empty]"; player3.Content="[empty]"; player4.Content="[empty]"; int pos=0; for(int i=0 ; i<users.Count() ; i++) { if(users[i].Equals(Client.GetInstance().GetNickname())) { pos=i; } } for(int i=pos ; i<users.Count() ; i++) { if(i==pos) { player1.Content=users[i]; } else if(i==pos+1) { player2.Content=users[i]; } else if(i==pos+2) { player3.Content=users[i]; } else if(i==pos+3) { player4.Content=users[i]; } } for(int i=pos ; i>=0 ; i--) { if(i==pos) { player1.Content=users[i]; } else if(i==pos-1) { player4.Content=users[i]; } else if(i==pos-2) { player3.Content=users[i]; } else if(i==pos-3) { player2.Content=users[i]; } } } )); } private void send_KeyDown(object sender, KeyEventArgs e) { if(e.Key==Key.Enter) { Client.GetInstance().WriteLine("MESSAGE_GAME:"+_roomName+":"+send.Text); send.Text=""; } } private void addImgListeners(Image img) { img.PreviewMouseDown+=myimg_MouseDown; img.PreviewMouseMove+=myimg_MouseMove; img.PreviewMouseUp+=myimg_MouseUp; img.LostMouseCapture+=myimg_LostMouseCapture; } public void RemoveImgListeners(Image img) { img.PreviewMouseDown-=myimg_MouseDown; img.PreviewMouseMove-=myimg_MouseMove; img.PreviewMouseUp-=myimg_MouseUp; img.LostMouseCapture-=myimg_LostMouseCapture; } public void AddEtalonListener(Image img) { img.MouseUp+=etalon_MouseUp; } public void RemoveEtalonListener(Image img) { img.MouseUp-=etalon_MouseUp; } public void AddBoardListener(Image img) { img.MouseDown+=boardMouseDown; } public void RemoveBoardListener(Image img) { img.MouseDown-=boardMouseDown; } private void boardMouseDown(object sender, MouseButtonEventArgs e) { Image selectedPiece=(Image) sender; int index=Pieces.GetInstance().getIndex(selectedPiece); Client.GetInstance().WriteLine("DRAW_FROM_BOARD:"+_roomName+":"+index); } public void etalon_MouseUp(object sender, MouseButtonEventArgs e) { if(temp_img!=null) { Image selectedPiece=(Image) sender; int c=Grid.GetColumn(selectedPiece); int r=Grid.GetRow(selectedPiece); int index=Pieces.GetInstance().getIndex(temp_img); Client.GetInstance().WriteLine("ADD_PIECE:"+r+":"+index+":"+c+":"+client_to_add+":"+_roomName); } } private void myimg_LostMouseCapture(object sender, MouseEventArgs e) { Image selectedPiece=(Image) sender; selectedPiece.ReleaseMouseCapture(); } private void myimg_MouseUp(object sender, MouseButtonEventArgs e) { Image selectedPiece=(Image) sender; mouseClick=e.GetPosition(null); canvasLeft=Canvas.GetLeft(selectedPiece); canvasTop=Canvas.GetTop(selectedPiece); if(canvasLeft<0) { canvasLeft=0; } if(canvasTop<0) { canvasTop=0; } if(canvasLeft>MyTableCanvas.ActualWidth) { canvasLeft=MyTableCanvas.ActualWidth-selectedPiece.ActualWidth; } if(canvasTop>MyTableCanvas.ActualHeight) { canvasTop=MyTableCanvas.ActualHeight-selectedPiece.ActualHeight; } selectedPiece.SetValue(Canvas.LeftProperty, canvasLeft); selectedPiece.SetValue(Canvas.TopProperty, canvasTop); selectedPiece.ReleaseMouseCapture(); if(StackCanvas.IsMouseOver) { if(!( etalon1.Children.Count==0 )&&!etalat) Client.GetInstance().WriteLine("ETALARE:"+_roomName); int index=Pieces.GetInstance().getIndex(selectedPiece); if(!( MyTableCanvas.Children.Count==1 )) Client.GetInstance().WriteLine("PUT_PIECE_ON_BORD:"+index+":"+_roomName+":"+"NotAWinner"); else Client.GetInstance().WriteLine("PUT_PIECE_ON_BORD:"+index+":"+_roomName+":"+"Winner"); } if(etalon1.IsMouseOver) { temp_img=selectedPiece; client_to_add=Client.GetInstance().GetNickname(); } else if(etalon2.IsMouseOver) { temp_img=selectedPiece; client_to_add=(String) player2.Content; } else if(etalon3.IsMouseOver) { client_to_add=(String) player3.Content; temp_img=selectedPiece; } else if(etalon4.IsMouseOver) { client_to_add=(String) player4.Content; temp_img=selectedPiece; } if(formatie) { int index=Pieces.GetInstance().getIndex(selectedPiece); selectedImages[n]=index; n++; if(n==3) { formatie=false; Client.GetInstance().WriteLine("FORMATION:"+selectedImages[0]+":"+selectedImages[1]+":"+selectedImages[2]+":"+Client.GetInstance().GetNickname()+":"+( PieceHandler._row1+1 )+":"+_roomName+":"+drawFromBoard); drawFromBoard=false; } } } private void myimg_MouseMove(object sender, MouseEventArgs e) { Image selectedPiece=(Image) sender; if(selectedPiece.IsMouseCaptured) { Point mouseCurrent=e.GetPosition(null); double Left=mouseCurrent.X-mouseClick.X; double Top=mouseCurrent.Y-mouseClick.Y; mouseClick=e.GetPosition(null); selectedPiece.SetValue(Canvas.LeftProperty, canvasLeft+Left); selectedPiece.SetValue(Canvas.TopProperty, canvasTop+Top); canvasLeft=Canvas.GetLeft(selectedPiece); canvasTop=Canvas.GetTop(selectedPiece); } } private void myimg_MouseDown(object sender, MouseButtonEventArgs e) { Image selectedPiece=(Image) sender; mouseClick=e.GetPosition(null); canvasLeft=Canvas.GetLeft(selectedPiece); canvasTop=Canvas.GetTop(selectedPiece); selectedPiece.CaptureMouse(); } private void DrawButtonClick(object sender, RoutedEventArgs e) { Client.GetInstance().WriteLine("DRAW:"+_roomName); } public void DrawPiece(string readData) { string[] pieces=readData.Split(':'); this.Dispatcher.Invoke((Action) ( () => { foreach(string index in pieces) { Canvas.SetLeft(Pieces.GetInstance().getImage(index), 0); Canvas.SetTop(Pieces.GetInstance().getImage(index), 0); MyTableCanvas.Children.Add(Pieces.GetInstance().getImage(index)); addImgListeners(Pieces.GetInstance().getImage(index)); } } )); } public void RemovePieces(int grid, bool myTable) { String allPieces=null; foreach(Image piece in GetGridAt(grid).Children) { int index=Pieces.GetInstance().getIndex(piece); allPieces=allPieces+":"+index; } if(allPieces!=null ) { this.Dispatcher.Invoke((Action) ( () => { foreach(string index in allPieces.Substring(1).Split(':')) { RemoveImgListeners(Pieces.GetInstance().getImage(index)); RemoveFromMyTable(Pieces.GetInstance().getImage(index)); RemoveChildFromGrid(GetGridAt(grid), Pieces.GetInstance().getImage(index)); } } )); if(myTable) DrawPiece(allPieces.Substring(1)); } } private void FormationButtonClick(object sender, RoutedEventArgs e) { selectedImages=new int[3]; formatie=true; n=0; } public string GetPlayerAt(int p) { string player2a=null; string player3a=null; string player4a=null; this.Dispatcher.Invoke((Action) ( () => { player2a=""+player2.Content; player3a=""+player3.Content; player4a=""+player4.Content; } )); switch(p) { case 2: return player2a; case 3: return player3a; case 4: return player4a; default: return ""; } } public Grid GetGridAt(int p) { switch(p) { case 1: return etalon1; case 2: return etalon2; case 3: return etalon3; case 4: return etalon4; default: return null; } } public void RemoveFromMyTable(Image local_image1) { MyTableCanvas.Children.Remove(local_image1); } public void AddRowToGrid(Grid etalon) { this.Dispatcher.Invoke((Action) ( () => { RowDefinition row=new RowDefinition(); row.Height=GridLength.Auto; etalon.RowDefinitions.Add(row); } )); } public void AddChildToGrid(Grid etalon, Image local_image, int r, int c) { etalon.Children.Add(local_image); Grid.SetRow(local_image, r); Grid.SetColumn(local_image, c); } public void RemoveChildFromGrid(Grid etalon, Image local_image) { etalon.Children.Remove(local_image); } public void SetImageValue(Image local_image, DependencyProperty dependencyProperty, int p) { this.Dispatcher.Invoke((Action) ( () => { local_image.SetValue(dependencyProperty, p); } )); } public Image GetToAdd(Grid etalon, int c, int r) { Image img=null; this.Dispatcher.Invoke((Action) ( () => { img=etalon.Children.Cast<Image>().First(e => Grid.GetRow(e)==r&&Grid.GetColumn(e)==c); } )); return img; } public void MoveRow(Grid etalon, int r) { this.Dispatcher.Invoke((Action) ( () => { foreach(Image i in etalon.Children.Cast<Image>().Where(e => Grid.GetRow(e)==r)) { Grid.SetColumn(i, Grid.GetColumn(i)+1); } } )); } public bool MyTableContains(UIElement element) { bool exists=false; this.Dispatcher.Invoke((Action) ( () => { exists=MyTableCanvas.Children.Contains(element); } )); return exists; } public void SetTurn(string readData) { String[] msg=readData.Split(':'); this.Dispatcher.Invoke((Action) ( () => { if(msg[0].Equals(Client.GetInstance().GetNickname())) { player1Turn.Content="X"; player2Turn.Content=""; player3Turn.Content=""; player4Turn.Content=""; } else if(msg[0].Equals(player2.Content)) { player1Turn.Content=""; player2Turn.Content="X"; player3Turn.Content=""; player4Turn.Content=""; } else if(msg[0].Equals(player3.Content)) { player1Turn.Content=""; player2Turn.Content=""; player3Turn.Content="X"; player4Turn.Content=""; } else if(msg[0].Equals(player4.Content)) { player1Turn.Content=""; player2Turn.Content=""; player3Turn.Content=""; player4Turn.Content="X"; } } )); } public void Etalat(string readData) { this.Dispatcher.Invoke((Action) ( () => { etalat=true; } )); } public void MovePieceToBonus(Image local_image, Grid etalon, string nickname) { etalon.Children.Remove(local_image); if(nickname==player1.Content.ToString()) stack1.Children.Add(local_image); else if(nickname==player2.Content.ToString()) stack2.Children.Add(local_image); else if(nickname==player3.Content.ToString()) stack3.Children.Add(local_image); else if(nickname==player4.Content.ToString()) stack4.Children.Add(local_image); } public void EndGame(string readData) { string[] msg=readData.Split(','); string winner=msg[0].Split(':').ElementAt(0); string scores=msg[0].Substring(msg[0].IndexOf(':')+1); string users=msg[1]; this.Dispatcher.Invoke((Action) ( () => { EndGameWindow endGame=new EndGameWindow(winner, scores, users, _roomName); endGame.Owner=this; endGame.ShowDialog(); } )); } private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { if(Client.Exists()) { if(!MainWindow.Exists()) { Client.GetInstance().WriteLine("EXIT_FROM_GAME:"+_roomName); Client.GetInstance().Close(); } } } private void ButtonQuitGameClick(object sender, RoutedEventArgs e) { this.Close(); } } } <file_sep>/TestChat/MessageControl/MessageReader.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Handlers; using Game; using UserControls; namespace MessageControl { class MessageReader { public static void getMessage() { String message=null; String keyword=null; String readData=null; while(Client.GetInstance().ClientConnected()) { message=Client.GetInstance().ReadLine(); if("".Equals(message.Trim())) continue; if(message.Contains(':')) { keyword=message.Substring(0, message.IndexOf(':')); readData=message.Substring(message.IndexOf(':')+1); } else { keyword=message; readData=""; } switch(keyword) { case "MESSAGE_GAME": GameWindow.GetInstance().SetText(readData); break; case "FORMATION": PieceHandler.AddFormationToCanvas(readData); break; case "DRAW": GameWindow.GetInstance().DrawPiece(readData); break; case "ADD_PIECE": PieceHandler.AddPieceToFormation(readData, false); break; case "ADD_PIECE_ON_FIRST_COL": PieceHandler.AddPieceToFormation(readData, true); break; case "DONT": GameWindow.GetInstance().ErrorText(readData); break; case "PUT_PIECE_ON_BORD": PieceHandler.PutPieceOnBoard(readData); break; case "MESSAGE_CHAT": MainUC.GetInstance().SetText(readData); break; case "NICKNAME_TAKEN": LoginUC.GetInstance().NicknameTaken(); break; case "WELCOME": MainWindow.GetInstance().Login(); break; case "NEW_USER_IN_CHAT": MainUC.GetInstance().AddPlayer(readData); break; case "NEW_USER_IN_GAME": if(GameWindow.Exists()) GameWindow.GetInstance().NewUser(readData); break; case "ALL_USERS_IN_ROOM": RoomUC.GetInstance().AddPlayer(readData); break; case "NEW_ROOM": MainUC.GetInstance().AddRoom(readData); break; case "MESSAGE_ROOM": RoomUC.GetInstance().SetText(readData); break; case "READY": RoomUC.GetInstance().SetReadyStatus(readData); break; case "START_GAME": RoomUC.GetInstance().StartTimer(); break; case "START_SPECTATING_GAME": RoomUC.GetInstance().StartTimer(); break; case "YOUR_TURN": if(GameWindow.Exists()) GameWindow.GetInstance().SetTurn(readData); break; case "REMOVE_PIECES": PieceHandler.RemovePieces(readData); break; case "DRAW_FROM_BOARD": PieceHandler.DrawFromBoard(readData); break; case "ETALARE": GameWindow.GetInstance().Etalat(readData); break; case "WINNER": GameWindow.GetInstance().EndGame(readData); break; default: GameWindow.GetInstance().ErrorText("Error 404:Keyword not found"); break; } } } } } <file_sep>/TestChat/UserControls/RoomUC.xaml.cs using Game; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace UserControls { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class RoomUC : UserControl { private string _roomName; static RoomUC _instance; DispatcherTimer timer; int time=3; public RoomUC() { InitializeComponent(); _instance=this; } public RoomUC(string roomName) { InitializeComponent(); _instance=this; _roomName=roomName; timer=new DispatcherTimer(); timer.Interval=new TimeSpan(0, 0, 1); timer.Tick+=timerTick; } public RoomUC(string roomName, bool spectator) { InitializeComponent(); _instance=this; _roomName=roomName; timer=new DispatcherTimer(); timer.Interval=new TimeSpan(0, 0, 1); timer.Tick+=timerTick; ready.IsEnabled=false; } public void AddPlayer(string message) { this.Dispatcher.Invoke((Action) ( () => { playerList.Items.Clear(); foreach(String user in message.Split(':')) { playerList.Items.Add(user); } } )); } private void QuitRomm(object sender, RoutedEventArgs e) { MainWindow.GetInstance().Switch(new MainUC()); Client.GetInstance().WriteLine("QUIT_ROOM:"+_roomName); _instance=null; } public void SetText(string message) { this.Dispatcher.Invoke((Action) ( () => { received.AppendText(message+"\n"); received.ScrollToEnd(); } )); } private void send_KeyDown(object sender, KeyEventArgs e) { if(e.Key==Key.Enter) { Client.GetInstance().WriteLine("MESSAGE_ROOM:"+_roomName+":"+send.Text); send.Text=""; } } public string getRoomName() { return _roomName; } public static bool Exists() { if(_instance==null) return false; else return true; } private void ReadyButton(object sender, RoutedEventArgs e) { Client.GetInstance().WriteLine("READY:"+_roomName); } public void StartTimer() { timer.Start(); } private void timerTick(object sender, EventArgs e) { if(time>0) { received.Foreground=Brushes.Red; received.AppendText(time+"\n"); time--; } else { timer.Stop(); new GameWindow(_roomName); MainWindow.GetInstance()._inGame=true; MainWindow.GetInstance().Close(); Client.GetInstance().WriteLine("SWITCH_TO_GAME:"+_roomName); } } public void SetReadyStatus(string readData) { string[] msg=readData.Split(':');//nickname-ready int index=0; foreach(String user in playerList.Items) { if(user.Split('-').ElementAt(0)==msg[0]) { index=playerList.Items.IndexOf(user); break; } } this.Dispatcher.Invoke((Action) ( () => { playerList.Items.RemoveAt(index); playerList.Items.Insert(index, msg[0]+"-"+msg[1]); } )); } public static RoomUC GetInstance() { return _instance; } } } <file_sep>/TestChat/Handlers/PieceHandler.cs using CanvasItems; using Game; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace Handlers { class PieceHandler { public static int _row1=-1; public static int _row2=-1; public static int _row3=-1; public static int _row4=-1; public static void AddPieceToFormation(String readData, bool firstRow) { GameWindow.GetInstance().Dispatcher.Invoke((Action) ( () => { String[] msg=readData.Split(':');//clientToAdd:row:imageIndex:column:piecesToTake:nickname int r=Int32.Parse(msg[1]); string piecesToTake=msg[4]; int c; if(firstRow) c=Int32.Parse(msg[3]); else c=Int32.Parse(msg[3])+1; Image local_image=CanvasItems.Pieces.GetInstance().getImage(msg[2]); if(msg[0].Equals(Client.GetInstance().GetNickname())) { AddPiece(GameWindow.GetInstance().GetGridAt(1), local_image, r, c, firstRow, piecesToTake, GameWindow.GetInstance().GetPlayerAt(1), msg[5]); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(2))) { AddPiece(GameWindow.GetInstance().GetGridAt(2), local_image, r, c, firstRow, piecesToTake, GameWindow.GetInstance().GetPlayerAt(2), msg[5]); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(3))) { AddPiece(GameWindow.GetInstance().GetGridAt(3), local_image, r, c, firstRow, piecesToTake, GameWindow.GetInstance().GetPlayerAt(3), msg[5]); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(4))) { AddPiece(GameWindow.GetInstance().GetGridAt(4), local_image, r, c, firstRow, piecesToTake, GameWindow.GetInstance().GetPlayerAt(4), msg[5]); } GameWindow.GetInstance().AddEtalonListener(local_image); GameWindow.GetInstance().temp_img=null; } )); } private static void AddPiece(Grid etalon, Image pieceToAdd, int r, int c, bool first_row, string piecesToTake, string playerToAdd, string nickname) { bool exceptionalCase=false; switch(piecesToTake) { case "0": if(first_row) { Image pieceOnBoard=GameWindow.GetInstance().GetToAdd(etalon, c, r); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard); GameWindow.GetInstance().MoveRow(etalon, r); } else { Image pieceOnBoard=GameWindow.GetInstance().GetToAdd(etalon, c-1, r); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard); } break; case "1": if(first_row) { Image pieceOnBoard=GameWindow.GetInstance().GetToAdd(etalon, c, r); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard); GameWindow.GetInstance().MovePieceToBonus(pieceOnBoard, etalon, nickname); } else { Image pieceOnBoard=GameWindow.GetInstance().GetToAdd(etalon, c-1, r); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard); GameWindow.GetInstance().MovePieceToBonus(pieceOnBoard, etalon, nickname); c=c-1; } break; case "2": Image pieceOnBoard1=GameWindow.GetInstance().GetToAdd(etalon, c-1, r); Image pieceOnBoard2=GameWindow.GetInstance().GetToAdd(etalon, c-2, r); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard1); GameWindow.GetInstance().RemoveEtalonListener(pieceOnBoard2); GameWindow.GetInstance().MovePieceToBonus(pieceOnBoard1, etalon, nickname); GameWindow.GetInstance().MovePieceToBonus(pieceOnBoard2, etalon, nickname); c=c-2; break; case "3": if(GameWindow.GetInstance().MyTableContains(pieceToAdd)) { GameWindow.GetInstance().RemoveImgListeners(pieceToAdd); GameWindow.GetInstance().RemoveFromMyTable(pieceToAdd); } GameWindow.GetInstance().MovePieceToBonus(pieceToAdd, etalon, nickname); exceptionalCase=true; break; } if(GameWindow.GetInstance().MyTableContains(pieceToAdd)) { GameWindow.GetInstance().RemoveImgListeners(pieceToAdd); GameWindow.GetInstance().RemoveFromMyTable(pieceToAdd); } if(!exceptionalCase) GameWindow.GetInstance().AddChildToGrid(etalon, pieceToAdd, r, c); } public static void RemovePieces(string readData) { GameWindow.GetInstance().Dispatcher.Invoke((Action) ( () => { String[] msg=readData.Split(':'); if(msg[0].Equals(Client.GetInstance().GetNickname())) { GameWindow.GetInstance().RemovePieces(1, true); _row1=-1; } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(2))) { _row2=-1; GameWindow.GetInstance().RemovePieces(2, false); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(3))) { _row3=-1; GameWindow.GetInstance().RemovePieces(3, false); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(4))) { _row4=-1; GameWindow.GetInstance().RemovePieces(4, false); } } )); } public static void AddFormationToCanvas(String readData) { GameWindow.GetInstance().Dispatcher.Invoke((Action) ( () => { String[] msg=readData.Split(':'); Image local_image1=CanvasItems.Pieces.GetInstance().getImage(msg[1]); Image local_image2=CanvasItems.Pieces.GetInstance().getImage(msg[2]); Image local_image3=CanvasItems.Pieces.GetInstance().getImage(msg[3]); if(msg[0].Equals(Client.GetInstance().GetNickname())) { GameWindow.GetInstance().RemoveImgListeners(local_image1); GameWindow.GetInstance().RemoveImgListeners(local_image2); GameWindow.GetInstance().RemoveImgListeners(local_image3); GameWindow.GetInstance().RemoveFromMyTable(local_image1); GameWindow.GetInstance().RemoveFromMyTable(local_image2); GameWindow.GetInstance().RemoveFromMyTable(local_image3); _row1++; AddFormation(GameWindow.GetInstance().GetGridAt(1), _row1, local_image1, local_image2, local_image3); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(2))) { _row2++; AddFormation(GameWindow.GetInstance().GetGridAt(2), _row2, local_image1, local_image2, local_image3); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(3))) { _row3++; AddFormation(GameWindow.GetInstance().GetGridAt(3), _row3, local_image1, local_image2, local_image3); } else if(msg[0].Equals(GameWindow.GetInstance().GetPlayerAt(4))) { _row4++; AddFormation(GameWindow.GetInstance().GetGridAt(4), _row4, local_image1, local_image2, local_image3); } GameWindow.GetInstance().AddEtalonListener(local_image1); GameWindow.GetInstance().AddEtalonListener(local_image3); } )); } private static void AddFormation(Grid etalon, int _row, Image local_image1, Image local_image2, Image local_image3) { GameWindow.GetInstance().AddRowToGrid(etalon); GameWindow.GetInstance().AddChildToGrid(etalon, local_image1, _row, 0); GameWindow.GetInstance().AddChildToGrid(etalon, local_image2, _row, 1); GameWindow.GetInstance().AddChildToGrid(etalon, local_image3, _row, 2); } public static void PutPieceOnBoard(string readData) { GameWindow.GetInstance().Dispatcher.Invoke((Action) ( () => { String[] mes=readData.Split(':'); Image piece=CanvasItems.Pieces.GetInstance().getImage(mes[1]); if(mes[0].Equals(Client.GetInstance().GetNickname())) { GameWindow.GetInstance().RemoveImgListeners(piece); GameWindow.GetInstance().RemoveFromMyTable(piece); } GameWindow.GetInstance().StackCanvas.Children.Add(piece); GameWindow.GetInstance().AddBoardListener(piece); } )); } public static void DrawFromBoard(string readData) { GameWindow.GetInstance().Dispatcher.Invoke((Action) ( () => { String[] mes=readData.Split(':'); String allpieces=null; foreach(String i in mes) { if(i.Equals(mes[0])) continue; allpieces=allpieces+":"+i; Image piece=CanvasItems.Pieces.GetInstance().getImage(i); GameWindow.GetInstance().StackCanvas.Children.Remove(piece); GameWindow.GetInstance().RemoveBoardListener(piece); } if(mes[0].Equals(Client.GetInstance().GetNickname())) { GameWindow.GetInstance().DrawPiece(allpieces.Substring(1)); } } )); } } } <file_sep>/Server/Room.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Server { class Room { private String _roomName; private List<User> clientsInRoom=new List<User>(); public UniqueRandom random; public List<string> piecesOnBoard; public Room(string roomName) { _roomName=roomName; } public string getRoomName() { return _roomName; } public void AddClientInRoom(String nickname, TcpClient clientSocket) { clientsInRoom.Add(new User(nickname, clientSocket)); } public List<User> GetClientsInRoom() { return clientsInRoom; } public void EndTurnFor(string nickname) { int index=clientsInRoom.FindIndex(c => c.Nickname==nickname); clientsInRoom.ElementAt(index).MyTurn=false; if(index+1==clientsInRoom.Count()) clientsInRoom.ElementAt(0).MyTurn=true; else clientsInRoom.ElementAt(index+1).MyTurn=true; } public string GetClientTurn() { return clientsInRoom.Single(c=> c.MyTurn==true).Nickname; } public void NextGame() { random=new UniqueRandom(Enumerable.Range(0, 105)); piecesOnBoard=new List<string>(); foreach(User user in clientsInRoom){ user.piecesOnFormations.Clear(); user.piecesOnTable.Clear(); user.formations.Clear(); } } } } <file_sep>/TestChat/UserControls/LoginUC.xaml.cs using Game; using MessageControl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace UserControls { /// <summary> /// Interaction logic for LoginUC.xaml /// </summary> public partial class LoginUC : UserControl{ static LoginUC _instance; public LoginUC() { InitializeComponent(); _instance=this; ipAddress.Text="127.0.0.1"; } private void Button_Click(object sender, RoutedEventArgs e) { connect(ipAddress.Text, nickame.Text); } private void connect(String ipAddress, String nickname) { String ip=ipAddress.Trim(); new Client(ip); Client.GetInstance().SetNickname(nickname); Thread messageReader=new Thread(() => MessageReader.getMessage()); messageReader.SetApartmentState(ApartmentState.STA); messageReader.Name="MessageReader"; messageReader.Start(); Client.GetInstance().WriteLine(nickname); } public void NicknameTaken() { this.Dispatcher.Invoke((Action) ( () => { error.Content="Alege alt nickname"; } )); } public static LoginUC GetInstance() { return _instance; } } } <file_sep>/Server/Pieces.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server { class Pieces { public List<int> pieces=new List<int>(); private static Pieces _instance; public Pieces() { GeneratePieces(); } public void GeneratePieces() { int c=0; int n=1; string zero="0"; for(int i=0 ; i<=105 ; i++) { if(i==52||i==105) { c=0; pieces.Insert(i, 500); continue; } if(i<52) { if(i%13!=0) { n++; } if(i%13==0) { c++; n=1; } } else { if(( i-1 )%13!=0) { n++; } if(( i-1 )%13==0) { c++; n=1; } } if(n<10) { zero="0"; } else { zero=""; } pieces.Insert(i, Int32.Parse(c.ToString()+zero+n.ToString())); } } public static Pieces GetInstance() { if(_instance==null) { _instance=new Pieces(); } return _instance; } } } <file_sep>/Server/HandleClient.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; namespace Server { public class HandleClient { TcpClient clientSocket; String nickname; public HandleClient(TcpClient clientSocket, String nickname) { this.clientSocket=clientSocket; this.nickname=nickname; doChat(); } private void doChat() { NetworkStream networkStream=clientSocket.GetStream(); StreamReader read=new StreamReader(networkStream); String[] msg=null; String message=null; String readData=null; Room room; User user; while(networkStream.CanRead) { message=read.ReadLine(); if(message!=null) { readData=message.Substring(message.IndexOf(':')+1); msg=message.Split(':'); Console.WriteLine("From client- "+nickname+": "+message); switch(msg[0]) { case "MESSAGE_CHAT": MessageSender.Broadcast("MESSAGE_CHAT:", nickname, readData, Server.clientsList); break; case "EXIT_FROM_CHAT": if(!msg[1].Equals("Am iesit din chat server")) { if(msg[2].Equals("false")) { room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.RemoveUser("ALL_USERS_IN_ROOM", nickname, room.GetClientsInRoom()); if(room.GetClientsInRoom().Count==0) { Server.roomList.Remove(room); } MessageSender.AllRooms(Server.roomList, Server.clientsList); } } MessageSender.RemoveUser("NEW_USER_IN_CHAT", nickname, Server.clientsList); break; case "EXIT_FROM_GAME"://roomName room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.RemoveUser("NEW_USER_IN_GAME", nickname, room.GetClientsInRoom()); break; case "SWITCH_TO_GAME"://roomName room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); if(room.GetClientsInRoom().Exists(c => c.Nickname==nickname)) { user=room.GetClientsInRoom().Single(c => c.Nickname==nickname); MessageSender.AllUsers("NEW_USER_IN_GAME", room.GetClientsInRoom(), false); String s=null; foreach(int i in room.random.Next14()) { s=s+":"+i; user.piecesOnTable.Add(i.ToString()); } MessageSender.MsgtoClient(nickname, "DRAW"+s, room.GetClientsInRoom()); MessageSender.Broadcast("YOUR_TURN:", room.GetClientsInRoom().ElementAt(0).Nickname, "end", room.GetClientsInRoom()); if(room.GetClientsInRoom().ElementAt(0).Nickname==nickname) { int index=room.random.Next(); MessageSender.MsgtoClient(nickname, "DRAW:"+index, room.GetClientsInRoom()); user.piecesOnTable.Add(index.ToString()); user.MyTurn=true; } } break; case "FORMATION"://piece1:piece2:piece3:nickname:row+1:roomName room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[6])); user=room.GetClientsInRoom().Single(c => c.Nickname==nickname); if(user.MyTurn) HandleFormations.Formatie(msg[1], msg[2], msg[3], msg[4], msg[5], msg[6]); else MessageSender.MsgtoClient(nickname, "DONT:Nu e tura ta!", room.GetClientsInRoom()); break; case "MESSAGE_GAME"://roomName:message room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.Broadcast("MESSAGE_GAME:", nickname, msg[2], room.GetClientsInRoom()); break; case "ADD_PIECE"://row:imageIndex:column:clientToAdd:roomName room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[5])); user=room.GetClientsInRoom().Single(c => c.Nickname==nickname); bool takePiece=true; if(user.MyTurn&&user.Etalat) {// TODO:resolve bug if(msg[4]==nickname) takePiece=false; HandleFormations.AddPiece(msg[1], msg[2], msg[3], msg[4], nickname, msg[5], takePiece); } else if(!user.MyTurn) MessageSender.MsgtoClient(nickname, "DONT:Nu e tura ta!", room.GetClientsInRoom()); else if(!user.Etalat) MessageSender.MsgtoClient(nickname, "DONT:nu te-ai etalat inca!", room.GetClientsInRoom()); break; case "DRAW"://roomName room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); user=room.GetClientsInRoom().Single(c => c.Nickname==nickname); if(user.FirstDraw&&user.MyTurn) { int index=room.random.Next(); MessageSender.MsgtoClient(nickname, "DRAW:"+index, room.GetClientsInRoom()); user.FirstDraw=false; user.piecesOnTable.Add(index.ToString()); } else if(!user.MyTurn) MessageSender.MsgtoClient(nickname, "DONT:Nu e tura ta!", room.GetClientsInRoom()); else if(!user.FirstDraw) MessageSender.MsgtoClient(nickname, "DONT:Ai tras deja!", room.GetClientsInRoom()); break; case "PUT_PIECE_ON_BORD"://index:roomName:winner room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[2])); user=room.GetClientsInRoom().Single(c => c.Nickname==nickname); if(!user.FirstDraw&&user.MyTurn) { if(msg[3]=="NotAWinner") { room.piecesOnBoard.Add(msg[1]); user.piecesOnTable.Remove(msg[1]); MessageSender.Broadcast("PUT_PIECE_ON_BORD:", nickname, msg[1], room.GetClientsInRoom()); room.EndTurnFor(nickname); MessageSender.Broadcast("YOUR_TURN:", room.GetClientTurn(), "end", room.GetClientsInRoom()); room.GetClientsInRoom().Single(c => c.Nickname==room.GetClientTurn()).FirstDraw=true; room.GetClientsInRoom().Single(c => c.Nickname==room.GetClientTurn()).MyTurn=true; } else { user.Winner=true; string points=null; string nicknames=null; foreach(User u in room.GetClientsInRoom()) { points=points+":"+u.Score; nicknames=nicknames+":"+u.Nickname; } MessageSender.Broadcast("WINNER:", nickname, points.Substring(1)+","+nicknames.Substring(1), room.GetClientsInRoom()); } } else if(!user.MyTurn) MessageSender.MsgtoClient(nickname, "DONT:Nu e tura ta!", room.GetClientsInRoom()); else if(user.FirstDraw) MessageSender.MsgtoClient(nickname, "DONT:Trage o piesa mai intai!", room.GetClientsInRoom()); break; case "CREATE_ROOM": MessageSender.RemoveUser("NEW_USER_IN_CHAT", nickname, Server.clientsList); Server.roomList.Add(new Room(msg[1])); room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); room.AddClientInRoom(nickname, clientSocket); MessageSender.AllUsers("ALL_USERS_IN_ROOM", room.GetClientsInRoom(), true); MessageSender.AllRooms(Server.roomList, Server.clientsList); break; case "QUIT_ROOM": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.RemoveUser("ALL_USERS_IN_ROOM", nickname, room.GetClientsInRoom()); if(room.GetClientsInRoom().Count==0) { Server.roomList.Remove(room); } Server.clientsList.Add(new User(nickname, clientSocket)); MessageSender.AllRooms(Server.roomList, Server.clientsList); MessageSender.AllUsers("NEW_USER_IN_CHAT", Server.clientsList, false); break; case "JOIN_ROOM": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.RemoveUser("NEW_USER_IN_CHAT", nickname, Server.clientsList); room.AddClientInRoom(nickname, clientSocket); MessageSender.AllUsers("ALL_USERS_IN_ROOM", room.GetClientsInRoom(), true); break; case "REJOIN_ROOM": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); foreach(User u in room.GetClientsInRoom()) u.Ready=false; MessageSender.AllUsers("ALL_USERS_IN_ROOM", room.GetClientsInRoom(), true); break; case "MESSAGE_ROOM": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); MessageSender.Broadcast("MESSAGE_ROOM:", nickname, msg[2], room.GetClientsInRoom()); break; case "READY": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); user.Ready=!user.Ready; MessageSender.Broadcast("READY:", nickname, ""+user.Ready, room.GetClientsInRoom()); if(room.GetClientsInRoom().All(u => u.Ready==true)) { MessageSender.Broadcast("START_GAME:", nickname, "start", room.GetClientsInRoom()); room.NextGame(); } break; case "ETALARE": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); if(user.formations.Exists(u => u.Split(':').ElementAt(0).Equals("1"))&& user.formations.Exists(u => u.Split(':').ElementAt(0).Equals("2"))&& user.ScoreOnFormation()>=45) { MessageSender.MsgtoClient(nickname, "ETALARE:you may", room.GetClientsInRoom()); user.Etalat=true; } else { user.formations.Clear(); user.piecesOnFormations.Clear(); MessageSender.Broadcast("REMOVE_PIECES:", nickname, "all", room.GetClientsInRoom()); } break; case "REMOVE_PIECES": room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); user.formations.Clear(); user.piecesOnFormations.Clear(); MessageSender.Broadcast("REMOVE_PIECES:", nickname, "all", room.GetClientsInRoom()); break; case "DRAW_FROM_BOARD"://roomName:index room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(msg[1])); user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); if(user.FirstDraw&&user.MyTurn&&user.Etalat) { List<string> allPieces=room.piecesOnBoard.FindAll(i => room.piecesOnBoard.IndexOf(i)>=room.piecesOnBoard.IndexOf(msg[2])).ToList(); String all=null; foreach(string i in allPieces) { all=all+":"+i; room.piecesOnBoard.Remove(i); } MessageSender.Broadcast("DRAW_FROM_BOARD:", nickname, all.Substring(1), room.GetClientsInRoom()); user.FirstDraw=false; } else if(!user.MyTurn) MessageSender.MsgtoClient(nickname, "DONT:Nu e tura ta!", room.GetClientsInRoom()); else if(!user.FirstDraw) MessageSender.MsgtoClient(nickname, "DONT:Ai tras deja!", room.GetClientsInRoom()); else if(!user.Etalat) MessageSender.MsgtoClient(nickname, "DONT:Nu te-ai etalat inca!", room.GetClientsInRoom()); break; default: Console.WriteLine("Error 404: Keyword not found"); break; } } } } } } <file_sep>/TestChat/UserControls/EndGameWindow.xaml.cs using Game; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace UserControls { /// <summary> /// Interaction logic for MenuWindow.xaml /// </summary> public partial class EndGameWindow : Window { private string _roomName; public EndGameWindow() { InitializeComponent(); } public EndGameWindow(string winner, string scores, string users,string roomName) { InitializeComponent(); _roomName=roomName; string[] user = users.Split(':'); string[] scor = scores.Split(':'); int i=0; foreach(var u in user.Zip(scor,Tuple.Create)){ RowDefinition row=new RowDefinition(); row.Height=GridLength.Auto; scoreBoard.RowDefinitions.Add(row); Label nicknameLabel=new Label(); nicknameLabel.Content=u.Item1; scoreBoard.Children.Add(nicknameLabel); Grid.SetRow(nicknameLabel, i); Grid.SetColumn(nicknameLabel, 0); Label scoreLabel=new Label(); scoreLabel.Content=u.Item2; scoreBoard.Children.Add(scoreLabel); Grid.SetRow(scoreLabel, i); Grid.SetColumn(scoreLabel, 1); i++; } } private void PlayAgainButtonClick(object sender, RoutedEventArgs e) { new MainWindow(_roomName); this.Close(); GameWindow.GetInstance().Close(); } } } <file_sep>/Server/User.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Server { class User { String _nickname; TcpClient _clientSocket; StreamWriter write=null; public List<string> formations=new List<String>(); public List<string> piecesOnFormations=new List<string>(); public List<string> piecesOnTable=new List<string>(); int _score=0; bool _ready=false; bool _myTurn=false; bool _firstDraw=false; bool _etalat=false; bool _winner=false; public User(String nickname, TcpClient clientSocket) { _nickname=nickname; _clientSocket=clientSocket; write=new StreamWriter(_clientSocket.GetStream()); } public string Nickname { get { return _nickname; } set { _nickname=value; } } public TcpClient Client { get { return _clientSocket; } set { _clientSocket=value; } } public bool Ready { get { return _ready; } set { _ready=value; } } public bool MyTurn { get { return _myTurn; } set { _myTurn=value; } } public bool FirstDraw { get { return _firstDraw; } set { _firstDraw=value; } } public bool Etalat { get { return _etalat; } set { _etalat=value; } } public bool Winner { get { return _winner; } set { _winner=value; } } public int Score { get { return CalculatePoints(); } set { _score=value; } } public int CalculatePoints() { int points=0; foreach(String index in piecesOnFormations) { int piece=Pieces.GetInstance().pieces[Int32.Parse(index)]; int number=Int32.Parse(piece.ToString().Substring(1, 2)); if(number==1) points=points+25; else if(number==0) points=points+50; else if(number<10) points=points+5; else if(number>=10) points=points+10; } if(_etalat||_winner) { if(_winner) { points=points+100; } else { foreach(String index in piecesOnTable) { int piece=Pieces.GetInstance().pieces[Int32.Parse(index)]; int number=Int32.Parse(piece.ToString().Substring(1, 2)); if(number==1) points=points-25; else if(number==0) points=points-50; else if(number<10) points=points-5; else if(number>=10) points=points-10; } } } else points=-100; _score=points; return _score; } public int ScoreOnFormation() { int points=0; foreach(String index in piecesOnFormations) { int piece=Pieces.GetInstance().pieces[Int32.Parse(index)]; int number=Int32.Parse(piece.ToString().Substring(1, 2)); if(number==1) points=points+25; else if(number==0) points=points+50; else if(number<10) points=points+5; else if(number>=10) points=points+10; } return points; } public void WriteLine(String message) { write.WriteLine(message); write.Flush(); } } } <file_sep>/Server/Server.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Server { class Server { public static List<User> clientsList=new List<User>(); public static List<Room> roomList=new List<Room>(); public Server() { TcpClient client=null; String nickname=null; StreamReader read; TcpListener server=new TcpListener(IPAddress.Any, 5150); Console.WriteLine("Chat server started"); server.Start(); while(true) { if(server.Pending()) { client=server.AcceptTcpClient(); read=new StreamReader(client.GetStream()); nickname=read.ReadLine(); if(clientsList.Exists(c=> c.Nickname==nickname)) { StreamWriter write=null; write=new StreamWriter(client.GetStream()); write.WriteLine("NICKNAME_TAKEN:"+nickname); write.Flush(); Console.WriteLine("Client "+nickname+" already exists"); } else { clientsList.Add(new User(nickname, client)); Thread chatThread=new Thread(() => ConnectToChat(client, nickname)); chatThread.Start(); MessageSender.MsgtoClient(nickname, "WELCOME:"+nickname, clientsList); Console.WriteLine("A new client has connected to chat "+nickname); MessageSender.AllUsers("NEW_USER_IN_CHAT", clientsList,false); MessageSender.AllRooms(roomList,clientsList); } } } } private void ConnectToChat(TcpClient client, string nickname) { new HandleClient(client, nickname); } static void Main(string[] args) { new Server(); } } } <file_sep>/TestChat/CanvasItems/Pieces.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Imaging; namespace CanvasItems { class Pieces { private static Pieces _instance; List<Image> image=new List<Image>(); List<CroppedBitmap> objImg=new List<CroppedBitmap>(); double scale=2; public Pieces() { _instance=this; CutImage(); LoadImage(); } private void CutImage() { BitmapImage src=new BitmapImage(); src.BeginInit(); src.UriSource=new Uri("pack://application:,,,/Image/Tiles.png", UriKind.Absolute); src.CacheOption=BitmapCacheOption.OnLoad; src.EndInit(); for(int i=0 ; i<5 ; i++) for(int j=0 ; j<13 ; j++) objImg.Add(new CroppedBitmap(src, new Int32Rect(j*32, i*48, 32, 48))); } private void LoadImage() { for(int i=0 ; i<106 ; i++) { if(i<53) { image.Add(new Image()); image[i].Source=objImg[i]; image[i].Width=objImg[i].Width*scale; image[i].Height=objImg[i].Height*scale; } else { image.Add(new Image()); image[i].Source=objImg[i-53]; image[i].Width=objImg[i-53].Width*scale; image[i].Height=objImg[i-53].Height*scale; } } } public Image getImage(String s) { int i=Int32.Parse(s); return image[i]; } public int getIndex(Image piece) { return image.IndexOf(piece); } public static Pieces GetInstance() { if(_instance==null) _instance=new Pieces(); return _instance; } } } <file_sep>/Server/MessageSender.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Server { class MessageSender { public static void Broadcast(String keyword, String nickname, String msg, List<User> userList) { foreach(User user in userList) { if(msg.Trim()==""||(TcpClient) user.Client==null) continue; user.WriteLine(keyword+nickname+":"+msg); Console.WriteLine(keyword+nickname+":"+msg); } } public static void AllUsers(string keyword, List<User> userList, bool room) { String allNicknames=null; foreach(User item in userList) { if(room) allNicknames=allNicknames+":"+item.Nickname+"-"+item.Ready; else allNicknames=allNicknames+":"+item.Nickname; } foreach(User user in userList) { user.WriteLine(keyword+allNicknames); } } public static void RemoveUser(string keyword, string nickname, List<User> userList) { if(userList.Exists(c => c.Nickname==nickname)) { userList.Remove(userList.Single(c => c.Nickname==nickname)); AllUsers(keyword, userList,false); } } public static void MsgtoClient(String nickname, String msg, List<User> userList) { if(userList.Exists(c => c.Nickname==nickname)) { userList.Single(c => c.Nickname==nickname).WriteLine(msg); } } public static void AllRooms(List<Room> roomsList, List<User> userList) { String allRooms=null; foreach(Room room in roomsList) { allRooms=allRooms+":"+room.getRoomName(); } foreach(User user in userList) { user.WriteLine("NEW_ROOM"+allRooms); } Console.WriteLine("Camere create"+allRooms); } } } <file_sep>/Server/HandleFormations.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Server { class HandleFormations { public static void Formatie(String msg1, String msg2, String msg3, String nickname, String row, String roomName) { Room room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(roomName)); User user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); int a=Pieces.GetInstance().pieces[Int32.Parse(msg1)]; int b=Pieces.GetInstance().pieces[Int32.Parse(msg2)]; int c=Pieces.GetInstance().pieces[Int32.Parse(msg3)]; Console.WriteLine(a+":"+b+":"+c+":"+nickname+":"+row); String res=testeaza(a, b, c, user, row); if(res.Equals("Nu este o formatie")) { MessageSender.MsgtoClient(nickname, "DONT:"+res, room.GetClientsInRoom()); } else { MessageSender.Broadcast("FORMATION:", nickname, msg1+":"+msg2+":"+msg3, room.GetClientsInRoom()); user.piecesOnFormations.Add(msg1); user.piecesOnFormations.Add(msg2); user.piecesOnFormations.Add(msg3); user.piecesOnTable.Remove(msg1); user.piecesOnTable.Remove(msg2); user.piecesOnTable.Remove(msg3); } Console.WriteLine(res); } private static string testeaza(int a, int b, int c, User user, String row) { if(testInitialNum(a, b)&&testFinalNum(b, c)&&testIntNum(a, c)) { user.formations.Add(numCode(a, b, c, row)); return "formatie"; } else if(testPereche(a, b)&&testPereche(b, c)&&testPereche(a, c)) { user.formations.Add(missingPiece(a, b, c, row)); return "formatie"; } else { return "Nu este o formatie"; } } private static string numCode(int a, int b, int c, String row) { if(a==500&&c==500) { a=b-1; c=b+1; } else if(c==500) { if(b.ToString().Substring(1, 2).Equals("13")) c=b-12; else c=a+2; } else if(a==500) { a=b-1; } return "1:"+a+":"+c+":"+row; } private static string missingPiece(int a, int b, int c, String row) { int a1=Int32.Parse(a.ToString().Substring(0, 1)); int b1=Int32.Parse(b.ToString().Substring(0, 1)); int c1=Int32.Parse(c.ToString().Substring(0, 1)); var list=new List<int>(new[] { 1, 2, 3, 4, 5 }); var result=list.Except(new[] { a1, b1, c1 }); int color1=result.ElementAt(0); int color2=result.ElementAt(1); String number=a.ToString().Substring(1, 2); if(number=="00") { number=b.ToString().Substring(1, 2); } if(number=="00") { number=c.ToString().Substring(1, 2); } return "2:"+color1+number+":"+color2+number+":"+row; } public static bool testInitialNum(int a, int b) { if(a==500&&( b==101||b==201||b==301||b==401 )) { return false; } else if(( b-a )==1||a==500||b==500) { return true; } else { return false; } } public static bool testFinalNum(int a, int b) { if(( b-a )==1||( a-b )==12||a==500||b==500) { return true; } else { return false; } } public static bool testIntNum(int a, int b) {// 11 12 13 if(( b-a )==2||a==500||b==500||( a-b )==11) { return true; } else { return false; } } public static bool testPereche(int a, int b) { if(Math.Abs(a-b)==100||Math.Abs(a-b)==200||Math.Abs(a-b)==300||a==500||b==500) { return true; } else { return false; } } public static void AddPiece(string row, string imageIndex, string column, string clientToAdd, string nickname, string roomName, bool takePiece) { Room room=Server.roomList.Cast<Room>().Single(r => r.getRoomName().Equals(roomName)); User userToAdd=room.GetClientsInRoom().Single(u => u.Nickname==clientToAdd); User user=room.GetClientsInRoom().Single(u => u.Nickname==nickname); String formationCod=userToAdd.formations.Cast<String>().First(e => e.Split(':').ElementAt(3).Equals(row)); string[] s=formationCod.Split(':');//1:404:406:row string formationType=s[0]; int firstPiece=Int32.Parse(s[1]); int pieceAfterFirst=firstPiece+1; int lastPiece=Int32.Parse(s[2]); int pieceBeforeLast=lastPiece-1; int pieceToAdd=Pieces.GetInstance().pieces[Int32.Parse(imageIndex)]; if(formationType.Equals("1")) {//numaratoare if(testInitialNum(pieceToAdd, firstPiece)//pieceToAdd:firstPiece:pieceAfterFirst &&testIntNum(pieceToAdd, pieceAfterFirst) &&column.Equals("0")) { MessageSender.Broadcast("ADD_PIECE_ON_FIRST_COL:", clientToAdd, row+":"+imageIndex+":"+column+":"+GetPieceNumberFirst(pieceToAdd, firstPiece, takePiece)+":"+nickname, room.GetClientsInRoom()); int index=userToAdd.formations.IndexOf(formationCod); userToAdd.formations[index]=formationType+":"+pieceToAdd+":"+lastPiece+":"+row; user.piecesOnFormations.Add(imageIndex); user.piecesOnTable.Remove(imageIndex); } else if(testFinalNum(lastPiece, pieceToAdd)//pieceBeforeLast:lastPiece:pieceToAdd &&testIntNum(pieceBeforeLast, pieceToAdd) &&!( pieceBeforeLast==100||pieceBeforeLast==200||pieceBeforeLast==300||pieceBeforeLast==400 ) &&!column.Equals("0")) { MessageSender.Broadcast("ADD_PIECE:", clientToAdd, row+":"+imageIndex+":"+column+":"+GetPieceNumber(lastPiece, pieceToAdd, takePiece)+":"+nickname, room.GetClientsInRoom()); int index=userToAdd.formations.IndexOf(formationCod); userToAdd.formations[index]=formationType+":"+firstPiece+":"+pieceToAdd+":"+row; user.piecesOnFormations.Add(imageIndex); user.piecesOnTable.Remove(imageIndex); } else { MessageSender.MsgtoClient(nickname, "DONT:Nu se lipeste!", room.GetClientsInRoom()); } } else if(formationType.Equals("2")) {//pereche if(pieceToAdd==firstPiece||pieceToAdd==lastPiece) { MessageSender.Broadcast("ADD_PIECE:", clientToAdd, row+":"+imageIndex+":"+column+":"+0+":"+nickname, room.GetClientsInRoom()); int index=userToAdd.formations.IndexOf(formationCod); userToAdd.formations[index]=formationType+":0:0:"+row; user.piecesOnFormations.Add(imageIndex); user.piecesOnTable.Remove(imageIndex); } else { MessageSender.MsgtoClient(nickname, "DONT:Nu se lipeste!", room.GetClientsInRoom()); } } } private static string GetPieceNumberFirst(int pieceToAdd, int firstPiece, bool takePiece) { int firstPieceNumber=Int32.Parse(firstPiece.ToString().Substring(1)); int pieceToAddNumber=Int32.Parse(pieceToAdd.ToString().Substring(1));//1 2 3 4 5 6 7 8 9 10 11 12 13 1 if(!takePiece) return "0"; if(firstPieceNumber+pieceToAddNumber==19) return "1"; else if(firstPieceNumber+pieceToAddNumber==3) return "3"; else return "1"; } private static string GetPieceNumber(int lastPiece, int pieceToAdd, bool takePiece) { int lastPieceNumber=Int32.Parse(lastPiece.ToString().Substring(1)); int pieceToAddNumber=Int32.Parse(pieceToAdd.ToString().Substring(1)); if(!takePiece) return "0"; else if(lastPieceNumber+pieceToAddNumber==19) return "2"; else if(lastPieceNumber+pieceToAddNumber==14) return "3"; else return "1"; } } } <file_sep>/TestChat/Client.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Game { public class Client { static Client _instance; TcpClient _tcpClient=new TcpClient(); NetworkStream _serverStream=default(NetworkStream); StreamWriter _writer=null; StreamReader _reader=null; string _nickName=null; public Client(String ip) { _tcpClient.Connect(ip, 5150); _serverStream=_tcpClient.GetStream(); _writer=new StreamWriter(_serverStream); _reader=new StreamReader(_serverStream); _instance=this; } public void WriteLine(String message) { _writer.WriteLine(message); _writer.Flush(); } public void Close() { _tcpClient.Close(); _serverStream.Close(); _writer.Close(); _reader.Close(); } public string ReadLine() { try { return _reader.ReadLine(); } catch(Exception e) { Console.WriteLine(e.StackTrace); } return ""; } public bool ClientConnected() { return _tcpClient.Connected; } public static Client GetInstance() { return _instance; } public static bool Exists() { if(_instance==null) return false; else return true; } public void SetNickname(string name) { _nickName=name; } public string GetNickname() { return _nickName; } } }
0c4fa2cdd47850f6cc0e80c1fef0644c1dfc83d2
[ "C#" ]
18
C#
danielmititelu/Remi
d25f4a75976d06f8c64be6908e5e412e64e6507e
2178035238bdb6dd0d3ba5ae1a16741d7d18c346
refs/heads/master
<file_sep>'use strict'; (function () { var random = function (wizardProperty) { return wizardProperty[Math.floor(Math.random() * wizardProperty.length)]; }; var shufle = function (array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // Пока есть элементы для перетасовки... while (currentIndex !== 0) { // Выбрать оставшийся элемент... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // И поменять его местами с текущим элементом. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; window.util = { random: random, shufle: shufle }; })(); <file_sep>'use strict'; (function () { var CLOUD_WIDTH = 420; var CLOUD_HEIGHT = 270; var CLOUD_X = 100; var CLOUD_Y = 10; var GAP = 10; var FONT_GAP = 30; var PREVIEW_GAP = 20; var BAR_HEIGHT = 130; var BAR_WIDTH = 40; var BAR_GAP = 50; var renderCloud = function (ctx, x, y, color) { ctx.fillStyle = color; ctx.fillRect(x, y, CLOUD_WIDTH, CLOUD_HEIGHT); }; var getMaxElement = function (arr) { var maxElement = arr[0]; for (var i = 0; i < arr.length; i++) { if (arr[i] > maxElement) { maxElement = arr[i]; } } return maxElement; }; window.renderStatistics = function (ctx, players, times) { var cloudxWithBarGup = CLOUD_X + BAR_GAP; var cloudyWithCloudHeight = CLOUD_Y + CLOUD_HEIGHT; var maxTime = getMaxElement(times); renderCloud(ctx, CLOUD_X + GAP, CLOUD_Y + GAP, 'rgba(0, 0, 0, 0.7)'); renderCloud(ctx, CLOUD_X, CLOUD_Y, '#fff'); ctx.fillStyle = '#000'; ctx.font = '16px PT Mono'; ctx.fillText('Ура вы победили!', CLOUD_X + PREVIEW_GAP, 40); ctx.fillText('Список результатов:', CLOUD_X + PREVIEW_GAP, 60); for (var i = 0; i < players.length; i++) { var barWidthWithBarGup = (BAR_WIDTH + BAR_GAP) * i; var randomSaturation = Math.floor(Math.random() * 100) + '%'; var timesHeight = -(BAR_HEIGHT * times[i]) / maxTime; ctx.fillStyle = players[i] === 'Вы' ? 'rgba(255, 0, 0, 1)' : 'hsl(240, ' + randomSaturation + ', 50%)'; ctx.fillRect(cloudxWithBarGup + barWidthWithBarGup, cloudyWithCloudHeight - BAR_GAP, BAR_WIDTH, timesHeight); ctx.fillStyle = '#000'; ctx.fillText(players[i], cloudxWithBarGup + barWidthWithBarGup, cloudyWithCloudHeight - FONT_GAP); ctx.fillText(Math.round(times[i]), cloudxWithBarGup + barWidthWithBarGup, BAR_HEIGHT + timesHeight + BAR_GAP + (CLOUD_Y + GAP) * 2); } }; })();
a5bf2a7f047bc11bba748760ebdd18559258e7c3
[ "JavaScript" ]
2
JavaScript
Melifaro2405/1345767-code-and-magick-20
c10fb5cb663940b35c8627f68dfa584e09bd3500
9b844925ddd6d1a5a7349b5699f2f2ff688c5776
refs/heads/master
<file_sep>import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.rules.ExpectedException.none; public class StackShould { @Rule public ExpectedException thrown = none(); private Stack stack; @Before public void setUp() throws Exception { stack = new Stack(); } @Test public void throw_exception_if_popped_when_empty() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("you can not pop an empty stack"); stack.pop(); } @Test public void pop_last_pushed_object() { Object pushed = "pushed"; stack.push(pushed); Object popped = stack.pop(); assertThat(popped, is(pushed)); } @Test public void pop_objects_in_reverse_push_order() { Object firstPushed = "first pushed"; Object lastPushed = "last pushed"; stack.push(firstPushed); stack.push(lastPushed); Object poppedFirst = stack.pop(); Object poppedSecond = stack.pop(); assertThat(poppedFirst, is(lastPushed)); assertThat(poppedSecond, is(firstPushed)); } }
69641943ca7ac64b1ff662cf6ba53f1ef6ac8387
[ "Java" ]
1
Java
fergusferguson/StackKata
172bf71571769dbf3daf945ea798bf3398bf3345
361e9a18b1978565e8f73cbf5777a00a40263f7b
refs/heads/master
<repo_name>shiwei924/test01<file_sep>/json_struct/json_struct/json_struct/main.c #include "cJSON_ENCONDING.h" #include <assert.h> int main(int argc, char **argv) { unsigned char *outData = NULL; int outLen = -1; int m= MsgEncode(NULL,60,&outData, &outLen); if(m==0) printf("编码成功\n"); printf("%s\n",outData); printf("%d\n", outLen); MsgKey_Req person; int type = -1; MsgDecode(outData, outLen,&person, &type); /* printf("%d\n",person.seckeyid); printf("%s\n", person.r2); printf("%s\n", person.serverId); printf("%s\n", person.clientId); printf("%d\n", person.rv); */ printf("%d\n", person.cmdType); printf("%s\n", person.r1); printf("%s\n", person.serverId); printf("%s\n", person.clientId); printf("%s\n", person.AuthCode); /* //将数据编码 char *string = create_monitor(); printf("编码成功\n"); //将数据解码 people person; int ret = cJSON_to_struct(string, &person); assert(ret==0);// 为真--不执行; 为假: 中断 // 释放: 编码内部申请堆空间,需要释放。 free(string); */ /* char *outData = NULL; int outLen = -1; create_xiawucha_MsgKey_Req(&outData, &outLen, 60); printf("%d\n",outLen); printf("%s\n", outData); int flag = -1; get_struct(outData, &flag); printf("%d\n",flag); MsgKey_Req person; cJSONMsgKey_Req_to_struct(outData, &person); */ /* char *outData = NULL; int outLen = -1; create_xiawucha_MsgKey_Res(&outData, &outLen, 61); printf("%d\n", outLen); printf("%s\n", outData); int flag = -1; get_struct(outData, &flag); printf("%d\n", flag); MsgKey_Res person; cJSONMsgKey_Res_to_struct(outData, &person); */ return 0; } <file_sep>/json_struct/json_struct/json_struct/cJSON_ENCONDING.c #include "cJSON_ENCONDING.h" #define bit(i) (0x0000<<i) #include <time.h> int create_xiawucha_MsgKey_Req(char **outdata, int * outlen,int type); int cJSONMsgKey_Req_to_struct(char *json_string, MsgKey_Req *person); int create_xiawucha_MsgKey_Res(char **outdata, int * outlen, int type); int cJSONMsgKey_Res_to_struct(char *json_string, MsgKey_Res *person); int get_struct(char *json_string, int * flag); /*---------------------------测试资料----------------------------*/ //cJSON打包1 //创建一个带有受支持决议清单的监视器 char* create_xiawucha_monitor(void) { people person; person.id = 5; strcpy(person.firstName, "hehe"); strcpy(person.lastName, "hehe1"); strcpy(person.email, "<PASSWORD>"); person.height = 12.7; //JSON成员如下: 全定义成 cJSON* 类型 cJSON *xiawucha = NULL; //子对象 cJSON *id = NULL; cJSON *firstName = NULL; cJSON *lastName = NULL; cJSON *email = NULL; cJSON *height = NULL; /////////////////////////////////////////////////////////////// //// 阶段1: 创建对象 //1. 创建总对象句柄 代表 { } cJSON * monitor = cJSON_CreateObject(); if (monitor == NULL) { goto end; } //2. 创建一个子对象: 作为第一个元素的值 xiawucha = cJSON_CreateObject(); if (xiawucha == NULL) { goto end; } //3 为对象添加一个元素: 其值为一个子对象 cJSON_AddItemToObject(monitor, "person", xiawucha); ///////////////////////////////////////////////////////////////////// // 结点二: 开始编码: //1.为子对象添加元素与值: int类型 id = cJSON_CreateNumber(person.id); if (id == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "id", id); //2添加字符串 firstName = cJSON_CreateString(person.firstName); if (firstName == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "firstName", firstName); //3. 添加字符串 lastName = cJSON_CreateString(person.lastName); if (lastName == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "lastName", lastName); //4. 添加字符串 email = cJSON_CreateString(person.email); if (email == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "email", email); //5. 添加double类型 height = cJSON_CreateNumber(person.height); if (height == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "height", height); //最后一步: //上面: 将初始化的数据---添加到--对象中。 //下面: 将对象---转换成要输出的字符串。 char *string = NULL; string = cJSON_Print(monitor);//将总对象---转换成: 字符串 if (string == NULL) { fprintf(stderr, "Failed to print monitor.\n"); } end: //清空对象。//返回输出的字符串: ---也可以使用输出参数。 cJSON_Delete(monitor); return string; } //cJSON打包: //和上面的方式不同---直接填值,可能不方便。 //没有使用链表。 char* create_monitor(void) { //JSON成员如下: 全定义成 cJSON* 类型 cJSON *xiawucha = NULL; //子对象 cJSON *id = NULL; cJSON *firstName = NULL; cJSON *lastName = NULL; cJSON *email = NULL; cJSON *height = NULL; /////////////////////////////////////////////////////////////// //// 阶段1: 创建对象 //1. 创建总对象句柄 代表 { } cJSON *monitor = cJSON_CreateObject(); if (monitor == NULL) { goto end; } //2. 创建一个子对象: 作为第一个元素的值 xiawucha = cJSON_CreateObject(); if (xiawucha == NULL) { goto end; } //3 为对象添加一个元素: 其值为一个子对象 cJSON_AddItemToObject(monitor, "person", xiawucha); ///////////////////////////////////////////////////////////////////// // 结点二: 开始编码: //1.为子对象添加元素与值: int类型 id = cJSON_CreateNumber(5); if (id == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "id", id); //2添加字符串 firstName = cJSON_CreateString("hehe"); if (firstName == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "firstName", firstName); //3. 添加字符串 lastName = cJSON_CreateString("hehe1"); if (lastName == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "lastName", lastName); //4. 添加字符串 email = cJSON_CreateString("hehe2"); if (email == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "email", email); //5. 添加double类型 height = cJSON_CreateNumber(17.6); if (height == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "height", height); //最后一步: //上面: 将初始化的数据---添加到--对象中。 //下面: 将对象---转换成要输出的字符串。 char *string = NULL; string = cJSON_Print(monitor);//将总对象---转换成: 字符串 if (string == NULL) { fprintf(stderr, "Failed to print monitor.\n"); } end: //清空对象。//返回输出的字符串: ---也可以使用输出参数。 cJSON_Delete(monitor); return string; } //首先: 解包 //参数1:打包得到的字符串; //参数2:解析的输出结构体---将获取的值: 赋予结构体成员 int cJSON_to_struct(char *json_string, people *person) { cJSON *item; //1. 将压缩的字符串: 解包成SJSON类型的句柄, 即{} cJSON *root = cJSON_Parse(json_string); if (root == NULL) { printf("Error before0: [%s]\n", cJSON_GetErrorPtr()); return -1; } else { //2. 解包成功,通过句柄获取: 通过键值获取一个元素 // 即: 获取结构体对象 person {} cJSON *object = cJSON_GetObjectItem(root, "person"); if (object == NULL) { printf("Error before1: [%s]\n", cJSON_GetErrorPtr()); cJSON_Delete(root); return -1; } //输出获取元素的: 键值,类型,与值 printf("cJSON_GetObjectItem: type=%d, key is %s, value is %s\n", object->type, object->string, object->valuestring); /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// // 开始获取子对象的成员 if (object != NULL) { //成员1: int 类型id----如果形成链表: 是不是就不用 “id”key值了---直接 // 使用头指针即可了。!!!!!!!!!!!!!!!!!!!! item = cJSON_GetObjectItem(object, "id"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%d\n", item->type, item->string, item->valueint); person->id = item->valueint; } //成员2. 获取结构体成员: firstname strcpy 或 memcpy item = cJSON_GetObjectItem(object, "firstName"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->firstName, item->valuestring, strlen(item->valuestring)); } //成员3: lastname strcpy 或 memcpy item = cJSON_GetObjectItem(object, "lastName"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->lastName, item->valuestring, strlen(item->valuestring)); } //获取成员4. email: strcpy 或 memcpy item = cJSON_GetObjectItem(object, "email"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->email, item->valuestring, strlen(item->valuestring)); } //height成员5. item = cJSON_GetObjectItem(object, "height"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuedouble=%f\n", item->type, item->string, item->valuedouble); person->height = item->valuedouble; } } //销毁成员 cJSON_Delete(root); } return 0; } /*-----------------------------测试阶段结束----------------------------------*/ /*-----------------------------总编码部分--------------------------------------*/ //参数传出参数 /*int MngClient_InitInfo(MngClient_Info * pCltInfo) { strcpy(pCltInfo->clientId, "clientID"); // 客户端编号 strcpy(pCltInfo->AuthCode, "authcode"); // 认证码 strcpy(pCltInfo->serverId, "serverID"); // 服务器端编号 strcpy(pCltInfo->serverip, "127.0.0.1"); ////IP地址 pCltInfo->serverport = 9999; //端口 pCltInfo->maxnode = 1; //共享内存keyid 创建共享内存时使用 pCltInfo->shmkey = ftok("/", 'x'); //共享内存keyid 创建共享内存时使用 // IPC_CreatShm(pCltInfo->shmkey, 100, &pCltInfo->shmhdl); return 0; }*/ // 大小写字符, 数子, 特殊字符: 输入长度--输出获取字符串 void GetRandString(int len, char * buf) { int flag = -1; srand(time(NULL)); char chars[] = "~!@#$%^&*()_+"; for (int i = 0; i < len; ++i) { flag = rand() % 4; switch (flag) { case 0: buf[i] = 'A' + rand() % 26; break; case 1: buf[i] = 'a' + rand() % 26; break; case 2: buf[i] = chars[rand() % strlen(chars)]; break; case 3: buf[i] = '0' + rand() % 10; break; default: break; } } } //总编码 int MsgEncode( void *pStruct, /*输入:结构体*/ int type, /*结构体编号*/ unsigned char **outData, /*out--字符串*/ int *outLen) //输出字符串长度 { //第一步:验证参数的正确性 /*if ( outData == NULL || outLen == NULL) { perror("输入参数无效\n"); return -1; }*/ //接受编码的数据 char *ceshi = NULL; int len = -1; //第二步:判断是哪个结构体 printf("%d\n",type); switch (type) { case ID_MsgKey_Req: printf("我进入了60号\n"); create_xiawucha_MsgKey_Req(&ceshi,&len,type); break; case ID_MsgKey_Res: printf("我进入了61号\n"); create_xiawucha_MsgKey_Res(&ceshi,&len,type); break; default: printf("123243243\n"); return -1; } *outData = ceshi; *outLen = len; return 0; } //总解码 int MsgDecode( unsigned char *inData, /*输入数据*/ int inLen, /*输入数据长度*/ void *pStruct /*out--结构体*/, int *type) /*out结构体编号*/ { //参数验证 if (inData == NULL || inLen <= 0) { return -1; } //获取第一个值: 赋值给输出---在根据其值判断。 int flag = -1; get_struct(inData, &flag); *type = flag; switch (flag) { case ID_MsgKey_Req: cJSONMsgKey_Req_to_struct(inData, (MsgKey_Req *)pStruct); break; case ID_MsgKey_Res: cJSONMsgKey_Res_to_struct(inData, (MsgKey_Res *)pStruct); break; default: break; } return 0; } /*------------------------------总解码部分结束----------------------------------*/ /*-------------------------------结构体部分1--------------------------------------*/ /*typedef struct _MsgKey_Req { //1 密钥协商 //2 密钥校验; //3 密钥注销 int cmdType; //报文类型 char clientId[12]; //客户端编号 char AuthCode[16]; //认证码 char serverId[12]; //服务器端编号 char r1[64]; //客户端随机数 }MsgKey_Req;*/ int create_xiawucha_MsgKey_Req(char **outdata,int * outlen,int type) { MsgKey_Req person; person.cmdType = 1; strcpy(person.clientId, "hehe"); strcpy(person.AuthCode, "<PASSWORD>"); strcpy(person.serverId, "hehe2"); strcpy(person.r1, "hehe2"); //JSON成员如下: 全定义成 cJSON* 类型 cJSON *xiawucha = NULL; //子对象 cJSON *cmdType = NULL; cJSON *clientId = NULL; cJSON *AuthCode = NULL; cJSON *serverId = NULL; cJSON *r1 = NULL; /////////////////////////////////////////////////////////////// //// 阶段1: 创建对象 //1. 创建总对象句柄 代表 { } cJSON * monitor = cJSON_CreateObject(); if (monitor == NULL) { printf("1\n"); goto end; } //2. 创建一个子对象: 作为第一个元素的值 xiawucha = cJSON_CreateObject(); if (xiawucha == NULL) { printf("2\n"); goto end; } //3 为对象添加一个元素: 其值为一个子对象 cJSON_AddItemToObject(monitor, "person", xiawucha); ///////////////////////////////////////////////////////////////////// // 结点二: 开始编码: //添加头--参数输入 cJSON *flag = cJSON_CreateNumber(type); if (flag == NULL) { printf("3\n"); goto end; } cJSON_AddItemToObject(xiawucha, "flag", flag); //1.为子对象添加元素与值: int类型 cmdType = cJSON_CreateNumber(person.cmdType); if (cmdType == NULL) { printf("4\n"); goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "cmdType", cmdType); //2添加字符串 clientId = cJSON_CreateString(person.clientId); if (clientId == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "clientId", clientId); //3. 添加字符串 AuthCode = cJSON_CreateString(person.AuthCode); if (AuthCode == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "AuthCode", AuthCode); //4. 添加字符串 serverId = cJSON_CreateString(person.serverId); if (serverId == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "serverId", serverId); //5. 添加字符串类型 r1= cJSON_CreateString(person.r1); if (r1 == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "r1", r1); //最后一步: //上面: 将初始化的数据---添加到--对象中。 //下面: 将对象---转换成要输出的字符串。 char *string = NULL; string = cJSON_Print(monitor);//将总对象---转换成: 字符串 if (string == NULL) { fprintf(stderr, "Failed to print monitor.\n"); } *outlen = strlen(string); *outdata = string; end: //清空对象。//返回输出的字符串: ---也可以使用输出参数。 cJSON_Delete(monitor); return 0; } int cJSONMsgKey_Req_to_struct(char *json_string, MsgKey_Req *person) { cJSON *item; //1. 将压缩的字符串: 解包成SJSON类型的句柄, 即{} cJSON *root = cJSON_Parse(json_string); if (root == NULL) { printf("Error before0: [%s]\n", cJSON_GetErrorPtr()); return -1; } else { //2. 解包成功,通过句柄获取: 通过键值获取一个元素 // 即: 获取结构体对象 person {} cJSON *object = cJSON_GetObjectItem(root, "person"); if (object == NULL) { printf("Error before1: [%s]\n", cJSON_GetErrorPtr()); cJSON_Delete(root); return -1; } //输出获取元素的: 键值,类型,与值 //printf("cJSON_GetObjectItem: type=%d, key is %s, value is %s\n", object->type, object->string, object->valuestring); /////////////////////////////////////////////////////////////////////////////////////////////////// /////阶段二: 开始获取子对象的成员 int直接赋值, char* 使用 strcpy 或 memset if (object != NULL) { //成员1: int 类型id----如果形成链表: 是不是就不用 “id”key值了---直接 // 使用头指针即可了。!!!!!!!!!!!!!!!!!!!! item = cJSON_GetObjectItem(object, "cmdType"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%d\n", item->type, item->string, item->valueint); person->cmdType = item->valueint; } //成员2. 获取结构体成员: firstname strcpy 或 memcpy item = cJSON_GetObjectItem(object, "clientId"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->clientId,item->valuestring, strlen(item->valuestring)+1); } //成员3: lastname strcpy 或 memcpy item = cJSON_GetObjectItem(object, "AuthCode"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->AuthCode, item->valuestring, strlen(item->valuestring)+1); } //获取成员4. email: strcpy 或 memcpy item = cJSON_GetObjectItem(object, "serverId"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->serverId, item->valuestring, strlen(item->valuestring)+1); } //获取成员5 r1 item = cJSON_GetObjectItem(object, "r1"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->r1, item->valuestring, strlen(item->valuestring)+1); } } //销毁成员 cJSON_Delete(root); } return 0; } /*------------------------------结构体结束1-------------------------------------*/ /*-----------------------------结构体部分2--------------------------------------*/ /*typedef struct _MsgKey_Res { int rv; //返回值 char clientId[12]; //客户端编号 char serverId[12]; //服务器编号 unsigned char r2[64]; //服务器端随机数 int seckeyid; //对称密钥编号 keysn }MsgKey_Res;*/ int create_xiawucha_MsgKey_Res(char **outdata, int * outlen,int type) { MsgKey_Res person; person.rv = 1; strcpy(person.clientId, "hehe"); strcpy(person.serverId, "hehe2"); strcpy(person.r2,"hehe2"); person.seckeyid = 1; //JSON成员如下: 全定义成 cJSON* 类型 cJSON *xiawucha = NULL; //子对象 cJSON *rv = NULL; cJSON *clientId = NULL; cJSON *serverId = NULL; cJSON *r2 = NULL; cJSON *seckeyid = NULL; /////////////////////////////////////////////////////////////// //// 阶段1: 创建对象 //1. 创建总对象句柄 代表 { } cJSON * monitor = cJSON_CreateObject(); if (monitor == NULL) { goto end; } //2. 创建一个子对象: 作为第一个元素的值 xiawucha = cJSON_CreateObject(); if (xiawucha == NULL) { goto end; } //3 为对象添加一个元素: 其值为一个子对象 cJSON_AddItemToObject(monitor, "person", xiawucha); ///////////////////////////////////////////////////////////////////// // 结点二: 开始编码: //添加头--参数输入 cJSON *flag = cJSON_CreateNumber(type); if (flag == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "flag", flag); //1.为子对象添加元素与值: int类型 rv = cJSON_CreateNumber(person.rv); if (rv == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "rv", rv); //2添加字符串 clientId = cJSON_CreateString(person.clientId); if (clientId == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "clientId", clientId); //3. 添加字符串 serverId = cJSON_CreateString(person.serverId); if (serverId == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "serverId", serverId); //4. 添加字符串类型 r2 = cJSON_CreateString(person.r2); if (r2 == NULL) { goto end; } cJSON_AddItemToObject(xiawucha,"r2",r2); //5int seckeyid = cJSON_CreateNumber(person.seckeyid); if (rv == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "seckeyid", seckeyid); //最后一步: //上面: 将初始化的数据---添加到--对象中。 //下面: 将对象---转换成要输出的字符串。 char *string = NULL; string = cJSON_Print(monitor);//将总对象---转换成: 字符串 if (string == NULL) { fprintf(stderr, "Failed to print monitor.\n"); } *outlen =strlen(string); *outdata = string; end: //清空对象。//返回输出的字符串: ---也可以使用输出参数。 cJSON_Delete(monitor); return 0; } int cJSONMsgKey_Res_to_struct(char *json_string, MsgKey_Res *person) { cJSON *item; //1. 将压缩的字符串: 解包成SJSON类型的句柄, 即{} cJSON *root = cJSON_Parse(json_string); if (root == NULL) { printf("Error before0: [%s]\n", cJSON_GetErrorPtr()); return -1; } else { //2. 解包成功,通过句柄获取: 通过键值获取一个元素 // 即: 获取结构体对象 person {} cJSON *object = cJSON_GetObjectItem(root, "person"); if (object == NULL) { printf("Error before1: [%s]\n", cJSON_GetErrorPtr()); cJSON_Delete(root); return -1; } //输出获取元素的: 键值,类型,与值 //printf("cJSON_GetObjectItem: type=%d, key is %s, value is %s\n", object->type, object->string, object->valuestring); /////////////////////////////////////////////////////////////////////////////////////////////////// /////阶段二: 开始获取子对象的成员 int直接赋值, char* 使用 strcpy 或 memset if (object != NULL) { //成员1: int 类型----如果形成链表: 是不是就不用 “id”key值了---直接 item = cJSON_GetObjectItem(object, "rv"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%d\n", item->type, item->string, item->valueint); person->rv = item->valueint; } //成员2. 获取结构体成员: strcpy 或 memcpy item = cJSON_GetObjectItem(object, "clientId"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->clientId, item->valuestring, strlen(item->valuestring)+1); } //获取成员3. : strcpy 或 memcpy item = cJSON_GetObjectItem(object, "serverId"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->serverId, item->valuestring, strlen(item->valuestring)+1); } //获取成员4 r2 item = cJSON_GetObjectItem(object, "r2"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(person->r2, item->valuestring, strlen(item->valuestring)+1); } //5 int item = cJSON_GetObjectItem(object, "seckeyid"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%d\n", item->type, item->string, item->valueint); person->seckeyid = item->valueint; } } //销毁成员 cJSON_Delete(root); } return 0; } /*------------------------------结构体结束2-------------------------------------*/ int get_struct(char *json_string,int * flag) { cJSON *item; //1. 将压缩的字符串: 解包成SJSON类型的句柄, 即{} cJSON *root = cJSON_Parse(json_string); if (root == NULL) { printf("Error before0: [%s]\n", cJSON_GetErrorPtr()); return -1; } else { //2. 解包成功,通过句柄获取: 通过键值获取一个元素 // 即: 获取结构体对象 person {} cJSON *object = cJSON_GetObjectItem(root, "person"); if (object == NULL) { printf("Error before1: [%s]\n", cJSON_GetErrorPtr()); cJSON_Delete(root); return -1; } if (object != NULL) { //成员1: int 类型id----如果形成链表: 是不是就不用 “id”key值了---直接 item = cJSON_GetObjectItem(object, "flag"); if (item != NULL) { *flag= item->valueint; printf("获取标志位%d\n",*flag); } } } return 0; } // 异想天开---失败: /* //参数1: 输入的结构体。 参数2: 结构体成员数 参数3: 0x0000 0000 // int =0; string=1 char* create_xiawucha_encoding(MsgKey_Req person, int n, int m) { /////////////////////////////////////////////////////////////// //// 阶段1: 创建对象 //1. 创建总对象句柄 代表 { } cJSON * monitor = cJSON_CreateObject(); if (monitor == NULL) { goto end; } //2. 创建一个子对象: 作为第一个元素的值 cJSON * xiawucha = cJSON_CreateObject(); if (xiawucha == NULL) { goto end; } //3 为对象添加一个元素: 其值为一个子对象 cJSON_AddItemToObject(monitor, "person", xiawucha); person.cmdType = 1; strcpy(person.clientId, "hehe"); strcpy(person.AuthCode, "<PASSWORD>"); strcpy(person.serverId, "hehe2"); strcpy(person.r1, "hehe2"); //JSON成员如下: 全定义成 cJSON* 类型 cJSON *xiawucha_int = NULL; cJSON *xiawucha_string = NULL; cJSON *AuthCode = NULL; cJSON *serverId = NULL; cJSON *r1 = NULL; ///////////////////////////////////////////////////////////////////// // 结点二: 开始编码: for (int i = 0; i < n; i++) { if (m & bit(i) == 0) //int { //1.为子对象添加元素与值: int类型 xiawucha_int = cJSON_CreateNumber(person.cmdType); if (xiawucha_int == NULL) { goto end; } //将数据添加到子项目中 cJSON_AddItemToObject(xiawucha, "xiawucha_int", xiawucha_int); } else // 字符串 { xiawucha_string = cJSON_CreateString(person.AuthCode); if (xiawucha_string == NULL) { goto end; } cJSON_AddItemToObject(xiawucha, "AuthCode", xiawucha_string); } } //最后一步: //上面: 将初始化的数据---添加到--对象中。 //下面: 将对象---转换成要输出的字符串。 char *string = NULL; string = cJSON_Print(monitor);//将总对象---转换成: 字符串 if (string == NULL) { fprintf(stderr, "Failed to print monitor.\n"); } end: //清空对象。//返回输出的字符串: ---也可以使用输出参数。 cJSON_Delete(monitor); return string; }*/ <file_sep>/json_struct/json_struct/json_struct/cJSON_ENCONDING.h #ifndef _cJSON_ENCONDING_ #define _cJSON_ENCONDING_ #include <stdio.h> #include <string.h> #include <sys/types.h> #include <stdlib.h> #include <unistd.h> #include "cJSON.h" /*----------------------------测试部分开始---------------------------*/ typedef struct { int id; char firstName[32]; char lastName[32]; char email[64]; float height; }people; char* create_monitor(void); int cJSON_to_struct(char *json_string, people *person); /*-----------------------------测试部分结束---------------------------*/ /*-----------------------------逻辑部分:编码-------------------------*/ //为了统一:数据赋值--定义一个总的结构体用于初始化数据的 typedef struct _MngClient_Info { char clientId[12]; // 客户端编号 char AuthCode[16]; // 认证码 char serverId[12]; // 服务器端编号 char serverip[32]; int serverport; int maxnode; // 最大网点数 客户端默认1个 int shmkey; // 共享内存keyid 创建共享内存时使用 int shmhdl; // 共享内存句柄 }MngClient_Info; // 初始化客户端 全局变量 //int MngClient_InitInfo(MngClient_Info *pCltInfo); /*----------------------------------------------------------------------------*/ #define KeyMng_NEWorUPDATE 1 //1 密钥协商 #define KeyMng_Check 2 //2 密钥校验 #define KeyMng_Revoke 3 //3 密钥注销 //密钥请求报文 #define ID_MsgKey_Req 60 typedef struct _MsgKey_Req { //1 密钥协商 //2 密钥校验; //3 密钥注销 int cmdType; //报文类型 char clientId[12]; //客户端编号 char AuthCode[16]; //认证码 char serverId[12]; //服务器端编号 char r1[64]; //客户端随机数 }MsgKey_Req; //密钥应答报文 #define ID_MsgKey_Res 61 typedef struct _MsgKey_Res { int rv; //返回值 char clientId[12]; //客户端编号 char serverId[12]; //服务器编号 unsigned char r2[64]; //服务器端随机数 int seckeyid; //对称密钥编号 keysn }MsgKey_Res; //总编码 int MsgEncode( void *pStruct, /*输入:结构体*/ int type, /*结构体编号*/ unsigned char **outData, /*out--字符串*/ int *outLen); //输出字符串长度 int MsgDecode( unsigned char *inData, /*输入数据*/ int inLen, /*输入数据长度*/ void *pStruct /*out--结构体*/, int *type); /*out结构体编号*/ int create_xiawucha_MsgKey_Req(char **outdata, int * outlen, int type); int cJSONMsgKey_Req_to_struct(char *json_string, MsgKey_Req *person); int create_xiawucha_MsgKey_Res(char **outdata, int * outlen, int type); int cJSONMsgKey_Res_to_struct(char *json_string, MsgKey_Res *person); int get_struct(char *json_string, int * flag); #endif // !_cJSON_ENCONDING_
52a5d6985ce5e2e9794283c73f7e607a29ce7a9d
[ "C" ]
3
C
shiwei924/test01
9d899fccedea2428148d3465b46f844a372037b8
652a3f5691fee5d89d25f14142e6378c24ecf5da
refs/heads/master
<file_sep>#################################################################################### # Description: A dynamic program to find the highest-scoring alignment for any arbitrary # DNA sequences X & &. # File: README.txt #################################################################################### PURPOSE The purpose of align.py is to find the highest-scoring alignment for any arbitrary DNA sequences X and Y, using dynamic programming. DESCRIPTION The program uses a recursive solution to calculate the score of an optimal-scoring sequence alignment. With the recursive solution, three possibilities are considered: (1) the optimal alignment ends with an aligned pair of letters, extending an optimal alignment of the prefixes of both X and Y, (2) the optimal alignment ends with a letter from X aligned to nothing (a deletion), and (3) the optimal alignment ends with a letter from Y aligned to nothing (an insertion). After the optimal score is determined, the program then traces back to determine the alignment that produces said score. The score and the alignment are the results of this program. EXECUTION INSTRUCTIONS To compile/run the align.py file, one must simply navigate to the directory containing the program, and run the following command: "python align.py fileName.fa" Where fileName.fa is the input file containing two DNA sequences, with X on the first line and Y on the second. An example of a valid input file is as follows: "ACGTAACT CCTACTGG" Upon executing the command above with a valid input file, the program will output the score of the optimal-scoring alignment, followed by the alignment of the two sequences.<file_sep>####################################################################################################################################################################### # Description: A dynamic program to find the highest-scoring alignment for any arbitrary DNA sequences X & &. # File: align.py ####################################################################################################################################################################### import sys def score(iLetter, jLetter): # Score matrix. s = [[2, -5, -5, -1, -5], [-5, 2, -1, -5, -5], [-5, -1, 2, -5, -5], [-1, -5, -5, 2, -5], [-5, -5, -5, -5, -5]] # Letter position. l = ['A', 'C', 'G', 'T', '-'] # Calculates score for given iLetter and jLetter. score = s[l.index(jLetter)][l.index(iLetter)] return score def opt(X, Y): m, n = len(X) + 1, len(Y) + 1 g = -5 M, N = [], [] # Instantiates the matrix M given the size of X and Y. M = [[0 for x in range(0, m)] for x in range(0, n)] # Fills first row and column of the matrix M. for i in range(1, m): M[0][i] = g * i # Note that in Python it's [row, column]. for j in range(1, n): M[j][0] = g * j # Calculate the score of an optimal-scoring sequence alignment via recurrence. for i in range(1, m): for j in range(1,n): M[j][i] = max(M[j-1][i-1] + score(X[i-1], Y[j-1]), M[j][i-1] + g, M[j-1][i] + g) return M def traceback(X, Y, M): xAlign, yAlign = '', '' g = -5 i, j = len(X), len(Y) # Traces back to start of matrix M to find alignment. while (i > 0 or j > 0): current = M[j][i] # Letter from X aligns to nothing (deletion). if (i > 0 and current == M[j][i-1] + g): xAlign += X[i-1] yAlign += '-' i -= 1 # Letter from Y aligns to nothing (insertion). elif (j > 0 and current == M[j-1][i] + g): xAlign += '-' yAlign += Y[j-1] j -= 1 # Aligned pair of letters (match). else: xAlign += X[i-1] yAlign += Y[j-1] i -= 1 j -= 1 # Reverse the sequences. xAlign = xAlign[::-1] yAlign = yAlign[::-1] return xAlign, yAlign def main(): X, Y = '', '' i = 0 # Inputs file from command line and sets X as the first sequence and Y as the second. file = open(sys.argv[1], 'r') for sequence in file: if i == 0: X = sequence.strip() elif i == 1: Y = sequence.strip() else: sys.stdout.write('Please input a file with two valid sequences.') main() i += 1 # Build matrix of alignment scores. M = opt(X, Y) optScore = M[len(Y)][len(X)] # Traceback to find the alignment that gives the optScore. xAlign, yAlign = traceback(X, Y, M) # Output results to stdout. sys.stdout.write('Score: ' + str(optScore) + '\n') sys.stdout.write(str(xAlign) + '\n') sys.stdout.write(str(yAlign) + '\n') main()
9b77c50850daddfa4d9df11c22c4570f82d7261f
[ "Python", "Text" ]
2
Text
githobbse/dna-alignment
8b801b1be4ccaed648c1f43a3d456094ca32eb0a
4e862135c8c5ea82e360a0fdcaf6a573cc67edf9
refs/heads/main
<repo_name>emmahermanson/rapVindie<file_sep>/music.py ############################ # SENTIMENT ANALYSIS # RAP VS. INDIE MUSIC ############################ # Created by <NAME> # 11.25.20 ############################ # ALBUM 1: Chance the Rapper's "Acid Rap" # ALBUM 2: The Head and the Heart's "The Head and The Heart" ############################ # importing lyrics from Genius.com into json files # part 1 of sentiment analysis ############################ import lyricsgenius token = "<KEY>" api = lyricsgenius.Genius(token) #################################################################################### # IMPORT CHANCE'S ALBUM # #################################################################################### artist1 = api.search_artist('Chance the Rapper', max_songs=1) song1 = api.search_song("Good Ass Intro", artist1.name) artist1.add_song(song1) song2 = api.search_song("Pusha Man", artist1.name) artist1.add_song(song2) song3 = api.search_song("Paranoia", artist1.name) artist1.add_song(song3) song4 = api.search_song("Cocoa Butter Kisses", artist1.name) artist1.add_song(song4) song5 = api.search_song("Juice", artist1.name) artist1.add_song(song5) song6 = api.search_song("Lost", artist1.name) artist1.add_song(song6) song7 = api.search_song("Everybody's Something", artist1.name) artist1.add_song(song7) song8 = api.search_song("Interlude (That's Love)", artist1.name) artist1.add_song(song8) song9 = api.search_song("Favorite Song", artist1.name) artist1.add_song(song9) song10 = api.search_song("NaNa", artist1.name) artist1.add_song(song10) song11 = api.search_song("Smoke Again", artist1.name) artist1.add_song(song11) song12 = api.search_song("Acid Rain", artist1.name) artist1.add_song(song12) song13 = api.search_song("Chain Smoker", artist1.name) artist1.add_song(song13) song14 = api.search_song("Everything's Good (Good Ass Outro)", artist1.name) artist1.add_song(song14) # save and print album # artist1.save_lyrics() print(artist1) #################################################################################### # IMPORT THE HEAD AND THE HEART ALBUM # #################################################################################### artist2 = api.search_artist("The Head And The Heart", max_songs=1) song_1 = api.search_song("Cats and Dogs", artist2.name) artist2.add_song(song_1) song_2 = api.search_song("Couer d'Alene", artist2.name) artist2.add_song(song_2) song_3 = api.search_song("Ghosts", artist2.name) artist2.add_song(song_3) song_4 = api.search_song("Down in the Valley", artist2.name) artist2.add_song(song_4) song_5 = api.search_song("Rivers and Roads", artist2.name) artist2.add_song(song_5) song_6 = api.search_song("Honey Come Home", artist2.name) artist2.add_song(song_6) song_7 = api.search_song("Lost in my Mind", artist2.name) artist2.add_song(song_7) song_8 = api.search_song("Winter Song", artist2.name) artist2.add_song(song_8) song_9 = api.search_song("Sounds Like Hallelujah", artist2.name) artist2.add_song(song_9) song_10 = api.search_song("Heaven Go Easy on Me", artist2.name) artist2.add_song(song_10) # save and print album # artist2.save_lyrics() print(artist2)
70e06973c3c37b66b826f25f95906f900d922f2c
[ "Python" ]
1
Python
emmahermanson/rapVindie
458230af4a7fbf8ebbfa7ec9ed5a699a579a99d7
ac00d5741e4503cd5ab4894a79915dd701941a79
refs/heads/master
<file_sep>const mongoose = require('mongoose'); //crear un objeto Schema let Schema = mongoose.Schema; //Definir mi colección let PintoresSchema = new Schema({ nombre:{ type: String, required: [true, 'Requerimos el nombre'] }, corriente:{ type: String, required: [true, 'Requerimos el estilo'], }, nacionalidad:{type: String}, pintura:{type: String}, }); module.exports = mongoose.model('Pintores',EstatalSchema);<file_sep>let mongoose = require('mongoose'); let Estatal = require('../models/Pintores'); let estatalController = {}; /*LISTAR*/ estatalController.list = (req, res)=>{ Estatal.find({}) .limit(20) .skip(0) .exec((err, pintor)=>{ if (err){ console.log('Error:',err); } res.render('../views/index',{ pintores: pintor, title: "Listado de pintores", year: new Date().getFullDate() }); }) }; module.exports = PintoresController;
69bb73b02d819f0d6f28d57decf06c55dfe6d342
[ "JavaScript" ]
2
JavaScript
OscarMendozaF/Examen
d0265f6b3e4d112f6f4e832138bf1d96ff900865
27ef07dd8e214bf40c77bfd0c5976b992f30e5a0
refs/heads/master
<repo_name>Vayne-Lover/Business-Analysis<file_sep>/README.md ### Business Analysis *** This repository is for Business Analysis Nanodegree. + p1 is project Analyze Survey Data. + p2 is project Predicting Catlog Demand. + p3 is project Visualize Movie Data. <file_sep>/p3/test.py # -*- coding: utf-8 -*- # Author: <EMAIL> import time import openpyxl as xl def main(): fileName = "movies.xlsx" wb = xl.Workbook() sheetName = wb.get_sheet_names() ws = wb.get_sheet_by_name(sheetName[0]) wb2 = xl.load_workbook(fileName) ori_sheetName = wb2.get_sheet_names() ori_ws = wb2.get_sheet_by_name(ori_sheetName[0]) count = 1 tempCount = 1 while tempCount <= ori_ws.max_row: if count == 1: for i in range(0, 21): ws[chr(ord("A")+ i)+ str(count)].value = ori_ws[chr(ord("A")+ i)+ str(count)].value count += 1 tempCount += 1 elif ori_ws["O" + str(tempCount)].value is None: count += 1 tempCount += 1 # print(ori_ws["O" + str(count)].value) # print(count, tempCount) else: companies = ori_ws["O" + str(tempCount)].value.split("|") for j in range(0, len(companies)): for i in range(0, 21): ws[chr(ord("A") + i) + str(count)].value = ori_ws[chr(ord("A") + i) + str(tempCount)].value ws["O" + str(count)].value = companies[j] count += 1 tempCount += 1 wb.save("q2.xlsx") if __name__ == "__main__": start = time.clock() main() end = time.clock() print(end-start)
99ac2a38eaa9a6da1ea48c92cf2e42c71247d188
[ "Markdown", "Python" ]
2
Markdown
Vayne-Lover/Business-Analysis
42b807dee14d45f2c79014019751962690b2d898
fc55dcd70ded2552e757627ab2424e8dfc88845e
refs/heads/master
<file_sep>using DRAWeb.App.Utilities; using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System.Threading.Tasks; using static DRAWeb.App.Utilities.EnumHelpers; namespace DRAWeb.App.Controllers { public class UserAccountController : BaseController { IUserBroker userService = null; public UserAccountController(IConfiguration _config,IUserBroker userBroker, ILoggerManager loggerManager) { logger = loggerManager; userService = userBroker; config = _config; } public IActionResult Login() { //logger.LogInfo("Hello, world!"); return View(); } [HttpPost] public async Task<IActionResult> Login(UserModel user) { var validUser = await userService.ValidateUserCredentials(user); if (validUser.Content != null) { if (validUser.Content.UserActive == 1) { SetUserSession(validUser.Content); return RedirectToAction("Landing", "Home"); } else { var userModel = validUser.Content; var activationURL = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{"Registration"}/{"Activate"}?{"userID="}{userModel.UserID}"; var notificationSent = await NotificationHelper.SendRegisterNotification(userModel.UserEmail, userModel.UserName, activationURL, config); if (!notificationSent) { logger.LogError("Sending notification failed for userID:" + user.UserID); } return RedirectToAction("Activate", "UserAccount"); } } else { SetNotification(validUser.Message,NotificationType.Failure,"Failed"); return View(); } } public IActionResult Logout() { var user = GetUserSession(); if (user != null) { DestroyUserSession(); } return View(); } public IActionResult ForgotPassword() { return View(); } [HttpPost] public async Task<IActionResult> ForgotPassword(ResetPassword user) { var message = await userService.UpdatePassword(user); if (message == "Updated") { var redirectURL = Url.Action("Login", "UserAccount"); SetNotification("Password Updated Successfully!!",NotificationType.Success,"Success", redirectURL); return View(); } else { SetNotification(message, NotificationType.Failure, "Failed"); return View(); } } public IActionResult Activate() { return View(); } } }<file_sep>using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Models; using DRAWeb.Proxy; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Core.Broker { public class RegistrationBroker : BrokerBase, IRegistrationBroker { public RegistrationBroker(IConfiguration _config, ILoggerManager loggerManager, IDRAAzureServiceProxy _proxy) { logger = loggerManager; config = _config; proxy = _proxy; } public async Task<ResponseMessage<UserModel>> RegisterUser(UserModel user) { return await Task.Run(() => proxy.RegisterUser(user)); } public async Task<string> ActivateUser(int userID) { return await Task.Run(() => proxy.ActivateUser(userID)); } } } <file_sep>using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Models; using DRAWeb.Proxy; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Core.Broker { public class UserBroker : BrokerBase, IUserBroker { public UserBroker(IConfiguration _config, ILoggerManager loggerManager, IDRAAzureServiceProxy _proxy) { logger = loggerManager; config = _config; proxy = _proxy; } public async Task<ResponseMessage<UserModel>> ValidateUserCredentials(UserModel user) { return await Task.Run(() => proxy.ValidateUserCredentials(user)); } public async Task<string> UpdatePassword(ResetPassword user) { return await Task.Run(() => proxy.UpdatePassword(user)); } } } <file_sep>using DRAWeb.Core.Broker; using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Proxy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Net; using System.Net.Mail; namespace DRAWeb.Infrastructure.DI { public static class IServiceDependencyInjection { public static IServiceCollection InjectApplicationDependency(this IServiceCollection services) { services.AddTransient<IUserBroker, UserBroker>(); services.AddTransient<IRegistrationBroker, RegistrationBroker>(); services.AddTransient<ILoggerManager, LoggerManager>(); services.AddTransient<IReportBroker, ReportBroker>(); services.AddTransient<IDRAAzureServiceProxy, DRAAzureServiceProxy>(); return services; } public static IConfiguration AddLoggerConfiguration(this IConfiguration configuration) { LoggerManager.LoadConfigucation("/nlog.config"); return configuration; } public static IServiceCollection InjectSMTPDependency(this IServiceCollection services) { services.AddTransient<SmtpClient>((serviceProvider) => { var config = serviceProvider.GetRequiredService<IConfiguration>(); return new SmtpClient() { Host = config.GetValue<String>("Email:Smtp:Host"), Port = config.GetValue<int>("Email:Smtp:Port"), Credentials = new NetworkCredential( config.GetValue<String>("Email:Smtp:Username"), config.GetValue<String>("Email:Smtp:Password") ) }; }); return services; } } } <file_sep>using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Proxy { public class DRAAzureServiceProxy : IDRAAzureServiceProxy { public static ILoggerManager logger; public static IConfiguration config; public DRAAzureServiceProxy(IConfiguration _config, ILoggerManager loggerManager) { logger = loggerManager; config = _config; } public static void SerializeJsonIntoStream(object value, Stream stream) { using (var sw = new StreamWriter(stream, new UTF8Encoding(false), 1024, true)) using (var jtw = new JsonTextWriter(sw) { Formatting = Formatting.None }) { var js = new JsonSerializer(); js.Serialize(jtw, value); jtw.Flush(); } } private static HttpContent CreateHttpContent(object content) { HttpContent httpContent = null; if (content != null) { var ms = new MemoryStream(); SerializeJsonIntoStream(content, ms); ms.Seek(0, SeekOrigin.Begin); httpContent = new StreamContent(ms); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } return httpContent; } public async Task<ResponseMessage<List<UserCompetencyMatrixModel>>> GetUserCompetencyMetrix(CompetenciesReportRequest reportRequest) { ResponseMessage<List<UserCompetencyMatrixModel>> result; string azureBaseUrl = config.GetValue<string>("DRAAzureAPIURL:DRAAzureAPIBaseURL"); string urlQueryStringParams = config.GetValue<string>("DRAAzureAPIURL:DRAReportsAPIURL"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, $"{azureBaseUrl}{urlQueryStringParams}")) using (var httpContent = CreateHttpContent(reportRequest)) { request.Content = httpContent; using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { var jsonString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { result = JsonConvert.DeserializeObject<ResponseMessage<List<UserCompetencyMatrixModel>>>(jsonString); } else { result = new ResponseMessage<List<UserCompetencyMatrixModel>>(); result = JsonConvert.DeserializeObject<ResponseMessage<List<UserCompetencyMatrixModel>>>(jsonString); } } } return result; } public async Task<ResponseMessage<UserModel>> ValidateUserCredentials(UserModel user) { ResponseMessage<UserModel> result; string azureBaseUrl = config.GetValue<string>("DRAAzureAPIURL:DRAAzureAPIBaseURL"); string urlQueryStringParams = config.GetValue<string>("DRAAzureAPIURL:DRALoginAPIURL"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, $"{azureBaseUrl}{urlQueryStringParams}")) using (var httpContent = CreateHttpContent(user)) { request.Content = httpContent; using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { var jsonString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { result = JsonConvert.DeserializeObject<ResponseMessage<UserModel>>(jsonString); } else { result = new ResponseMessage<UserModel>(); result = JsonConvert.DeserializeObject<ResponseMessage<UserModel>>(jsonString); } } } return result; } public async Task<ResponseMessage<UserModel>> RegisterUser(UserModel user) { ResponseMessage<UserModel> result; string azureBaseUrl = config.GetValue<string>("DRAAzureAPIURL:DRAAzureAPIBaseURL"); string urlQueryStringParams = config.GetValue<string>("DRAAzureAPIURL:DRARegisterAPIURL"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, $"{azureBaseUrl}{urlQueryStringParams}")) using (var httpContent = CreateHttpContent(user)) { request.Content = httpContent; using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { var jsonString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.Created) { result = JsonConvert.DeserializeObject<ResponseMessage<UserModel>>(jsonString); } else { result = new ResponseMessage<UserModel>(); result = JsonConvert.DeserializeObject<ResponseMessage<UserModel>>(jsonString); } } } return result; } public async Task<string> UpdatePassword(ResetPassword user) { string result; string azureBaseUrl = config.GetValue<string>("DRAAzureAPIURL:DRAAzureAPIBaseURL"); string urlQueryStringParams = config.GetValue<string>("DRAAzureAPIURL:DRAResetPasswordAPIURL"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, $"{azureBaseUrl}{urlQueryStringParams}")) using (var httpContent = CreateHttpContent(user)) { request.Content = httpContent; using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { var jsonString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { result = "Updated"; } else { ; result = JsonConvert.DeserializeObject<string>(jsonString); } } } return result; } public async Task<string> ActivateUser(int userID) { string result; string azureBaseUrl = config.GetValue<string>("DRAAzureAPIURL:DRAAzureAPIBaseURL"); string urlQueryStringParams = config.GetValue<string>("DRAAzureAPIURL:DRAActivateAccountAPIURL"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, $"{azureBaseUrl}{urlQueryStringParams}")) using (var httpContent = CreateHttpContent(userID)) { request.Content = httpContent; using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { var jsonString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { result = "Updated"; } else { ; result = JsonConvert.DeserializeObject<string>(jsonString); } } } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using DRAWeb.Logger; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using static DRAWeb.App.Utilities.EnumHelpers; namespace DRAWeb.App.Controllers { public class QuestionnaireController : BaseController { public QuestionnaireController(IConfiguration _config, ILoggerManager loggerManager) { logger = loggerManager; config = _config; } public IActionResult Index() { ViewBag.RedirectionURL = ""; var eligibleMonths = config.GetValue<int>("AppSettings:TestEligibleAfter"); var user = GetUserSession(); if (user != null) { var QuestionnaireURL = config.GetValue<string>("AppSettings:QuestionnaireURL").ToString(); QuestionnaireURL = QuestionnaireURL.Replace("#FN#", user.UserName); QuestionnaireURL = QuestionnaireURL.Replace("#LN#", user.UserSurname); QuestionnaireURL = QuestionnaireURL.Replace("#Career#", user.JobTitle); ViewBag.RedirectionURL = QuestionnaireURL; if (user.IsTestTaken) { if (DateTime.Compare(user.LastTestTakenOn.AddMonths(eligibleMonths), DateTime.Now) < 0) { return View(); } else { SetNotification("Last test taken on " + user.LastTestTakenOn.ToShortDateString() + " should be atleast " + eligibleMonths + " months", NotificationType.Warning, "Warning", Url.Action("Landing", "Home")); return View(); } } else { return View(); } } else { return RedirectToAction("Login", "UserAccount"); } } } }<file_sep>using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using OfficeOpenXml; using OfficeOpenXml.Drawing.Chart; using OfficeOpenXml.Style; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using static DRAWeb.App.Utilities.EnumHelpers; namespace DRAWeb.App.Controllers { public class ReportController : BaseController { IReportBroker reportService = null; public ReportController(IConfiguration _config, ILoggerManager loggerManager, IReportBroker service) { reportService = service; logger = loggerManager; config = _config; } public async Task<IActionResult> UserCompetency() { var user = GetUserSession(); if (user == null) { return RedirectToAction("Login", "UserAccount"); } else { if (user.IsTestTaken) { List<UserCompetencyMatrixModel> lstMetrix = await GetUserCompetency(); if (lstMetrix == null) { SetNotification("Failed to execute the request!!", NotificationType.Failure, "Failed"); } return View(lstMetrix); } return View(); } } public async Task<List<UserCompetencyMatrixModel>> GetUserCompetency() { var user = GetUserSession(); if (user != null) { var request = new CompetenciesReportRequest(); request.UserID = user.UserID; var result = await reportService.GetUserCompetencyMetrix(request); if (result != null) { if (result.Content != null) { return result.Content; } } } return null; } [HttpGet] public async Task<IActionResult> ExportExcel() { //step1: create array to holder header labels string[] col_names = new string[]{ "Type", "Main Group", "Sub Group", "Competency", "Required Level", "Current Level", "Gap" }; //step2: create result byte array byte[] byteData; var result = await GetUserCompetency(); if (result == null) { SetNotification("Failed to execute the request!!", NotificationType.Failure, "Failed"); return View("UserCompetency"); } //step3: create a new package using memory safe structure using (var package = new ExcelPackage()) { //step4: create a new worksheet var worksheet = package.Workbook.Worksheets.Add("final"); //step5: fill in header row //worksheet.Cells[row,col]. {Style, Value} for (int i = 0; i < col_names.Length; i++) { worksheet.Cells[1, i + 1].Style.Font.Size = 14; //font worksheet.Cells[1, i + 1].Value = col_names[i]; //value worksheet.Cells[1, i + 1].Style.Font.Bold = true; //bold //border the cell worksheet.Cells[1, i + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin); //set background color for each sell worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 243, 214)); } int row = 2; //step6: loop through query result and fill in cells foreach (var item in result.ToList()) { for (int col = 1; col <= col_names.Length; col++) { worksheet.Cells[row, col].Style.Font.Size = 12; //worksheet.Cells[row, col].Style.Font.Bold = true; worksheet.Cells[row, col].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin); } //set row,column data //worksheet.Cells[row, 1,].Merge worksheet.Cells[row, 1].Value = item.Type; worksheet.Cells[row, 2].Value = item.MainGroup; worksheet.Cells[row, 3].Value = item.SubGroup; worksheet.Cells[row, 4].Value = item.Competency; worksheet.Cells[row, 5].Value = item.RequiredLevel; worksheet.Cells[row, 6].Value = item.CurrentLevel; worksheet.Cells[row, 7].Style.Fill.PatternType = ExcelFillStyle.Solid; switch (item.Gap) { case 0: worksheet.Cells[row, 7].Style.Fill.BackgroundColor.SetColor(Color.Red); break; case 1: worksheet.Cells[row, 7].Style.Fill.BackgroundColor.SetColor(Color.Orange); break; case 2: worksheet.Cells[row, 7].Style.Fill.BackgroundColor.SetColor(Color.LightGray); break; default: worksheet.Cells[row, 7].Style.Fill.BackgroundColor.SetColor(Color.White); break; } worksheet.Cells[row, 7].Value = item.Gap; //toggle background color //even row with ribbon style if (row % 2 == 0) { for (int i = 1; i < col_names.Length; i++) { worksheet.Cells[row, i].Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Cells[row, i].Style.Fill.BackgroundColor.SetColor(Color.LightGray); } } row++; } //step7: auto fit columns worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); //--------------------------------------------------------------------------------------------- #region PieChart //create a WorkSheet //ExcelWorksheet worksheet1 = package.Workbook.Worksheets.Add("DummyChart"); ////fill cell data with a loop, note that row and column indexes start at 1 //Random rnd = new Random(); //for (int i = 1; i <= 10; i++) //{ // worksheet1.Cells[1, i].Value = "Value " + i; // worksheet1.Cells[2, i].Value = rnd.Next(5, 15); //} ////create a new piechart of type Pie3D //ExcelPieChart pieChart = worksheet1.Drawings.AddChart("pieChart", eChartType.Pie3D) as ExcelPieChart; ////set the title //pieChart.Title.Text = "PieChart Example"; ////select the ranges for the pie. First the values, then the header range //pieChart.Series.Add(ExcelRange.GetAddress(2, 1, 2, 10), ExcelRange.GetAddress(1, 1, 1, 10)); ////position of the legend //pieChart.Legend.Position = eLegendPosition.Bottom; ////show the percentages in the pie //pieChart.DataLabel.ShowPercent = true; ////size of the chart //pieChart.SetSize(500, 400); ////add the chart at cell C5 //pieChart.SetPosition(4, 0, 2, 0); #endregion //---------------------------------------------------------------------------------------------------------- #region Line Chart //ExcelWorksheet worksheet2 = package.Workbook.Worksheets.Add("Dummy Line"); ////fill cell data with a loop, note that row and column indexes start at 1 //Random rnd1 = new Random(); //for (int i = 2; i <= 11; i++) //{ // worksheet2.Cells[1, i].Value = "Value " + (i - 1); // worksheet2.Cells[2, i].Value = rnd1.Next(5, 25); // worksheet2.Cells[3, i].Value = rnd1.Next(5, 25); //} //worksheet2.Cells[2, 1].Value = "Age 1"; //worksheet2.Cells[3, 1].Value = "Age 2"; ////create a new piechart of type Line //ExcelLineChart lineChart = worksheet2.Drawings.AddChart("lineChart", eChartType.Line) as ExcelLineChart; ////set the title //lineChart.Title.Text = "LineChart Example"; ////create the ranges for the chart //var rangeLabel = worksheet2.Cells["B1:K1"]; //var range1 = worksheet2.Cells["B2:K2"]; //var range2 = worksheet2.Cells["B3:K3"]; ////add the ranges to the chart //lineChart.Series.Add(range1, rangeLabel); //lineChart.Series.Add(range2, rangeLabel); ////set the names of the legend //lineChart.Series[0].Header = worksheet.Cells["A2"].Value.ToString(); //lineChart.Series[1].Header = worksheet.Cells["A3"].Value.ToString(); ////position of the legend //lineChart.Legend.Position = eLegendPosition.Right; ////size of the chart //lineChart.SetSize(700, 300); ////add the chart at cell B6 //lineChart.SetPosition(5, 0, 1, 0); #endregion //------------------------------------------------------------------------------------------------ List<ColumnChart> chartData = new List<ColumnChart>(); var grpType = result.GroupBy(x => x.Type); foreach (var grp in grpType) { chartData.Add(new ColumnChart() { Type = grp.Key, RequiredLevel = grp.Average(x => x.RequiredLevel), CurrentLevel = grp.Average(x => x.CurrentLevel) }); } if (chartData.Any()) { var ws = package.Workbook.Worksheets.Add("newsheet"); var count = chartData.Count; //Some data for (var i = 1; i <= chartData.Count; i++) { var item = chartData[i - 1]; var area = (i + 1 + 10).ToString(); ws.Cells["A" + area].Value = item.Type; ws.Cells["B" + area].Value = item.RequiredLevel; ws.Cells["C" + area].Value = item.CurrentLevel; } //Create the chart var chartRequiredLevel = (ExcelBarChart)ws.Drawings.AddChart("RequiredLevel", eChartType.ColumnClustered); chartRequiredLevel.SetSize(1000, 600); chartRequiredLevel.SetPosition(10, 10); chartRequiredLevel.Style = eChartStyle.Style10; chartRequiredLevel.Title.Text = "User Competency Graph"; chartRequiredLevel.Series.Add(ExcelRange.GetAddress(12, 2, chartData.Count + 1 + 10, 2), ExcelRange.GetAddress(12, 1, chartData.Count + 1 + 10, 1)).Header = "Average of Required Level"; chartRequiredLevel.Series.Add(ExcelRange.GetAddress(12, 3, chartData.Count + 1 + 10, 3), ExcelRange.GetAddress(12, 1, chartData.Count + 1 + 10, 1)).Header = "Average of Current Level"; chartRequiredLevel.Legend.Position = eLegendPosition.Right; chartRequiredLevel.VaryColors = true; } //step8: convert the package as byte array byteData = package.GetAsByteArray(); }//end using //step9: return byte array as a file return File(byteData, "application/vnd.ms-excel", $"UserCompetency{DateTime.Now.ToString("MMddyyyy")}.xls"); }//end fun } public class ColumnChart { public string Type { get; set; } public double RequiredLevel { get; set; } public double CurrentLevel { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; namespace DRAWeb.App.Utilities { public class EmailHelper { public async static Task<bool> SendEmail(SmtpClient client, MailMessage mail) { var mailSent = false; try { await Task.Run(() => client.Send(mail)); mailSent = true; } catch (System.Exception) { return mailSent; } return mailSent; } } } <file_sep>using DRAWeb.App.Models; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; namespace DRAWeb.App.Controllers { public class ErrorController : BaseController { public IActionResult PageNotFound() { return View(); } public IActionResult ServerError() { return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using Microsoft.Extensions.Configuration; using System; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace DRAWeb.App.Utilities { public class NotificationHelper { //private async void SendEmailNotification(string userEmail, string userName, int userID) //{ // using (var smtpClient = HttpContext.RequestServices.GetRequiredService<SmtpClient>()) // { // var fromEmail = config.GetValue<string>("AppSettings:ActivationEmailFrom"); // var emailSubject = config.GetValue<string>("AppSettings:ActivationEmailSubject"); // var actionURL = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{"Registration"}/{"Activate"}?{"UserID="}{userID}"; // var cts = new CancellationTokenSource(); // cts.CancelAfter(TimeSpan.FromSeconds(2)); // await smtpClient.SendMailAsync(new MailMessage(from: fromEmail, // to: userEmail, // subject: emailSubject, // body: "<a href='" + actionURL + "'>Click to Activate Account</a>" // )); // } //} public async static Task<bool> SendRegisterNotification(string userEmail, string userName, string activationURL,IConfiguration config) { var mailSent = false; var fromEmail = config.GetValue<string>("AppSettings:ActivationEmailFrom"); var emailSubject = config.GetValue<string>("AppSettings:ActivationEmailSubject"); var host = config.GetValue<String>("Email:Smtp:Host"); var port = config.GetValue<int>("Email:Smtp:Port"); var credentials = new NetworkCredential(config.GetValue<String>("Email:Smtp:Username"), config.GetValue<String>("Email:Smtp:Password")); var client = new SmtpClient() { Port = port, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Host = host, EnableSsl = true, Credentials = credentials }; var mail = new MailMessage(new MailAddress(fromEmail), new MailAddress(userEmail)) { Subject = emailSubject, Body = "<a href='" + activationURL + "'>Click to Activate Account</a>", IsBodyHtml = true, }; mailSent = await EmailHelper.SendEmail(client, mail); return mailSent; } } } <file_sep>using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using static DRAWeb.App.Utilities.EnumHelpers; namespace DRAWeb.App.Controllers { public class BaseController : Controller { public ILoggerManager logger; public IConfiguration config; public BaseController() { } public void SetUserSession(UserModel user) { const string sessionKey = "UserSession"; DestroyUserSession(); TempData.Add(sessionKey, JsonConvert.SerializeObject(user)); TempData.Keep(); //var serialisedData = JsonConvert.SerializeObject(user); //HttpContext.Session.SetString(sessionKey, serialisedData); } public UserModel GetUserSession() { const string sessionKey = "UserSession"; var value = (string)TempData.Peek(sessionKey); //var value = HttpContext.Session.GetString(sessionKey); if (value != null) return JsonConvert.DeserializeObject<UserModel>(value); return null; } public void DestroyUserSession() { const string sessionKey = "UserSession"; if (TempData.Keys.Contains("UserSession")) TempData.Remove(sessionKey); //HttpContext.Session.Remove(sessionKey); } public void SetNotification(string message, NotificationType type = NotificationType.Success, string title = "Success", string redirectURL = "") { TempData["Notification"] = JsonConvert.SerializeObject(new { Message = message, Type = type, Title = title, Redirection = redirectURL }); } } }<file_sep>using DRAWeb.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Core.Interface { public interface IRegistrationBroker { Task<ResponseMessage<UserModel>> RegisterUser(UserModel user); Task<string> ActivateUser(int userID); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; using DRAWeb.App.Utilities; using DRAWeb.Core.Interface; using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using static DRAWeb.App.Utilities.EnumHelpers; namespace DRAWeb.App.Controllers { public class RegistrationController : BaseController { IRegistrationBroker registerService = null; public RegistrationController(IConfiguration _config, IRegistrationBroker registrationBroker, ILoggerManager loggerManager) { logger = loggerManager; registerService = registrationBroker; config = _config; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> Register(UserModel user) { var validUser = await registerService.RegisterUser(user); if (validUser.Content != null) { var userModel = validUser.Content; var activationURL = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{"Registration"}/{"Activate"}?{"userID="}{userModel.UserID}"; var notificationSent = await NotificationHelper.SendRegisterNotification(userModel.UserEmail, userModel.UserName, activationURL, config); if (!notificationSent) { logger.LogError("Sending notification failed for userID:" + user.UserID); } ViewData["Notification"] = validUser.Message; return RedirectToAction("Successfull", "Registration"); } else { SetNotification(validUser.Message, NotificationType.Failure, "Failed"); return View(); } } public IActionResult Successfull() { return View(); } public async Task<IActionResult> Activate(int userID) { var message = await registerService.ActivateUser(userID); if (message == "Updated") { return View(); } else { var homePageURL = Url.Action("Index", "Home"); SetNotification(message,NotificationType.Failure, "Failed", homePageURL); return View(); } } } }<file_sep>using DRAWeb.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Core.Interface { public interface IUserBroker { Task<ResponseMessage<UserModel>> ValidateUserCredentials(UserModel user); Task<string> UpdatePassword(ResetPassword user); } } <file_sep>using DRAWeb.Logger; using DRAWeb.Models; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace DRAWeb.Proxy { public interface IDRAAzureServiceProxy { Task<ResponseMessage<List<UserCompetencyMatrixModel>>> GetUserCompetencyMetrix(CompetenciesReportRequest reportRequest); Task<ResponseMessage<UserModel>> ValidateUserCredentials(UserModel user); Task<ResponseMessage<UserModel>> RegisterUser(UserModel user); Task<string> UpdatePassword(ResetPassword user); Task<string> ActivateUser(int userID); } } <file_sep>using DRAWeb.Logger; using DRAWeb.Proxy; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Text; namespace DRAWeb.Core.Broker { public class BrokerBase { public ILoggerManager logger; public IConfiguration config; public IDRAAzureServiceProxy proxy; } } <file_sep>using DRAWeb.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace DRAWeb.Core.Interface { public interface IReportBroker { Task<ResponseMessage<List<UserCompetencyMatrixModel>>> GetUserCompetencyMetrix(CompetenciesReportRequest request); } }
1eb4147bb690f393a563ea3ed037f5712bbe16f4
[ "C#" ]
17
C#
kishorShivane/DRAWebApplication
a886c5be26593f84ce51dd4e4683a0b09f933dda
b0d2e5032cc35aea4de07a298ddb350b8e2923f7
refs/heads/master
<file_sep>#' PO2PLS: Probabilistic Two-way Orthogonal Partial Least Squares #' #' This package implements the probabilistic O2PLS method. #' #' @author #' <NAME> (\email{<EMAIL>}), #' <NAME> (\email{J.J.Houwing@@lumc.nl}), #' <NAME> (\email{G.Jong<EMAIL>}), #' <NAME> (\email{<EMAIL>}), #' <NAME> (\email{H.Uh<EMAIL>}). #' #' Maintainer: <NAME> (\email{s.el_bouhaddani@@lumc.nl}). #' #' @docType package #' @name PO2PLS-package #' @keywords Probabilistic-O2PLS #' @import OmicsPLS Rcpp RcppArmadillo #' @importFrom Rcpp evalCpp #' @useDynLib PO2PLS, .registration=TRUE NULL #' Construct a block-diagonal matrix #' #' @param A Numerical matrix. Upper diagonal block. #' @param B Numerical matrix. Off diagonal block. #' @param C Numerical matrix. Lower diagonal block #' #' @return A block diagonal matrix of the form \eqn{\begin{bmatrix} A & B \\ B' & C \end{bmatrix}}. #' #' @details This function is typically called for constructing the covariance matrix of $(x,y)$. #' #' @export blockm<-function(A,B,C) #input: Matrices A,B,C #output: the block matrix # A B #t(B) C { M = rbind(cbind(A,B),cbind(t(B),C)) return(M) } #' Generate parameter values of a PO2PLS model #' #' @param X Numerical data matrix or positive integer. This parameter should either be a dataset \eqn{X} or the number of desired \eqn{X} variables. #' @param Y Numerical data matrix or positive integer. This parameter should either be a dataset \eqn{Y} or the number of desired \eqn{Y} variables. #' @param alpha Numeric vector. The length should be either one or three, with each entry between 0 and 1. It represents the proportion of noise relative to the variation of \eqn{X}, \eqn{Y}, and \eqn{U}, respectively. If only one number is given, it is used for all three parts. #' @param type Character. Should be one of "random", "o2m" or "unit". Specifies which kind of parameters should be generated. If "o2m" is chosen, \code{X} and \code{Y} should be data matrices. #' #' @return A list with #' \item{W}{\eqn{X} joint loadings} #' \item{Wo}{\eqn{X} specific loadings} #' \item{C}{\eqn{Y} joint loadings} #' \item{Co}{\eqn{Y} specific loadings} #' \item{B}{Regression matrix of \eqn{U} on \eqn{T}} #' \item{SigT}{Covariance matrix of \eqn{T}} #' \item{SigTo}{Covariance matrix of \eqn{To}} #' \item{SigUo}{Covariance matrix of \eqn{Uo}} #' \item{SigH}{Covariance matrix of \eqn{H}} #' \item{sig2E}{Variance of \eqn{E}} #' \item{sig2F}{Variance of \eqn{F}} #' #' @details A list of PO2PLS parameters are generated based on the value of \code{type}: #' \item{\code{type="random"}}{Variance parameters are randomly sampled from a uniform distribution on 1 and 3 (1 and 4 for \eqn{B}).} #' \item{\code{type="o2m"}}{O2PLS is fitted to \code{X} and \code{Y} first using \code{\link{o2m}} from the OmicsPLS package, and the corresponding PO2PLS parameters are derived from the result.} #' \item{\code{type="unit"}}{The diagonal of each covariance matrix is a decreasing sequence from the number of components to one.} #' #' @inheritParams PO2PLS #' #' @export generate_params <- function(X, Y, r, rx, ry, alpha = 0.1, type=c('random','o2m','unit')){ type=match.arg(type) p = ifelse(is.matrix(X) & type == "o2m", ncol(X), X) q = ifelse(is.matrix(Y) & type == "o2m", ncol(Y), Y) if(type=="o2m"){ return(with(o2m(X, Y, r, rx, ry, stripped=TRUE),{ list( W = W., Wo = suppressWarnings(orth(P_Yosc.)), C = C., Co = suppressWarnings(orth(P_Xosc.)), B = abs(cov(Tt,U)%*%MASS::ginv(cov(Tt)))*diag(1,r), SigT = cov(Tt)*diag(1,r), SigTo = sign(rx)*cov(T_Yosc.)*diag(1,max(1,rx)), SigUo = sign(ry)*cov(U_Xosc.)*diag(1,max(1,ry)), SigH = cov(H_UT)*diag(1,r), sig2E = (ssq(X)-ssq(Tt)-ssq(T_Yosc.))/prod(dim(X)) + 0.01, sig2F = (ssq(Y)-ssq(U)-ssq(U_Xosc.))/prod(dim(Y)) + 0.01 )})) } if(type=="random"){ if(length(alpha) == 1) alpha <- rep(alpha, 3) if(!(length(alpha) %in% c(1,3))) stop("length alpha should be 1 or 3") outp <- list( W = orth(matrix(rnorm(p*r), p, r)+1), Wo = suppressWarnings(sign(rx)*orth(matrix(rnorm(p*max(1,rx)), p, max(1,rx))+seq(-p/2,p/2,length.out = p))), C = orth(matrix(rnorm(q*r), q, r)+1), Co = suppressWarnings(sign(ry)*orth(matrix(rnorm(q*max(1,rx)), q, max(1,ry))+seq(-q/2,q/2,length.out = q))), B = diag(sort(runif(r,1,4),decreasing = TRUE),r), SigT = diag(sort(runif(r,1,3),decreasing = TRUE),r), SigTo = sign(rx)*diag(sort(runif(max(1,rx),1,3),decreasing = TRUE),max(1,rx)), SigUo = sign(ry)*diag(sort(runif(max(1,ry),1,3),decreasing = TRUE),max(1,ry)) ) outp$SigH = diag(alpha[3]/(1-alpha[3])*(mean(diag(outp$SigT%*%outp$B))),r) #cov(H_UT)*diag(1,r), return(with(outp, { c(outp, sig2E = alpha[1]/(1-alpha[1])*(mean(diag(SigT)) + mean(diag(SigTo)))/p, sig2F = alpha[2]/(1-alpha[2])*(mean(diag(SigT%*%B^2 + SigH)) + mean(diag(SigUo)))/q) })) } if(type=="unit"){ if(length(alpha) == 1) alpha <- rep(alpha, 3) if(!(length(alpha) %in% c(1,3))) stop("length alpha should be 1 or 3") outp <- list( W = orth(matrix(rnorm(p*r), p, r)+1), Wo = suppressWarnings(sign(rx)*orth(matrix(rnorm(p*max(1,rx)), p, max(1,rx))+seq(-p/2,p/2,length.out = p))), C = orth(matrix(rnorm(q*r), q, r)+1), Co = suppressWarnings(sign(ry)*orth(matrix(rnorm(q*max(1,rx)), q, max(1,ry))+seq(-q/2,q/2,length.out = q))), B = diag(r:1,r), SigT = diag(r:1,r), SigTo = sign(rx)*diag(max(1,rx):1,max(1,rx)), SigUo = sign(ry)*diag(max(1,ry):1,max(1,ry)) ) outp$SigH = diag(alpha[3]/(1-alpha[3])*(mean(diag(outp$SigT%*%outp$B))),r) #cov(H_UT)*diag(1,r), with(outp, { c(outp, sig2E = alpha[1]/(1-alpha[1])*(mean(diag(SigT)) + mean(diag(SigTo)))/p, sig2F = alpha[2]/(1-alpha[2])*(mean(diag(SigT%*%B^2 + SigH)) + mean(diag(SigUo)))/q) }) } } #' @export generate_data <- function(N, params, distr = rnorm){ W = params$W C = params$C Wo = params$Wo Co = params$Co B = params$B SigT = params$SigT SigTo = params$SigTo + 1e-6*SigT[1]*(params$SigTo[1]==0) SigH = params$SigH sig2E = params$sig2E sig2F = params$sig2F SigU = SigT%*%B^2 + SigH SigUo = params$SigUo + 1e-6*SigU[1]*(params$SigUo[1]==0) p = nrow(W) q = nrow(C) r = ncol(W) rx = ncol(Wo) ry = ncol(Co) Gamma = rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)) VarZ = blockm( blockm( blockm(SigT, SigT%*%B, SigU), matrix(0,2*r,rx), SigTo), matrix(0,2*r+rx,ry), SigUo) # MASS::mvrnorm(n = N, # mu = rep(0,p+q), # Sigma = Gamma %*% VarZ %*% t(Gamma) + # diag(rep(c(sig2E,sig2F),c(p,q)))) Z <- scale(matrix(distr(N*(2*r+rx+ry)), N)) Z <- Z %*% chol(VarZ) Z[,2*r+1:rx] <- sign(ssq(Wo))*Z[,2*r+1:rx] Z[,2*r+rx+1:ry] <- sign(ssq(Co))*Z[,2*r+rx+1:ry] EF <- cbind(scale(matrix(distr(N*p), N))*sqrt(sig2E), scale(matrix(distr(N*q), N))*sqrt(sig2F)) Z %*% t(Gamma) + EF } #' @export Lemma <- function(X, SigmaZ, invZtilde, Gamma, sig2E, sig2F, p, q, r, rx, ry){ GammaEF <- Gamma GammaEF[1:p,c(1:r,2*r+1:rx)] <- 1/sig2E* GammaEF[1:p,c(1:r,2*r+1:rx)] GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] <- 1/sig2F* GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] #invSEF <- diag(1/diag(SigmaEF)) #invS <- invSEF - invSEF %*% Gamma %*% MASS::ginv(MASS::ginv(SigmaZ) + t(Gamma)%*%invSEF%*%Gamma) %*% t(Gamma) %*% invSEF GGef <- t(Gamma) %*% GammaEF VarZc <- SigmaZ - (t(Gamma %*% SigmaZ) %*% GammaEF) %*% SigmaZ + (t(Gamma %*% SigmaZ) %*% GammaEF) %*% invZtilde %*% GGef %*% SigmaZ EZc <- X %*% (GammaEF %*% SigmaZ) EZc <- EZc - X %*% ((GammaEF %*% invZtilde) %*% (GGef %*% SigmaZ)) # MASS::ginv(t(0)) return(list(EZc = EZc, VarZc = VarZc)) } #' @export E_step_slow <- function(X, Y, params){ ## retrieve parameters W = params$W C = params$C Wo = params$Wo Co = params$Co B = params$B SigT = params$SigT SigTo = (ssq(Wo)>0)*params$SigTo +0# + 1e-10*(ssq(Wo)==0) SigUo = (ssq(Co)>0)*params$SigUo +0# + 1e-10*(ssq(Co)==0) SigH = params$SigH sig2E = params$sig2E sig2F = params$sig2F SigU = SigT%*%B^2 + SigH ## define dimensions N = nrow(X) p = nrow(W) q = nrow(C) r = ncol(W) rx = ncol(Wo) ry = ncol(Co) ## concatenate data dataXY <- cbind(X,Y) ## Gamma is the generalized loading matrix, with PO2PLS structure Gamma = rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)) ## Gamma multiplied by inverse SigmaEF GammaEF <- Gamma GammaEF[1:p,c(1:r,2*r+1:rx)] <- 1/sig2E* GammaEF[1:p,c(1:r,2*r+1:rx)] GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] <- 1/sig2F* GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] GGef <- t(Gamma) %*% GammaEF ## diagonal cov matrix of (E,F), hopefully NOT NEEDED # SigmaEF = diag(rep(c(sig2E,sig2F),c(p,q))) ## ALMOST diagonal cov matrix of (T,U,To,Uo) SigmaZ = blockm( blockm( blockm(SigT, SigT%*%B, SigU), matrix(0,2*r,rx), SigTo), matrix(0,2*r+rx,ry), SigUo) ## inverse middle term lemma invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + GGef) ## Calculate conditional expectations with efficient lemma # print(all.equal(invS,invS_old)) tmp <- Lemma(dataXY, SigmaZ, invZtilde, Gamma, sig2E, sig2F,p,q,r,rx,ry) # print(all.equal(Lemma(cbind(X,Y), SigmaZ, invS, Gamma, sig2E, sig2F,p,q,r,rx,ry), Lemma_old(cbind(X,Y), SigmaZ, invS, Gamma))) ## Define Szz as expected crossprod of Z VarZc = tmp$VarZc EZc = tmp$EZc Szz = VarZc + crossprod(EZc)/N ## For compatibility # invEF_Gamma <- rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F) # inv2EF_Gamma <- rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/(sig2E^2), # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/(sig2F^2)) # invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + # t(Gamma) %*% rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F)) # # invS_Gamma <- invEF_Gamma - invEF_Gamma %*% invZtilde %*% crossprod(invEF_Gamma,Gamma) ## inverse in middle term in lemma # invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + # t(Gamma) %*% rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F)) ## Calculate cond mean of E,F # invS_covEF <- diag(1,p+q) - invEF_Gamma %*% invZtilde %*% t(Gamma) # covEF = rbind(diag(sig2E,p), diag(0,q,p)) # mu_EF_old = dataXY - dataXY %*% invEF_Gamma %*% invZtilde %*% t(Gamma) mu_EF = dataXY mu_EF <- mu_EF - (dataXY %*% (GammaEF %*% invZtilde)) %*% t(Gamma) ## Calculate immediately expected crossprod of E,F # Ceeff_old = SigmaEF - t(SigmaEF) %*% invS_covEF + crossprod(mu_EF) / N # Ceeff = Gamma %*% MASS::ginv(MASS::ginv(SigmaZ) + t(Gamma)%*%invSEF%*%Gamma) %*% t(Gamma) + # crossprod(mu_EF) / N # print(all.equal(mu_EF_old, mu_EF)) # print(all.equal(Ceeff_old, Ceeff)) ## Take trace of the matrix # Cee_old <- sum(diag(Ceeff_old[1:p,1:p]))/p Cee <- sum(diag( crossprod(rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), 0*C, matrix(0,q,rx), 0*Co)))%*%invZtilde ))/p + ssq(mu_EF[,1:p])/N/p # Cff_old <- sum(diag(Ceeff_old[-(1:p),-(1:p)]))/q Cff <- sum(diag( crossprod(rbind(cbind(0*W, matrix(0,p,r), 0*Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)))%*%invZtilde ))/q + ssq(mu_EF[,-(1:p)])/N/q # cat('Cee\n'); print(all.equal(Cee_old,Cee)); # print(all.equal(Cff_old,Cff)) # Cee <- sum(diag( # crossprod(rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), # cbind(matrix(0,q,r), 0*C, matrix(0,q,rx), 0*Co)))%*%invZtilde # ))/p + ssq(mu_EF[,1:p])/N/p # Cff <- sum(diag( # crossprod(rbind(cbind(0*W, matrix(0,p,r), 0*Wo, matrix(0,p,ry)), # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)))%*%invZtilde # ))/q + ssq(mu_EF[,-(1:p)])/N/q #covE = rbind(diag(sig2E,p), diag(0,q,p)) #mu_E = cbind(X,Y) %*% invS %*% covE #Cee = sum(diag(diag(sig2E,p) - t(covE) %*% invS %*% covE + crossprod(mu_E) / N))/p #covF = rbind(diag(0,p,q), diag(sig2F,q)) #mu_F = cbind(X,Y) %*% invS %*% covF #Cff = sum(diag(diag(sig2F,q) - t(covF) %*% invS %*% covF + crossprod(mu_F) / N))/q covH = rbind(0*W, C%*%SigH) covHEF = rbind(0*W, C%*%SigH/sig2F) # invS_covH <- (covH/sig2F - invEF_Gamma %*% invZtilde %*% crossprod(invEF_Gamma,covH)) # mu_H_old = dataXY %*% invS_covH # mu_H_old <- dataXY %*% invS %*% covH mu_H <- dataXY %*% covHEF mu_H <- mu_H - (dataXY %*% (GammaEF %*% invZtilde)) %*% (t(Gamma) %*% covHEF) # Chh_old = SigH - t(covH) %*% invS_covH + crossprod(mu_H) / N # Chh_old <- SigH - t(covH) %*% invS %*% covH + crossprod(mu_H) / N Chh <- SigH Chh <- Chh - t(covH) %*% covHEF Chh <- Chh + (t(covH) %*% GammaEF %*% invZtilde) %*% (t(Gamma) %*% covHEF) Chh <- Chh + crossprod(mu_H) / N # print(all.equal(mu_H_old, mu_H)) # print(all.equal(Chh_old, Chh)) ## diagonal cov matrix of (X,Y), hopefully NOT NEEDED # SigmaXY = Gamma %*% SigmaZ %*% t(Gamma) + SigmaEF ## INVERSE diagonal cov matrix of (E,F), hopefully NOT NEEDED # invSEF <- diag(1/diag(SigmaEF)) ## INVERSE diagonal cov matrix of (X,Y), hopefully NOT NEEDED # invS <- invSEF - invSEF %*% Gamma %*% MASS::ginv(MASS::ginv(SigmaZ) + t(Gamma)%*%invSEF%*%Gamma) %*% t(Gamma) %*% invSEF # if(use_lemma == TRUE){MASS::ginv(t(0))} ## log of det SigmaXY, see matrix determinant lemma logdet <- log(det(diag(2*r+rx+ry) + GGef%*%SigmaZ))+p*log(sig2E)+q*log(sig2F) ## representation of SigmaXY %*% invS XYinvS <- ssq(cbind(X/sqrt(sig2E), Y/sqrt(sig2F))) XYinvS <- XYinvS - sum(diag(crossprod(dataXY %*% GammaEF) %*% invZtilde)) ## Log likelihood loglik = N*(p+q)*log(2*pi) + N * logdet + XYinvS loglik = - loglik/2 # print(all.equal(XYinvS, sum(diag(dataXY %*% invS %*% t(dataXY))))) # MASS::ginv(t(0)) comp_log <- - N/2*(p+q)*log(2*pi) comp_log <- comp_log - N/2*(p*log(sig2E)+q*log(sig2F)) comp_log <- comp_log - N/2*ssq(cbind(X/sqrt(sig2E), Y/sqrt(sig2F))) comp_log <- comp_log + N*sum(diag(crossprod(EZc,dataXY)%*%GammaEF)) comp_log <- comp_log - N/2*sum(diag(GGef%*%Szz)) list( EZc = EZc, Szz = Szz, mu_T = matrix(EZc[,1:r],N,r), mu_U = matrix(EZc[,r+1:r],N,r), mu_To = matrix(EZc[,2*r+1:rx],N,rx), mu_Uo = matrix(EZc[,2*r+rx+1:ry],N,ry), Stt = matrix(Szz[1:r, 1:r],r,r), Suu = matrix(Szz[r+1:r, r+1:r],r,r), Stoto = matrix(Szz[2*r+1:rx, 2*r+1:rx],rx,rx), Suouo = matrix(Szz[2*r+rx+1:ry, 2*r+rx+1:ry],ry,ry), Sut = matrix(Szz[r+1:r, 1:r],r,r), Stto = matrix(Szz[1:r, 2*r+1:rx],r,rx), Suuo = matrix(Szz[r+1:r, 2*r+rx+1:ry],r,ry), See = Cee, Sff = Cff, Shh = Chh, loglik = loglik, comp_log = comp_log ) } #' @export E_step <- function(X, Y, params){ ## retrieve parameters W = params$W C = params$C Wo = params$Wo Co = params$Co B = params$B SigT = params$SigT SigTo = (ssq(Wo)>0)*params$SigTo +0# + 1e-10*(ssq(Wo)==0) SigUo = (ssq(Co)>0)*params$SigUo +0# + 1e-10*(ssq(Co)==0) SigH = params$SigH sig2E = params$sig2E sig2F = params$sig2F SigU = SigT%*%B^2 + SigH ## define dimensions N = nrow(X) p = nrow(W) q = nrow(C) r = ncol(W) rx = ncol(Wo) ry = ncol(Co) ## concatenate data dataXY <- cbind(X,Y) ## Gamma is the generalized loading matrix, with PO2PLS structure Gamma = rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)) ## Gamma multiplied by inverse SigmaEF GammaEF <- Gamma GammaEF[1:p,c(1:r,2*r+1:rx)] <- 1/sig2E* GammaEF[1:p,c(1:r,2*r+1:rx)] GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] <- 1/sig2F* GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] GGef <- t(Gamma) %*% GammaEF ## diagonal cov matrix of (E,F), hopefully NOT NEEDED # SigmaEF = diag(rep(c(sig2E,sig2F),c(p,q))) ## ALMOST diagonal cov matrix of (T,U,To,Uo) SigmaZ = blockm( blockm( blockm(SigT, SigT%*%B, SigU), matrix(0,2*r,rx), SigTo), matrix(0,2*r+rx,ry), SigUo) ## inverse middle term lemma invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + GGef) ## Calculate conditional expectations with efficient lemma # print(all.equal(invS,invS_old)) tmp <- Lemma(dataXY, SigmaZ, invZtilde, Gamma, sig2E, sig2F,p,q,r,rx,ry) # print(all.equal(Lemma(cbind(X,Y), SigmaZ, invS, Gamma, sig2E, sig2F,p,q,r,rx,ry), Lemma_old(cbind(X,Y), SigmaZ, invS, Gamma))) ## Define Szz as expected crossprod of Z VarZc = tmp$VarZc EZc = tmp$EZc Szz = VarZc + crossprod(EZc)/N ## For compatibility # invEF_Gamma <- rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F) # inv2EF_Gamma <- rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/(sig2E^2), # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/(sig2F^2)) # invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + # t(Gamma) %*% rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F)) # # invS_Gamma <- invEF_Gamma - invEF_Gamma %*% invZtilde %*% crossprod(invEF_Gamma,Gamma) ## inverse in middle term in lemma # invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + # t(Gamma) %*% rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry))/sig2E, # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)/sig2F)) # ## Calculate cond mean of E,F # # invS_covEF <- diag(1,p+q) - invEF_Gamma %*% invZtilde %*% t(Gamma) # # covEF = rbind(diag(sig2E,p), diag(0,q,p)) # # mu_EF_old = dataXY - dataXY %*% invEF_Gamma %*% invZtilde %*% t(Gamma) # mu_EF = dataXY # mu_EF <- mu_EF - (dataXY %*% (GammaEF %*% invZtilde)) %*% t(Gamma) # # ## Calculate immediately expected crossprod of E,F # # Ceeff_old = SigmaEF - t(SigmaEF) %*% invS_covEF + crossprod(mu_EF) / N # # Ceeff = Gamma %*% MASS::ginv(MASS::ginv(SigmaZ) + t(Gamma)%*%invSEF%*%Gamma) %*% t(Gamma) + # # crossprod(mu_EF) / N # # print(all.equal(mu_EF_old, mu_EF)) # # print(all.equal(Ceeff_old, Ceeff)) # # ## Take trace of the matrix # # Cee_old <- sum(diag(Ceeff_old[1:p,1:p]))/p # Cee <- sum(diag( # crossprod(rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), # cbind(matrix(0,q,r), 0*C, matrix(0,q,rx), 0*Co)))%*%invZtilde # ))/p + ssq(mu_EF[,1:p])/N/p # # Cff_old <- sum(diag(Ceeff_old[-(1:p),-(1:p)]))/q # Cff <- sum(diag( # crossprod(rbind(cbind(0*W, matrix(0,p,r), 0*Wo, matrix(0,p,ry)), # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)))%*%invZtilde # ))/q + ssq(mu_EF[,-(1:p)])/N/q # # cat('Cee\n'); print(all.equal(Cee_old,Cee)); # # print(all.equal(Cff_old,Cff)) # # # Cee <- sum(diag( # # crossprod(rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), # # cbind(matrix(0,q,r), 0*C, matrix(0,q,rx), 0*Co)))%*%invZtilde # # ))/p + ssq(mu_EF[,1:p])/N/p # # Cff <- sum(diag( # # crossprod(rbind(cbind(0*W, matrix(0,p,r), 0*Wo, matrix(0,p,ry)), # # cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)))%*%invZtilde # # ))/q + ssq(mu_EF[,-(1:p)])/N/q # # # #covE = rbind(diag(sig2E,p), diag(0,q,p)) # #mu_E = cbind(X,Y) %*% invS %*% covE # #Cee = sum(diag(diag(sig2E,p) - t(covE) %*% invS %*% covE + crossprod(mu_E) / N))/p # # #covF = rbind(diag(0,p,q), diag(sig2F,q)) # #mu_F = cbind(X,Y) %*% invS %*% covF # #Cff = sum(diag(diag(sig2F,q) - t(covF) %*% invS %*% covF + crossprod(mu_F) / N))/q # # covH = rbind(0*W, C%*%SigH) # covHEF = rbind(0*W, C%*%SigH/sig2F) # # invS_covH <- (covH/sig2F - invEF_Gamma %*% invZtilde %*% crossprod(invEF_Gamma,covH)) # # mu_H_old = dataXY %*% invS_covH # # mu_H_old <- dataXY %*% invS %*% covH # mu_H <- dataXY %*% covHEF # mu_H <- mu_H - (dataXY %*% (GammaEF %*% invZtilde)) %*% (t(Gamma) %*% covHEF) # # Chh_old = SigH - t(covH) %*% invS_covH + crossprod(mu_H) / N # # Chh_old <- SigH - t(covH) %*% invS %*% covH + crossprod(mu_H) / N # Chh <- SigH # Chh <- Chh - t(covH) %*% covHEF # Chh <- Chh + (t(covH) %*% GammaEF %*% invZtilde) %*% (t(Gamma) %*% covHEF) # Chh <- Chh + crossprod(mu_H) / N # # print(all.equal(mu_H_old, mu_H)) # # print(all.equal(Chh_old, Chh)) # # ## diagonal cov matrix of (X,Y), hopefully NOT NEEDED # # SigmaXY = Gamma %*% SigmaZ %*% t(Gamma) + SigmaEF # ## INVERSE diagonal cov matrix of (E,F), hopefully NOT NEEDED # # invSEF <- diag(1/diag(SigmaEF)) # ## INVERSE diagonal cov matrix of (X,Y), hopefully NOT NEEDED # # invS <- invSEF - invSEF %*% Gamma %*% MASS::ginv(MASS::ginv(SigmaZ) + t(Gamma)%*%invSEF%*%Gamma) %*% t(Gamma) %*% invSEF # # if(use_lemma == TRUE){MASS::ginv(t(0))} # ## log of det SigmaXY, see matrix determinant lemma # logdet <- log(det(diag(2*r+rx+ry) + GGef%*%SigmaZ))+p*log(sig2E)+q*log(sig2F) # ## representation of SigmaXY %*% invS # XYinvS <- ssq(cbind(X/sqrt(sig2E), Y/sqrt(sig2F))) # XYinvS <- XYinvS - sum(diag(crossprod(dataXY %*% GammaEF) %*% invZtilde)) # ## Log likelihood # loglik = N*(p+q)*log(2*pi) + N * logdet + XYinvS # loglik = - loglik/2 # # print(all.equal(XYinvS, sum(diag(dataXY %*% invS %*% t(dataXY))))) # # MASS::ginv(t(0)) # # comp_log <- - N/2*(p+q)*log(2*pi) # comp_log <- comp_log - N/2*(p*log(sig2E)+q*log(sig2F)) # comp_log <- comp_log - N/2*ssq(cbind(X/sqrt(sig2E), Y/sqrt(sig2F))) # comp_log <- comp_log + N*sum(diag(crossprod(EZc,dataXY)%*%GammaEF)) # comp_log <- comp_log - N/2*sum(diag(GGef%*%Szz)) # # list( # EZc = EZc, # Szz = Szz, # mu_T = matrix(EZc[,1:r],N,r), # mu_U = matrix(EZc[,r+1:r],N,r), # mu_To = matrix(EZc[,2*r+1:rx],N,rx), # mu_Uo = matrix(EZc[,2*r+rx+1:ry],N,ry), # Stt = matrix(Szz[1:r, 1:r],r,r), # Suu = matrix(Szz[r+1:r, r+1:r],r,r), # Stoto = matrix(Szz[2*r+1:rx, 2*r+1:rx],rx,rx), # Suouo = matrix(Szz[2*r+rx+1:ry, 2*r+rx+1:ry],ry,ry), # Sut = matrix(Szz[r+1:r, 1:r],r,r), # Stto = matrix(Szz[1:r, 2*r+1:rx],r,rx), # Suuo = matrix(Szz[r+1:r, 2*r+rx+1:ry],r,ry), # See = Cee, # Sff = Cff, # Shh = Chh, # loglik = loglik, # comp_log = comp_log # ) return(E_step_test(dataXY, p, q, r, rx, ry, N, SigmaZ, GammaEF, invZtilde, Gamma, GGef, EZc, Szz, W, C, Wo, Co, SigT, SigH, sig2E, sig2F)) } #' @export E_step_test <- function(dataXY, p, q, r, rx, ry, N, SigmaZ, GammaEF, invZtilde, Gamma, GGef, EZc, Szz, W, C, Wo, Co, SigT, SigH, sig2E, sig2F){ return(E_step_testC(dataXY, p, q, r, rx, ry, N, SigmaZ, GammaEF, invZtilde, Gamma, GGef, EZc, Szz, W, C, Wo, Co, SigT, SigH, sig2E, sig2F)) } #' @export M_step <- function(E_fit, params, X, Y, orth_type = c("SVD","QR")){ orth_x = ssq(params$Wo) > 0 orth_y = ssq(params$Co) > 0 orth_type = match.arg(orth_type) with(E_fit,{ N = nrow(X) r = ncol(mu_T) rx = ncol(mu_To) ry = ncol(mu_Uo) params$B = Sut %*% MASS::ginv(Stt) * diag(1,r) params$SigT = Stt*diag(1,r) params$SigTo = Stoto*diag(1,rx) params$SigUo = Suouo*diag(1,ry) params$SigH = Shh*diag(1,r)#abs(Suu - 2*Sut%*%params_old$B + Stt%*%params_old$B^2) params$sig2E = See params$sig2F = Sff params$W = orth(t(X/N) %*% mu_T - params$Wo%*%t(Stto),type = orth_type)#%*%MASS::ginv(Stt) params$C = orth(t(Y/N) %*% mu_U - params$Co%*%t(Suuo),type = orth_type)#%*%MASS::ginv(Suu) params$Wo = suppressWarnings(orth_x*orth(t(X/N) %*% mu_To - params$W%*%Stto,type = orth_type))#%*%MASS::ginv(Stoto) params$Co = suppressWarnings(orth_y*orth(t(Y/N) %*% mu_Uo - params$C%*%Suuo,type = orth_type))#%*%MASS::ginv(Suouo) params }) } #' @export jitter_params <- function(params, amount = NULL){ suppressWarnings(params[1:4] <- lapply(params[1:4], function(e) sign(ssq(e))*orth(jitter(e,amount = 1)))) params } #' @export diagnostics.PO2PLS <- function(th, th0){ c( W = max(abs(crossprod(th$W,th0$W))), C = max(abs(crossprod(th$C,th0$C))), Wo = max(abs(crossprod(th$Wo,th0$Wo))), Co = max(abs(crossprod(th$Co,th0$Co))), varTo_T = sum(diag(th$SigTo))/sum(diag(th$SigT))/ncol(th$Wo)*ncol(th$W), varUo_U = sum(diag(th$SigUo))/sum(diag(th$SigT%*%th$B+th$SigH))/ncol(th$Co)*ncol(th$C), varU_T = sum(diag(th$SigT%*%th$B+th$SigH))/sum(diag(th$SigT)) ) } #' @export PO2PLS <- function(X, Y, r, rx, ry, steps = 1e5, tol = 1e-6, init_param='o2m', orth_type = "SVD", random_restart = FALSE, homogen_joint = FALSE){ if(all(c("W","Wo","C","Co","B","SigT","SigTo","SigUo","SigH","sig2E","sig2F") %in% names(init_param))) {message('using old fit \n'); params <- init_param} else {params <- generate_params(X, Y, r, rx, ry, type = init_param)} logl = 0*0:steps tic <- proc.time() print(paste('started',date())) i_rr <- 0 random_restart_original <- random_restart random_restart <- TRUE while(random_restart){ if(i_rr > 0) { message("Log-likelihood: ", logl[i+1]) message(paste("random restart no",i_rr)) } params_max <- params for(i in 1:steps){ E_next = E_step(X, Y, params) params_next = M_step(E_next, params, X, Y, orth_type = orth_type) if(homogen_joint){ params_next$B <- diag(1, r) params_next$SigH <- diag(1e-4, r) } params_next$B <- abs(params_next$B) if(i == 1) logl[1] = E_next$logl logl[i+1] = E_next$logl if(i > 1 && abs(logl[i+1]-logl[i]) < tol) break if(i %in% c(1e1, 1e2, 1e3, 5e3, 1e4, 4e4)) { print(data.frame(row.names = 1, steps = i, time = unname(proc.time()-tic)[3], diff = logl[i+1]-logl[i], logl = logl[i+1])) } if(logl[i+1] > max(logl[1:i])) params_max <- params_next params = params_next } if(!any(diff(logl[-1]) < -1e-10) | !random_restart_original) { random_restart = FALSE break } i_rr <- i_rr + 1 params <- jitter_params(params) params[-(1:4)] <- generate_params(X, Y, r, rx, ry, type = 'r')[-(1:4)] } # params <- params_max signB <- sign(diag(params$B)) params$B <- params$B %*% diag(signB,r) params$C <- params$C %*% diag(signB,r) ordSB <- order(diag(params$SigT %*% params$B), decreasing = TRUE) params$W <- params$W[,ordSB] params$C <- params$C[,ordSB] message("Nr steps was ", i) message("Negative increments: ", any(diff(logl[0:i+1]) < 0), "; Last increment: ", signif(logl[i+1]-logl[i],4)) message("Log-likelihood: ", logl[i+1]) outputt <- list(params = params_next, logl = logl[0:i+1][-1]) class(outputt) <- "PO2PLS" return(outputt) } #' @export PO2PLS_slow <- function(X, Y, r, rx, ry, steps = 1e5, tol = 1e-6, init_param='o2m', orth_type = "SVD", random_restart = FALSE){ if(all(c("W","Wo","C","Co","B","SigT","SigTo","SigUo","SigH","sig2E","sig2F") %in% names(init_param))) {message('using old fit \n'); params <- init_param} else {params <- generate_params(X, Y, r, rx, ry, type = init_param)} logl = 0*0:steps tic <- proc.time() print(paste('started',date())) i_rr <- 0 random_restart_original <- random_restart random_restart <- TRUE while(random_restart){ if(i_rr > 0) { message("Log-likelihood: ", logl[i+1]) message(paste("random restart no",i_rr)) } params_max <- params for(i in 1:steps){ E_next = E_step_slow(X, Y, params) params_next = M_step(E_next, params, X, Y, orth_type = orth_type) params_next$B <- abs(params_next$B) if(i == 1) logl[1] = E_next$logl logl[i+1] = E_next$logl if(i > 1 && abs(logl[i+1]-logl[i]) < tol) break if(i %in% c(1e1, 1e2, 1e3, 5e3, 1e4, 4e4)) { print(data.frame(row.names = 1, steps = i, time = unname(proc.time()-tic)[3], diff = logl[i+1]-logl[i], logl = logl[i+1])) } if(logl[i+1] > max(logl[1:i])) params_max <- params_next params = params_next } if(!any(diff(logl[-1]) < -1e-10) | !random_restart_original) { random_restart = FALSE break } i_rr <- i_rr + 1 params <- jitter_params(params) params[-(1:4)] <- generate_params(X, Y, r, rx, ry, type = 'r')[-(1:4)] } # params <- params_max signB <- sign(diag(params$B)) params$B <- params$B %*% diag(signB,r) params$C <- params$C %*% diag(signB,r) ordSB <- order(diag(params$SigT %*% params$B), decreasing = TRUE) params$W <- params$W[,ordSB] params$C <- params$C[,ordSB] message("Nr steps was ", i) message("Negative increments: ", any(diff(logl[0:i+1]) < 0), "; Last increment: ", signif(logl[i+1]-logl[i],4)) message("Log-likelihood: ", logl[i+1]) outputt <- list(params = params_next, logl = logl[0:i+1][-1]) class(outputt) <- "PO2PLS" return(outputt) } #' @export plot_accur.PO2PLS <- function(fit){ library(ggplot2) library(gridExtra) fit_o2m <- o2m(X,Y,ncol(parms$W),ncol(parms$Wo),ncol(parms$Co)) g1 <- ggplot(reshape2::melt(fit$diags[,1:4]), aes(x=Var1,y=value)) + geom_line(aes(col=Var2,linetype=grepl('o',Var2))) g2 <- ggplot(reshape2::melt(fit$diags[,5:6]), aes(x=Var1,y=value)) + geom_line(aes(col=Var2)) g3 <- ggplot(reshape2::melt(fit$diags[,7]), aes(x=1:nrow(fit$diags),y=value)) + geom_line() g4 <- qplot(x=1:length(fit$logl), y=fit$logl, geom='line') grid.arrange(g1,g2,g3,g4) print("### MAX ABS CROSSPROD WITH TRUE LOADINGS") print(apply(fit$diags,2,function(e) c(min=which.min(e), max=which.max(e)))) print("### MAX VALUES FOR O2PLS") print(c( W = max(abs(crossprod(fit_o2m$W.,parms$W))), C = max(abs(crossprod(fit_o2m$C.,parms$C))), Wo = max(abs(crossprod(orth(fit_o2m$P_Y),parms$Wo))), Co = max(abs(crossprod(orth(fit_o2m$P_X),parms$Co))) )) print("### MAX CROSSPROD JOINT AND ORTHOGONAL SPACE") print(c(W=max(abs(crossprod(parms$W,parms$Wo))), C=max(abs(crossprod(parms$C,parms$Co))))) } #' @export cov.PO2PLS <- function(fit){ with(fit$par, blockm(W%*%SigT%*%t(W)+Wo%*%SigTo%*%t(Wo) , W%*%SigT%*%B%*%t(C) , C%*%(SigT%*%B^2+SigH)%*%t(C)+Co%*%SigUo%*%t(Co))) } #' @export variances.PO2PLS <- function(fit, data, type_var = c("complete","component","variable")){ type_var = match.arg(type_var) N = nrow(data) p = nrow(fit$par$W) q = nrow(fit$par$C) r = ncol(fit$par$W) rx= ncol(fit$par$Wo) ry= ncol(fit$par$Co) SigU = with(fit$par, SigT%*%B^2 + SigH) dataEF <- cbind(data[,1:p]/fit$par$sig2E, data[,-(1:p)]/fit$par$sig2F) Gamma = with(fit$par, { rbind(cbind(W, matrix(0,p,r), Wo, matrix(0,p,ry)), cbind(matrix(0,q,r), C, matrix(0,q,rx), Co)) }) SigmaZ = with(fit$par,{ blockm( blockm( blockm(SigT, SigT%*%B, SigU), matrix(0,2*r,rx), SigTo), matrix(0,2*r+rx,ry), SigUo) }) GammaEF <- Gamma GammaEF[1:p,c(1:r,2*r+1:rx)] <- 1/fit$par$sig2E* GammaEF[1:p,c(1:r,2*r+1:rx)] GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] <- 1/fit$par$sig2F* GammaEF[-(1:p),c(r+1:r,2*r+rx+1:ry)] GGef <- t(Gamma) %*% GammaEF invZtilde <- MASS::ginv(MASS::ginv(SigmaZ) + GGef) VarZc <- SigmaZ - (t(Gamma %*% SigmaZ) %*% GammaEF) %*% SigmaZ + (t(Gamma %*% SigmaZ) %*% GammaEF) %*% invZtilde %*% GGef %*% SigmaZ EZc <- data %*% (GammaEF %*% SigmaZ) EZc <- EZc - data %*% ((GammaEF %*% invZtilde) %*% (GGef %*% SigmaZ)) Szz = VarZc + crossprod(EZc)/N E3Zc <- EZc%*%crossprod(EZc)/N + 3*EZc%*%VarZc E4Zc <- (crossprod(EZc)/N)^2 + 6*(crossprod(EZc)/N)%*%VarZc + 3*crossprod(VarZc) if(type_var == "component"){ Iobs = lapply(1:ncol(Gamma), function(comp_k) { Bobs <- diag(c(rep(1/fit$par$sig2E,p), rep(1/fit$par$sig2F,q)))*Szz[comp_k,comp_k] SSt1 <- Szz[comp_k,comp_k]*crossprod(dataEF)/N SSt2 <- crossprod(dataEF, E3Zc[,comp_k]%*%t(GammaEF[,comp_k]))/N SSt3 <- GammaEF[,comp_k] %*% as.matrix(E4Zc[comp_k,comp_k]) %*% t(GammaEF[,comp_k]) list(Bobs = Bobs, SSt1 = SSt1, SSt2 = SSt2, SSt3 = SSt3, SEs = -diag(MASS::ginv((Bobs - SSt1 + SSt2 + t(SSt2) - SSt3)))) }) return(Iobs) } if(type_var == "variable"){ Sigmaef_inv = (1/rep(c(fit$par$sig2E,fit$par$sig2F),c(p,q))) Iobs = list() Iobs$Bobs = lapply(1:ncol(data), function(j) Reduce(`+`, lapply(1:N, function(i) Szz*Sigmaef_inv[j]))) Iobs$SSt1 = lapply(1:ncol(data), function(j) Reduce(`+`, lapply(1:N, function(i) data[i,j]^2*Sigmaef_inv[j]^2*Szz))) Iobs$SSt2 = lapply(1:ncol(data), function(j) Reduce(`+`, lapply(1:N, function(i) data[i,j]*Sigmaef_inv[j]^2*E3Zc[i,]%*%t(Gamma[j,])))) Iobs$SSt3 = lapply(1:ncol(data), function(j) Reduce(`+`, lapply(1:N, function(i) Sigmaef_inv[j]^2*E4Zc%*%Gamma[j,]%*%t(Gamma[j,])))) #Iobs$SEs = with(Iobs, -diag(MASS::ginv((Bobs - SSt1 + SSt2 + t(SSt2) - SSt3)))) return(Iobs) } if(type_var == "complete"){ Sigmaef_inv = diag(1/rep(c(fit$par$sig2E,fit$par$sig2F),c(p,q))) Iobs = list() Iobs$Bobs = Reduce(`+`, lapply(1:N, function(i) Szz %x% Sigmaef_inv)) Iobs$muS = Reduce(`+`, lapply(1:N, function(i) EZc[i,] %x% (Sigmaef_inv %*% (data[i,])) )) Iobs$VarS = Reduce(`+`, lapply(1:N, function(i) VarZc %x% (Sigmaef_inv^2 %*% tcrossprod(data[i,])) - (E4Zc %x% Sigmaef_inv^2) %*% tcrossprod(c(Gamma)) )) Iobs$SSt = Reduce(`+`, lapply(1:N, function(i) Iobs$VarS - tcrossprod(Iobs$muS) )) Iobs$Iobs = with(Iobs, (Bobs - SSt)) Iobs$Iobs = with(Iobs, Iobs[-which(c(Gamma)==0),-which(c(Gamma)==0)]) #Iobs$SEs = with(Iobs, -diag(MASS::ginv((Bobs - SSt1 + SSt2 + t(SSt2) - SSt3)))) return(Iobs) } }
5d971a986e713429f94129056436e2660a2a862e
[ "R" ]
1
R
Sanne-Meijering/PO2PLS
bf65208b9a8166cc5b298b2be5eafaff43c3bfd8
a3a824827f0786cbc40993b378bfcd137eac96bf
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Text; namespace Airport_Panel_2 { class Passenger { // public string numOfFlight; public int index; public string firstName; public string secondName; public string nationality; public string passport; public string dateOfBirthday; public string sex; public string airclass; public void PassengersOutput() { Console.WriteLine($"{index,2}{firstName,15}{secondName,15}{nationality,10} {passport,10}{dateOfBirthday,12}{sex,8}{airclass,10}"); Console.WriteLine("-------------------------------------------------------------------------------------------------------------"); } } } <file_sep>using System; namespace Lab1._3._3 { class Program { static void Main(string[] args) { Console.Write("Введите число: "); int a = Convert.ToInt32(Console.ReadLine()); decimal factorial = 1; for (int i = a; i > 0; i--) { factorial *= i; } Console.WriteLine("Factorial = " + factorial); } } } <file_sep>using System; using System.Collections.Generic; namespace Lab1._5 { class Program { static void Main(string[] args) { Console.WriteLine("Enter first number"); int a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number"); int b = Convert.ToInt32(Console.ReadLine()); int dif = a- b ; if (dif < 0) { dif *= -1; } Console.WriteLine("Absolute difference = " + dif); Console.WriteLine(); Console.WriteLine("----------------------------------------------------------------------------------------------------------------------"); double unaryA = 0; for (int i =0; i<a; i++) { unaryA += Math.Pow(10, i); } double unaryB = 0; for (int i = 0; i < b; i++) { unaryB += Math.Pow(10, i); } double unaryDif = 0; for (int i = 0; i < dif; i++) { unaryDif += Math.Pow(10, i); } Console.WriteLine("Unary a = " + unaryA+ "\r\nUnary b = " + unaryB + "\r\nUnary difference = " + unaryDif); } } } <file_sep>using System; using System.Collections.Generic; namespace Airport_Panel { class Flight { public DateTime date; public int number; public string city; public string airline; public string terminal; public static string[] Status = new string[9] { "checkIn", "gateClosed", "arrived", "departed", "unknown", "canceled", "expected", "delayed", "inFlight" }; public string status; public string gate; public Flight(DateTime date, int number, string city, string airline, string terminal, string gate) { this.date = date; this.number = number; this.city = city; this.airline = airline; this.terminal = terminal; this.status = Status[new Random().Next(0, Status.Length)]; ; this.gate = gate; } public void Output() { Console.WriteLine($" date of arrival: {date} number of flight: {number} city: {city} airline: {airline} terminal: {terminal} gate: {gate} "); } } class Program { static void Main(string[] args) { DateTime date = new DateTime(2019, 5, 13); Flight flight1 = new Flight(date, 312, "Kyiv", "MAU", "B1", "G13"); Flight flight2 = new Flight(date, 442, "Boryspil", "7days", "B1", "G5"); Flight flight3 = new Flight(date, 218, "Lviv", "Turkish airlines", "B2", "G8"); Flight flight4 = new Flight(date, 125, "Odessa", "Fly emirates", "B3", "G25"); List<Flight> flights = new List<Flight>(){ flight1, flight2, flight3, flight4 }; for(int i = 0; i<flights.Count; i++) { flights[i].Output(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2._3 { enum CurrencyTypes { UAH, USD, EU }; class Money { public double Amount; public CurrencyTypes CurrencyType; public Money() { } public Money(double Amount, CurrencyTypes CurrencyType) { this.CurrencyType = CurrencyType; this.Amount = Amount; } public static Money operator ++(Money first) { first.Amount += 1; return first; } public static Money operator --(Money first) { first.Amount -= 1; return first; } public static Money operator *(Money first, int x) { first.Amount = first.Amount* x; return first; } public static bool operator true(Money first) { if (first.CurrencyType == CurrencyTypes.UAH) return true; else return false; } public static bool operator false(Money first) { if (first.CurrencyType == CurrencyTypes.UAH) return true; else return false; } public static Money operator +(Money first, double a) { first.Amount = first.Amount + a; return first; } public static bool operator >(Money first, Money second) { if (first.CurrencyType == second.CurrencyType) if (first.Amount > second.Amount) { return true; } else { return false; } else { if (first.CurrencyType == CurrencyTypes.UAH) { if (second.CurrencyType == CurrencyTypes.USD) { second.Amount *= 26; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } else { second.Amount *= 30; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } } else if (first.CurrencyType == CurrencyTypes.USD) { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } else { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 30; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } } else { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } else { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 26; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return true; } else { return false; } } } } } public static bool operator <(Money first, Money second) { if (first.CurrencyType == second.CurrencyType) if (first.Amount > second.Amount) { return false; } else { return true; } else { if (first.CurrencyType == CurrencyTypes.UAH) { if (second.CurrencyType == CurrencyTypes.USD) { second.Amount *= 26; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } else { second.Amount *= 30; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } } else if (first.CurrencyType == CurrencyTypes.USD) { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } else { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 30; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } } else { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } else { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 26; second.CurrencyType = CurrencyTypes.UAH; if (first.Amount > second.Amount) { return false; } else { return true; } } } } } public static Money operator +(Money first, Money second) { if (first.CurrencyType == second.CurrencyType) return new Money{Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType}; else { if(first.CurrencyType== CurrencyTypes.UAH) { if(second.CurrencyType == CurrencyTypes.USD) { second.Amount *= 26; second.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; }else { second.Amount *= 30; second.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; } } else if(first.CurrencyType == CurrencyTypes.USD) { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; } else { first.Amount /= 26; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 30; second.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; } } else { if (second.CurrencyType == CurrencyTypes.UAH) { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; } else { first.Amount /= 30; first.CurrencyType = CurrencyTypes.UAH; second.Amount /= 26; second.CurrencyType = CurrencyTypes.UAH; return new Money { Amount = first.Amount + second.Amount, CurrencyType = first.CurrencyType }; } } } } } class Program { static void Main(string[] args) { Money f = new Money(32, CurrencyTypes.UAH); Money s = new Money(10, CurrencyTypes.EU); Money t = new Money(); t = f + s; f = f + 10.0; Console.WriteLine(t.Amount); s--; f++; bool m = f > s; if (f) { Console.WriteLine("F is UAH"); } Console.WriteLine(t.Amount); t*=3; Console.WriteLine(t.Amount); Console.WriteLine(f > s); Console.ReadKey(); } } } <file_sep>using System; namespace Lab1._3._2 { class Program { static void Main(string[] args) { Console.Write("Введите первое число: "); double first = Convert.ToDouble(Console.ReadLine()); Console.Write("Введите другое число: "); double second = Convert.ToDouble(Console.ReadLine()); long a; Console.WriteLine(@"Select the arithmetic operation: 1. Multiplication 2. Divide 3. Addition 4. Subtraction 5. Exponentiation "); a = long.Parse(Console.ReadLine()); switch (a) { case 1: Console.WriteLine("Результатом умножения есть " + (first * second)); break; case 2: Console.WriteLine("Результатом деления есть " + first / second); break; case 3: Console.WriteLine("Результатом сумирования есть " + (first + second)); break; case 4: Console.WriteLine("Результатом вычитания есть " + (first - second)); break; case 5: Console.WriteLine("Результатом поднесения к степени есть " + (Math.Pow(first, second))); break; default: Console.WriteLine("Введите одно из этих чисел"); break; } } } } <file_sep>using System; namespace Lab1._4 { class Program { enum ComputerType { desktop, laptop, server } struct Computer { public int CPU; public float frequency; public int RAM; public int memory; // public ComputerType type; } static void Main(string[] args) { int[][] computers = new int[4][]; computers[0] = new int[3] { 2, 2, 1 }; computers[1] = new int[3] { 0, 3, 0 }; computers[2] = new int[3] { 3, 2, 0 }; computers[3] = new int[3] { 1, 1, 2 }; Computer desktop; desktop.CPU = 4; desktop.frequency = 2.5f; desktop.RAM = 6; desktop.memory = 500; Computer laptop; laptop.CPU = 2; laptop.frequency = 1.7f; laptop.RAM = 4; laptop.memory = 250; Computer server; server.CPU = 8; server.frequency = 3f; server.RAM = 16; server.memory = 2000; int CounterDesktop = 0; int CounterLaptop = 0; int CounterServer = 0; int TotalNumber = 0; for (int j = 0; j < computers.Length; j++) { for (int i = 0; i < computers[j].Length; i++) { TotalNumber += computers[j][i]; if (i == 0) { CounterDesktop += computers[j][0]; } else if (i == 1) { CounterLaptop += computers[j][1]; } else if (i == 2) { CounterServer += computers[j][2]; } } } //int TotalNumber = CounterDesktop + CounterLaptop + CounterServer; Console.WriteLine("Number of desktops - " + CounterDesktop); Console.WriteLine("Number of laptops - " + CounterLaptop); Console.WriteLine("Number of servers - " + CounterServer); Console.WriteLine("Total sum of computers = " + TotalNumber); Console.WriteLine("-----------------------------------------------------------------------------------------------"); Computer[] ArrayOfComputers = new Computer[3]; ArrayOfComputers[0] = desktop; ArrayOfComputers[1] = laptop; ArrayOfComputers[2] = server; int Max = 0; int IndexMax = 0; foreach (Computer i in ArrayOfComputers) { if (i.memory > Max) { Max = i.memory; IndexMax = Array.IndexOf(ArrayOfComputers, i); } } Console.WriteLine("Max memory is "+Max+"GB and it has index "+IndexMax); Console.WriteLine("-----------------------------------------------------------------------------------------------"); int MinCPU = 10; int IndexMinCPU = 0; foreach (Computer i in ArrayOfComputers) { if (i.CPU < MinCPU) { MinCPU = i.CPU; IndexMinCPU = Array.IndexOf(ArrayOfComputers, i); } } float MinRAM = 20F; int IndexMinRAM = 0; foreach (Computer i in ArrayOfComputers) { if (i.RAM < MinRAM) { MinRAM = i.RAM; IndexMinRAM = Array.IndexOf(ArrayOfComputers, i); } } if (IndexMinCPU == IndexMinRAM) { Console.WriteLine("Index of computer with min productivity = "+IndexMinRAM); } Console.WriteLine("-----------------------------------------------------------------------------------------------"); desktop.RAM = 8; Console.WriteLine("New RAM of desktops = " + desktop.RAM); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; namespace Lab2._1 { class Program { public interface ILibraryUser { void AddBook() { } void RemoveBook() { } void BookInfo() { } void BooksCount() { } } public class LibraryUser { public string FirstName { get; } public string LastName { get; } public int ID { get; } public int Phone { get; set; } public int BookLimit { get; } public LibraryUser(string FirstName, string LastName, int ID, int Phone, int BookLimit) { this.FirstName = FirstName; this.LastName = LastName; this.ID = ID; this.Phone = Phone; this.BookLimit = BookLimit; } private List<string> bookList = new List<string>(); private string this [int index] { get { try { return bookList[index]; } catch(Exception e) { return e.Message; } } set { try { bookList[index] = value; } catch (Exception e) { Console.WriteLine(e.Message); } } } public void AddBook(string name) { bookList.Add(name); Console.WriteLine("{0} Succesfully added", name); Console.WriteLine("--------------------------------------------"); } public void RemoveBook(int ind) { bookList.RemoveAt(ind); Console.WriteLine("{0} Succesfully removed", bookList[ind]); Console.WriteLine("--------------------------------------------"); } public void RemoveBook(string bookName) { bookList.Remove(bookName); Console.WriteLine("{0} Succesfully removed", bookName); Console.WriteLine("--------------------------------------------"); } public void BookInfo(int index) { Console.WriteLine(bookList[index]); Console.WriteLine("--------------------------------------------"); } public void BooksCount() { Console.WriteLine("{0} - total number of books", bookList.Count); Console.WriteLine("--------------------------------------------"); } public void PrintListOfBooks() { for(int i = 0; i<bookList.Count; i++) { Console.WriteLine(bookList[i]); } Console.WriteLine("--------------------------------------------"); } } static void Main(string[] args) { LibraryUser user1 = new LibraryUser("John", "Snow", 1, 0987654321, 8); LibraryUser user2 = new LibraryUser("Bob", "Marley", 2, 1234567890, 11); user1.AddBook("<NAME>"); user1.AddBook("House"); user1.AddBook("Waves"); user1.AddBook("Rat"); user1.AddBook("Snack"); user1.AddBook("Bang"); user1.AddBook("Crack"); user1.PrintListOfBooks(); user1.RemoveBook(0); user1.PrintListOfBooks(); user1.RemoveBook("Rat"); user1.PrintListOfBooks(); user1.BookInfo(2); user1.BooksCount(); } } } <file_sep>using System; namespace Lab1._2 { class Program { static void Main(string[] args) { // Use "Debugging" and "Watch" to study variables and constants //1) declare variables of all simple types: //bool, char, byte, sbyte, short, ushort, int, uint, long, ulong, decimal, float, double // their names should be: //boo, ch, b, sb, sh, ush, i, ui, l, ul, de, fl, d0 // initialize them with 1, 100, 250.7, 150, 10000, -25, -223, 300, 100000.6, 8, -33.1 // Check results (types and values). Is possible to do initialization? // Fix compilation errors (change values for impossible initialization) bool boo = true; char ch = ' '; byte b = 1; sbyte sb = -100; short sh = 150; ushort ush = 65000; int i = -223; uint ui = 300; long l = -9000000; ulong ul = 10000; decimal de = -33.1M; float fl = 100000.6F; double d0 = 250.7; //2) declare constants of int and double. Try to change their values. const int a = 128; const double c = 2345894.9; //3) declare 2 variables with var. Initialize them 20 and 20.5. Check types. // Try to reinitialize by 20.5 and 20 (change values). What results are there? var a1 = 20; var a2 = 20.5; //We can't change int type of a1 to double, but we can write 20 to double var // 4) declare variables of System.Int32 and System.Double. // Initialize them by values of i and d0. Is it possible? int axe = -223; double bob = 250.7; if (true) { // 5) declare variables of int, char, double // with names i, ch, do // is it possible? //It is impossible because we can't create variables with the same type // 6) change values of variables from 1) } // 7)check values of variables from 1). Are they changed? Think, why // 8) use implicit/ explicit conversion to convert variables from 1). // Is it possible? // Fix compilation errors (in case of impossible conversion commemt that line). // int -> char // bool -> short // double -> long // float -> char // int to char // decimal -> double // byte -> uint // ulong -> sbyte // 9) and reverse conversion with fixing compilation errors. // 10) declare int nullable value. Initialize it with 'null'. // Try to initialize variable i with 'null'. Is it possible? } } } <file_sep>using System; using System.Collections.Generic; namespace Airport_Panel_2 { public enum Actions { FlightDelete = 1, FlightAdd, FlightEdit, search, PassengerDelete, PassengerAdd, PassengerEdit, exit }; public enum SearchE { byNum = 1, byTime, byCity }; class Program { static void Main(string[] args) { Random rnd = new Random(); // about passengers string[] firstNames = { "Yuriy", "Vasya", "Vlad", "Kiril", "Julia", "Nastya", "Kate", "Bob", "Jack", "Artem", "Diana", "Lera", "Anya" }; string[] secondNames = { "Kosenko", "Pavlenko", "Kotlarenko", "Kharchenko", "Polishchuk", "Rudenko", "Fesenko", "Lazarenko", "Osadchyi", "Marynenko", "Komendant", "Poshukailo", "Savchenko" }; string[] nationalities = { "Ukranian", "Pole", "German", "British", "Slovak", "Italian", "Russian" }; string[] passports = new string[13]; for (int i = 0; i < firstNames.Length; i++) { int a = rnd.Next(000000, 999999); string b = ""; for (int j = 0; j < 2; j++) { b += (char)(rnd.Next(1040, 1071)); } passports[i] = b + a; //Console.WriteLine(passports[i]); } string[] datesOfBirthday = new string[13]; for (int i = 0; i < firstNames.Length; i++) { int a = rnd.Next(01, 31); int b = rnd.Next(01, 12); int c = rnd.Next(1950, 2019); datesOfBirthday[i] = String.Format($"{a}.{b}.{c}"); //Console.WriteLine(datesOfBirthday[i]); } string[] sexs = { "male", "female" }; string[] airclasses = { "economy", "busines" }; int n = 5; string[] cities = { "Kyiv", "Boryspil", "Viena", "Los Angeles", "Moskow", "Minsk", "Warsaw" }; string[] airlines = { "7up", "MAU", "Turkish Airlines", "Emirates", "Ryanair", "Wizz Air" }; int[] flightNumbers = new int[10]; for (int i = 0; i < flightNumbers.Length; i++) { flightNumbers[i] = rnd.Next(1,50); } string[] terminals = { "D1", "D2", "D3", "D4" }; string[] statuses = { "checkIn", "gateClosed", "arrived", "departed", "unknown", "canceled", "expected", "delayed", "inFlight" }; int[] gates = new int[10]; for (int i = 0; i < gates.Length; i++) { gates[i] = rnd.Next(50); } DateTime date = DateTime.Now; List<Flight> flights = new List<Flight>(); for (int i = 0; i <= n; i++) { List<Passenger> passengers = new List<Passenger>(); flights.Add(new Flight()); flights[i].index = i+1; flights[i].date = date + TimeSpan.FromHours(2.0); flights[i].city = cities[rnd.Next(0, cities.Length)]; flights[i].flightNumber = flightNumbers[rnd.Next(0, flightNumbers.Length)]; flights[i].airline = airlines[rnd.Next(0, airlines.Length)]; flights[i].terminal = terminals[rnd.Next(0, terminals.Length)]; flights[i].status = statuses[rnd.Next(0, statuses.Length)]; flights[i].gate = gates[rnd.Next(0, gates.Length)]; flights[i].passengers = passengers; date += TimeSpan.FromHours(2.0); for (int j = 0; j <= firstNames.Length; j++) { passengers.Add(new Passenger()); passengers[j].index = j+1; passengers[j].firstName = firstNames[rnd.Next(0, firstNames.Length)]; passengers[j].secondName = secondNames[rnd.Next(0, secondNames.Length)]; passengers[j].nationality = nationalities[rnd.Next(0, nationalities.Length)]; passengers[j].passport = passports[rnd.Next(0, passports.Length)]; passengers[j].dateOfBirthday = datesOfBirthday[rnd.Next(0, datesOfBirthday.Length)]; passengers[j].sex = sexs[rnd.Next(0, sexs.Length)]; passengers[j].airclass = airclasses[rnd.Next(0, airclasses.Length)]; } } Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } Actions ac; Methods.Menu(); do { ac = (Actions)Enum.Parse(typeof(Actions), Console.ReadLine()); if (ac > 0 && (int)ac <9) { switch (ac) { case Actions.FlightDelete: Methods.FlightDelete(flights); Console.WriteLine(""); break; case Actions.FlightAdd: Methods.FlightAdd(flights); Console.WriteLine(""); break; case Actions.FlightEdit: Methods.FlightEdit(flights); Console.WriteLine(""); break; case Actions.search: Console.WriteLine(@"Choose how to search: 1.By number 2.By time 3.By city"); SearchE sch; sch = (SearchE)Enum.Parse(typeof(Actions), Console.ReadLine()); if (sch > 0 && (int)sch < 4) { switch (sch) { case SearchE.byNum: Methods.SearchByNum(flights); break; case SearchE.byTime: Methods.SearchByTime(flights); break; case SearchE.byCity: Methods.SearchByCity(flights); break; } Methods.Menu(); } break; case Actions.PassengerDelete: Methods.PassengerDelete(flights); break; case Actions.PassengerAdd: Methods.PassengerAdd(flights); break; case Actions.PassengerEdit: Methods.PassengerEdit(flights); break; case Actions.exit: break; default: Console.WriteLine("Incorrect number!"); break; } } else { Console.WriteLine("Incorrect number, try again"); Methods.Menu(); } } while (ac != Actions.exit); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Airport_Panel_2 { class Flight { public int index; public DateTime date; public int flightNumber; public string city; public string airline; public string terminal; public string status; public int gate; public List<Passenger> passengers; public void FlightOutput() { Console.WriteLine($"{index}{date,25}{flightNumber,10}{city,22}{airline,20}{terminal,8}{status,18}{gate,9}"); Console.WriteLine("--------------------------------------------------------------------------------------------------------------------"); } } } <file_sep>using System; namespace Lab1._3._1 { class Program { static void Main(string[] args) { for (int i = 0; ; i++) { Console.WriteLine("Enter your steps "); double a = double.Parse(Console.ReadLine()); if (a == 3827183 || a == 3817283) { Console.WriteLine("It is the right order!"); break; } else { Console.WriteLine("Try again!"); Console.WriteLine("If you want to exit press 1. To try again press any number"); byte b = byte.Parse(Console.ReadLine()); if (b == 1) { break; } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Lab2._2 { class Program { static void Main(string[] args) { Rectangle obj = new Rectangle(); Console.WriteLine("Enter left position of cursor"); obj.left = int.Parse(Console.ReadLine()); Console.WriteLine("Enter top position of cursor"); obj.top = int.Parse(Console.ReadLine()); Console.WriteLine("Enter length of the rectangle:"); obj.length = int.Parse(Console.ReadLine()); Console.WriteLine("Enter width of the rectangle:"); obj.width = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the symbol for the border:"); obj.symbol = Console.ReadLine(); Console.WriteLine("Enter your text:"); obj.text = Console.ReadLine(); obj.Draw(obj.left, obj.top, obj.length, obj.width, obj.symbol, obj.text); } } public class Rectangle { public int left; public int top; public int length; public int width; public string symbol; public string text; public void Draw(int left, int top, int length, int width, string symbol, string text) { for (int i = 0; i < width; i++) { Console.SetCursorPosition(left, top); for (int j =0; j< length; j++) { if(j == length - 1) { Console.WriteLine(symbol); } else if (i == 0 || i == width - 1) { Console.Write(symbol); } else if (j == 0) { Console.Write(symbol); } else { Console.Write(" "); } } top += 1; } Console.SetCursorPosition(left + (length / 2) - (text.Length/2), top - width / 2 ); Console.Write(text); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Airport_Panel_2 { static class Methods { public static void FlightDelete(List<Flight> flights) { Console.WriteLine("Enter the index of the element which you want to FlightDelete: "); int del; del = int.Parse(Console.ReadLine()); if (del > 0 && del < flights.Count) { flights.Remove(flights[del - 1]); for (int i = 0; i < flights.Count; i++) { flights[i].index = i + 1; } Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } } else { Console.WriteLine("Inncorect index"); } Menu(); } public static void FlightAdd(List<Flight> flights) { Console.WriteLine("Enter on which position you want to FlightAdd a new element: "); int n; n = int.Parse(Console.ReadLine()) - 1; if (n > 0 && n <= flights.Count) { flights.Insert(n, new Flight()); flights[n].index = n; Console.WriteLine("Enter date(дд.мм.рррр гг:хх:сс): "); string d = Console.ReadLine(); if (DateTime.TryParse(d, out DateTime da)) { flights[n].date = DateTime.Parse(d); } else { Console.WriteLine("Incorrect date, try again"); FlightAdd(flights); } Console.WriteLine("Enter number of flight: "); string fl = Console.ReadLine(); if (Int32.TryParse(fl, out int x) && int.Parse(fl) < 150 && int.Parse(fl) > 0) { flights[n].flightNumber = int.Parse(fl); } else { Console.WriteLine("Incorrect number, try again"); FlightAdd(flights); } Console.WriteLine("Enter city: "); string c = Console.ReadLine(); if (c.Length > 0 && c.Length < 15) { flights[n].city = c; } else { Console.WriteLine("Incorrect city, try again"); FlightAdd(flights); } Console.WriteLine("Enter airline: "); string air = Console.ReadLine(); if (air.Length > 0 && air.Length < 20) { flights[n].airline = air; } else { Console.WriteLine("Incorrect airline, try again"); FlightAdd(flights); } Console.WriteLine("Enter terminal: "); string ter = Console.ReadLine(); if (ter.Length > 0 && ter.Length < 5) { flights[n].terminal = ter; } else { Console.WriteLine("Incorrect terminal, try again"); FlightAdd(flights); } Console.WriteLine("Enter status: "); string st = Console.ReadLine(); if (st.Length > 0 && st.Length < 20) { flights[n].status = st; } else { Console.WriteLine("Incorrect status, try again"); FlightAdd(flights); } Console.WriteLine("Enter gates: "); string ga = Console.ReadLine(); if (Int32.TryParse(ga, out int v) && int.Parse(ga) < 100 && int.Parse(ga) > 0) { flights[n].gate = int.Parse(ga); } else { Console.WriteLine("Incorrect gate, try again"); FlightAdd(flights); } for (int i = 0; i < flights.Count; i++) { flights[i].index = i + 1; } Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } } else { Console.WriteLine("Inncorect index"); } Menu(); } public static void FlightEdit(List<Flight> flights) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } Console.WriteLine("Enter the index of the element which you want to FlightEdit"); int dc = int.Parse(Console.ReadLine()); if (dc > 0 && dc <= flights.Count) { flights[dc].index = dc; Console.WriteLine("Enter new date(дд.мм.рррр гг:хх:сс): "); string d = Console.ReadLine(); if (DateTime.TryParse(d, out DateTime da)) { flights[dc].date = DateTime.Parse(d); } else { Console.WriteLine("Incorrect date, try again"); FlightAdd(flights); } Console.WriteLine("Enter new number of flight: "); string fl = Console.ReadLine(); if (Int32.TryParse(fl, out int x) && int.Parse(fl) < 150 && int.Parse(fl) > 0) { flights[dc].flightNumber = int.Parse(fl); } else { Console.WriteLine("Incorrect number, try again"); FlightAdd(flights); } Console.WriteLine("Enter new city: "); string c = Console.ReadLine(); if (c.Length > 0 && c.Length < 15) { flights[dc].city = c; } else { Console.WriteLine("Incorrect city, try again"); FlightAdd(flights); } Console.WriteLine("Enter new airline: "); string air = Console.ReadLine(); if (air.Length > 0 && air.Length < 20) { flights[dc].airline = air; } else { Console.WriteLine("Incorrect airline, try again"); FlightAdd(flights); } Console.WriteLine("Enter new terminal: "); string ter = Console.ReadLine(); if (ter.Length > 0 && ter.Length < 5) { flights[dc].terminal = ter; } else { Console.WriteLine("Incorrect terminal, try again"); FlightAdd(flights); } Console.WriteLine("Enter new status: "); string st = Console.ReadLine(); if (st.Length > 0 && st.Length < 20) { flights[dc].status = st; } else { Console.WriteLine("Incorrect status, try again"); FlightAdd(flights); } Console.WriteLine("Enter new gates: "); string ga = Console.ReadLine(); if (Int32.TryParse(ga, out int v) && int.Parse(ga) < 100 && int.Parse(ga) > 0) { flights[dc].gate = int.Parse(ga); } else { Console.WriteLine("Incorrect gate, try again"); FlightAdd(flights); } Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } } else { Console.WriteLine("Inncorect index"); } Menu(); } public static void PassengerDelete(List<Flight> flights) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } Console.WriteLine("Choose flight:"); int f = int.Parse(Console.ReadLine()); if (f > 0 && f < flights.Count) { flights[f - 1].FlightOutput(); for (int i = 0; i < flights[f - 1].passengers.Count; i++) { flights[f - 1].passengers[i].PassengersOutput(); } Console.WriteLine("Enter index of passenger who you want to delete:"); int del = int.Parse(Console.ReadLine()); if (del > 0 && del < flights[f - 1].passengers.Count) { flights[f - 1].passengers.Remove(flights[f - 1].passengers[del - 1]); for (int i = 0; i < flights[f - 1].passengers.Count; i++) { flights[f - 1].passengers[i].index = i + 1; } Console.WriteLine("\r\nindex: First Name: Second Name: Nationality: Passport: Date: Sex: Airclass: \r\n"); for (int i = 0; i < flights[f - 1].passengers.Count; i++) { flights[f - 1].passengers[i].PassengersOutput(); } } else { Console.WriteLine("Inncorect index"); } } else { Console.WriteLine("Inncorect index of flight"); } Menu(); } public static void PassengerEdit(List<Flight> flights) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } Console.WriteLine("Choose flight:"); int f = int.Parse(Console.ReadLine()) - 1; if (f > 0 && f < flights.Count) { flights[f].FlightOutput(); for (int i = 0; i < flights[f].passengers.Count; i++) { flights[f].passengers[i].PassengersOutput(); } Console.WriteLine("Enter index of passenger who you want to edit:"); int change = int.Parse(Console.ReadLine()) - 1; if (change > 0 && change < flights[f].passengers.Count) { flights[f].passengers[change].index = change; Console.WriteLine("Enter new first name:"); string first = Console.ReadLine(); if (first.Length < 10) { flights[f].passengers[change].firstName = first; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerEdit(flights); } Console.WriteLine("Enter new second name:"); string second = Console.ReadLine(); if (second.Length < 20) { flights[f].passengers[change].secondName = second; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerEdit(flights); } Console.WriteLine("Enter new nationality:"); string nationality = Console.ReadLine(); if (nationality.Length < 20) { flights[f].passengers[change].nationality = nationality; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerEdit(flights); } Console.WriteLine("Enter new passport:"); string passport = Console.ReadLine(); if (passport.Length < 10) { flights[f].passengers[change].passport = passport; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerEdit(flights); } Console.WriteLine("Enter new date of birthday(dd.mm.YYYY:"); string date = Console.ReadLine(); if (date.Length < 11) { flights[f].passengers[change].dateOfBirthday = date; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerEdit(flights); } Console.WriteLine("Enter new sex:"); string sex = Console.ReadLine(); if (sex.Length < 12) { flights[f].passengers[change].sex = sex; } else { Console.WriteLine("Too much symbols! Try again!"); } Console.WriteLine("Enter new airclass:"); string airclass = Console.ReadLine(); if (airclass.Length < 10) { flights[f].passengers[change].airclass = airclass; } else { Console.WriteLine("Too much symbols! Try again!"); } for (int i = 0; i < flights[f].passengers.Count; i++) { flights[f].passengers[i].index = i + 1; } flights[f].FlightOutput(); Console.WriteLine("\r\nindex: First Name: Second Name: Nationality: Passport: Date: Sex: Airclass: \r\n"); for (int i = 0; i < flights[f].passengers.Count; i++) { flights[f].passengers[i].PassengersOutput(); } } } Menu(); } public static void PassengerAdd(List<Flight> flights) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); for (int i = 0; i < flights.Count; i++) { flights[i].FlightOutput(); } Console.WriteLine("Choose flight:"); int f = int.Parse(Console.ReadLine()) - 1; if (f > 0 && f < flights.Count) { Console.WriteLine("Enter on which position do you want to add a passenger:"); int add = int.Parse(Console.ReadLine()) - 1; if (add > 0 && add < flights[f].passengers.Count) { flights[f].passengers.Insert(add, new Passenger()); flights[f].passengers[add].index = add; Console.WriteLine("Enter new first name:"); string first = Console.ReadLine(); if (first.Length < 10) { flights[f].passengers[add].firstName = first; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerAdd(flights); } Console.WriteLine("Enter new second name:"); string second = Console.ReadLine(); if (second.Length < 20) { flights[f].passengers[add].secondName = second; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerAdd(flights); } Console.WriteLine("Enter new nationality:"); string nationality = Console.ReadLine(); if (nationality.Length < 20) { flights[f].passengers[add].nationality = nationality; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerAdd(flights); } Console.WriteLine("Enter new passport:"); string passport = Console.ReadLine(); if (passport.Length < 10) { flights[f].passengers[add].passport = passport; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerAdd(flights); } Console.WriteLine("Enter new date of birthday(dd.mm.YYYY:"); string date = Console.ReadLine(); if (date.Length < 11) { flights[f].passengers[add].dateOfBirthday = date; } else { Console.WriteLine("Too much symbols! Try again!"); PassengerAdd(flights); } Console.WriteLine("Enter new sex:"); string sex = Console.ReadLine(); if (sex.Length < 12) { flights[f].passengers[add].sex = sex; } else { Console.WriteLine("Too much symbols! Try again!"); } Console.WriteLine("Enter new airclass:"); string airclass = Console.ReadLine(); if (airclass.Length < 10) { flights[f].passengers[add].airclass = airclass; } else { Console.WriteLine("Too much symbols! Try again!"); } } for (int i = 0; i < flights[f].passengers.Count; i++) { flights[f].passengers[i].index = i + 1; } Console.WriteLine("\r\nindex: First Name: Second Name: Nationality: Passport: Date: Sex: Airclass: \r\n"); for (int i = 0; i < flights[f].passengers.Count; i++) { flights[f].passengers[i].PassengersOutput(); } } else { Console.WriteLine("Inncorect index"); } Menu(); } public static void Menu() { Console.WriteLine(@"Type a number: 1.Flight delete 2.Flight add 3.Flight edit 4.Search 5.Passenger delete 6.Passenger add 7.Passenger edit 8.Exit menu"); } /* delegate void Search(List<Flight> flights); Search srch = SearchByNum;*/ public static void SearchByNum(List<Flight> flights) { Console.WriteLine("Enter number of necessary flight"); int num = int.Parse(Console.ReadLine()); for (int i = 0; i < flights.Count; i++) { if (flights[i].flightNumber == num) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); flights[i].FlightOutput(); Console.WriteLine("\r\nindex: First Name: Second Name: Nationality: Passport: Date: Sex: Airclass: \r\n"); for (int j = 0; j < flights[i].passengers.Count; j++) { flights[i].passengers[j].PassengersOutput(); } return; } } Console.WriteLine("Flight with this number is not found"); } public static void SearchByTime(List<Flight> flights) { Console.WriteLine("Enter time of necessary flight"); DateTime time = DateTime.Parse(Console.ReadLine()); for (int i = 0; i < flights.Count; i++) { if (flights[i].date == time) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); flights[i].FlightOutput(); } } Console.WriteLine("Flight with this time is not found"); } public static void SearchByCity(List<Flight> flights) { Console.WriteLine("Enter city of necessary flight"); string city = Console.ReadLine(); for (int i = 0; i < flights.Count; i++) { if (flights[i].city == city) { Console.WriteLine($"index: date of arrival: number of flight: city: airline: terminal: status: gate:\r\n\r\n"); flights[i].FlightOutput(); } } Console.WriteLine("Flight with this city is not found"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2._2._2 { class Program { static int Factorial(int x) { if (x == 0) { return 1; } else { return x * Factorial(x - 1); } } static void Main(string[] args) { Console.WriteLine("Enter number to calculate the factorial:"); int x = int.Parse(Console.ReadLine()); Console.WriteLine(Factorial(x)); Console.ReadKey(); } } }
25fd9ab9941efc4f807d47368f90a57797d8d6dc
[ "C#" ]
15
C#
Born2drum/Main_Academy
9f75aef114974414c4abb897fea8daae0bd0ec68
689140b43185b87f6e2cbfcfa8f1f85bcf3b9499
refs/heads/master
<repo_name>DmitryArbuzov/DemoProject<file_sep>/DemoProject/CommonUI/ServiceView/ServiceView.swift // // ServiceView.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol ServiceView: UIView { associatedtype Model: ServiceViewModel func update(with model: Model) } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/Presenter/RepositoryInfoPresenter.swift // // RepositoryInfoPresenter.swift // DemoProject // // Created by <NAME> on 19.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class RepositoryInfoPresenter { private let repositoryURL: URL private let vcsService: VCSService weak var view: RepositoryInfoViewInput? init(repositoryURL: URL, vcsService: VCSService) { self.repositoryURL = repositoryURL self.vcsService = vcsService } } // MARK: - RepositoryInfoViewOutput extension RepositoryInfoPresenter: RepositoryInfoViewOutput { func viewDidLoad() { view?.updateState(.loading) vcsService.obtainRepositoryInfo(by: repositoryURL) { [weak view] (result) in DispatchQueue.main.async { switch result { case .success(let repository): view?.updateState(.data(viewModel: .init(repositoryName: repository.name))) case .failure(let error): view?.updateState(.error(description: error.localizedDescription)) } } } } } <file_sep>/DemoProject/Network/URLRequestBuilder/URLRequestBuilderImpl.swift // // URLRequestBuilderImpl.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class URLRequestBuilderImpl { private let baseURL: URL init(baseURL: URL) { self.baseURL = baseURL } } // MARK: - URLRequestBuilder extension URLRequestBuilderImpl: URLRequestBuilder { func urlRequest<Request: NetworkRequest>(from request: Request) throws -> URLRequest { guard var url = URL(string: request.path, relativeTo: request.baseURL ?? baseURL), var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) else { throw URLRequestBuilderError.unableToCreateURL } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // На этом этапе очень много кода надо написать(или использовать Alamofire) для корректной поддержки // всех HTTPMethods, ParameterEncoding и Encodable parameters. // Беру для демо просто случай get c formURLEncoded в query и приведение параметров к [String: String] if request.method == .get, let parameters = request.parameters as? [String: String] { let queryItemsFromParameters = parameters.map { URLQueryItem(name: $0.key, value: $0.value) } urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItemsFromParameters guard let newURL = urlComponents.url else { throw URLRequestBuilderError.unableToCreateURL } url = newURL } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = request.method.rawValue urlRequest.cachePolicy = request.cachePolicy urlRequest.timeoutInterval = request.timeoutInterval if let headers = request.headers { for (headerField, headerValue) in headers { urlRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return urlRequest } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/Assembly/RepositoriesListAssembly.swift // // RepositoriesListAssembly.swift // DemoProject // // Created by <NAME> on 07.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoriesListAssembly { func module() -> Module } <file_sep>/DemoProject/Network/URLRequestBuilder/URLRequestBuilder.swift // // URLRequestBuilder.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol URLRequestBuilder { func urlRequest<Request: NetworkRequest>(from request: Request) throws -> URLRequest } <file_sep>/DemoProject/Services/API/VCSService/Models/SearchRepositoriesResponse.swift // // SearchRepositoriesResponse.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct SearchRepositoriesResponse: Decodable { let totalCount: Int let items: [Repository] } <file_sep>/DemoProject/CommonUI/ServiceView/SimpleErrorView/SimpleErrorView.swift // // SimpleErrorView.swift // DemoProject // // Created by <NAME> on 20.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class SimpleErrorView: UIView, ServiceView { typealias Model = SimpleErrorViewModel private let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(with model: Model) { label.text = model.description } private func setupViews() { backgroundColor = Color.background setupLabel() } private func setupLabel() { label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) label.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true label.numberOfLines = 0 label.textAlignment = .center label.font = .preferredFont(forTextStyle: .body) label.tintColor = Color.tint } } <file_sep>/DemoProject/Network/NetworkError.swift // // NetworkError.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum NetworkError: Error { case incorrectRequest(Error) // Этот кейс в проде надо промапить в конкретные ошибки типа .noConnection и пр. case underlyingNetworkError(Error) } <file_sep>/DemoProject/CommonUI/ServiceView/ServiceViewPresentable.swift // // ServiceViewPresentable.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol ServiceViewPresentable: UIViewController { var serviceView: UIView? { get set } func showServiceView<ServiceView, Model>( ofType viewType: ServiceView.Type, with model: Model ) where ServiceView: DemoProject.ServiceView, Model == ServiceView.Model func hideServiceView() } extension ServiceViewPresentable { func showServiceView<ServiceView, Model>( ofType viewType: ServiceView.Type, with model: Model ) where ServiceView: DemoProject.ServiceView, Model == ServiceView.Model { let serviceView = ServiceView() view.addSubview(serviceView) serviceView.addConstraintsToSuperviewEdges() serviceView.update(with: model) self.serviceView = serviceView } func hideServiceView() { guard serviceView != nil else { return } serviceView?.removeFromSuperview() serviceView = nil } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/Router/RepositoriesListRouter.swift // // RepositoriesListRouter.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoriesListRouter: BaseRouter { } extension RepositoriesListRouter: RepositoriesListRouterInput { func openRepositoryInfo(by url: URL) { let repositoryInfoVC = assemblyFactory.repositoryInfo().module(repositoryURL: url).viewController viewController.navigationController?.pushViewController(repositoryInfoVC, animated: true) } func showAlert(text: String) { let alert = UIAlertController(title: text, message: nil, preferredStyle: .alert) alert.addAction(.init(title: "OK", style: .default)) viewController.present(alert, animated: true) } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/Cells/RepositoryListCell.swift // // RepositoryListCell.swift // DemoProject // // Created by <NAME> on 05.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoryListCell: UICollectionViewCell { private enum Constants { enum Avatar { static let size = CGSize(width: 40, height: 40) static let rightMargin: CGFloat = 10 } enum Title { static let bottomMargin: CGFloat = 5 static let textStyle = UIFont.TextStyle.title3 static let numberOfLines = 2 } enum Description { static let bottomMargin: CGFloat = 8 static let textStyle = UIFont.TextStyle.caption2 static let numberOfLines = 2 } enum Border { static let height: CGFloat = 0.5 static let color = Color.tint.withAlphaComponent(0.25) } static let contentInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) } private let avatarImageView = CachedImageView(image: Image.avatarPlaceholder) private let titleLabel = UILabel() private let descriptionLabel = UILabel() private let infoView = RepositoryListCellInfoView() override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func preferredLayoutAttributesFitting( _ layoutAttributes: UICollectionViewLayoutAttributes ) -> UICollectionViewLayoutAttributes { frame.size.width = layoutAttributes.size.width return layoutAttributes } private func setupViews() { backgroundColor = Color.background setupSelectedBackgroundView() setupBorder() setupAvatarImageView() setupTitleLabel() setupDescriptionLabel() setupInfoView() } private func setupSelectedBackgroundView() { let view = UIView() view.backgroundColor = Color.tint.withAlphaComponent(0.1) selectedBackgroundView = view } private func setupBorder() { let border = UIView() border.translatesAutoresizingMaskIntoConstraints = false border.backgroundColor = Constants.Border.color contentView.addSubview(border) border.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true border.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true border.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true border.heightAnchor.constraint(equalToConstant: Constants.Border.height).isActive = true } private func setupAvatarImageView() { avatarImageView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(avatarImageView) avatarImageView.widthAnchor.constraint(equalToConstant: Constants.Avatar.size.width).isActive = true avatarImageView.heightAnchor.constraint(equalToConstant: Constants.Avatar.size.height).isActive = true avatarImageView.leadingAnchor.constraint( equalTo: contentView.leadingAnchor, constant: Constants.contentInsets.left ).isActive = true avatarImageView.topAnchor.constraint( equalTo: contentView.topAnchor, constant: Constants.contentInsets.top ).isActive = true avatarImageView.contentMode = .scaleAspectFit avatarImageView.backgroundColor = Color.background avatarImageView.tintColor = Color.tint } private func setupTitleLabel() { titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.leadingAnchor.constraint( equalTo: avatarImageView.trailingAnchor, constant: Constants.Avatar.rightMargin ).isActive = true titleLabel.topAnchor.constraint( equalTo: contentView.topAnchor, constant: Constants.contentInsets.top ).isActive = true titleLabel.trailingAnchor.constraint( equalTo: contentView.trailingAnchor, constant: -Constants.contentInsets.right ).isActive = true titleLabel.font = .preferredFont(forTextStyle: Constants.Title.textStyle) titleLabel.adjustsFontForContentSizeCategory = true titleLabel.numberOfLines = Constants.Title.numberOfLines } private func setupDescriptionLabel() { descriptionLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(descriptionLabel) descriptionLabel.leadingAnchor.constraint( equalTo: avatarImageView.trailingAnchor, constant: Constants.Avatar.rightMargin ).isActive = true descriptionLabel.topAnchor.constraint( equalTo: titleLabel.bottomAnchor, constant: Constants.Title.bottomMargin ).isActive = true descriptionLabel.trailingAnchor.constraint( equalTo: contentView.trailingAnchor, constant: -Constants.contentInsets.right ).isActive = true descriptionLabel.font = .preferredFont(forTextStyle: Constants.Description.textStyle) descriptionLabel.adjustsFontForContentSizeCategory = true descriptionLabel.numberOfLines = Constants.Description.numberOfLines } private func setupInfoView() { infoView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(infoView) infoView.leadingAnchor.constraint( equalTo: avatarImageView.trailingAnchor, constant: Constants.Avatar.rightMargin ).isActive = true infoView.trailingAnchor.constraint( equalTo: contentView.trailingAnchor, constant: -Constants.contentInsets.right ).isActive = true infoView.bottomAnchor.constraint( equalTo: contentView.bottomAnchor, constant: -Constants.contentInsets.bottom ).isActive = true } } // MARK: - ConfigurableCell extension RepositoryListCell: ConfigurableCell { // Расчет высоты и верстка упрощены для демо. // С другой стороны, если верстка позволяет, такое упрощение идет только на пользу. // В совсем простых ячейках можно использовать autosizing. (Но есть нюансы) // Но опять же зависит от минимальных требований по поддержке девайсов и ОС static func height(with model: CellModel, forWidth width: CGFloat) -> CGFloat { var height = Constants.contentInsets.top height += UIFont.preferredFont(forTextStyle: Constants.Title.textStyle).lineHeight * CGFloat(Constants.Title.numberOfLines) height += Constants.Title.bottomMargin height += UIFont.preferredFont(forTextStyle: Constants.Description.textStyle).lineHeight * CGFloat(Constants.Description.numberOfLines) height += Constants.Description.bottomMargin height += RepositoryListCellInfoView.height() height += Constants.contentInsets.bottom return height } func configure(with model: CellModel) { guard let model = model as? RepositoryListCellModel else { return } titleLabel.text = model.title descriptionLabel.text = model.description avatarImageView.setImage(url: model.authorAvatar, placeholder: Image.avatarPlaceholder) infoView.set( language: model.language, languageColor: model.languageColor, starsCount: model.starsCount, forksCount: model.forksCount ) } } <file_sep>/DemoProject/Resources/GitHubColors.swift // // GitHubColors.swift // DemoProject // // Created by <NAME> on 18.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation // swiftlint:disable type_body_length enum GitHubColors { static let colors: [String: String] = [ "Mercury": "#ff2b2b", "TypeScript": "#2b7489", "PureBasic": "#5a6986", "Objective-C++": "#6866fb", "Self": "#0579aa", "NewLisp": "#87AED7", "Fortran": "#4d41b1", "Ceylon": "#dfa535", "Rebol": "#358a5b", "Frege": "#00cafe", "AspectJ": "#a957b0", "Omgrofl": "#cabbff", "HolyC": "#ffefaf", "Shell": "#89e051", "HiveQL": "#dce200", "AppleScript": "#101F1F", "Eiffel": "#946d57", "XQuery": "#5232e7", "RUNOFF": "#665a4e", "RAML": "#77d9fb", "MTML": "#b7e1f4", "Elixir": "#6e4a7e", "SAS": "#B34936", "MQL4": "#62A8D6", "MQL5": "#4A76B8", "Agda": "#315665", "wisp": "#7582D1", "Dockerfile": "#384d54", "SRecode Template": "#348a34", "D": "#ba595e", "PowerBuilder": "#8f0f8d", "Kotlin": "#F18E33", "Opal": "#f7ede0", "TI Program": "#A0AA87", "Crystal": "#000100", "Objective-C": "#438eff", "Batchfile": "#C1F12E", "Oz": "#fab738", "Mirah": "#c7a938", "ZIL": "#dc75e5", "Objective-J": "#ff0c5a", "ANTLR": "#9DC3FF", "Roff": "#ecdebe", "Ragel": "#9d5200", "FreeMarker": "#0050b2", "Gosu": "#82937f", "Zig": "#ec915c", "Ruby": "#701516", "Nemerle": "#3d3c6e", "Jupyter Notebook": "#DA5B0B", "Component Pascal": "#B0CE4E", "Nextflow": "#3ac486", "Brainfuck": "#2F2530", "SystemVerilog": "#DAE1C2", "APL": "#5A8164", "Hack": "#878787", "Go": "#00ADD8", "Ring": "#2D54CB", "PHP": "#4F5D95", "Cirru": "#ccccff", "SQF": "#3F3F3F", "ZAP": "#0d665e", "Glyph": "#c1ac7f", "1C Enterprise": "#814CCC", "WebAssembly": "#04133b", "Java": "#b07219", "MAXScript": "#00a6a6", "Scala": "#c22d40", "Makefile": "#427819", "Perl": "#0298c3", "Jsonnet": "#0064bd", "Arc": "#aa2afe", "LLVM": "#185619", "GDScript": "#355570", "Verilog": "#b2b7f8", "Factor": "#636746", "Haxe": "#df7900", "Forth": "#341708", "Red": "#f50000", "YARA": "#220000", "Hy": "#7790B2", "mcfunction": "#E22837", "Volt": "#1F1F1F", "AngelScript": "#C7D7DC", "LSL": "#3d9970", "eC": "#913960", "Terra": "#00004c", "CoffeeScript": "#244776", "HTML": "#e34c26", "Lex": "#DBCA00", "UnrealScript": "#a54c4d", "Idris": "#b30000", "Swift": "#ffac45", "Modula-3": "#223388", "C": "#555555", "AutoHotkey": "#6594b9", "P4": "#7055b5", "Isabelle": "#FEFE00", "G-code": "#D08CF2", "Metal": "#8f14e9", "Clarion": "#db901e", "Vue": "#2c3e50", "JSONiq": "#40d47e", "Boo": "#d4bec1", "AutoIt": "#1C3552", "Genie": "#fb855d", "Clojure": "#db5855", "EQ": "#a78649", "Visual Basic": "#945db7", "CSS": "#563d7c", "Prolog": "#74283c", "SourcePawn": "#5c7611", "AMPL": "#E6EFBB", "Shen": "#120F14", "wdl": "#42f1f4", "Harbour": "#0e60e3", "Yacc": "#4B6C4B", "Tcl": "#e4cc98", "Quake": "#882233", "BlitzMax": "#cd6400", "PigLatin": "#fcd7de", "xBase": "#403a40", "Lasso": "#999999", "Processing": "#0096D8", "VHDL": "#adb2cb", "Elm": "#60B5CC", "Dhall": "#dfafff", "Propeller Spin": "#7fa2a7", "Rascal": "#fffaa0", "Alloy": "#64C800", "IDL": "#a3522f", "Slice": "#003fa2", "YASnippet": "#32AB90", "ATS": "#1ac620", "Ada": "#02f88c", "Nu": "#c9df40", "LFE": "#4C3023", "SuperCollider": "#46390b", "Oxygene": "#cdd0e3", "ASP": "#6a40fd", "Assembly": "#6E4C13", "Gnuplot": "#f0a9f0", "FLUX": "#88ccff", "C#": "#178600", "Turing": "#cf142b", "Vala": "#fbe5cd", "ECL": "#8a1267", "ObjectScript": "#424893", "NetLinx": "#0aa0ff", "Perl 6": "#0000fb", "MATLAB": "#e16737", "Emacs Lisp": "#c065db", "Stan": "#b2011d", "SaltStack": "#646464", "Gherkin": "#5B2063", "QML": "#44a51c", "Pike": "#005390", "DataWeave": "#003a52", "LOLCODE": "#cc9900", "ooc": "#b0b77e", "XSLT": "#EB8CEB", "XC": "#99DA07", "J": "#9EEDFF", "Mask": "#f97732", "EmberScript": "#FFF4F3", "TeX": "#3D6117", "Pep8": "#C76F5B", "R": "#198CE7", "Cuda": "#3A4E3A", "KRL": "#28430A", "Vim script": "#199f4b", "Lua": "#000080", "Asymptote": "#4a0c0c", "Ren'Py": "#ff7f7f", "Golo": "#88562A", "PostScript": "#da291c", "Fancy": "#7b9db4", "OCaml": "#3be133", "ColdFusion": "#ed2cd6", "Pascal": "#E3F171", "F#": "#b845fc", "API Blueprint": "#2ACCA8", "ActionScript": "#882B0F", "F*": "#572e30", "Fantom": "#14253c", "Zephir": "#118f9e", "Click": "#E4E6F3", "Smalltalk": "#596706", "Ballerina": "#FF5000", "DM": "#447265", "Ioke": "#078193", "PogoScript": "#d80074", "LiveScript": "#499886", "JavaScript": "#f1e05a", "Wollok": "#a23738", "Rust": "#dea584", "ABAP": "#E8274B", "ZenScript": "#00BCD1", "Slash": "#007eff", "Erlang": "#B83998", "Pan": "#cc0000", "LookML": "#652B81", "Scheme": "#1e4aec", "Squirrel": "#800000", "Nim": "#37775b", "Python": "#3572A5", "Max": "#c4a79c", "Solidity": "#AA6746", "Common Lisp": "#3fb68b", "Dart": "#00B4AB", "Nix": "#7e7eff", "Nearley": "#990000", "Nit": "#009917", "Chapel": "#8dc63f", "Groovy": "#e69f56", "Dylan": "#6c616e", "E": "#ccce35", "Parrot": "#f3ca0a", "Grammatical Framework": "#79aa7a", "Game Maker Language": "#71b417", "VCL": "#148AA8", "Papyrus": "#6600cc", "C++": "#f34b7d", "NetLinx+ERB": "#747faa", "Common Workflow Language": "#B5314C", "Clean": "#3F85AF", "X10": "#4B6BEF", "Puppet": "#302B6D", "Jolie": "#843179", "PLSQL": "#dad8d8", "sed": "#64b970", "Pawn": "#dbb284", "Standard ML": "#dc566d", "PureScript": "#1D222D", "Julia": "#a270ba", "nesC": "#94B0C7", "q": "#0040cd", "Haskell": "#5e5086", "NCL": "#28431f", "Io": "#a9188d", "Rouge": "#cc0088", "Racket": "#3c5caa", "NetLogo": "#ff6375", "AGS Script": "#B9D9FF", "Meson": "#007800", "Dogescript": "#cca760", "PowerShell": "#012456" ] } <file_sep>/DemoProject/Factories/AssemblyFactory/AssemblyFactoryImpl.swift // // AssemblyFactoryImpl.swift // DemoProject // // Created by <NAME> on 07.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class AssemblyFactoryImpl { private let serviceFactory: ServiceFactory init(serviceFactory: ServiceFactory) { self.serviceFactory = serviceFactory } } // MARK: - AssemblyFactory extension AssemblyFactoryImpl: AssemblyFactory { func repositoriesList() -> RepositoriesListAssembly { RepositoriesListAssemblyImpl(assemblyFactory: self, serviceFactory: serviceFactory) } func repositoryInfo() -> RepositoryInfoAssembly { RepositoryInfoAssemblyImpl(assemblyFactory: self, serviceFactory: serviceFactory) } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/Assembly/RepositoryInfoAssembly.swift // // RepositoryInfoAssembly.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoryInfoAssembly { func module(repositoryURL: URL) -> Module } <file_sep>/DemoProject/Network/NetworkRequest.swift // // NetworkRequest.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol NetworkRequest { associatedtype Parameters: Encodable = String typealias HTTPHeaders = [String: String] typealias CachePolicy = URLRequest.CachePolicy var baseURL: URL? { get } var path: String { get } var method: HTTPMethod { get } var parameters: Parameters? { get } var headers: HTTPHeaders? { get } var cachePolicy: CachePolicy { get } var encoding: ParameterEncoding { get } var timeoutInterval: TimeInterval { get } } extension NetworkRequest { var baseURL: URL? { nil } var method: HTTPMethod { .get } var parameters: Parameters? { nil } var headers: HTTPHeaders? { nil } var cachePolicy: CachePolicy { .useProtocolCachePolicy } var encoding: ParameterEncoding { .formURL } var timeoutInterval: TimeInterval { 60.0 } } <file_sep>/DemoProject/Base/HeaderFooterModel.swift // // HeaderFooterModel.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol HeaderFooterModel { } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/Presenter/RepositoriesListPresenter.swift // // RepositoriesListPresenter.swift // DemoProject // // Created by <NAME> on 12.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoriesListPresenter { private enum Constants { static let pageSize = 20 } private var query = "" private var repositories = [RepositoryListCellModel]() private var overallRepositoriesCount = 0 private var isLoading = false private let vcsService: VCSService weak var view: RepositoriesListViewInput? var router: RepositoriesListRouterInput! init(vcsService: VCSService) { self.vcsService = vcsService } private func obtainNextPage() { let page = repositories.count / Constants.pageSize obtainPage(page) } private func obtainPage(_ page: Int) { guard isLoading == false, nextPageExists() else { return } isLoading = true vcsService.findRepositories( query: query, page: page, perPage: Constants.pageSize, completion: { [weak self] (result) in guard let self = self else { return } switch result { case .success(let responseModel): let newCellModels = self.cellModels(from: responseModel.items) DispatchQueue.main.async { self.isLoading = false if page == 0 { self.repositories = [] } self.repositories.append(contentsOf: newCellModels) self.overallRepositoriesCount = responseModel.totalCount self.view?.updateState(.data(viewModel: self.makeViewModel())) } case .failure(let error): DispatchQueue.main.async { self.isLoading = false if page == 0 { self.view?.updateState(.error(description: error.localizedDescription)) } else { self.view?.updateState(.data(viewModel: self.makeViewModel())) self.router.showAlert(text: error.localizedDescription) } } } } ) } private func nextPageExists() -> Bool { repositories.count < overallRepositoriesCount || repositories.count == 0 } private func color(forLanguage language: String?) -> UIColor? { guard let language = language, let languageColorHEX = GitHubColors.colors[language] else { return nil } return UIColor(hexString: languageColorHEX) } private func cellModels(from repositories: [Repository]) -> [RepositoryListCellModel] { repositories.map { (repository) in RepositoryListCellModel( onSelectHandler: { [weak router = self.router] in router?.openRepositoryInfo(by: repository.url) }, title: repository.name, description: repository.description ?? "", starsCount: repository.stargazersCount, forksCount: repository.forksCount, language: repository.language ?? "Unknown", languageColor: color(forLanguage: repository.language), authorAvatar: repository.owner.avatarUrl ) } } private func makeViewModel() -> RepositoriesListViewModel { .init(items: self.repositories, overallFound: self.overallRepositoriesCount, query: self.query) } } // MARK: - RepositoriesListViewOutput extension RepositoriesListPresenter: RepositoriesListViewOutput { func didTriggerRefresh() { obtainPage(0) } func queryWasChanged(newQuery: String) { query = newQuery view?.updateState(.loading) obtainPage(0) } func viewWantsNextPage() { obtainNextPage() } } <file_sep>/DemoProject/Services/API/VCSService/GitHubAPIService.swift // // GitHubAPIServiceImpl.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class GitHubAPIService: BaseAPIService { init(networkClient: NetworkClient) { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase super.init(networkClient: networkClient, decoder: decoder) } } // MARK: - VCSService extension GitHubAPIService: VCSService { func findRepositories( query: String, page: Int, perPage: Int, completion: @escaping (Result<SearchRepositoriesResponse, APIError>) -> Void ) { let request = GitHubFindRepositoriesRequest(query: query, page: page, perPage: perPage) performRequest(request, completion: completion) } func obtainRepositoryInfo(by url: URL, completion: @escaping (Result<Repository, APIError>) -> Void) { let request = GitHubRepositoryInfoRequest(repositoryUrl: url) performRequest(request, completion: completion) } } <file_sep>/DemoProject/Base/Cells/CellModel.swift // // CellModel.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol CellModel { typealias OnSelectHandler = () -> Void var cellClass: ConfigurableCell.Type { get } var onSelectHandler: (() -> Void)? { get } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/RepositoriesListViewModel.swift // // RepositoriesListViewModel.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct RepositoriesListViewModel { let items: [CellModel] let overallFound: Int let query: String } <file_sep>/DemoProject/Services/API/APIRequest.swift // // APIRequest.swift // DemoProject // // Created by <NAME> on 14.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol APIRequest: NetworkRequest { associatedtype Response: Decodable } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/CollectionViewLayout/CustomFlowLayout.swift // // CustomFlowLayout.swift // DemoProject // // Created by <NAME> on 19.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class CustomFlowLayout: UICollectionViewFlowLayout { private enum Constants { static let minCellWidth: CGFloat = 300 static let estimatedCellHeight: CGFloat = 100 static let maxColumns: CGFloat = 3 } var cellWidth: CGFloat = 0 override init() { super.init() minimumLineSpacing = 0 sectionInsetReference = .fromSafeArea } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func invalidateLayout() { updateCellWidth() estimatedItemSize = .init(width: cellWidth, height: Constants.estimatedCellHeight) super.invalidateLayout() } private func updateCellWidth() { guard let collectionView = collectionView else { self.cellWidth = .leastNonzeroMagnitude return } let layoutFrame = collectionView.safeAreaLayoutGuide.layoutFrame let safeAreaInsets = collectionView.safeAreaInsets var availableWidth = layoutFrame.width - sectionInset.left - sectionInset.right if layoutFrame.width > layoutFrame.height && safeAreaInsets.left > safeAreaInsets.right { // Обработка бага iOS. При повороте экрана в landscape на iPhone с челкой, safeAreaInsets.right бывает == 0 availableWidth -= safeAreaInsets.left } var columnNumber = Constants.maxColumns var cellWidth: CGFloat = 0 while cellWidth < Constants.minCellWidth { let interitemSpacingSum = minimumInteritemSpacing * (columnNumber - 1) cellWidth = (availableWidth - interitemSpacingSum) / columnNumber columnNumber -= 1 } self.cellWidth = cellWidth.rounded(.down) } } <file_sep>/DemoProject/CommonUI/LoadingView/LoadingViewPresentable.swift // // LoadingViewPresentable.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol LoadingViewPresentable: UIViewController { associatedtype LoadingViewType: LoadingView var loadingView: LoadingViewType? { get set } func showLoadingView(with model: LoadingViewType.Model) func hideLoadingView() } extension LoadingViewPresentable { func showLoadingView(with model: LoadingViewType.Model) { let loadingView = LoadingViewType() view.addSubview(loadingView) loadingView.addConstraintsToSuperviewEdges() loadingView.update(with: model) self.loadingView = loadingView } func hideLoadingView() { guard loadingView != nil else { return } loadingView?.removeFromSuperview() loadingView = nil } } <file_sep>/DemoProject/Resources/Color.swift // // Color.swift // DemoProject // // Created by <NAME> on 09.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit // В настоящем проекте это должно генерироваться автоматически через SwiftGen enum Color { static let background = UIColor(named: "background")! static let tint = UIColor(named: "tint")! } <file_sep>/DemoProject/Network/NetworkClient.swift // // NetworkClient.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol NetworkClient { func performRequest<Request: NetworkRequest>( _ request: Request, completion: @escaping (Result<NetworkResponse, NetworkError>) -> Void ) } <file_sep>/DemoProject/Base/Module.swift // // Module.swift // DemoProject // // Created by <NAME> on 07.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit struct Module { let viewController: UIViewController } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/Cells/RepositoryListCellModel.swift // // RepositoryListCellModel.swift // DemoProject // // Created by <NAME> on 05.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit struct RepositoryListCellModel: CellModel { let cellClass: ConfigurableCell.Type = RepositoryListCell.self var onSelectHandler: (() -> Void)? let title: String let description: String let starsCount: UInt let forksCount: UInt let language: String let languageColor: UIColor? let authorAvatar: URL? } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/RepositoriesListViewController.swift // // ViewController.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit // В проде будет некоторая иерархия базовых контроллеров. А dataSource коллекции будет помещен в отдельный класс final class RepositoriesListViewController: BaseViewController, LoadingViewPresentable, ServiceViewPresentable { var loadingView: SimpleLoadingView? var serviceView: UIView? private let flowLayout = CustomFlowLayout() private var collectionView: UICollectionView! private let output: RepositoriesListViewOutput private var cellModels = [CellModel]() // Упрощено до ячеек. В общем решении будет использован массив [SectionModel] init(output: RepositoriesListViewOutput) { self.output = output super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() output.queryWasChanged(newQuery: "Swift") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if collectionView.refreshControl == nil { setupRefreshControl() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.collectionViewLayout.invalidateLayout() } private func setupViews() { setupCollectionView() } private func setupCollectionView() { collectionView = .init(frame: .zero, collectionViewLayout: flowLayout) view.addSubview(collectionView) collectionView.addConstraintsToSuperviewEdges() collectionView.backgroundColor = Color.background collectionView.dataSource = self collectionView.delegate = self collectionView.register(RepositoryListCell.self, forCellWithReuseIdentifier: RepositoryListCell.reuseIdentifier) } private func setupRefreshControl() { let refreshControl = UIRefreshControl() refreshControl.tintColor = Color.tint refreshControl.addTarget(self, action: #selector(didTriggerRefresh), for: .valueChanged) collectionView.refreshControl = refreshControl collectionView.refreshControl?.layer.zPosition = -1 } @objc private func didTriggerRefresh() { output.didTriggerRefresh() } private func showErrorView(text: String) { showServiceView(ofType: SimpleErrorView.self, with: SimpleErrorViewModel(description: text)) } private func hideRefreshControl() { if collectionView.refreshControl?.isRefreshing == true { DispatchQueue.main.async { self.collectionView.refreshControl?.endRefreshing() } } } private func updateTitle(query: String, found: Int) { title = "Query: \(query), Found: \(found)" } private func applyNewViewModel(_ viewModel: RepositoriesListViewModel) { // !!! Просто костыль для демо красивой анимации вставки // В проде на этом этапе нужно items(sections) прогнать через diff алгоритм и применить анимированные апдейты // Например, https://github.com/onmyway133/DeepDiff let cellsDiffCount = viewModel.items.count - cellModels.count cellModels = viewModel.items let cellsCount = cellModels.count if cellsDiffCount >= 0 { let insertedIndexPaths = ((cellsCount - cellsDiffCount)..<cellsCount).map { IndexPath(item: $0, section: 0) } collectionView.performBatchUpdates({ collectionView.insertItems(at: insertedIndexPaths) }, completion: nil) } else { collectionView.reloadData() } updateTitle(query: viewModel.query, found: viewModel.overallFound) } } // MARK: - UICollectionViewDataSource extension RepositoriesListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cellModels.count } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cellModel = cellModels[indexPath.item] let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cellModel.cellClass.reuseIdentifier, for: indexPath ) if let cell = cell as? ConfigurableCell { cell.configure(with: cellModel) } return cell } func collectionView( _ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath ) { if indexPath.item == cellModels.count - 6 { output.viewWantsNextPage() } } } // MARK: - UICollectionViewDelegateFlowLayout extension RepositoriesListViewController: UICollectionViewDelegateFlowLayout { func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let cellModel = cellModels[indexPath.item] let cellWidth = flowLayout.cellWidth let cellHeight = cellModel.cellClass.height(with: cellModel, forWidth: cellWidth) return CGSize(width: cellWidth, height: cellHeight) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cellModel = cellModels[indexPath.item] collectionView.deselectItem(at: indexPath, animated: true) cellModel.onSelectHandler?() } } // MARK: - RepositoriesListViewInput extension RepositoriesListViewController: RepositoriesListViewInput { func updateState(_ state: RepositoriesListViewState) { switch state { case .data(let viewModel): applyNewViewModel(viewModel) hideRefreshControl() hideServiceView() hideLoadingView() case .loading: hideServiceView() showLoadingView(with: .init(title: " Loading...")) case .error(let description): hideRefreshControl() hideLoadingView() showErrorView(text: description) } } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/Assembly/RepositoriesListAssemblyImpl.swift // // RepositoriesListAssemblyImpl.swift // DemoProject // // Created by <NAME> on 07.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class RepositoriesListAssemblyImpl: BaseAssembly { } // MARK: - RepositoriesListAssembly extension RepositoriesListAssemblyImpl: RepositoriesListAssembly { func module() -> Module { let presenter = RepositoriesListPresenter(vcsService: serviceFactory.vcsService()) let view = RepositoriesListViewController(output: presenter) let router = RepositoriesListRouter(assemblyFactory: assemblyFactory, viewController: view) presenter.view = view presenter.router = router return .init(viewController: view) } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/RepositoriesListViewOutput.swift // // RepositoriesListViewOutput.swift // DemoProject // // Created by <NAME> on 12.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoriesListViewOutput { func didTriggerRefresh() func queryWasChanged(newQuery: String) func viewWantsNextPage() } <file_sep>/DemoProject/Base/BaseRouter.swift // // BaseRouter.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit class BaseRouter { let assemblyFactory: AssemblyFactory let viewController: UIViewController init(assemblyFactory: AssemblyFactory, viewController: UIViewController) { self.assemblyFactory = assemblyFactory self.viewController = viewController } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/View/RepositoryInfoViewOutput.swift // // RepositoryInfoViewOutput.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoryInfoViewOutput { func viewDidLoad() } <file_sep>/README.md ## Общеe Небольшой демо проект для собеседований. Архитектура: MVP+Router+SOA. Многое намеренно упрощено. В некоторых таких местах есть комментарии. Намеренно не использована ни одна внешняя зависимость. В некоторых местах есть комментарии с указанием, чтобы я использовал из внешних зависимостей. ## UI * Реализована многоколоночная динамическая верстка на UICollectionView. * Поддерживаются все размеры экранов и все ориентации устройств. * Поддерживается темная тема. * Поддерживаются динамические шрифты (Accessibility). * Поддерживаются интерфейсы с написанием справа налево. Т.к. в проекте я не использовал внешние зависимости, код верстки может показаться несколько громоздким. В проде совершенно оправданно использовать какой-либо DSL поверх нативного API Autolayout наподобие **SnapKit**. ## Архитектура Последние 4 года в hh.ru команды под моим руководством при разработке использовали паттерн VIPER. За это время создано более 200 новых VIPER модулей. Считаю, что в момент, когда принималось решение использовать VIPER, это было оправданно. VIPER описывает понятные границы ответственностей. Был удобен в т.ч. для последовательного разбиения Legacy MVC модулей на части (выделение роутера, интерактора). Несомненно, VIPER для ряда случаев создает излишние накладные расходы. В данный момент для нового проекта я предпочту скорее MVVM-C + RxSwift (Combine в будущем) ## Сетевой клиент Представлена самая простая реализация. Ее можно усложнять в плане поддержки отмены запросов, разных способов энкодинга, добавить поддержку хидеров авторизации, retrier, ssl pinning и т.д. С другой стороны для всего этого можно просто взять Alamofire, где все это есть. Но, само собой, об Alamofire будет знать лишь один класc. Тот, который будет реализовывать интерфейс NetworkClient. Т.е. при необходимости слезть с Alamofire переписать нужно будет только один класс (и его прямые зависимости). Любые другие части проекта никак не будут знать про Alamofire. ## Что далее? Планирую постепенно реализовать еще 2 варианта демо проекта: 1. MVVM-C, RxSwift, все другие необходимые внешние зависимости. 2. Вариант на SwiftUI+Combine. <file_sep>/DemoProject/Factories/ServiceFactory/ServiceFactoryImpl.swift // // ServiceFactoryImpl.swift // DemoProject // // Created by <NAME> on 05.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class ServiceFactoryImpl { } // MARK: - ServiceFactory extension ServiceFactoryImpl: ServiceFactory { func vcsService() -> VCSService { GitHubAPIService( networkClient: NetworkClientImpl( urlRequestBuilder: URLRequestBuilderImpl( baseURL: Constants.gitHubAPIBaseURL ) ) ) } } <file_sep>/DemoProject/CommonUI/LoadingView/LoadingViewModel.swift // // LoadingViewModel.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol LoadingViewModel { } <file_sep>/DemoProject/Network/NetworkClientImpl.swift // // NetworkClientImpl.swift // DemoProject // // Created by <NAME> on 10.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation final class NetworkClientImpl { private let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil) private let constructingQueue = DispatchQueue(label: "\(NetworkClientImpl.self)", qos: .utility) private let urlRequestBuilder: URLRequestBuilder init(urlRequestBuilder: URLRequestBuilder) { self.urlRequestBuilder = urlRequestBuilder } } // MARK: - NetworkClient extension NetworkClientImpl: NetworkClient { func performRequest<Request: NetworkRequest>( _ request: Request, completion: @escaping (Result<NetworkResponse, NetworkError>) -> Void ) { constructingQueue.async { [weak self] in guard let self = self else { return } var urlRequest: URLRequest do { urlRequest = try self.urlRequestBuilder.urlRequest(from: request) } catch { completion(.failure(.incorrectRequest(error))) return } let task = self.session.dataTask( with: urlRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let error = error { completion(.failure(.underlyingNetworkError(error))) } else if let response = response as? HTTPURLResponse { completion(.success(.init(data: data, response: response))) } } ) task.resume() } } } <file_sep>/DemoProject/CommonUI/ServiceView/ServiceViewModel.swift // // ServiceViewModel.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol ServiceViewModel { } <file_sep>/DemoProject/CommonUI/LoadingView/LoadingView.swift // // LoadingView.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol LoadingView: UIView { associatedtype Model: LoadingViewModel func update(with model: Model) } <file_sep>/DemoProject/Services/API/VCSService/Models/Repository.swift // // Repository.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct Repository: Codable { let id: Int let name: String let description: String? let stargazersCount: UInt let forksCount: UInt let language: String? let owner: RepositoryOwner let url: URL } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/View/RepositoryInfoViewState.swift // // RepositoryInfoViewState.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum RepositoryInfoViewState { case data(viewModel: RepositoryInfoViewModel) case loading case error(description: String) } <file_sep>/DemoProject/CommonUI/LoadingView/SimpleLoadingView/SimpleLoadingView.swift // // SimpleLoadingView.swift // DemoProject // // Created by <NAME> on 20.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class SimpleLoadingView: UIView, LoadingView { private enum Constants { enum Title { static let topMargin: CGFloat = 10 } } private let activityIndicator = UIActivityIndicatorView(style: .white) private let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func layoutSubviews() { super.layoutSubviews() if !activityIndicator.isAnimating { activityIndicator.startAnimating() } } func update(with model: SimpleLoadingViewModel) { titleLabel.text = model.title } private func setupViews() { backgroundColor = Color.background setupActivityIndicator() setupTitleLabel() } private func setupActivityIndicator() { activityIndicator.translatesAutoresizingMaskIntoConstraints = false addSubview(activityIndicator) activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true activityIndicator.color = Color.tint } private func setupTitleLabel() { titleLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(titleLabel) titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true titleLabel.topAnchor.constraint( equalTo: activityIndicator.bottomAnchor, constant: Constants.Title.topMargin ).isActive = true titleLabel.textAlignment = .center titleLabel.font = .preferredFont(forTextStyle: .caption1) titleLabel.tintColor = Color.tint } } <file_sep>/DemoProject/Factories/ServiceFactory/ServiceFactory.swift // // ServiceFactory.swift // DemoProject // // Created by <NAME> on 05.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol ServiceFactory { func vcsService() -> VCSService } <file_sep>/DemoProject/Services/API/VCSService/Requests/GitHubFindRepositoriesRequest.swift // // GitHubFindRepositoriesRequest.swift // DemoProject // // Created by <NAME> on 14.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct GitHubFindRepositoriesRequest: APIRequest { typealias Response = SearchRepositoriesResponse let path: String = "search/repositories" let parameters: [String: String]? init(query: String, page: Int, perPage: Int) { parameters = [ "q": query, "page": String(page), "per_page": String(perPage), "sort": "stars" ] } } <file_sep>/DemoProject/Services/API/VCSService/Models/RepositoryOwner.swift // // RepositoryOwner.swift // DemoProject // // Created by <NAME> on 15.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct RepositoryOwner: Codable { let id: Int let avatarUrl: URL? } <file_sep>/DemoProject/Base/Cells/ReusableCell.swift // // ReusableCell.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol ReusableCell { static var reuseIdentifier: String { get } } extension ReusableCell { static var reuseIdentifier: String { String(describing: self) } } <file_sep>/DemoProject/CommonUI/ServiceView/SimpleErrorView/SimpleErrorViewModel.swift // // SimpleErrorViewModel.swift // DemoProject // // Created by <NAME> on 21.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit struct SimpleErrorViewModel: ServiceViewModel { let description: String } <file_sep>/DemoProject/Network/NetworkResponse.swift // // NetworkResponse.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct NetworkResponse { let data: Data? let response: HTTPURLResponse } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/RepositoriesListViewInput.swift // // RepositoriesListViewInput.swift // DemoProject // // Created by <NAME> on 12.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoriesListViewInput: AnyObject { func updateState(_ state: RepositoriesListViewState) } <file_sep>/DemoProject/Network/URLRequestBuilder/URLRequestBuilderError.swift // // URLRequestBuilderError.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum URLRequestBuilderError: Error { case unableToCreateURL } <file_sep>/DemoProject/CommonUI/CachedImageView.swift // // CachedImageView.swift // DemoProject // // Created by <NAME> on 15.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class CachedImageView: UIImageView { private static var cache = [URL: UIImage]() private var currentTask: URLSessionDataTask? // Реализация на коленке func setImage(url: URL?, placeholder: UIImage?) { cancelLoading() guard let url = url else { image = placeholder return } if let cachedImage = Self.cache[url] { image = cachedImage return } image = placeholder currentTask = URLSession.shared.dataTask(with: url) { [weak self] (data, _, _) in guard let data = data, self?.currentTask?.originalRequest?.url == url else { return } guard let image = UIImage(data: data) else { return } DispatchQueue.main.async { Self.cache[url] = image self?.image = image } } currentTask?.resume() } func cancelLoading() { currentTask?.cancel() } } <file_sep>/DemoProject/Services/API/VCSService/VCSService.swift // // GitHubAPIService.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol VCSService { func findRepositories( query: String, page: Int, perPage: Int, completion: @escaping (Result<SearchRepositoriesResponse, APIError>) -> Void ) func obtainRepositoryInfo(by url: URL, completion: @escaping (Result<Repository, APIError>) -> Void) } <file_sep>/DemoProject/Services/API/APIError.swift // // APIError.swift // DemoProject // // Created by <NAME> on 14.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum APIError: Error { // Тут другие кейсы, которые может прислать API case network(NetworkError) case decoding(DecodingError) // Этот кейс тоже в проде должен быть превращен в несколько более конкретных в т.ч. с парсингом данных // в тех сервисах, где может придти в ответ тело ошибки case unacceptableStatusCode(code: Int, reason: String?) case noData case unknown(Error) } <file_sep>/DemoProject/Factories/AssemblyFactory/AssemblyFactory.swift // // AssemblyFactory.swift // DemoProject // // Created by <NAME> on 07.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol AssemblyFactory { func repositoriesList() -> RepositoriesListAssembly func repositoryInfo() -> RepositoryInfoAssembly } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/Router/RepositoriesListRouterInput.swift // // RepositoriesListRouterInput.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoriesListRouterInput: AnyObject { func openRepositoryInfo(by url: URL) func showAlert(text: String) } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/Cells/RepositoryListCellInfoView.swift // // RepositoryListCellInfoView.swift // DemoProject // // Created by <NAME> on 09.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoryListCellInfoView: UIView { private enum Constants { enum Icon { static let size = CGSize(width: 16, height: 16) } enum LanguageIcon { static let size = CGSize(width: 13, height: 13) static let defaulColor = UIColor.lightGray } enum Label { static let margins = UIEdgeInsets(top: 1, left: 3, bottom: 0, right: 1) static let textStyle = UIFont.TextStyle.footnote static let minWidth: CGFloat = 25 } } static func height() -> CGFloat { Constants.Label.margins.top + UIFont.preferredFont(forTextStyle: Constants.Label.textStyle).lineHeight + Constants.Label.margins.bottom } private let languageIconView = UIView() private let languageNameLabel = UILabel() private let starsIconView = UIImageView(image: Image.star) private let starsCountLabel = UILabel() private let forksIconView = UIImageView(image: Image.fork) private let forksCountLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func set(language: String, languageColor: UIColor?, starsCount: UInt, forksCount: UInt) { languageIconView.backgroundColor = languageColor ?? Constants.LanguageIcon.defaulColor languageNameLabel.text = language starsCountLabel.text = String(starsCount) forksCountLabel.text = String(forksCount) } private func setupViews() { setupLanguageIconView() setupLanguageLabel() setupStartCountLabel() setupStarsIconView() setupForksCountLabel() setupForksIconView() } private func setupLanguageIconView() { languageIconView.translatesAutoresizingMaskIntoConstraints = false addSubview(languageIconView) languageIconView.widthAnchor.constraint(equalToConstant: Constants.LanguageIcon.size.width).isActive = true languageIconView.heightAnchor.constraint(equalToConstant: Constants.LanguageIcon.size.height).isActive = true languageIconView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true languageIconView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true languageIconView.layer.masksToBounds = true languageIconView.layer.cornerRadius = Constants.LanguageIcon.size.width / 2.0 } private func setupLanguageLabel() { languageNameLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(languageNameLabel) languageNameLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: Constants.Label.minWidth).isActive = true languageNameLabel.leadingAnchor.constraint( equalTo: languageIconView.trailingAnchor, constant: Constants.Label.margins.left ).isActive = true languageNameLabel.topAnchor.constraint( equalTo: topAnchor, constant: Constants.Label.margins.top ).isActive = true languageNameLabel.bottomAnchor.constraint( equalTo: bottomAnchor, constant: Constants.Label.margins.bottom ).isActive = true languageNameLabel.font = .preferredFont(forTextStyle: Constants.Label.textStyle) languageNameLabel.adjustsFontForContentSizeCategory = true } private func setupStartCountLabel() { starsCountLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(starsCountLabel) starsCountLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: Constants.Label.minWidth).isActive = true starsCountLabel.centerXAnchor.constraint( equalTo: centerXAnchor, constant: (Constants.Icon.size.width + Constants.Label.margins.left) / 2.0 ).isActive = true starsCountLabel.topAnchor.constraint( equalTo: topAnchor, constant: Constants.Label.margins.top ).isActive = true starsCountLabel.bottomAnchor.constraint( equalTo: bottomAnchor, constant: Constants.Label.margins.bottom ).isActive = true starsCountLabel.setContentCompressionResistancePriority(UILayoutPriority(1000), for: .vertical) starsCountLabel.font = .preferredFont(forTextStyle: Constants.Label.textStyle) starsCountLabel.adjustsFontForContentSizeCategory = true } private func setupStarsIconView() { starsIconView.translatesAutoresizingMaskIntoConstraints = false addSubview(starsIconView) starsIconView.widthAnchor.constraint(equalToConstant: Constants.Icon.size.width).isActive = true starsIconView.heightAnchor.constraint(equalToConstant: Constants.Icon.size.height).isActive = true starsIconView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true starsIconView.trailingAnchor.constraint( equalTo: starsCountLabel.leadingAnchor, constant: -Constants.Label.margins.left ).isActive = true languageNameLabel.trailingAnchor.constraint( lessThanOrEqualTo: starsIconView.leadingAnchor, constant: Constants.Label.margins.right ).isActive = true starsIconView.tintColor = Color.tint } private func setupForksCountLabel() { forksCountLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(forksCountLabel) forksCountLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: Constants.Label.minWidth).isActive = true forksCountLabel.trailingAnchor.constraint( equalTo: trailingAnchor, constant: -Constants.Label.margins.right ).isActive = true forksCountLabel.topAnchor.constraint( equalTo: topAnchor, constant: Constants.Label.margins.top ).isActive = true forksCountLabel.font = .preferredFont(forTextStyle: Constants.Label.textStyle) forksCountLabel.adjustsFontForContentSizeCategory = true } private func setupForksIconView() { forksIconView.translatesAutoresizingMaskIntoConstraints = false addSubview(forksIconView) forksIconView.heightAnchor.constraint(equalToConstant: Constants.Icon.size.height).isActive = true forksIconView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true forksIconView.trailingAnchor.constraint( equalTo: forksCountLabel.leadingAnchor, constant: -Constants.Label.margins.left ).isActive = true forksIconView.tintColor = Color.tint } } <file_sep>/DemoProject/Resources/Constants.swift // // Constants.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum Constants { static let gitHubAPIBaseURL = URL(string: "https://api.github.com")! } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoriesList/View/RepositoriesListViewState.swift // // RepositoriesListViewState.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation enum RepositoriesListViewState { case data(viewModel: RepositoriesListViewModel) case loading case error(description: String) } <file_sep>/DemoProject/Services/API/BaseAPIService.swift // // BaseAPIService.swift // DemoProject // // Created by <NAME> on 04.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation class BaseAPIService { let networkClient: NetworkClient let decoder: JSONDecoder init( networkClient: NetworkClient, decoder: JSONDecoder ) { self.networkClient = networkClient self.decoder = decoder } func performRequest<Request: APIRequest>( _ request: Request, completion: @escaping (Result<Request.Response, APIError>) -> Void ) { networkClient.performRequest(request) { [weak self, decoder] result in guard let self = self else { return } switch result { case .success(let networkResponse): if let validationError = self.validateResponse(networkResponse) { completion(.failure(validationError)) return } guard let data = networkResponse.data else { completion(.failure(.noData)) return } do { let responseModel = try decoder.decode(Request.Response.self, from: data) completion(.success(responseModel)) } catch let error as DecodingError { completion(.failure(.decoding(error))) } catch { completion(.failure(.unknown(error))) } case .failure(let networkError): completion(.failure(.network(networkError))) } } } func validateResponse(_ response: NetworkResponse) -> APIError? { let statusCode = response.response.statusCode guard statusCode >= 200 && statusCode <= 299 else { var reason = "" if let data = response.data { reason = String(data: data, encoding: .utf8) ?? "" } return APIError.unacceptableStatusCode(code: statusCode, reason: reason) } return nil } } <file_sep>/DemoProject/Network/ParameterEncoding.swift // // ParameterEncoding.swift // DemoProject // // Created by <NAME> on 15.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation public enum ParameterEncoding { case formURL case json case propertyList } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/View/RepositoryInfoViewInput.swift // // RepositoryInfoViewInput.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation protocol RepositoryInfoViewInput: AnyObject { func updateState(_ state: RepositoryInfoViewState) } <file_sep>/DemoProject/Base/ViewController/BaseViewController.swift // // BaseViewController.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) view.backgroundColor = Color.background } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/Assembly/RepositoryInfoAssemblyImpl.swift // // RepositoryInfoAssemblyImpl.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoryInfoAssemblyImpl: BaseAssembly { } // MARK: - RepositoryInfoAssembly extension RepositoryInfoAssemblyImpl: RepositoryInfoAssembly { func module(repositoryURL: URL) -> Module { let presenter = RepositoryInfoPresenter(repositoryURL: repositoryURL, vcsService: serviceFactory.vcsService()) let view = RepositoryInfoViewController(output: presenter) presenter.view = view return .init(viewController: view) } } <file_sep>/DemoProject/Resources/Image.swift // // Image.swift // DemoProject // // Created by <NAME> on 09.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit // В настоящем проекте это должно генерироваться автоматически через SwiftGen enum Image { static var star: UIImage { return UIImage(named: "star")! } static var fork: UIImage { return UIImage(named: "fork")! } static var avatarPlaceholder: UIImage { return UIImage(named: "avatarPlaceholder")! } } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/View/RepositoryInfoViewController.swift // // RepositoryInfoViewController.swift // DemoProject // // Created by <NAME> on 19.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit final class RepositoryInfoViewController: BaseViewController, LoadingViewPresentable, ServiceViewPresentable { var loadingView: SimpleLoadingView? var serviceView: UIView? private let output: RepositoryInfoViewOutput private let infoLabel = UILabel() init(output: RepositoryInfoViewOutput) { self.output = output super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() output.viewDidLoad() } private func setupViews() { setupInfoLabel() } private func setupInfoLabel() { infoLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(infoLabel) infoLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true infoLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true infoLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true infoLabel.textAlignment = .center infoLabel.font = .preferredFont(forTextStyle: .largeTitle) infoLabel.tintColor = Color.tint } } // MARK: - RepositoryInfoViewInput extension RepositoryInfoViewController: RepositoryInfoViewInput { func updateState(_ state: RepositoryInfoViewState) { switch state { case .data(let viewModel): hideServiceView() hideLoadingView() infoLabel.text = viewModel.repositoryName title = viewModel.repositoryName case .loading: hideServiceView() showLoadingView(with: .init(title: " Loading...")) case .error(let description): hideLoadingView() showServiceView(ofType: SimpleErrorView.self, with: .init(description: description)) } } } <file_sep>/DemoProject/Base/BaseAssembly.swift // // BaseAssembly.swift // DemoProject // // Created by <NAME> on 08.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation class BaseAssembly { let assemblyFactory: AssemblyFactory let serviceFactory: ServiceFactory init(assemblyFactory: AssemblyFactory, serviceFactory: ServiceFactory) { self.assemblyFactory = assemblyFactory self.serviceFactory = serviceFactory } } <file_sep>/DemoProject/Base/SectionModel.swift // // SectionModel.swift // DemoProject // // Created by <NAME> on 22.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct SectionModel { let header: HeaderFooterModel? = nil let items: [CellModel] let footer: HeaderFooterModel? = nil } <file_sep>/DemoProject/Scenes/Repositories/Modules/RepositoryInfo/View/RepositoryInfoViewModel.swift // // RepositoryInfoViewModel.swift // DemoProject // // Created by <NAME> on 23.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct RepositoryInfoViewModel { let repositoryName: String } <file_sep>/DemoProject/Base/Cells/ConfigurableCell.swift // // ConfigurableCell.swift // DemoProject // // Created by <NAME> on 05.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit protocol ConfigurableCell: UICollectionViewCell, ReusableCell { static func height(with model: CellModel, forWidth width: CGFloat) -> CGFloat func configure(with model: CellModel) } <file_sep>/DemoProject/Services/API/VCSService/Requests/GitHubRepositoryInfoRequest.swift // // GitHubRepositoryInfoRequest.swift // DemoProject // // Created by <NAME> on 17.03.2020. // Copyright © 2020 dm. All rights reserved. // import Foundation struct GitHubRepositoryInfoRequest: APIRequest { typealias Response = Repository let baseURL: URL? let path: String init(repositoryUrl: URL) { baseURL = repositoryUrl.baseURL path = repositoryUrl.path } } <file_sep>/DemoProject/Extensions/UIColor/UIColor+HEX.swift // // UIColor+HEX.swift // DemoProject // // Created by <NAME> on 18.03.2020. // Copyright © 2020 dm. All rights reserved. // import UIKit extension UIColor { convenience init?(hexString: String) { var colorString = hexString if colorString.hasPrefix("#") { colorString.remove(at: colorString.startIndex) } if colorString.count != 6 { return nil } var rgbValue: UInt64 = 0 Scanner(string: colorString).scanHexInt64(&rgbValue) self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: 1) } }
c7800b991585a3b4c2fcc638feb0fcb047636041
[ "Swift", "Markdown" ]
70
Swift
DmitryArbuzov/DemoProject
1d2d18f0fa21838f0af9376e57a0296acfdec814
1fef806a0d0375e101616f95384db9eedd4979ec
refs/heads/master
<file_sep>//Unity Socket Server-CLient tutorial : http://unitybuster.blogspot.co.uk/2010/08/unity-3d-clientserver-socket-connection.html private var textFieldString = "Socket Testing String"; private var myTCP; public var pause; function Awake() { myTCP = gameObject.AddComponent(clientTcp); pause = false; } function OnGUI () { if(myTCP.socketReady==false){ if (GUI.Button (Rect (20,10,80,20),"Connect")) { myTCP.setupSocketServer(); } } else { // myTCP.maintainConnection(); if (GUI.Button (Rect (20,40,80,20), "Start Game")) { //myTCP.writeSocket("Meessage from the Server"); myTCP.readSocket(); } if (GUI.Button (Rect (20,70,80,20), "End Game")) { myTCP.writeSocket("End Finished"); myTCP.closeSocket(); } textFieldString = GUI.TextField (Rect (25, 100, 300, 30), textFieldString); if (GUI.Button (Rect (20,140,80,20),"Disconnect")) { myTCP.closeSocket(); textFieldString = "Socket Disconnected..."; } } } <file_sep>using UnityEngine; using System.Collections; public class Disabler : MonoBehaviour { } <file_sep># BioFeedbackGaming The Unity Server <file_sep>using UnityEngine; using System.Collections; public class Sate : MonoBehaviour { public static string state; public clientTcp mess; // Use this for initialization void Start () { } // Update is called once per frame void Update () { string action = clientTcp.mess; if(action.Contains("Idle")) { state = "Idle"; } else if (action.Contains("Walking")) { state = "Walking"; } else if ( action.Contains("Running")) { state = "Running"; } else { //in case message is something else, no change } } void OnGUI() { GUI.Label (new Rect (100, 200, 100, 200), "Action : " + state); } } <file_sep>using UnityEngine; using System.Collections; public class SpawnManager : MonoBehaviour { public GameObject[] enemies; public int enemyCount; private Vector3 spawnPoint; public static clientTcp mess; private string msg; // Use this for initialization void Start () { enemies = GameObject.FindGameObjectsWithTag("Enemy"); enemyCount = enemies.Length; } // Update is called once per frame void Update () { msg = clientTcp.mess; if (msg.Contains("Spawn")) { InvokeRepeating("SpawnEnemy", 1, 2); } } void SpawnEnemy() { spawnPoint.x = Random.Range(-10, 10); spawnPoint.y = 5f; spawnPoint.z = Random.Range(-10, 10); Instantiate(enemies[UnityEngine.Random.Range(0, enemies.Length - 1)], spawnPoint, Quaternion.identity); CancelInvoke(); } }
5aa4e45cf6f1980b158f071c5a157450e528a75a
[ "JavaScript", "C#", "Markdown" ]
5
JavaScript
JCels/BioFeedbackGaming
ce36103216bac8457454ef24c5ed4a1027dfbc3a
c680c091d868eb46b1c69081acb2c650f575a211
refs/heads/master
<repo_name>lukas-raberg/apples-of-my-eye<file_sep>/404.php <?php get_template_part('header') ?> <div class="category-wrapper"> <h1 class="blog-name">Fel 404</h1> <h2 class="centered">Sidan kunde inte hittas.</h2> <p class="centered">Sidan, artikeln eller inlägget du letar efter kan inte hittas. Testa att klicka på bakåt eller gå till <a class="link" href="/">startsidan</a></p> </div> <?php get_footer(); ?> <file_sep>/single.php <?php get_template_part('header') ?> <div class="singlehero"> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?> <?php the_post_thumbnail('fill'); // Fullsize image for the single post ?> <?php endif; ?> </div> <div class="single-wrapper"> <main role="main"> <section> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="selected-title-thin"></div> <h2 class="selected-title"> <?php the_title(); ?> </h2> <div class="selected-title-thin-less"></div> <div class="meta-single"> <div class="meta-micro meta-micro-pad"> <strong>Text:</strong> <?php the_author(); ?> </div> <div class="meta-micro meta-micro-pad"> <strong>Foto:</strong> <?php echo get_post_meta($post->ID, 'Fotograf:', true); ?> </div> <div class="meta-micro meta-micro-pad"> <strong>Publicerat: </strong><?php the_date(); ?> </div> <div class="meta-micro meta-micro-pad"> <strong>I kategorin:</strong> <?php the_category(', '); ?> </div> <div class="meta-micro"> <strong>Taggat med:</strong><span class="tags"><?php the_tags( ' ', '', ''); ?></span> </div> </div> <div class="single-intro"> <?php the_excerpt(); ?> </div> <div class="singlesingle"> <?php the_content(); ?> <?php edit_post_link(); ?> </div> <div class="comments"> <span class="tags BYT"> <h3 class="comment-reply-title">Dela med dig:</h3> <?php echo do_shortcode("[Sassy_Social_Share]"); ?> </span> </div> <div class="comments"> <?php comments_template( '', true ); // Remove if you don't want comments ?> </div> </article> <?php endwhile; ?> <?php else: ?> <article> <h1><?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?></h1> </article> <?php endif; ?> </section> </main> </div> <?php get_footer(); ?><file_sep>/authors-old.php <div class="authors-wrapper"> <div class="author-col"> <div class="author-header">Hanna <?php echo get_avatar('class="author-avatar"'); ?> <span class="author-name"><?php the_author('2');?></span> <span class="author-bio"><?php // echo get_the_author_meta('description'); ?>En kort presentation av varje skribent. Inte långt alls. Två eller tre meningar. Ungefär tre rader långt.</span> </div> <div class="author-list"> Senaste inlägg av <?php the_author_firstname(); ?> <?php query_posts('author=2&cat=-7'); ?> </div> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail(); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <p class="author-meta-data"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php the_date(); ?> </p> <h2 class="author-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <p class="author-excerpt"> <?php the_excerpt(); ?> </p> </article> <?php endwhile; ?> </div> <?php else: ?> <?php endif; ?> <div class="author-col"> <div class="author-header">LINA <?php echo get_avatar('class="author-avatar"'); ?> <span class="author-name"><?php the_author('4');?></span> <span class="author-bio"><?php // echo get_the_author_meta('description'); ?>En kort presentation av varje skribent. Inte långt alls. Två eller tre meningar. Ungefär tre rader långt.</span> </div> <div class="author-list"> Senaste inlägg av <?php the_author_firstname(); ?> <?php query_posts('author=4&cat=-7'); ?> </div> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail(); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <p class="author-meta-data"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php the_date(); ?> </p> <h2 class="author-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <p class="author-excerpt"> <?php the_excerpt(); ?> </p> </article> <?php endwhile; ?> </div> <?php else: ?> <?php endif; ?> <div class="author-col"> <div class="author-header">MARITA <?php echo get_avatar('class="author-avatar"'); ?> <span class="author-name"><?php the_author('5');?></span> <span class="author-bio"><?php // echo get_the_author_meta('description'); ?>En kort presentation av varje skribent. Inte långt alls. Två eller tre meningar. Ungefär tre rader långt.</span> </div> <div class="author-list"> Senaste inlägg av <?php the_author_firstname(); ?> <?php query_posts('author=5&cat=-7'); ?> </div> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail(); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <p class="author-meta-data"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php the_date(); ?> </p> <h2 class="author-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <p class="author-excerpt"> <?php the_excerpt(); ?> </p> </article> <?php endwhile; ?> </div> <?php else: ?> <?php endif; ?> <div class="author-col"> <div class="author-header">ELEONOR <?php echo get_avatar('class="author-avatar"'); ?> <span class="author-name"><?php the_author('6');?></span> <span class="author-bio"><?php // echo get_the_author_meta('description'); ?>En kort presentation av varje skribent. Inte långt alls. Två eller tre meningar. Ungefär tre rader långt.</span> </div> <div class="author-list"> Senaste inlägg av <?php the_author_firstname(); ?> <?php query_posts('author=6&cat=-7'); ?> </div> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail(); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <p class="author-meta-data"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php the_date(); ?> </p> <h2 class="author-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <p class="author-excerpt"> <?php the_excerpt(); ?> </p> </article> <?php endwhile; ?> </div> <?php else: ?> <?php endif; ?> </div><file_sep>/eyeson.php <div class="selected" id="eyeson"> <?php query_posts('cat=7&posts_per_page=1'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="selected-img"><?php the_post_thumbnail('selected'); ?></div> <div class="selected-puff"> <h3 class="featured-category"> <?php echo get_cat_name(7); ?> </h3> <h3 class="selected-title"> <div class="selected-title-thin"></div> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <div class="selected-title-thin"></div> </h3> <div class="authors"><?php echo get_author_name(); ?></div> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> </div> <file_sep>/single-blog.php <?php /* * Template Name: Blog * Template Post Type: post */ get_header(); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="blog-intro"> <h5 class="blog-name"><?php the_author_meta('display_name'); ?></h5> </div> <div class="single-blog-wrapper"> <main role="main"> <section> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="selected-title"> <?php the_title(); ?> </h1> <div class="author-single"> <?php the_author(); ?><br /> <?php the_date(); ?><br /> <?php _e( '', 'html5blank' ); the_category(', '); ?> </div> <div class="blog-single"> <?php the_content(); ?> <?php edit_post_link(); ?> </div> <div class="blog-meta"> <div class="blog-meta-tags"> <span class="tags"> <?php _e( '', 'html5blank' ); the_tags('<span class="bold">Taggat med:</span><br />', '', ''); ?> </span> <div style="height:2em;"></div> <span class="tags"> <span class="bold">Dela med dig:<br /></span> <?php echo do_shortcode("[Sassy_Social_Share]"); ?> </span> </div> <div class="comments-blog"> <?php comments_template(); // Remove if you don't want comments ?> </div> </div> </article> <?php endwhile; ?> <?php else: ?> <article> <h1><?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?></h1> </article> <?php endif; ?> </section> </main> </div> <?php get_footer(); ?><file_sep>/tag-blog.php <?php /* * Template Name: Blog * Template Post Type: Blog */ get_header(); ?> <div class="category-wrapper"> <h5 class="blog-name"><?php _e( 'Tag Archive: ', 'html5blank' ); echo single_tag_title('', false); ?></h5> <main role="main"> <!-- section --> <section> <?php get_template_part('loop-blog'); ?> <?php get_template_part('pagination'); ?> </section> <!-- /section --> </main> </div> <?php get_footer(); ?><file_sep>/js/scripts.js (function ($, root, undefined) { $(function () { 'use strict'; // DOM ready, take it away }); $(document).ready(function () { $(".menu-btn a").click(function () { $(".overlay").fadeToggle(200); $(this).toggleClass('btn-open').toggleClass('btn-close'); }); $('.menu a').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); }); })(jQuery, this); <file_sep>/single copy.php <?php /* * Template Name: Food * Template Post Type: post */ get_header(); ?> <div class="singlehero"> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?> <?php the_post_thumbnail('fill'); // Fullsize image for the single post ?> <?php endif; ?> </div> <div class="single-wrapper"> <main role="main"> <section> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="selected-title-thin"></div> <h2 class="selected-title"> <?php the_title(); ?> </h2> <div class="selected-title-thin"></div> <div class="author-single"> <?php the_author(); ?><br /> <?php the_date(); ?><br /> <?php $category = get_the_category(); if ( $category[0]->cat_name == "Article" ) { $name = $category[1]->cat_name; $cat_id = get_cat_ID( $name ); $link = get_category_link( $cat_id ); echo '<a href="'. esc_url( $link ) .'"">'. $name .'</a>'; } else { $name = $category[0]->cat_name; $cat_id = get_cat_ID( $name ); $link = get_category_link( $cat_id ); echo '<a href="'. esc_url( $link ) .'"">'. $name .'</a>'; } ?> </div> <div class="singlesingle"> <span class="p1"> <?php the_content(); ?> <?php edit_post_link(); ?> </span> </div> <div class="single-sidebar"> <span class="tags"> <?php the_tags( '<span class="bold">Taggat med:</span><br /> ', '<br />' ); ?> </span> <div style="height:2em;"></div> <span class="tags BYT"> <span class="bold">Dela med dig:<br /></span> [ikon] Facebook<br /> [ikon] Twitter<br /> [ikon] Email<br /> [ikon] Kopiera länk </span> </div> <div class="comments"> <?php comments_template( '', true ); // Remove if you don't want comments ?> </div> </article> <?php endwhile; ?> <?php else: ?> <article> <h1><?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?></h1> </article> <?php endif; ?> </section> </main> </div> <?php get_footer(); ?><file_sep>/articles-NEWLOOP.php <div class="featured-wrapper"> <?php $loop = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'travel, article', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="featured featured-fill"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <?php $loop = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'cocktails, article', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="featured featured-fill"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <?php $loop = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'lifestyle, article', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="featured featured-fill"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <?php $loop = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'food, article', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="featured featured-fill"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <div class="clearboth"></div><file_sep>/map.php <div class="map" id="map"> <?php echo do_shortcode('[map_bank maps_id="12" map_title="hide" map_description="hide" map_height="600" map_width="100" map_themes="muted_monotone"]'); ?> </div><file_sep>/articles.php <div class="featured-wrapper"> <?php query_posts('cat=6&posts_per_page=1'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="featured featured-fill featured-first"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> <?php query_posts('cat=2&posts_per_page=1'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="featured featured-fill featured-second"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> <?php query_posts('cat=4&posts_per_page=1'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="featured featured-fill featured-first"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> <?php query_posts('cat=3&posts_per_page=1'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="featured featured-fill featured-second"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail('large'); ?> <h2 class="featured-category"> <?php the_category(); ?> </h2> <div class="selected-title-thin"></div> <h3 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> <div class="selected-title-thin"></div> <span class="featured-author"> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <div class="clearboth" id="blogs"></div><file_sep>/featured OLD full size bg img.php <div class="featured-wrapper"> <?php query_posts('cat=8&posts_per_page=5'); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="featured featured-fill" style="background-image: url('<?php echo wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ); ?>');"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <span class="featured-category"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> </span> <h2 class="featured-title"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <span class="featured-author"> av <br /> <?php the_author(); ?> </span> </article> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <div class="clearboth"></div> /*------------------------------------*\ FEATURED \*------------------------------------*/ .featured-wrapper { position:relative; width:98%; margin:1%; display:block; clear:both; overflow:visible; } .featured { width:100%; float:left; margin:0; background:blue; } .last { margin:0; } .featured h2 { text-align:center; } .featured a { color:white; font-size:1.5em; margin-bottom:1em; } .category-featured { } ul.post-categories { list-style-type:none; padding:1em 0 0 0; text-align:center; font-weight:300; font-size:0.875em; letter-spacing:3px; text-transform:uppercase; } li.post-categories { } .featured-title { font-family: 'Alegreya', serif; font-style:normal; font-weight:100; font-size:1em; text-align:left; padding:0 .6em; height:auto; color:white; } .featured-category, .author { font-size:0.875em; text-align:center; color:white; margin:0 auto; display:block; text-transform:uppercase; font-weight:300; letter-spacing:3px; padding:2em 0 0 0; } .featured-author { font-size:.75em; text-align:center; color:white; margin:0 auto; display:block; text-transform:uppercase; font-weight:300; letter-spacing:2px; padding:1em 0; } .featured-fill { overflow:hidden; display:block; background-repeat:no-repeat; background-position:center center; background-size:cover; background-color:black; box-shadow: inset 0 0 0 1000px rgba(0,0,0,.5); } .featured-fill:hover { box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3); } @media only screen and (min-width:768px) { .featured-title { font-size:.75em; height:8em; } .featured { max-width:50%; float:left; } @media only screen and (min-width:1279px) { .featured-title { font-size:1.375em; } } @media only screen and (min-width:1439px) { .featured-title { font-size:1.625em; } }<file_sep>/footer.php <footer class="footer"> <div class="footer-inner"> <div class="footer-nav"> <div class="footer-nav-container"> <ul> <span class="headline">Curated</span> <li><a href="../../#eyeson">Eyes on</a></li> <li><a href="../../#map">Map</a></li> </ul> </div> <div class="footer-nav-container"> <ul> <span class="headline">Articles</span> <li><a href="/lifestyle/">Lifestyle</a></li> <li><a href="/cocktails/">Cocktails</a></li> <li><a href="/food/">Food</a></li> <li><a href="/getaways/">Getaways</a></li> </ul> </div> <div class="footer-nav-container"> <ul> <span class="headline">Blogs</span> <li><a href="/author/hanna/"><NAME></a></li> <li><a href="/author/eleonor/"><NAME></a></li> <li><NAME></li> <li><a href="/author/marita/"><NAME></a></li> </ul> </div> <div class="footer-nav-container"> <ul> <span class="headline">Misc.</span> <li><a href="/about-us/">About us</a></li> <li><a href="/collaborate-with-us/">Collaborate with us</a></li> </ul> </div> </div> <div class="footer-logo"> <a href="/"><img class="" alt="Apples of my eye: Logotype" src="<?php echo get_template_directory_uri(); ?>/img/apples-of-my-eye-logo-white.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/apples-of-my-eye-logo-white.png'; this.onerror=null;"></a> </div> <div class="socials-footer"> <a href="https://www.facebook.com/applesofmyeye.magazine/"><img class="icons-footer" alt="Apples of my eye: Facebook" src="<?php echo get_template_directory_uri(); ?>/img/fb-neg.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/fb-neg.png'; this.onerror=null;"></a> <a href="https://www.instagram.com/applesofmyeye_magazine/"><img class="icons-footer" alt="Apples of my eye: Instagram" src="<?php echo get_template_directory_uri(); ?>/img/insta-neg.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/insta-neg.png'; this.onerror=null;"></a> <a href="mailto:<EMAIL>"><img class="icons-footer" alt="Apples of my eye: Email" src="<?php echo get_template_directory_uri(); ?>/img/email-neg.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/email-neg.png'; this.onerror=null;"></a> </div> <div class="copyright"> <span class="x-small centered white">Copyright 2018 Apples of My Eye.</span> </div> </div> </footer> </body> <div id="fb-root"></div> </html> <file_sep>/category-all.php <?php get_header(); ?> <div class="category-wrapper"> <?php $args = array ( 'cat' => array(18), 'posts_per_page' => -1, //showposts is deprecated 'orderby' => 'date' //You can specify more filters to get the data ); $cat_posts = new WP_query($args); if ($cat_posts->have_posts()) : while ($cat_posts->have_posts()) : $cat_posts->the_post(); get_template_part( 'content', 'category' ); endwhile; endif; ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="category-list"> <a class="category-title" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="category-img"> <?php the_post_thumbnail('large'); ?> </div> <div class="category-text"> <h2 class="featured-category"> <?php the_date(); ?> </h2> <h2 class="category-category"> <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> </h2> <h3 class="category-title"> <?php the_title(); ?> </h3> <span class="category-excerpt"> <?php the_excerpt(); ?> </span> <span class="category-author"> av <br /> <?php the_author(); ?> </span> </div> </article> </div> </a> <?php endwhile; ?> <?php else: ?> <?php endif; ?> </div> <div class="clearboth"></div> <?php get_footer(); ?><file_sep>/loop-blog.php <?php query_posts( array( 'post_type' => array( 'blog', 'post' ), 'showposts' => 1000, 'orderby' => 'desc') ); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="category-list"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="category-img"> <?php the_post_thumbnail('large'); ?> </div> <div class="category-text"> <h2 class="featured-category"> <?php the_category(', '); ?> <?php the_tags(); ?> </h2> <div class="selected-title-thin"> </div> <a class="category-title" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <h3 class="category-title"> <?php the_title(); ?> </h3> </a> <span class="category-excerpt"> <?php the_excerpt(); ?> </span> <div class="selected-title-thin"> </div> <span class="category-author"> <?php the_author(); ?> </span> </div> </div> <?php endwhile; ?> <?php else: ?> <?php endif; ?><file_sep>/authors.php <div class="authors-wrapper"> <div class="author-col first"> <div class="author-header"> <div class="avatar-box"><img class="avatar" src="./static/hanna.jpg" alt="<NAME> i blå skjorta, i bakgrund en gråblå vägg."></div> <div class="author-name"><a href="../author/hanna/"><?php the_author_meta( 'display_name', 2 ); ?></a></div> <div class="author-bio"><?php the_author_meta('user_description', 2); ?></div> </div> <?php $loop = new WP_Query( array( 'author' => '2', 'posts_per_page' => '1', 'post_type' => 'blog', 'category_name' => 'blog', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="author-title-thin"></div> <p class="author-meta-data"><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php echo get_the_date(); ?></p> <h2 class="author-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="author-excerpt center"><?php the_excerpt(); ?></p> <div class="author-title-thin"></div> </article> <?php endwhile; if ( $loop->max_num_pages > 1 ) : ?> <?php endif; endif; wp_reset_postdata(); ?> </div> <div class="author-col not-last"> <div class="author-header"> <div class="avatar-box"><img class="avatar" src="./static/marita.jpg" alt="Marita i gul blus skrattar framför en rosa vägg."></div> <div class="author-name"><a href="../author/marita/"><?php the_author_meta( 'display_name', 5 ); ?></a></div> <div class="author-bio"><?php the_author_meta('user_description', 5); ?></div> </div> <?php $loop = new WP_Query( array( 'author' => '5', 'posts_per_page' => '1', 'post_type' => 'blog', 'category_name' => 'blog', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="author-title-thin"></div> <p class="author-meta-data"><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php echo get_the_date(); ?></p> <h2 class="author-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="author-excerpt center"><?php the_excerpt(); ?></p> <div class="author-title-thin"></div> </article> <?php endwhile; if ( $loop->max_num_pages > 1 ) : ?> <?php endif; endif; wp_reset_postdata(); ?> </div> <div class="author-col not-last-alt"> <div class="author-header"> <div class="avatar-box"><img class="avatar" src="./static/eleonor.jpg" alt="Eleonor i ljusblå stickad tröja skrattandes framför en gråblå vägg."></div> <div class="author-name"><a href="../author/eleonor/"><?php the_author_meta( 'display_name', 6 ); ?></a></div> <div class="author-bio"><?php the_author_meta('user_description', 6); ?></div> </div> <?php $loop = new WP_Query( array( 'author' => '6', 'posts_per_page' => '1', 'post_type' => 'blog', 'category_name' => 'blog', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="author-title-thin"></div> <p class="author-meta-data"><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php echo get_the_date(); ?></p> <h2 class="author-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="author-excerpt center"><?php the_excerpt(); ?></p> <div class="author-title-thin"></div> </article> <?php endwhile; if ( $loop->max_num_pages > 1 ) : ?> <?php endif; endif; wp_reset_postdata(); ?> </div> <div class="author-col last"> <div class="author-header"> <div class="avatar-box"><img class="avatar" src="./static/lina.jpg" alt="<NAME> i rosa tröja framför en rosa vägg."></div> <div class="author-name"><?php the_author_meta( 'display_name', 4 ); ?></div> <div class="author-bio"><?php the_author_meta('user_description', 4); ?></div> </div> <?php $loop = new WP_Query( array( 'author' => '4', 'posts_per_page' => '1', 'post_type' => 'blog', 'category_name' => 'blog', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <article class="auth" id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="author-title-thin"></div> <p class="author-meta-data"><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?> | <?php echo get_the_date(); ?></p> <h2 class="author-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="author-excerpt center"><?php the_excerpt(); ?></p> <div class="author-title-thin"></div> </article> <?php endwhile; if ( $loop->max_num_pages > 1 ) : ?> <?php endif; endif; wp_reset_postdata(); ?> </div> </div> <div class="clearboth"></div><file_sep>/navigation.php <a href="/"><img class="nav-logo" alt="Apples of my eye: Logotype" src="<?php echo get_template_directory_uri(); ?>/img/apples-of-my-eye-logo.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/apples-of-my-eye-logo.png'; this.onerror=null;"></a> <div class="socials-header"> <a href="https://www.facebook.com/applesofmyeye.magazine/"><img class="social" alt="Apples of my eye: Facebook" src="<?php echo get_template_directory_uri(); ?>/img/fb.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/fb.png'; this.onerror=null;"></a> <a href="https://www.instagram.com/applesofmyeye_magazine/"><img class="social" alt="Apples of my eye: Instagram" src="<?php echo get_template_directory_uri(); ?>/img/insta.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/insta.png'; this.onerror=null;"></a> <a href="mailto:<EMAIL>"><img class="social social-last" alt="Apples of my eye: Email" src="<?php echo get_template_directory_uri(); ?>/img/email.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/email.png'; this.onerror=null;"></a> </div> <div class="topnav"> <ul> <li><a href="/lifestyle/">Lifestyle</a></li> <li><a href="/cocktails/">Cocktails</a></li> <li><a href="/food/">Food</a></li> <li><a href="/getaways/">Getaways</a></li> <li><a href="../../#map">Map</a></li> </ul> </div> <div class="menu-btn"> <a class="btn-open" href="javascript:void(0)"></a> </div> <div class="overlay"> <div class="menu"> <ul> <a href="/eyes-on/"><li>Eyes on</li></a> <a href="/lifestyle"><li>Lifestyle</li></a> <a href="/cocktails/"><li>Cocktails</li></a> <a href="/food/"><li>Food</li></a> <a href="/getaways/"><li>Getaways</li></a> <a href="../../#blogs" class="local"><li>Blogs</li></a> <a href="../../#map" class="local"><li>Map</li></a> <a href="/about-us/"><li>About us</li></a> <a href="/collaborate-with-us/"><li>Collaborate with us</li></a> </ul> <div class="socials-menu"> <a href="https://www.facebook.com/applesofmyeye.magazine/"><img class="social-menu" alt="Apples of my eye: Facebook" src="<?php echo get_template_directory_uri(); ?>/img/fb.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/fb.png'; this.onerror=null;"></a> <a href="https://www.instagram.com/applesofmyeye_magazine/"><img class="social-menu" alt="Apples of my eye: Instagram" src="<?php echo get_template_directory_uri(); ?>/img/insta.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/insta.png'; this.onerror=null;"></a> <a href="mailto:<EMAIL>"><img class="social-menu" alt="Apples of my eye: Email" src="<?php echo get_template_directory_uri(); ?>/img/email.svg" onerror="this.src='<?php echo get_template_directory_uri(); ?>/img/email.png'; this.onerror=null;"></a> </div> </div> </div><file_sep>/header.php <!doctype html> <html <?php language_attributes(); ?> class="no-js"> <head> <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script> <script> WebFont.load({ google: { families: ['Alegreya Sans', 'Alegreya'] } }); </script> <link href="https://fonts.googleapis.com/css?family=Alegreya+Sans:300,400,400i,500,700|Alegreya:200,200i,400,400i,700,700i" rel="stylesheet" type="text/css"> <script async defer src="https://maps.googleapis.com/maps/api/js?key=<KEY>" type="text/javascript"></script> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-114982698-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-114982698-1'); </script> <meta charset="<?php bloginfo('charset'); ?>"> <title> <?php if (is_home () ) { bloginfo('name'); } elseif ( is_category() ) { single_cat_title(); echo ' - ' ; bloginfo('name'); } elseif (is_single() ) { single_post_title();} elseif (is_page() ) { single_post_title();} else { wp_title('',true); } ?> </title> <link href="<?php echo get_template_directory_uri(); ?>/img/icons/favicon.ico" rel="shortcut icon"> <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="<?php bloginfo('description'); ?>"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <header class="stick"> <?php get_template_part('navigation'); ?> </header><file_sep>/index.php <?php get_header(); ?> <?php get_template_part('eyeson')?> <?php get_template_part('articles'); ?> <?php get_template_part('authors'); ?> <?php get_template_part('introimg')?> <?php get_template_part('manifest'); ?> <?php get_template_part('map'); ?> <?php get_footer(); ?> <file_sep>/category-blog.php <?php /* * Template Name: Blog * Template Post Type: Blog */ get_header(); ?> <div class="blog-wrapper"> <h5 class="blog-name"><?php the_category('display_name'); ?></h5> <?php query_posts( array( 'post_type' => array( 'blog' ), 'showposts' => 1000, 'paged' => $paged, 'orderby' => 'desc') ); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <div class="blog-list"> <a class="category-title" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="category-img"> <?php the_post_thumbnail('large'); ?> </div> <div class="category-text"> <div class="selected-title-thin"></div> <h3 class="category-title"> <?php the_title(); ?> </h3> <span class="category-excerpt"> <?php the_excerpt(); ?> </span> <div class="selected-title-thin"></div> <span class="category-author"> <?php the_author(); ?> </span> </div> </article> </div> </a> <?php endwhile; ?> <?php else: ?> <?php endif; ?> <div class="clearboth"></div> </div> <?php get_footer(); ?>
dad6a6defea793e69150387dd1ffe1ea61d9e1cd
[ "JavaScript", "PHP" ]
20
PHP
lukas-raberg/apples-of-my-eye
86e70e78372880cfc410d964ffe848e1ca558e2a
4af986ade315b5dbf1302faaa2c767a3f4992952
refs/heads/master
<file_sep><pre> {"repository"=> {"name"=>"dotfiles", "created_at"=>"2011-12-08T10:25:37Z", "updated_at"=>"2012-01-08T19:58:35Z", "url"=>"https://api.github.com/repos/luisobo/dotfiles", "id"=>2939311, "pushed_at"=>"2012-01-08T19:54:04Z", "owner"=> {"gravatar_id"=>"f9970f7693ac2fe9a237ee30d748249b", "avatar_url"=>"https://secure.gravatar.com/avatar/f9970f7693ac2fe9a237ee30d748249b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png", "url"=>"https://api.github.com/users/luisobo", "id"=>825073, "login"=>"luisobo" } }, "sender"=> {"gravatar_id"=>"f9970f7693ac2fe9a237ee30d748249b", "avatar_url"=>"https://secure.gravatar.com/avatar/f9970f7693ac2fe9a237ee30d748249b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png", "url"=>"https://api.github.com/users/luisobo", "id"=>825073, "login"=>"luisobo" }, "action"=>"closed", "issue"=> {"number"=>1, "created_at"=>"2012-01-08T19:51:19Z", "pull_request"=> {"diff_url"=>nil, "patch_url"=>nil, "html_url"=>nil }, "body"=>"hahaha", "comments"=>0, "title"=>"test issue", "updated_at"=>"2012-01-08T21:58:38Z", "url"=>"https://api.github.com/repos/luisobo/dotfiles/issues/1", "id"=>2762495, "assignee"=>nil, "milestone"=>nil, "closed_at"=>"2012-01-08T21:58:38Z", "labels"=>[], "user"=> {"avatar_url"=>"https://secure.gravatar.com/avatar/f9970f7693ac2fe9a237ee30d748249b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png", "gravatar_id"=>"f9970f7693ac2fe9a237ee30d748249b", "url"=>"https://api.github.com/users/luisobo", "id"=>825073, "login"=>"luisobo" }, "html_url"=>"https://github.com/luisobo/dotfiles/issues/1", "state"=>"closed" } } </pre><file_sep>source :rubygems gem 'sinatra' gem 'heroku' gem 'thin' gem 'foreman'<file_sep>require 'sinatra' set :kanbanery_board_id => 'replace' set :kanbanery_workspace => 'replace' set :kanbanery_auth_token => 'replace'<file_sep>require 'sinatra' require 'json' require 'net/http' require 'net/https' require 'uri' require './lib/kanbanery.rb' require './config.rb' kanbanery = Kanbithub::Kanbanery.new settings.kanbanery_auth_token, settings.kanbanery_workspace, settings.kanbanery_board_id post '/' do data = JSON.parse(params[:payload]) if data['issue'] if data['action'] == "opened" kanbanery.create_task_form_github data['issue'] end end end<file_sep>module Kanbithub class Kanbanery def initialize(auth_token, workspace, board_id) @auth_token = auth_token @workspace = workspace @board_id = board_id @uri = URI.parse "https://#{@workspace}.kanbanery.com/api/v1/projects/#{@board_id}/tasks.json" @http = Net::HTTP.new @uri.host, @uri.port @http.use_ssl = true @header = { 'X-Kanbanery-ApiToken' => auth_token } end def create_task_form_github(github_issue) data = form_task_data github_issue resp, data = @http.post(@uri.request_uri, data, @header) end private def form_task_data(github_issue) title = github_issue['title'] task_type = task_type_from_labels github_issue['labels'] description = "More info: #{github_issue['html_url']}" "task[title]=#{title}&task[task_type_name]=#{task_type}&task[description]=#{description}" end def task_type_from_labels(labels) labels = labels.collect { |l| l['name'] }.each(&:downcase!) if labels.include? 'bug' 'bug' elsif labels.include? 'chore' 'chore' else 'feature' end end end end<file_sep>## Features When a issue is created on Github it automatically recreates it on Kanbanery: * Same title * Same task type based on GitHub labels (Feature, Bug or Chore at this moment) * Description with a link to the Github Issue ## Installation Create the hook for GitHub Issues <pre>curl -u "USERNAME:PASSWORD" -i https://api.github.com/repos/USERNAME/REPO/hooks \ -d '{ "name": "web", "config":{"url":"YOUR URL HERE"},"events":["issues"]}'</pre> Edit the config file and deploy. I use heroku.
5bc8a3fda33e11296fa7da4d0c7489fddaa8980e
[ "Markdown", "Ruby" ]
6
Markdown
luisobo/kanbithub
6c8b10d0b43a251220d7e7da594ec7c535be8fab
ddaac2a354cb640e30d582362adc86d548d3dc4e
refs/heads/master
<repo_name>su-susu/mosen<file_sep>/README.md # mosen front-end <file_sep>/mt-project/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-default/index.css' // import axios from 'axios'; Vue.use(ElementUI) Vue.use(Router) export default new Router({ routes: [ { path: '/', component: HelloWorld }, { path: '/Registry', component: resolve => require(['../components/Registry.vue'], resolve) }, { path: '/Login', component: resolve => require(['../components/Login.vue'],resolve) }, // 卖家相关界面的path { path: '/Seller/home', component: resolve => require(['../components/seller/home.vue'],resolve) } , { path: '/Seller/addGoods', component: resolve => require(['../components/seller/addGoods.vue'],resolve) }, { path: '/Seller/editGoods', component: resolve => require(['../components/seller/editGoods.vue'],resolve) }, { path: '/Seller/orderMsg', component: resolve => require(['../components/seller/orderMsg.vue'],resolve) }, { path: '/Seller/editImfo', component: resolve => require(['../components/seller/editImfo.vue'],resolve) } , //买家有关界面path { path: '/customer/info', component: resolve => require(['../components/customer/info.vue'],resolve) }, { path: '/customer/cart', component: resolve => require(['../components/customer/cart.vue'],resolve) }, ] })
6e87c9462832eec5e9402fede3f2dd87eebb869f
[ "Markdown", "JavaScript" ]
2
Markdown
su-susu/mosen
40d002774f828b979a81f24f80ed57418af19866
d90e1cf7e556e4a5579dd4c11a4437997371608b
refs/heads/master
<repo_name>hanouchen/monsters-rolodex<file_sep>/src/App.js import React, { Component } from 'react'; import { CardList } from './components/card-list/car-list.component'; import { SearchBox } from './components/search-box/search-box.component'; // import logo from './logo.svg'; import './App.css'; class MyApp extends Component { constructor () { super(); this.state = { monsters: [], searchField: '', }; } componentDidMount () { fetch('https://jsonplaceholder.typicode.com/users', {mode: 'cors'}) .then(response => response.json()) .then(users => this.setState({ monsters: users })) .catch(error => { console.log(error); }); } handleChange = (e) => this.setState({ searchField: e.target.value}); render () { const { monsters, searchField } = this.state; const filteredMonsters = monsters.filter(({ name }) => name.toLowerCase().includes(searchField.toLowerCase()) ); return ( <div className="App"> <h1>Monster Roledex</h1> <SearchBox placeholder='search monsters' onChange={this.handleChange}/> <CardList monsters={filteredMonsters}/> </div> ); } } export default MyApp;
8bc0bf432ecf936001a1250a6384712ce186f813
[ "JavaScript" ]
1
JavaScript
hanouchen/monsters-rolodex
0317ce377f960db7006c20f0b88820c16dd1b1ab
4193b929c681c42e6e92c9a289c1b7c5461c408f
refs/heads/master
<file_sep><script> $(document).ready(function(){ //Cargar Sucursal $(".go-sucursal").click(function(){ var id_sucursal = $("#id_sucursal").val(); var url1 = $(this).attr("id"); $.ajax({ url: url1+id_sucursal, type:"post", success: function(){ $(".pages").load(url1+id_sucursal); }, error:function(){ //alert("Error.. No se subio la imagen"); } }); }); //End }); </script> <style> .center{ text-align: center; } .header{ background: #88B32F; } .izquierda{ text-align: right; } .go-sucursal{ cursor: pointer; } </style> <div class="tab-content"> <div class="row"> <div class="col-md-2"> <h3 id="../sucursales/Cindex/index/" class="go-sucursal"><i class="fa fa-arrow-left"></i>REGRESAR</h3> </div> <div class="col-md-10 izquierda"> <h3>SUCURSAL : <?php echo $sucursales[0]->nombre_sucursal; ?></h3> </div> </div> <div class="row"> <input type="hidden" value="<?php echo $sucursales[0]->id_sucursal; ?>" name="id_sucursal" id="id_sucursal"> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-sitemap'></i>Nodos </a> <a class="list-group-item go-sucursal" id="../sucursales/Cindex/cargar_nodos/"> <p class="center"><img src="../../../asset_/img/domain-transfer.png"></p> </a> </div> </div> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-file-text'></i>Ordenes </a> <a class="list-group-item go-sucursal" id="../sucursales/Cindex/ordenes/<?php echo $sucursales[0]->id_sucursal; ?>"> <p class="center"><img src="../../../asset_/img/ordenes.png"></p> </a> </div> </div> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-file-text'></i>Productos </a> <a class="list-group-item go-sucursal" id=""> <p class="center"><img src="../../../asset_/img/catalogo.png"></p> </a> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-check'></i>Pedidos </a> <a class="list-group-item go-sucursal" id=""> <p class="center"><img src="../../../asset_/img/pedidos.png"></p> </a> </div> </div> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-money'></i>Cortes </a> <a class="list-group-item go-sucursal" id=""> <p class="center"><img src="../../../asset_/img/cortes.png"></p> </a> </div> </div> <div class="col-md-4"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-bell'></i>Notificacion </a> <a class="list-group-item go-sucursal" id=""> <p class="center"><img src="../../../asset_/img/notificacion.png"></p> </a> </div> </div> </div> </div> <file_sep>SET FOREIGN_KEY_CHECKS=0; -- Dump de la Base de Datos -- Fecha: martes 20 diciembre 2016 - 04:22:47 -- -- Version: 1.1.1, del 18 de Marzo de 2005, <EMAIL> -- Soporte y Updaters: http://insidephp.sytes.net -- -- Host: `localhost` Database: `db_global_lapizzeria` -- ------------------------------------------------------ -- Server version 10.1.16-MariaDB -- -- Table structure for table `log_backups` -- DROP TABLE IF EXISTS log_backups; CREATE TABLE `log_backups` ( `id_bk` int(11) NOT NULL AUTO_INCREMENT, `nombre_bk` varchar(50) DEFAULT NULL, `fecha_bk` datetime NOT NULL, `link_bk` varchar(50) DEFAULT NULL, KEY `Índice 1` (`id_bk`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; -- -- Dumping data for table `log_backups` -- LOCK TABLES log_backups WRITE; INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('4', '1', '2016-10-11 19:34:23', '1'); INSERT INTO log_backups VALUES('5', '2016-Oct-16-05-00-24db_global_lapizzeria_bk.sql.gz', '2016-10-16 05:00:25', '2016-Oct-16-05-00-24db_global_lapizzeria_bk.sql.gz'); INSERT INTO log_backups VALUES('6', '2016-Nov-25-03-45-06db_global_lapizzeria_bk.sql.gz', '2016-11-25 03:45:06', '2016-Nov-25-03-45-06db_global_lapizzeria_bk.sql.gz'); INSERT INTO log_backups VALUES('7', '2016-Dec-13-05-12-09db_global_lapizzeria_bk.sql.gz', '2016-12-13 05:12:10', '2016-Dec-13-05-12-09db_global_lapizzeria_bk.sql.gz'); UNLOCK TABLES; -- -- Table structure for table `sr_accesos` -- DROP TABLE IF EXISTS sr_accesos; CREATE TABLE `sr_accesos` ( `id_acceso` int(11) NOT NULL AUTO_INCREMENT, `id_rol` int(11) NOT NULL DEFAULT '0', `id_menu` int(11) NOT NULL DEFAULT '0', `id_usuario` int(11) NOT NULL DEFAULT '0', `estado` int(11) NOT NULL DEFAULT '0', KEY `Índice 1` (`id_acceso`), KEY `FK_sr_accesos_sr_roles` (`id_rol`), KEY `FK_sr_accesos_sr_menu` (`id_menu`), CONSTRAINT `FK_sr_accesos_sr_menu` FOREIGN KEY (`id_menu`) REFERENCES `sr_menu` (`id_menu`) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `FK_sr_accesos_sr_roles` FOREIGN KEY (`id_rol`) REFERENCES `sr_roles` (`id_rol`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=139 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_accesos` -- LOCK TABLES sr_accesos WRITE; INSERT INTO sr_accesos VALUES('1', '1', '1', '1', '1'); INSERT INTO sr_accesos VALUES('5', '1', '4', '1', '1'); INSERT INTO sr_accesos VALUES('6', '1', '5', '1', '1'); INSERT INTO sr_accesos VALUES('54', '1', '6', '1', '1'); INSERT INTO sr_accesos VALUES('55', '15', '1', '0', '1'); INSERT INTO sr_accesos VALUES('58', '15', '4', '0', '1'); INSERT INTO sr_accesos VALUES('59', '15', '5', '0', '0'); INSERT INTO sr_accesos VALUES('60', '15', '6', '0', '0'); INSERT INTO sr_accesos VALUES('115', '1', '7', '0', '1'); INSERT INTO sr_accesos VALUES('116', '15', '7', '0', '1'); INSERT INTO sr_accesos VALUES('119', '19', '1', '0', '0'); INSERT INTO sr_accesos VALUES('120', '19', '4', '0', '0'); INSERT INTO sr_accesos VALUES('121', '19', '5', '0', '0'); INSERT INTO sr_accesos VALUES('122', '19', '6', '0', '1'); INSERT INTO sr_accesos VALUES('123', '19', '7', '0', '0'); INSERT INTO sr_accesos VALUES('124', '20', '1', '0', '0'); INSERT INTO sr_accesos VALUES('125', '20', '4', '0', '0'); INSERT INTO sr_accesos VALUES('126', '20', '5', '0', '0'); INSERT INTO sr_accesos VALUES('127', '20', '6', '0', '0'); INSERT INTO sr_accesos VALUES('128', '20', '7', '0', '0'); INSERT INTO sr_accesos VALUES('129', '21', '1', '0', '0'); INSERT INTO sr_accesos VALUES('130', '21', '4', '0', '0'); INSERT INTO sr_accesos VALUES('131', '21', '5', '0', '0'); INSERT INTO sr_accesos VALUES('132', '21', '6', '0', '0'); INSERT INTO sr_accesos VALUES('133', '21', '7', '0', '0'); INSERT INTO sr_accesos VALUES('134', '1', '8', '0', '1'); INSERT INTO sr_accesos VALUES('135', '15', '8', '0', '1'); INSERT INTO sr_accesos VALUES('136', '19', '8', '0', '1'); INSERT INTO sr_accesos VALUES('137', '20', '8', '0', '0'); INSERT INTO sr_accesos VALUES('138', '21', '8', '0', '0'); UNLOCK TABLES; -- -- Table structure for table `sr_avatar` -- DROP TABLE IF EXISTS sr_avatar; CREATE TABLE `sr_avatar` ( `id_avatar` int(100) NOT NULL AUTO_INCREMENT, `nombre_avatar` varchar(200) NOT NULL DEFAULT '0', `genero_avatar` char(50) NOT NULL DEFAULT '0', `usuario_avatar` varchar(50) NOT NULL DEFAULT '0', `usuario_id` int(11) unsigned DEFAULT NULL, `url_avatar` varchar(100) NOT NULL DEFAULT '0', `estado_avatar` int(11) NOT NULL DEFAULT '0', KEY `Índice 1` (`id_avatar`) ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_avatar` -- LOCK TABLES sr_avatar WRITE; INSERT INTO sr_avatar VALUES('1', '0', 'm', 'personal', '1', 'avatar_rafael.png', '1'); INSERT INTO sr_avatar VALUES('2', '0', 'm', 'sistema', NULL, 'avatar1_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('3', '0', 'm', 'sistema', NULL, 'avatar2_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('4', '0', 'm', 'sistema', NULL, 'avatar4_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('5', '0', 'm', 'sistema', NULL, 'avatar6_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('6', '0', 'm', 'sistema', NULL, 'avatar7_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('7', '0', 'm', 'sistema', NULL, 'avatar11_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('8', '0', 'm', 'personal', '2', 'jose.lopez.png', '1'); INSERT INTO sr_avatar VALUES('9', '0', 'f', 'sistema', NULL, 'avatar3_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'f', 'sistema', NULL, 'avatar5_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'f', 'sistema', NULL, 'avatar8_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'f', 'sistema', NULL, 'avatar9_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'f', 'sistema', NULL, 'avatar10_big@2x.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'm', 'personal', '1', 'avatar-924111135a76cec9a4bfbb02d1efa0cf.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'm', 'personal', '1', 'Codeschool - jQuery The Return Flight (2013).png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'm', 'personal', '1', 'no_user_logo.png', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'm', 'personal', '1', 'no-profile.gif', '1'); INSERT INTO sr_avatar VALUES('10', '0', 'm', 'personal', '1', 'flexible-deployment-icon.png', '1'); INSERT INTO sr_avatar VALUES('11', 'nike_zoom_soldier_VII.jpg', 'm', 'personal', '1', 'nike_zoom_soldier_VII.jpg', '1'); INSERT INTO sr_avatar VALUES('12', '2007_toyota_yaris_s_virginia_beach_va_7080041433458508257.jpg', 'm', 'personal', '1', '2007_toyota_yaris_s_virginia_beach_va_7080041433458508257.jpg', '1'); INSERT INTO sr_avatar VALUES('13', 'Nahum H.png', 'm', 'personal', '9', 'Nahum H.png', '1'); INSERT INTO sr_avatar VALUES('14', 'Nahum H.png', 'm', 'personal', '9', 'Nahum H.png', '1'); INSERT INTO sr_avatar VALUES('15', 'Nahum H.png', 'm', 'personal', '9', 'Nahum H.png', '1'); INSERT INTO sr_avatar VALUES('16', 'nahum.jpg', 'm', 'personal', '9', 'nahum.jpg', '1'); INSERT INTO sr_avatar VALUES('17', 'Nahum H.png', 'm', 'personal', '10', 'Nahum H.png', '1'); INSERT INTO sr_avatar VALUES('18', 'circle_logo.png', 'M', 'personal', '1', 'circle_logo.png', '1'); INSERT INTO sr_avatar VALUES('19', '0', 'M', 'sistema', NULL, 'detective.png', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_cargos` -- DROP TABLE IF EXISTS sr_cargos; CREATE TABLE `sr_cargos` ( `id_cargo` int(11) NOT NULL AUTO_INCREMENT, `nombre_cargo` varchar(50) NOT NULL DEFAULT '0', `estado_cargo` int(11) NOT NULL DEFAULT '0', KEY `Índice 1` (`id_cargo`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_cargos` -- LOCK TABLES sr_cargos WRITE; INSERT INTO sr_cargos VALUES('1', 'Super Administrador', '1'); INSERT INTO sr_cargos VALUES('2', 'Administrador', '1'); INSERT INTO sr_cargos VALUES('10', 'Gerente Sucursal', '1'); INSERT INTO sr_cargos VALUES('11', 'Mesero', '1'); INSERT INTO sr_cargos VALUES('12', 'Cocinero', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_config` -- DROP TABLE IF EXISTS sr_config; CREATE TABLE `sr_config` ( `id_config` int(100) NOT NULL AUTO_INCREMENT, `id_rol` int(100) NOT NULL DEFAULT '0', `pages_config` varchar(50) DEFAULT NULL, `url_config` varchar(250) NOT NULL DEFAULT '0', `accion` varchar(100) NOT NULL DEFAULT '0', `estado_config` int(1) NOT NULL DEFAULT '0', KEY `Índice 1` (`id_config`), KEY `FK_sr_config_sr_roles` (`id_rol`), CONSTRAINT `FK_sr_config_sr_roles` FOREIGN KEY (`id_rol`) REFERENCES `sr_roles` (`id_rol`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_config` -- LOCK TABLES sr_config WRITE; INSERT INTO sr_config VALUES('1', '1', 'login', 'login.php', 'checked', '1'); INSERT INTO sr_config VALUES('2', '1', 'user-lockscreen', 'user-lockscreen.php', 'checked', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_empresa` -- DROP TABLE IF EXISTS sr_empresa; CREATE TABLE `sr_empresa` ( `id_empresa` int(100) NOT NULL AUTO_INCREMENT, `nombre_empresa` varchar(50) DEFAULT NULL, `rubro_empresa` varchar(50) DEFAULT NULL, `logo_empresa` varchar(255) DEFAULT NULL, `pais` varchar(50) DEFAULT NULL, `departamento` varchar(50) DEFAULT NULL, `municipio` varchar(50) DEFAULT NULL, `telefono` varchar(50) DEFAULT NULL, `fax` varchar(50) DEFAULT NULL, `nit` varchar(50) DEFAULT NULL, `nombre_alcalde` varchar(250) DEFAULT NULL, `nombre_secretario` varchar(250) DEFAULT NULL, `jefe_registro_familiar` varchar(250) DEFAULT NULL, `estado_emrpesa` int(1) DEFAULT NULL, KEY `Índice 1` (`id_empresa`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_empresa` -- LOCK TABLES sr_empresa WRITE; INSERT INTO sr_empresa VALUES('1', 'La Pizzeria', 'Comida', '1410201642251lapizzeria.png', 'El Salvador', '', '', '23456789', '23456789', '', '', '', '', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_librerias` -- DROP TABLE IF EXISTS sr_librerias; CREATE TABLE `sr_librerias` ( `id_lib` int(100) NOT NULL AUTO_INCREMENT, `codigo_lib` int(10) DEFAULT NULL, `location` varchar(50) DEFAULT NULL, `parte` varchar(50) DEFAULT NULL, `url_libreria` varchar(50) DEFAULT NULL, `descripcion_lib` varchar(50) DEFAULT NULL, `estado_lib` int(1) DEFAULT NULL, KEY `Índice 1` (`id_lib`), KEY `FK_sr_librerias_sr_nombre_libreria` (`codigo_lib`), CONSTRAINT `FK_sr_librerias_sr_nombre_libreria` FOREIGN KEY (`codigo_lib`) REFERENCES `sr_nombre_libreria` (`id_nombre`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_librerias` -- LOCK TABLES sr_librerias WRITE; INSERT INTO sr_librerias VALUES('1', '1', 'login', 'header', 'assets/css/style.css', 'nada', '1'); INSERT INTO sr_librerias VALUES('2', '1', 'login', 'header', 'assets/css/ui.css', 'nada', '1'); INSERT INTO sr_librerias VALUES('3', '1', 'login', 'header', 'assets/plugins/bootstrap-loading/lada.min.css', 'nada', '1'); INSERT INTO sr_librerias VALUES('4', '6', 'dashboard', 'header', 'assets/js/forms.js', 'nada', '1'); INSERT INTO sr_librerias VALUES('4', '6', 'dashboard', 'header', 'assets/js/change_pages.js', 'nada', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_log_acceso` -- DROP TABLE IF EXISTS sr_log_acceso; CREATE TABLE `sr_log_acceso` ( `id_log` int(11) NOT NULL AUTO_INCREMENT, `id_usuario` int(11) DEFAULT NULL, `fecha` datetime DEFAULT NULL, KEY `Índice 1` (`id_log`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sr_log_acceso` -- LOCK TABLES sr_log_acceso WRITE; UNLOCK TABLES; -- -- Table structure for table `sr_menu` -- DROP TABLE IF EXISTS sr_menu; CREATE TABLE `sr_menu` ( `id_menu` int(100) NOT NULL AUTO_INCREMENT, `nombre_menu` varchar(50) DEFAULT NULL, `url_menu` varchar(200) DEFAULT NULL, `icon_menu` varchar(200) DEFAULT NULL, `class_menu` varchar(200) DEFAULT NULL, `id_rol_menu` int(50) DEFAULT NULL, `estado_menu` varchar(1) DEFAULT NULL, PRIMARY KEY (`id_menu`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_menu` -- LOCK TABLES sr_menu WRITE; INSERT INTO sr_menu VALUES('1', 'INICIO', 'dashboard.php', 'icon-home', 'nav-active active', '1', '1'); INSERT INTO sr_menu VALUES('4', 'CONFIGURACION', 'configuracion.php', 'fa fa-cogs', NULL, '1', '1'); INSERT INTO sr_menu VALUES('5', 'BACKUP', 'backup.php', 'fa fa-check', '', '1', '1'); INSERT INTO sr_menu VALUES('6', 'PASSWORD', '<PASSWORD>', 'fa fa-unlock', '', '1', '1'); INSERT INTO sr_menu VALUES('7', 'ADMINISTRACION', 'sucursal.php', 'fa fa-cogs', '', '1', '1'); INSERT INTO sr_menu VALUES('8', 'ADMIN SUCURSAL', 'backend/sucursales/index/id', 'fa fa-download', 'null', '1', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_nombre_libreria` -- DROP TABLE IF EXISTS sr_nombre_libreria; CREATE TABLE `sr_nombre_libreria` ( `id_nombre` int(11) NOT NULL AUTO_INCREMENT, `nombre_libreria` varchar(50) NOT NULL DEFAULT '0', `estado_libreria` int(1) NOT NULL DEFAULT '0', KEY `Índice 1` (`id_nombre`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_nombre_libreria` -- LOCK TABLES sr_nombre_libreria WRITE; INSERT INTO sr_nombre_libreria VALUES('1', 'CSS', '1'); INSERT INTO sr_nombre_libreria VALUES('2', 'JQUERY', '1'); INSERT INTO sr_nombre_libreria VALUES('3', 'JSON', '1'); INSERT INTO sr_nombre_libreria VALUES('4', 'ANGULAR', '1'); INSERT INTO sr_nombre_libreria VALUES('5', 'HTML', '1'); INSERT INTO sr_nombre_libreria VALUES('6', 'JAVASCRIPT', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_roles` -- DROP TABLE IF EXISTS sr_roles; CREATE TABLE `sr_roles` ( `id_rol` int(11) NOT NULL AUTO_INCREMENT, `nombre_rol` varchar(50) DEFAULT NULL, `estado_rol` varchar(50) DEFAULT NULL, KEY `Índice 1` (`id_rol`) ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_roles` -- LOCK TABLES sr_roles WRITE; INSERT INTO sr_roles VALUES('1', 'SuperAdministrador', '1'); INSERT INTO sr_roles VALUES('15', 'Administrador', '1'); INSERT INTO sr_roles VALUES('19', 'Gerente Sucursal', '1'); INSERT INTO sr_roles VALUES('20', 'Mesero', '1'); INSERT INTO sr_roles VALUES('21', 'Cocinero', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_submenu` -- DROP TABLE IF EXISTS sr_submenu; CREATE TABLE `sr_submenu` ( `id_submenu` int(11) NOT NULL AUTO_INCREMENT, `nombre_submenu` varchar(50) DEFAULT NULL, `url_submenu` varchar(50) DEFAULT NULL, `titulo_submenu` varchar(50) DEFAULT NULL, `id_menu` int(50) DEFAULT NULL, `estado_submen` int(50) DEFAULT NULL, KEY `Índice 1` (`id_submenu`), KEY `FK_sr_submenu_sr_menu` (`id_menu`), CONSTRAINT `FK_sr_submenu_sr_menu` FOREIGN KEY (`id_menu`) REFERENCES `sr_menu` (`id_menu`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_submenu` -- LOCK TABLES sr_submenu WRITE; INSERT INTO sr_submenu VALUES('5', 'Animaciones', 'backend/animacion/Canimacion/index', 'Configuracion', '4', '1'); INSERT INTO sr_submenu VALUES('6', 'Informacion General', 'backend/info/Cinfo/index', 'Informacion General', '4', '1'); INSERT INTO sr_submenu VALUES('7', 'Menus', 'backend/menu/Cmenu/index', 'Menus', '4', '1'); INSERT INTO sr_submenu VALUES('8', 'Base de Datos', 'backend/backup/Cbackup/index', 'Demo', '5', '1'); INSERT INTO sr_submenu VALUES('9', 'Restaurar BK', 'backend/backup/Cbackup/restaurarBk', 'BK Files', '5', '1'); INSERT INTO sr_submenu VALUES('10', 'Avatar', 'backend/avatar/Cavatar/index', 'Avatar', '4', '0'); INSERT INTO sr_submenu VALUES('11', 'Usuarios', 'backend/usuarios/Cusuarios/index', 'Usuarios', '7', '1'); INSERT INTO sr_submenu VALUES('13', 'Menus Accesos', 'backend/acceso/Cacceso/index', 'Accesos Menus', '4', '1'); INSERT INTO sr_submenu VALUES('14', 'Password', 'backend/menu/Cmenu/cambiarPassword', 'Password', '6', '1'); INSERT INTO sr_submenu VALUES('15', 'Sucursales', 'backend/admin/Csucursales/index', 'Sucursales', '7', '1'); INSERT INTO sr_submenu VALUES('16', 'Paises', 'backend/admin/Cpais', 'Paises', '7', '1'); INSERT INTO sr_submenu VALUES('17', 'Departamentos', 'backend/admin/Cdepartamentos', 'Departamentos', '7', '1'); INSERT INTO sr_submenu VALUES('18', 'Impuestos', 'backend/admin/Cimpuesto', 'Impuestos', '7', '1'); INSERT INTO sr_submenu VALUES('19', 'Usuarios Admin', 'backend/acceso/Cacceso/index', 'Usuarios Admin', '4', '1'); INSERT INTO sr_submenu VALUES('20', 'Dashboard', 'backend/admin/Cdashboard/index', 'Dashboard', '1', '1'); INSERT INTO sr_submenu VALUES('21', 'Roles', 'backend/acceso/Cacceso/index', 'Roles', '7', '1'); INSERT INTO sr_submenu VALUES('22', 'Sucursal', 'backend/sucursales/Cindex', 'Sucursal', '8', '1'); INSERT INTO sr_submenu VALUES('23', 'Generador Cupon', 'backend/cupon/Cindex/index', 'Generador Cupon', '7', '1'); INSERT INTO sr_submenu VALUES('24', 'Productos', 'backend/productos/Cproductos/index', 'Productos', '7', '1'); INSERT INTO sr_submenu VALUES('25', 'Unidad de Medida', 'backend/productos/Cproductos/unidadMedida', 'Unidad de Medida', '7', '1'); UNLOCK TABLES; -- -- Table structure for table `sr_usuarios` -- DROP TABLE IF EXISTS sr_usuarios; CREATE TABLE `sr_usuarios` ( `id_usuario` int(100) NOT NULL AUTO_INCREMENT, `nombres` varchar(100) DEFAULT NULL, `apellidos` varchar(100) DEFAULT NULL, `telefono` varchar(100) DEFAULT NULL, `celular` varchar(100) DEFAULT NULL, `direccion` varchar(100) DEFAULT NULL, `dui` varchar(100) DEFAULT NULL, `usuario` varchar(100) DEFAULT NULL, `password` text, `nickname` varchar(100) DEFAULT NULL, `fecha` date DEFAULT NULL, `genero` char(100) DEFAULT NULL, `cargo` int(11) DEFAULT NULL, `rol` int(11) DEFAULT NULL, `id_departamento` int(10) DEFAULT NULL, `avatar` varchar(100) DEFAULT NULL, `fecha_creacion` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `estado` int(11) DEFAULT NULL, PRIMARY KEY (`id_usuario`), KEY `FK_sr_usuarios_sr_roles` (`rol`), KEY `FK_sr_usuarios_sr_cargos` (`cargo`), KEY `FK_sr_usuarios_sys_pais_departamento` (`id_departamento`), CONSTRAINT `FK_sr_usuarios_sr_cargos` FOREIGN KEY (`cargo`) REFERENCES `sr_cargos` (`id_cargo`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_sr_usuarios_sr_roles` FOREIGN KEY (`rol`) REFERENCES `sr_roles` (`id_rol`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_sr_usuarios_sys_pais_departamento` FOREIGN KEY (`id_departamento`) REFERENCES `sys_pais_departamento` (`id_departamento`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sr_usuarios` -- LOCK TABLES sr_usuarios WRITE; INSERT INTO sr_usuarios VALUES('3', 'Rafael', 'Tejada', '343', '53434', 'Chalate', '34343', 'rafael', '7c4a8d09ca3762af61e59520943dc26494f8941b', 'Rafael.Tejada', '1989-10-24', 'M', '1', '1', '14', 'avatar1_big@2x.png', '0000-00-00 00:00:00', '1'); INSERT INTO sr_usuarios VALUES('4', 'Jose', 'Lopez', '22504746', '23456789', 'san salvador', '232323232', 'jose', '4a3487e57d90e2084654b6d23937e75af5c8ee55', 'Jose.Lopez', '2012-12-12', 'M', '11', '20', '15', 'avatar2_big@2x.png', '0000-00-00 00:00:00', '1'); INSERT INTO sr_usuarios VALUES('5', 'a', 'b', 'c', 'd', 'e', 'r', 'sds', '845f160ac35907dec84bb7fb0d335d0ce8a11fef', 'a.b', '2012-12-12', 'M', '11', '20', '14', 'avatar1_big@2x.png', '0000-00-00 00:00:00', '1'); INSERT INTO sr_usuarios VALUES('6', 'sd', 'sds', 'sd', 'sd', 'sds', 'sds', 'sds', 'd6e1285e1c84d3d5885c2124fdacc780e9fc0a94', 'sd.sds', '1212-12-12', 'M', '2', '15', '15', 'avatar2_big@2x.png', '0000-00-00 00:00:00', '1'); INSERT INTO sr_usuarios VALUES('7', 'ss', 'ss', 'ss', 'ss', 'ss', 'ss', 'ssd', '3fdb13677b10691debb3909dd917b00ee751115a', 'ss.ss', '1212-12-12', 'M', '2', '15', '14', 'avatar6_big@2x.png', '0000-00-00 00:00:00', '1'); INSERT INTO sr_usuarios VALUES('8', 'Claudia', 'Quijada', '2323232', '73434343', 'Chalatenango', '34343434', 'claudia', '568095ee7b98b0afceb32540a1ca5540eaa72666', 'Claudia.Quijada', '1993-08-20', 'F', '10', '19', '14', 'avatar3_big@2x.png', '0000-00-00 00:00:00', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_catalogo_materiales` -- DROP TABLE IF EXISTS sys_catalogo_materiales; CREATE TABLE `sys_catalogo_materiales` ( `id_inventario` int(11) NOT NULL AUTO_INCREMENT, `nombre_matarial` varchar(50) NOT NULL, `descripcion_meterial` varchar(200) NOT NULL, `codigo_material` varchar(50) NOT NULL, `estatus` tinyint(1) NOT NULL, `proveedorCheck` tinyint(1) NOT NULL, `fecha_creacion` date DEFAULT NULL, PRIMARY KEY (`id_inventario`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_catalogo_materiales` -- LOCK TABLES sys_catalogo_materiales WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_categoria_producto` -- DROP TABLE IF EXISTS sys_categoria_producto; CREATE TABLE `sys_categoria_producto` ( `id_categoria_producto` int(11) NOT NULL AUTO_INCREMENT, `nombre_categoria_producto` varchar(150) CHARACTER SET utf8 DEFAULT NULL, `descripcion` varchar(150) CHARACTER SET utf8 DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id_categoria_producto`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_categoria_producto` -- LOCK TABLES sys_categoria_producto WRITE; INSERT INTO sys_categoria_producto VALUES('1', 'pizza', 'pizza', '2016-12-10 00:00:00'); UNLOCK TABLES; -- -- Table structure for table `sys_cupon` -- DROP TABLE IF EXISTS sys_cupon; CREATE TABLE `sys_cupon` ( `id_cupon` int(11) NOT NULL AUTO_INCREMENT, `codigo_cupon` varchar(50) DEFAULT NULL, `valor_cupon` double DEFAULT NULL, `estado_cupon` int(11) DEFAULT NULL, `descripcion_cupon` varchar(50) DEFAULT NULL, `fecha_creacion_cupon` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id_cupon`), KEY `id_cupon` (`id_cupon`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_cupon` -- LOCK TABLES sys_cupon WRITE; INSERT INTO sys_cupon VALUES('1', '3wfekz', '10', '0', NULL, '2016-12-06 20:06:41'); INSERT INTO sys_cupon VALUES('2', '8e4wlb', '10', '0', NULL, '2016-12-06 20:06:43'); INSERT INTO sys_cupon VALUES('3', 'xghl3i', '10', '0', NULL, '2016-12-06 20:06:43'); INSERT INTO sys_cupon VALUES('4', '53acwg', '10', '0', NULL, '2016-12-06 20:06:43'); INSERT INTO sys_cupon VALUES('5', '6bq3qy', '10', '0', NULL, '2016-12-06 20:06:43'); INSERT INTO sys_cupon VALUES('6', 'vhkw4yjvxt', '8', '0', 'Navidad', '2016-12-06 20:17:35'); INSERT INTO sys_cupon VALUES('7', 'elspxl8m15', '8', '0', 'Navidad', '2016-12-06 20:17:35'); UNLOCK TABLES; -- -- Table structure for table `sys_detalle_producto` -- DROP TABLE IF EXISTS sys_detalle_producto; CREATE TABLE `sys_detalle_producto` ( `id_detalle_producto` int(11) NOT NULL AUTO_INCREMENT, `name_detalle` varchar(150) CHARACTER SET utf8 DEFAULT NULL, `id_producto` int(11) DEFAULT NULL, `descripcion` varchar(150) CHARACTER SET utf8 DEFAULT NULL, `cantidad` varchar(50) COLLATE utf8_spanish_ci DEFAULT NULL, `unidad_medida_id` int(11) DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id_detalle_producto`), KEY `FK1_Detalle_producto_Producto` (`id_producto`), KEY `FK2_Detalle_producto_Unidad_medida` (`unidad_medida_id`), CONSTRAINT `FK1_Detalle_producto_Producto` FOREIGN KEY (`id_producto`) REFERENCES `sys_productos` (`id_producto`), CONSTRAINT `FK2_Detalle_producto_Unidad_medida` FOREIGN KEY (`unidad_medida_id`) REFERENCES `sys_unidad_medida` (`id_unidad_medida`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_detalle_producto` -- LOCK TABLES sys_detalle_producto WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_nodo` -- DROP TABLE IF EXISTS sys_nodo; CREATE TABLE `sys_nodo` ( `id_nodo` int(100) NOT NULL AUTO_INCREMENT, `nombre_nodo` varchar(50) DEFAULT NULL, `categoria_nodo` varchar(50) DEFAULT NULL, `url_nodo` varchar(250) DEFAULT NULL, `estado_nodo` int(1) DEFAULT NULL, PRIMARY KEY (`id_nodo`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_nodo` -- LOCK TABLES sys_nodo WRITE; INSERT INTO sys_nodo VALUES('7', 'Bebidas', 'Bebidas', 'Bebidas', '1'); INSERT INTO sys_nodo VALUES('8', 'horno', 'horno', 'demo', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_pais` -- DROP TABLE IF EXISTS sys_pais; CREATE TABLE `sys_pais` ( `id_pais` int(11) NOT NULL AUTO_INCREMENT, `nombre_pais` varchar(50) DEFAULT NULL, `id_usuario` int(11) DEFAULT NULL, `registro_legal` varchar(50) DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, `fecha_actualizacion` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `estado` int(1) DEFAULT NULL, PRIMARY KEY (`id_pais`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_pais` -- LOCK TABLES sys_pais WRITE; INSERT INTO sys_pais VALUES('7', 'El Salvador', '3', '10000111', '2016-11-13 22:11:07', '2016-11-13 15:10:38', '1'); INSERT INTO sys_pais VALUES('8', 'Guatemala', '3', '12345', '2016-11-13 22:11:39', '2016-11-13 15:15:34', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_pais_departamento` -- DROP TABLE IF EXISTS sys_pais_departamento; CREATE TABLE `sys_pais_departamento` ( `id_departamento` int(11) NOT NULL AUTO_INCREMENT, `id_pais` int(11) DEFAULT NULL, `nombre_departamento` varchar(50) DEFAULT NULL, `usuario` int(2) DEFAULT NULL, `estado_departamento` int(1) DEFAULT NULL, `fecha_creacion` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id_departamento`), KEY `FK_sys_pais_departamento_sys_pais` (`id_pais`), CONSTRAINT `FK_sys_pais_departamento_sys_pais` FOREIGN KEY (`id_pais`) REFERENCES `sys_pais` (`id_pais`) ON DELETE SET NULL ON UPDATE SET NULL ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_pais_departamento` -- LOCK TABLES sys_pais_departamento WRITE; INSERT INTO sys_pais_departamento VALUES('14', '7', 'San Salvador', '3', '1', '2016-11-13 15:05:53'); INSERT INTO sys_pais_departamento VALUES('15', '7', 'San Miguel', '3', '1', '2016-11-13 15:59:47'); UNLOCK TABLES; -- -- Table structure for table `sys_pais_impuesto` -- DROP TABLE IF EXISTS sys_pais_impuesto; CREATE TABLE `sys_pais_impuesto` ( `id_impuesto` int(11) NOT NULL AUTO_INCREMENT, `id_pais` int(11) DEFAULT NULL, `nombre_impuesto` varchar(50) DEFAULT NULL, `monto_impuesto` float DEFAULT NULL, `descripcion_impuesto` varchar(255) DEFAULT NULL, `creado` date DEFAULT NULL, `id_usuario` int(11) DEFAULT NULL, `estado_impuesto` int(11) DEFAULT NULL, PRIMARY KEY (`id_impuesto`), KEY `FK_sys_pais_cobros_sys_sucursal` (`id_pais`), KEY `FK_sys_pais_cobros_sr_usuarios` (`id_usuario`), CONSTRAINT `FK_sys_pais_cobros_sr_usuarios` FOREIGN KEY (`id_usuario`) REFERENCES `sr_usuarios` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `FK_sys_pais_cobros_sys_pais` FOREIGN KEY (`id_pais`) REFERENCES `sys_pais` (`id_pais`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_pais_impuesto` -- LOCK TABLES sys_pais_impuesto WRITE; INSERT INTO sys_pais_impuesto VALUES('2', '7', 'Iva', '0.13', 'Impuesto Sobre la Renta', '2016-11-14', '3', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_productos` -- DROP TABLE IF EXISTS sys_productos; CREATE TABLE `sys_productos` ( `id_producto` int(11) NOT NULL AUTO_INCREMENT, `nombre_producto` varchar(150) COLLATE utf8_spanish_ci DEFAULT NULL, `categoria_id` int(11) DEFAULT NULL, `description_producto` varchar(150) COLLATE utf8_spanish_ci DEFAULT NULL, `video` varchar(150) COLLATE utf8_spanish_ci DEFAULT NULL, `image` varchar(150) COLLATE utf8_spanish_ci DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id_producto`), KEY `FK1_Producto_Categoria_Producto` (`categoria_id`), CONSTRAINT `FK1_Producto_Categoria_Producto` FOREIGN KEY (`categoria_id`) REFERENCES `sys_categoria_producto` (`id_categoria_producto`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_productos` -- LOCK TABLES sys_productos WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_productos_sucursal` -- DROP TABLE IF EXISTS sys_productos_sucursal; CREATE TABLE `sys_productos_sucursal` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_sucursal` int(11) DEFAULT NULL, `id_producto` int(11) DEFAULT NULL, `precio` varchar(50) COLLATE utf8_spanish_ci DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK1_ProductoSucursal_Sucursal` (`id_sucursal`), KEY `FK2_ProductoSucursal_Producto` (`id_producto`), CONSTRAINT `FK1_ProductoSucursal_Sucursal` FOREIGN KEY (`id_sucursal`) REFERENCES `sys_sucursal` (`id_sucursal`), CONSTRAINT `FK2_ProductoSucursal_Producto` FOREIGN KEY (`id_producto`) REFERENCES `sys_productos` (`id_producto`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_productos_sucursal` -- LOCK TABLES sys_productos_sucursal WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_proveedores` -- DROP TABLE IF EXISTS sys_proveedores; CREATE TABLE `sys_proveedores` ( `id_proveedor` int(11) NOT NULL AUTO_INCREMENT, `nombre_proveedor` varchar(50) DEFAULT NULL, `descripcion_proveedor` varchar(200) DEFAULT NULL, `correo_proveedor` varchar(100) DEFAULT NULL, `direccion_proveedor` varchar(250) DEFAULT NULL, `telefono_proveedor` varchar(100) DEFAULT NULL, `contacto_referencia_proveedor` varchar(100) DEFAULT NULL, `fecha_creacion_proveedor` datetime NOT NULL, PRIMARY KEY (`id_proveedor`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_proveedores` -- LOCK TABLES sys_proveedores WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_sucursal` -- DROP TABLE IF EXISTS sys_sucursal; CREATE TABLE `sys_sucursal` ( `id_sucursal` int(11) NOT NULL AUTO_INCREMENT, `id_departamento` int(10) DEFAULT NULL, `nombre_sucursal` varchar(50) DEFAULT NULL, `direccion` varchar(50) DEFAULT NULL, `telefono` varchar(50) DEFAULT NULL, `celular` varchar(50) DEFAULT NULL, `referencia_zona` varchar(50) DEFAULT NULL, `fecha_creacion` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `estado` int(11) NOT NULL, `creado_usuario` int(11) NOT NULL, PRIMARY KEY (`id_sucursal`), KEY `FK_sys_sucursal_sys_pais_departamento` (`id_departamento`), CONSTRAINT `FK_sys_sucursal_sys_pais_departamento` FOREIGN KEY (`id_departamento`) REFERENCES `sys_pais_departamento` (`id_departamento`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_sucursal` -- LOCK TABLES sys_sucursal WRITE; INSERT INTO sys_sucursal VALUES('6', '14', 'Castanios', 'MultiPlaza', '22345678', '43567823', 'Centro Comercial', '2016-11-13 15:06:57', '1', '3'); INSERT INTO sys_sucursal VALUES('7', '15', 'El Volcan', 'el volcan', '23232', '232323', 'el volcan', '2016-11-13 16:15:35', '1', '3'); INSERT INTO sys_sucursal VALUES('8', '14', 'Escalon Norte', 'Escalon Norte', '22456789', '23456789', 'Luceiro', '2016-11-23 21:07:04', '1', '3'); UNLOCK TABLES; -- -- Table structure for table `sys_sucursal_impuesto` -- DROP TABLE IF EXISTS sys_sucursal_impuesto; CREATE TABLE `sys_sucursal_impuesto` ( `id_impuesto` int(11) NOT NULL AUTO_INCREMENT, `id_sucursal` int(11) DEFAULT NULL, `nombre_impuesto` varchar(50) DEFAULT NULL, `monto_impuesto` float DEFAULT NULL, `descripcion_impuesto` varchar(255) DEFAULT NULL, `creado` date DEFAULT NULL, `id_usuario` int(11) DEFAULT NULL, `estado_impuesto` int(11) DEFAULT NULL, PRIMARY KEY (`id_impuesto`), KEY `FK_sys_sucursal_cobros_sys_sucursal` (`id_sucursal`), KEY `FK_sys_sucursal_cobros_sr_usuarios` (`id_usuario`), CONSTRAINT `FK_sys_sucursal_cobros_sr_usuarios` FOREIGN KEY (`id_usuario`) REFERENCES `sr_usuarios` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `FK_sys_sucursal_cobros_sys_sucursal` FOREIGN KEY (`id_sucursal`) REFERENCES `sys_sucursal` (`id_sucursal`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_sucursal_impuesto` -- LOCK TABLES sys_sucursal_impuesto WRITE; INSERT INTO sys_sucursal_impuesto VALUES('4', '6', 'Iva', '0.13', 'Impuesto Sobre la Renta', '2016-11-14', '3', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_sucursal_int_usuarios` -- DROP TABLE IF EXISTS sys_sucursal_int_usuarios; CREATE TABLE `sys_sucursal_int_usuarios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_sucursal` int(11) DEFAULT '0', `id_usuario` int(11) DEFAULT '0', `estado` int(11) DEFAULT '0', `creado_por` int(11) DEFAULT '0', PRIMARY KEY (`id`), KEY `FK_sys_sucursal_int_usuarios_sys_sucursal` (`id_sucursal`), KEY `FK_sys_sucursal_int_usuarios_sr_usuarios` (`id_usuario`), CONSTRAINT `FK_sys_sucursal_int_usuarios_sr_usuarios` FOREIGN KEY (`id_usuario`) REFERENCES `sr_usuarios` (`id_usuario`), CONSTRAINT `FK_sys_sucursal_int_usuarios_sys_sucursal` FOREIGN KEY (`id_sucursal`) REFERENCES `sys_sucursal` (`id_sucursal`) ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_sucursal_int_usuarios` -- LOCK TABLES sys_sucursal_int_usuarios WRITE; INSERT INTO sys_sucursal_int_usuarios VALUES('15', '6', '4', '1', '3'); INSERT INTO sys_sucursal_int_usuarios VALUES('16', '7', '4', '1', '3'); INSERT INTO sys_sucursal_int_usuarios VALUES('17', '6', '8', '1', '3'); INSERT INTO sys_sucursal_int_usuarios VALUES('18', '7', '8', '1', '3'); INSERT INTO sys_sucursal_int_usuarios VALUES('19', '8', '8', '1', '3'); UNLOCK TABLES; -- -- Table structure for table `sys_sucursal_nodo` -- DROP TABLE IF EXISTS sys_sucursal_nodo; CREATE TABLE `sys_sucursal_nodo` ( `id_nodo_sucursal` int(100) NOT NULL AUTO_INCREMENT, `id_sucursal` int(100) NOT NULL DEFAULT '0', `id_nodo` int(100) NOT NULL DEFAULT '0', `sucursal_estado_nodo` int(100) NOT NULL DEFAULT '0', PRIMARY KEY (`id_nodo_sucursal`), KEY `id_nodo` (`id_nodo_sucursal`), KEY `FK_sys_sucursal_nodo_sys_nodo` (`id_nodo`), KEY `FK_sys_sucursal_nodo_sys_sucursal` (`id_sucursal`), CONSTRAINT `FK_sys_sucursal_nodo_sys_nodo` FOREIGN KEY (`id_nodo`) REFERENCES `sys_nodo` (`id_nodo`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_sys_sucursal_nodo_sys_sucursal` FOREIGN KEY (`id_sucursal`) REFERENCES `sys_sucursal` (`id_sucursal`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_sucursal_nodo` -- LOCK TABLES sys_sucursal_nodo WRITE; INSERT INTO sys_sucursal_nodo VALUES('7', '6', '7', '0'); INSERT INTO sys_sucursal_nodo VALUES('8', '7', '7', '1'); INSERT INTO sys_sucursal_nodo VALUES('9', '8', '7', '0'); INSERT INTO sys_sucursal_nodo VALUES('10', '6', '8', '0'); INSERT INTO sys_sucursal_nodo VALUES('11', '7', '8', '1'); INSERT INTO sys_sucursal_nodo VALUES('12', '8', '8', '1'); UNLOCK TABLES; -- -- Table structure for table `sys_sucursal_promocion` -- DROP TABLE IF EXISTS sys_sucursal_promocion; CREATE TABLE `sys_sucursal_promocion` ( `id_promocion` int(11) NOT NULL AUTO_INCREMENT, `id_sucursal` int(11) NOT NULL DEFAULT '0', `nombre_promocion` varchar(255) NOT NULL DEFAULT '0', PRIMARY KEY (`id_promocion`), KEY `FK_sys_sucursal_promocion_sys_sucursal` (`id_sucursal`), CONSTRAINT `FK_sys_sucursal_promocion_sys_sucursal` FOREIGN KEY (`id_sucursal`) REFERENCES `sys_sucursal` (`id_sucursal`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `sys_sucursal_promocion` -- LOCK TABLES sys_sucursal_promocion WRITE; UNLOCK TABLES; -- -- Table structure for table `sys_tipo_unidad_medida` -- DROP TABLE IF EXISTS sys_tipo_unidad_medida; CREATE TABLE `sys_tipo_unidad_medida` ( `id_tipo_unidad_medida` int(11) NOT NULL AUTO_INCREMENT, `name_tipo_unidad_medida` varchar(150) CHARACTER SET utf8 DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id_tipo_unidad_medida`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_tipo_unidad_medida` -- LOCK TABLES sys_tipo_unidad_medida WRITE; INSERT INTO sys_tipo_unidad_medida VALUES('1', 'Masa', '2016-11-29 00:00:00'); INSERT INTO sys_tipo_unidad_medida VALUES('2', 'Volumen', '2016-11-29 00:00:00'); INSERT INTO sys_tipo_unidad_medida VALUES('3', 'Cantidad de Sustancias', '2016-11-29 00:00:00'); UNLOCK TABLES; -- -- Table structure for table `sys_unidad_medida` -- DROP TABLE IF EXISTS sys_unidad_medida; CREATE TABLE `sys_unidad_medida` ( `id_unidad_medida` int(11) NOT NULL AUTO_INCREMENT, `nombre_unidad_medida` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `Símbolo_unidad_medida` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `id_tipo_unidad_medida` int(11) DEFAULT NULL, `valor_unidad_medida` int(11) DEFAULT NULL, `fecha_creacion` datetime DEFAULT NULL, PRIMARY KEY (`id_unidad_medida`), KEY `FK1_Unidada_medida_Tipo_unidad_medida` (`id_tipo_unidad_medida`), CONSTRAINT `FK1_Unidada_medida_Tipo_unidad_medida` FOREIGN KEY (`id_tipo_unidad_medida`) REFERENCES `sys_tipo_unidad_medida` (`id_tipo_unidad_medida`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Dumping data for table `sys_unidad_medida` -- LOCK TABLES sys_unidad_medida WRITE; INSERT INTO sys_unidad_medida VALUES('1', 'masa', 'm', '1', '2', '2016-12-10 00:00:00'); UNLOCK TABLES; SET FOREIGN_KEY_CHECKS=1; -- Dump de la Base de Datos Completo.<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Cindex extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->database('default'); $this->load->model('backend/sucursales/cliente_model'); $this->load->model('backend/sucursales/sucursales_model'); } public function index() { $this->load->view('backend/sucursales/Vindex.php'); } public function reporte_nuevos(){ $data = $this->sucursales_model->clientesNuevos(); $html=""; $html="<table> <tr> <th>Nombre Completo</th> <th>DUI</th> <th>Direccion</th> <th>Telefono</th> <th>Email</th> <th>Creado</th> <th>Actualizado</th> </tr>"; foreach ($data as $value) { $html .= "<tr>"; $html .= "<td>"; $html .= $value->nombre_completo; $html .= "</td>"; $html .= "<td>"; $html .= $value->dui; $html .= "</td>"; $html .= "<td>"; $html .= $value->direccion; $html .= "</td>"; $html .= "<td>"; $html .= $value->telefono; $html .= "</td>"; $html .= "<td>"; $html .= $value->email; $html .= "</td>"; $html .= "<td>"; $html .= $value->fecha_creado; $html .= "</td>"; $html .= "<td>"; $html .= $value->ultima_actualizacion; $html .= "</td>"; $html .= "<tr>"; } $html .="</table>"; echo $html; } public function reporte_modificados(){ $data = $this->sucursales_model->clientesModificados(); $html=""; $html="<table> <tr> <th>Nombre Completo</th> <th>DUI</th> <th>Direccion</th> <th>Telefono</th> <th>Email</th> <th>Creado</th> <th>Actualizado</th> </tr>"; foreach ($data as $value) { $html .= "<tr>"; $html .= "<td>"; $html .= $value->nombre_completo; $html .= "</td>"; $html .= "<td>"; $html .= $value->dui; $html .= "</td>"; $html .= "<td>"; $html .= $value->direccion; $html .= "</td>"; $html .= "<td>"; $html .= $value->telefono; $html .= "</td>"; $html .= "<td>"; $html .= $value->email; $html .= "</td>"; $html .= "<td>"; $html .= $value->fecha_creado; $html .= "</td>"; $html .= "<td>"; $html .= $value->ultima_actualizacion; $html .= "</td>"; $html .= "<tr>"; } $html .="</table>"; echo $html; } public function reporte_todos(){ $data = $this->sucursales_model->clientesTodos(); $html=""; $html="<table> <tr> <th>Nombre Completo</th> <th>DUI</th> <th>Direccion</th> <th>Telefono</th> <th>Email</th> <th>Creado</th> <th>Actualizado</th> </tr>"; foreach ($data as $value) { $html .= "<tr>"; $html .= "<td>"; $html .= $value->nombre_completo; $html .= "</td>"; $html .= "<td>"; $html .= $value->dui; $html .= "</td>"; $html .= "<td>"; $html .= $value->direccion; $html .= "</td>"; $html .= "<td>"; $html .= $value->telefono; $html .= "</td>"; $html .= "<td>"; $html .= $value->email; $html .= "</td>"; $html .= "<td>"; $html .= $value->fecha_creado; $html .= "</td>"; $html .= "<td>"; $html .= $value->ultima_actualizacion; $html .= "</td>"; $html .= "<tr>"; } $html .="</table>"; echo $html; } public function formulario($dui) { $cliente = $this->cliente_model->buscarCliente($dui); $data =1; if($cliente!="") { echo json_encode($cliente); } else { echo json_encode($data); } //$this->load->view('portal/formulario/Vformulario.php'); } public function crearCliente(){ $this->cliente_model->crearCliente($_POST); } public function actualizarCliente(){ $this->cliente_model->actualizarCliente($_POST); } } <file_sep><html> <head> <script type="text/javascript"> function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); var options = { title: 'Sucursales' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } function drawChart2() { var data1 = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, 350] ]); var optionss = { chart: { title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017', } }; var chart = new google.charts.Bar(document.getElementById('columnchart_material')); chart.draw(data1, optionss); } function drawStuff() { var data = new google.visualization.arrayToDataTable([ ['Move', 'Percentage'], ["King's pawn (e4)", 44], ["Queen's pawn (d4)", 31], ["Knight to King 3 (Nf3)", 12], ["Queen's bishop pawn (c4)", 10], ['Other', 3] ]); var options = { title: 'Chess opening moves', width: 900, legend: { position: 'none' }, chart: { subtitle: 'popularity by percentage' }, axes: { x: { 0: { side: 'top', label: 'White to move'} // Top x-axis. } }, bar: { groupWidth: "90%" } }; var chart = new google.charts.Bar(document.getElementById('top_x_div')); // Convert the Classic options to Material options. chart.draw(data, google.charts.Bar.convertOptions(options)); } google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart2); google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawStuff); </script> <style> .order{ position: relative; display: inline-block; } </style> </head> <body> <div class="list-group"> <a href="#" class="list-group-item active"> Cras justo odio </a> <a href="#" class="list-group-item">Dapibus ac facilisis in</a> <a href="#" class="list-group-item">Morbi leo risus</a> <a href="#" class="list-group-item">Porta ac consectetur ac</a> <a href="#" class="list-group-item">Vestibulum at eros</a> </div> <div class="order" id="piechart" style="width: 800px; height: 500px;"></div> <div class="order" id="columnchart_material" style="width: 600px; height: 500px;"></div> <div class="order" id="top_x_div" style="width: 600px; height: 500px;"></div> </body> </html> <file_sep><!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <link rel="stylesheet" type="text/css" media="screen" href="css/master.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script> $(document).ready(function(){ // CONVERTIR FECHAS A TEXTO $(".wrapper").click(function(){ if($(this).css("background") == "none") { $(this).css("background","green"); } else{ $(this).css("background","none"); } }); $(".wrapper").dblclick(function(){ $(this).remove(); }); var tiempo = { hora: 0, minuto: 0, segundo: 0 }; var tiempo_corriendo = null; tiempo_corriendo = setInterval(function(){ // Segundos tiempo.segundo++; if(tiempo.segundo >= 60) { tiempo.segundo = 0; tiempo.minuto++; } // Minutos if(tiempo.minuto >= 60) { tiempo.minuto = 0; tiempo.hora++; } $("#hira").text(tiempo.hora < 10 ? '0' + tiempo.hora : tiempo.hora); $("#minuto").text(tiempo.minuto < 10 ? '0' + tiempo.minuto : tiempo.minuto); $("#segundo").text(tiempo.segundo < 10 ? '0' + tiempo.segundo : tiempo.segundo); }, 1000); }); </script> </head> <style> body{ background: black; color: white; } .wrapper { width:350px; height:100%; display:inline-block; position: relative; margin: 10px; background: none; } .title{ background: grey; color: white; text-align: center; top: 0px; } .time{ text-align:right; padding: 10px; } </style> <body> <div class="tab-content"> <div class="row"> <div class="col-md-12 title"> <?php foreach ($sucursales as $sucursal) { ?> <h2>Sucursal : <?php echo $sucursal->nombre_sucursal.' / '. $sucursal->nombre_nodo; ?></h2> <?php } ?> </div> </div> </div> <div class="wrapper"> <div class="list-group"> <a href="#" class="list-group-item active"> <i class='fa fa-home'></i>ORDEN - # 220 </a> <a href="" name="" class="list-group-item nodo" > <table class="table table-hover"> <tr> <td>#</td> <td>Item</td> <td>Cantidad</td> <td>Indicacion</td> </tr> <tr> <td>1</td> <td>Licuado de leche</td> <td>2</td> <td>Poca Azucar</td> </tr> <tr> <td>2</td> <td>Licuado de leche</td> <td>2</td> <td>Poca Azucar</td> </tr> </table> </a> <div class="time"> <i id="hora"></i> : <i id="minuto"></i> : <i id="segundo"></i> </div> </div> </div> </body> </html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class sucursales_model extends CI_Model { const cargos = 'sr_cargos'; const roles = 'sr_roles'; const avatar = 'sr_avatar'; const usuarios = 'sr_usuarios'; const sys_sucursal = 'sys_sucursal'; const sys_pais_departamento = 'sys_pais_departamento'; const sys_pais = 'sys_pais'; const sys_sucursal_int_usuarios = 'sys_sucursal_int_usuarios'; const sys_nodo = 'sys_nodo'; const sys_sucursal_nodo = 'sys_sucursal_nodo'; public function __construct() { parent::__construct(); } public function clientesNuevos() { $query = $this->db->query('select * from sys_cliente WHERE HOUR(TIMEDIFF(NOW(), fecha_creado)) <=24'); return $query->result(); } public function clientesModificados() { $query = $this->db->query('select * from sys_cliente WHERE ultima_actualizacion != "0000-00-00 00:00:00"'); return $query->result(); } public function clientesTodos() { $query = $this->db->query('select * from sys_cliente'); return $query->result(); } public function getSucursalesByUser($id_user) { $this->db->select('*'); $this->db->from(self::sys_sucursal); $this->db->join(self::sys_sucursal_int_usuarios,' on '. self::sys_sucursal_int_usuarios.'.id_sucursal = '. self::sys_sucursal.'.id_sucursal'); $this->db->join(self::usuarios,' on '. self::usuarios.'.id_usuario = '. self::sys_sucursal_int_usuarios.'.id_usuario'); $this->db->where(self::usuarios.'.id_usuario',$id_user); $query = $this->db->get(); //echo $this->db->queries[0]; if($query->num_rows() > 0 ) { return $query->result(); } } public function getSucursalesById($id_sucursal) { $this->db->select('*'); $this->db->from(self::sys_sucursal); $this->db->join(self::sys_sucursal_nodo,' on '. self::sys_sucursal_nodo.'.id_sucursal = '. self::sys_sucursal.'.id_sucursal'); $this->db->join(self::sys_nodo,' on '. self::sys_nodo.'.id_nodo = '. self::sys_sucursal_nodo.'.id_nodo'); $this->db->where(self::sys_sucursal.'.id_sucursal',$id_sucursal); $query = $this->db->get(); //echo $this->db->queries[0]; if($query->num_rows() > 0 ) { return $query->result(); } } public function getSucursalesByNodo($id_sucursal) { $this->db->select('*'); $this->db->from(self::sys_sucursal); $this->db->join(self::sys_sucursal_nodo,' on '. self::sys_sucursal_nodo.'.id_sucursal = '. self::sys_sucursal.'.id_sucursal'); $this->db->join(self::sys_nodo,' on '. self::sys_nodo.'.id_nodo = '. self::sys_sucursal_nodo.'.id_nodo'); $this->db->where(self::sys_sucursal.'.id_sucursal',$id_sucursal); $this->db->where(self::sys_sucursal_nodo.'.sucursal_estado_nodo',1); $query = $this->db->get(); //echo $this->db->queries[0]; if($query->num_rows() > 0 ) { return $query->result(); } } public function getSucursalByNodoId($id_nodo,$id_sucursal) { $this->db->select('*'); $this->db->from(self::sys_sucursal); $this->db->join(self::sys_sucursal_nodo,' on '. self::sys_sucursal_nodo.'.id_sucursal = '. self::sys_sucursal.'.id_sucursal'); $this->db->join(self::sys_nodo,' on '. self::sys_nodo.'.id_nodo = '. self::sys_sucursal_nodo.'.id_nodo'); $this->db->where(self::sys_sucursal.'.id_sucursal',$id_sucursal); //$this->db->where(self::sys_sucursal_nodo.'.sucursal_estado_nodo',1); $this->db->where(self::sys_sucursal_nodo.'.id_nodo',$id_nodo); $query = $this->db->get(); //echo $this->db->queries[0]; if($query->num_rows() > 0 ) { return $query->result(); } } } /* * end of application/models/consultas_model.php */ <file_sep> <!DOCTYPE html> <html> <head> <title>formulario</title> <script src="../../../../assets/plugins/jquery/jquery-1.11.1.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script> $(document).ready(function(){ $("#crear").show(); $("#actualizar").hide(); $("#loading").hide(); $("#buscar").click(function(){ $("#crear").hide(); $("#loading").show(); $(".msj").empty(); var value = $("#dui").val(); //$(".msj").html(value); //Buscar cliente $.ajax({ url: "../../../backend/sucursales/Cindex/formulario/"+value, type:"post", dataType:'json', cache: false, success: function(data){ if(data!=null){ var obj = JSON.stringify(data); //console.log(JSON.stringify(data)); if(data==1) { $("#crear").show(); $(".msj").text("Cliente no Existe.. Desea Crear Un Cliente."); $("#nombre").val(""); $("#direccion").val(""); $("#telefono").val(""); $("#email").val(""); $("#id_cliente").val(""); $("#actualizar").hide(); } else { console.log(data[0].nombre_completo); $("#nombre").val(data[0].nombre_completo); $("#direccion").val(data[0].direccion); $("#telefono").val(data[0].telefono); $("#email").val(data[0].email); $("#id_cliente").val(data[0].id_cliente); $("#actualizar").show(); $("#crear").hide(); $(".msj").text("Encontrado Con Exito."); } } $("#loading").hide(); //$(".pages").load("../sucursales/Cindex/formulario/"+id_sucursal); }, error:function(){ //alert("Error.. No se subio la imagen"); } }); }); $("#crear").click(function(){ $("#loading").show(); var dui = $("#dui").val(); var nombre = $("#nombre").val(); var direccion = $("#direccion").val(); var telefono = $("#telefono").val(); var email = $("#email").val(); if((dui !="") &&(nombre !="") && (direccion !="") && (telefono!="") && (email=!"") ){ $.ajax({ url: "../../../backend/sucursales/Cindex/crearCliente", type:"post", data:$('#cliente').serialize(), success: function(){ $("#loading").hide(); $(".msj").text("Cliente Creado Con Exito :)"); }, error:function(){ //alert("Error.. No se subio la imagen"); } }); } else { $("#loading").hide(); $(".msj").text("Campos Vacios :)"); } }); $("#actualizar").click(function(){ $("#loading").show(); $(".msj").empty(); $.ajax({ url: "../../../backend/sucursales/Cindex/actualizarCliente", type:"post", data:$('#cliente').serialize(), success: function(){ $("#loading").hide(); $(".msj").text("Cliente Actualizo Correctamente."); }, error:function(){ //alert("Error.. No se subio la imagen"); } }); }); $("#nombre, #direccion ,#telefono, #email").keyup(function(){ $(".msj").text("Debe Guardar Los Cambios."); }); }); </script> <style> a.sucursal:hover{ background: #88B32F; color: black; } .centro{ text-align: center; } #clientes{ text-align: center; } .datos{ margin: 0 auto; width: 500px; } .msj{ padding: 10px; } </style> </head> <body> <form id="cliente"> <div class="content"> <div class="row"> <div class="tab-content"> <div class="row centro"> <div class="col-md-12"> <div class="list-group"> <a href="#" class="list-group-item active"> <img src="../../../../img/top_logo.png"> </a> <div class="datos"> <table width="100%" border="0" id="clientes"> <tr> <td><i class='fa fa-user-plus'></i>DUI :</td> <td> <input type="text" id="dui" name="dui"> </td> <td> <a href="#" id="buscar" class="btn btn-default">Buscar</a> <input type="hidden" id="id_cliente" name="id_cliente" value=""> </td> </tr> <tr> <td><i class='fa fa-user-plus'></i>Nombre Completo :</td> <td><input type="text" id="nombre" name="nombre"></input></td> <td></td> </tr> <tr> <td><i class='fa fa-user-plus'></i>Dirección :</td> <td><input type="text" id="direccion" name="direccion"></input></td> <td></td> </tr> <tr> <td><i class='fa fa-user-plus'></i>Telefono :</td> <td><input type="text" id="telefono" name="telefono"></input></td> <td></td> </tr> <tr> <td><i class='fa fa-user-plus'></i>Email :</td> <td><input type="text" id="email" name="email"></input></td> <td></td> </tr> <tr> <td></td> <td> <a href="#" id="crear" class="btn btn-primary">Crear Cliente</a> <a href="#" id="actualizar" class="btn btn-primary">Actualizar Cliente</a> </td> <td></td> </tr> <tr> <td colspan="3"> <a id=""> <span id="loading"> <img src="../../../../img/loadding.gif" width="50px"> </span> <p class="msj alert alert-info">Formulario - Busqueda Cliente</p> </a> </td> </tr> </table> </div> </div> </div> </div> </div> </div> </div> </form> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Cusuarios extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->database('default'); $this->load->model('backend/usuarios/usuarios_model'); $this->load->model('backend/admin/pais_model'); } public function index() { $data['cargos'] = $this->usuarios_model->cargos(); $data['roles'] = $this->usuarios_model->roles(); $data['avatar'] = $this->usuarios_model->avatar(); $data['usuario'] = $this->usuarios_model->getAllUsers(); $data['sucursal'] = $this->usuarios_model->getAllSucursal(); $data['departamentos'] = $this->usuarios_model->getAllDepartamentos(); $data['pais'] = $this->pais_model->getPaises(); $this->load->view('backend/usuarios/Vusuarios.php',$data); } public function guardar_usuario(){ $this->usuarios_model->save_user($_POST); } public function eliminar_usuario($id){ echo $id; $this->usuarios_model->eliminar_usuario($id); } public function userAdmin(){ $data['cargos'] = $this->usuarios_model->cargos(); $data['roles'] = $this->usuarios_model->roles(); $data['avatar'] = $this->usuarios_model->avatar(); $data['usuario'] = $this->usuarios_model->getAllUsers(); $data['sucursal'] = $this->usuarios_model->getAllSucursal(); $this->load->view('backend/usuarios/VuserAdmin.php',$data); } } <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class cliente_model extends CI_Model { const cliente = 'sys_cliente'; public function __construct() { parent::__construct(); } public function buscarCliente($dui) { $this->db->select('*'); $this->db->from(self::cliente); $this->db->where(self::cliente.'.dui',$dui); $query = $this->db->get(); //echo $this->db->queries[0]; if($query->num_rows() > 0 ) { return $query->result(); } } public function crearCliente($cliente){ $date = date("Y-m-d"); $data = array( 'dui' => $cliente['dui'], 'nombre_completo' => $cliente['nombre'], 'direccion' => $cliente['direccion'], 'telefono' => $cliente['telefono'], 'email' => $cliente['email'], 'fecha_creado' => $date, 'ultima_actualizacion' => "0000-00-00 00:00:00" ); $this->db->insert(self::cliente,$data); } public function actualizarCliente($cliente){ $data = array( 'dui' => $cliente['dui'], 'nombre_completo' => $cliente['nombre'], 'direccion' => $cliente['direccion'], 'telefono' => $cliente['telefono'], 'email' => $cliente['email'], ); $this->db->where('id_cliente', $cliente['id_cliente']); $this->db->update(self::cliente, $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Cdashboard extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->database('default'); //$this->load->model('backend/admin/dashboard_model'); } public function index() { //$data['departamentos'] = $this->dashboard_model->getDepartamentos(); $this->load->view('backend/admin/Vdashboard.php'); } }
2d4c65413412f8f6227ba5035608d402dac39881
[ "SQL", "PHP" ]
10
PHP
dkrock24/unicomer
5fb6149723aa77e78aa9d460092e784e55f295e2
00a4f5886eb4e1aa34bda0848f67232c8ad291f3
refs/heads/master
<repo_name>wsy121250155/javaWeb-test<file_sep>/Ajax-Demo/src/web/AjaxServlet.java package web; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Point; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import data.Loader; public class AjaxServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 3986978137150125590L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Loader loader = new Loader(); List<Point> list = loader.getPoints(); LinkedList<JSONObject> jsonList = new LinkedList<JSONObject>(); for (Point p : list) { JSONObject jsobj = JSONObject.fromObject(p); jsonList.add(jsobj); } JSONArray json = JSONArray.fromObject(jsonList); PrintWriter out = resp.getWriter(); out.println(json.toString()); out.flush(); out.close(); } // public static void main(String[] args){ // AjaxServlet as = new AjaxServlet(); // try { // as.doPost(HttpServletRequest.class.newInstance(),HttpServletResponse.class.newInstance()); // } catch (InstantiationException | IllegalAccessException // | ServletException | IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } } <file_sep>/Ajax-Demo/src/data/Loader.java package data; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.List; import model.Point; public class Loader { public static void main(String[] args){ Loader loader = new Loader(); String path = "src/tables/000001.csv"; File file = new File(path); List<String> list = loader.readLines(file,true); for(String s : list){ System.out.println(s); } } private String path = "D:/file/workspace-ee/Ajax-Demo/WebContent/tables/000001.csv"; public List<Point> getPoints(){ LinkedList<Point> list = new LinkedList<Point>(); File file = new File(path); String str = file.getAbsolutePath(); List<String> lines = readLines(file,true); for(String s : lines){ String[] temp = s.split(","); double close = Double.valueOf(temp[0]); double volume = Double.valueOf(temp[1]); Point p = new Point(close,volume); list.add(p); } return list; } public List<String> getLines(){ // LinkedList<Point> list = new LinkedList<Point>(); File file = new File(path); // String str = file.getAbsolutePath(); List<String> lines = readLines(file,true); return lines; } private List<String> readLines(File file,boolean hasHeader){ FileReader fr = null; BufferedReader br = null; LinkedList<String> list = new LinkedList<String>(); try { fr = new FileReader(file); br = new BufferedReader(fr); if(hasHeader){ br.readLine(); } String line = null; while((line = br.readLine()) != null){ list.add(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try{ if(br!= null){ br.close(); } if(fr != null){ fr.close(); } }catch(IOException e){ e.printStackTrace(); } } return list; } } <file_sep>/Ajax-Demo/src/model/Point.java package model; public class Point { private double close; private double volume; public double getClose() { return close; } public void setClose(double close) { this.close = close; } public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } public Point(double close, double volume) { super(); this.close = close; this.volume = volume; } }
33b70ad7e4d2822e05b5406a985ab6b63e42328b
[ "Java" ]
3
Java
wsy121250155/javaWeb-test
14ad14cf4bd52e9d42b1fb6abf53b17990e22760
825503b86c1655de37585db89bfe5d6fc8cc31e3
refs/heads/master
<file_sep>package com.utd.Entity; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * * @author <NAME> * This class maintains a heap data structure. The heap used here is min heap. * By setting the heapsize to 'n', we can restrict a maximum of 'n' values which contains the top most 'n' values among 'x' values */ public class MinHeap extends Census { public Integer heapMaxSize; private ArrayList<MinHeapNode> heapListNodes = null; // ArrayList of nodes /** * Default Constructor */ public MinHeap() { heapMaxSize = 101; heapListNodes = new ArrayList<MinHeapNode>(heapMaxSize); heapListNodes.add(null); // add 1 node in pos 0 to satisfy heap property } /** * Parameterized constructor * @param heapMaxSize */ public MinHeap(int heapMaxSize) { this.heapMaxSize = heapMaxSize+1; heapListNodes = new ArrayList<MinHeapNode>(this.heapMaxSize); heapListNodes.add(null); // add 1 node in pos 0 to satisfy heap property } /** * Insert values into heap * @param input */ public void insert(MinHeapNode input) { /* * If currentSize < heapMaxSize, then simply insert and percolate down * If not, then deleteMin and insert at the root, and then percolate down * So till the end, you will maintain max 5 values */ if(heapListNodes.size() < heapMaxSize) { // if heap size didn't exceed, then simply insert and heapifyUp heapListNodes.add(input); heapifyUp(input); return; } // If the root of the heap is lesser than the input value, then replace the root with the input value and then heapifyDown if(input.value > heapListNodes.get(1).value) { heapListNodes.set(1, input); heapifyDown(); } } /** * Heap property * Top Down approach */ private void heapifyDown() { MinHeapNode currentNode = heapListNodes.get(1); int hole = 1, child; for(;(hole*2) < heapListNodes.size();hole=child) { child = hole*2; if(child != heapListNodes.size()-1 && heapListNodes.get(child).value > heapListNodes.get(child+1).value) ++child; if(currentNode.value < heapListNodes.get(child).value) break; else heapListNodes.set(hole, heapListNodes.get(child)); } heapListNodes.set(hole, currentNode); } /** * Heap property * Bottom Up approach * @param input */ private void heapifyUp(MinHeapNode input) { int hole = heapListNodes.size()-1; for(heapListNodes.set(0, input);heapListNodes.get(hole).value < heapListNodes.get(hole/2).value;hole/=2) heapListNodes.set(hole, heapListNodes.get(hole/2)); heapListNodes.set(hole, input); } /** * Simply print the heap values (printing will not be sorted in any particular order) */ public void PrintHeapValues() { for(int i=1;i<heapListNodes.size();i++) System.out.println(heapListNodes.get(i)); System.out.println("Heap size: " + (heapListNodes.size()-1)); } /** * Convert all values in heap into a list * Values in this list are in sorted order (non-decreasing order) * @return */ public List<MinHeapNode> getListOfAllValuesInHeap() { List<MinHeapNode> list = new LinkedList<MinHeapNode>(); while(heapListNodes.size() > 2) { list.add(heapListNodes.get(1)); heapListNodes.set(1, heapListNodes.get(heapListNodes.size()-1)); heapListNodes.remove(heapListNodes.size()-1); heapifyDown(); } list.add(heapListNodes.get(1)); return list; } } <file_sep># NetApp_Challenge Submitted proposal to NetApp for a small consulting project - "Help us identify high growth markets" ------------------ Question: (https://www.mindsumo.com/solutions/45985) We'd like to identify metropolitan areas experiencing higher than average growth. This is often a sign of favorable financial circumstances and purchasing behavior. These economic growth signals could help us discover new pockets of potential clients. Using the U.S. Census data below, write a script in Java, Python, C/C++, or Javascript that calculates the following metrics: 1) Top five cities to target based on highest population growth (% change) between 2010-2012. (50,000 population minimum) 2) Top five cities to avoid based on the most shrinking population (% change) between 2010-2012. (50,000 population minimum) 3) Top five states with highest cumulative growth (% change combined across all metropolitan areas) between 2010-2012. <file_sep>package com.utd.Entity; /** * * @author <NAME> * Node class for maintaining heap * Each node contains info like city, state, and a appropriate value based on which sorting occurs */ public class MinHeapNode { public String city; public String state; public double value; /** * Default Constructor */ public MinHeapNode() { } /** * Parameterized constructor * @param heapMaxSize */ public MinHeapNode(String city, String state, double diffValue) { this.city = city; this.state = state; this.value = diffValue; } @Override public String toString() { return "City: " + city + "\tState: " + state + "\tValue: " + value; } }
73d853e15c3e174445e1b63a6e7fa9781e4ee127
[ "Markdown", "Java" ]
3
Java
maanick90/NetApp_Challenge
de58117c8cdd209510ab8014a155afa7dce36d7f
22a3ce4dcb168481fffc7b69d973d9413f6e1726
refs/heads/master
<file_sep># Algo Proj 4a <file_sep>/** * Team: fitsmu * <NAME> * <NAME> * * board.h: Declaration of soduku board class */ #pragma once #include <iostream> #include "d_matrix.h" typedef int ValueType; // The type of the value in a cell const int Blank = -1; // Indicates that a cell is blank const int SquareSize = 3; // The number of cells in a small square // (usually 3). The board has // SquareSize^2 rows and SquareSize^2 // columns. const int BoardSize = SquareSize * SquareSize; const int MinValue = 1; const int MaxValue = 9; // Stores the entire Sudoku board class board { public: board(int); void clear(); void initialize(ifstream &); void print() const; bool isBlank(const int&, const int&) const; ValueType getCell(const int&, const int&) const; void setCell(const int&, const int&, const ValueType&); void clearCell(const int&, const int&); bool isSolved() const; void printConflicts() const; private: // The following matrices go from 1 to BoardSize in each // dimension, i.e., they are each (BoardSize) * (BoardSize) // Sudoku board values matrix<ValueType> value; // Conflict Vectors matrix<bool> rows; matrix<bool> cols; matrix<bool> squares; };<file_sep>/** * Team: fitsmu * <NAME> * <NAME> * * fitsmu-4a.cpp: Main program file */ #include <iostream> #include <fstream> #include "board.h" int main() // main method of program { // declare input files to read ifstream fin; string files[] = { "data/sudoku1.txt", "data/sudoku2.txt", "data/sudoku3.txt" }; // cycle through each of the files for (int i = 0; i < 3; i++) { // Read the grid from the file. string fileName = files[i]; std::cout << "Reading " << fileName << std::endl; fin.open(fileName.c_str()); if (!fin) { cerr << "Cannot open " << fileName << std::endl; exit(1); } try { board b1(SquareSize); while (fin && fin.peek() != 'Z') { // initialize board and print information to console b1.initialize(fin); b1.print(); b1.printConflicts(); // check if the board is solved if (b1.isSolved()) { std::cout << "The board has been solved!" << std::endl; } else { std::cout << "The board has NOT been solved." << std::endl; } } } catch (indexRangeError &ex) { std::cout << ex.what() << std::endl; fin.close(); exit(1); } std::cout << std::endl << std::endl; fin.close(); } }<file_sep>/** * Team: fitsmu * <NAME> * <NAME> * * board.cpp: Implentations of board class functions */ #include <fstream> #include "board.h" template<typename T> ostream &operator<<(ostream &ostr, const vector<T> &v) // Overloaded output operator for vector class. { for (int i = 0; i < v.size(); i++) ostr << v[i] << " "; std::cout << std::endl; return ostr; } int squareNumber(const int& i, const int& j) // Return the square number of cell i,j (counting from left to right, // top to bottom. Note that i and j each go from 1 to BoardSize. // Range of square values is 1 to 9. { return SquareSize * ((i - 1) / SquareSize) + (j - 1) / SquareSize + 1; } board::board(int sqSize) : value(BoardSize, BoardSize), rows(BoardSize), cols(BoardSize), squares(BoardSize) // Board constructor { clear(); } bool board::isSolved() const // Checks if a board is completely filled and all the constraints are met. { bool boardFull = true, noColConflict = true, noRowConflict = true, noSqConflict = true; for (int i = 1; i <= BoardSize; i++) { for (int j = 1; j <= BoardSize; j++) { boardFull = boardFull && value[i][j] != Blank; noRowConflict = noRowConflict && rows[i - 1].at(j - 1); noColConflict = noColConflict && cols[i - 1].at(j - 1); noSqConflict = noSqConflict && squares[i - 1].at(j - 1); } } return boardFull && noColConflict && noRowConflict && noSqConflict; } void board::printConflicts() const // Prints the conflicts of the board to the screen in a table { std::cout << "\nConflicts:\n"; std::cout << "Digit: 1 2 3 4 5 6 7 8 9" << std::endl << std::endl; for (int i = 0; i < rows.rows(); i++) { std::cout << "Row " << i + 1 << ": " << rows[i]; } std::cout << std::endl; for (int i = 0; i < cols.rows(); i++) { std::cout << "Col " << i + 1 << ": " << cols[i]; } std::cout << std::endl; for (int i = 0; i < squares.rows(); i++) { std::cout << "Sqr " << i + 1 << ": " << squares[i]; } std::cout << std::endl; } void board::clear() // Mark all possible values as legal for each board entry { for (int i = 1; i <= BoardSize; i++) for (int j = 1; j <= BoardSize; j++) { value[i - 1][j - 1] = Blank; } } void board::initialize(ifstream &fin) // Read a Sudoku board from the input file stream. { char ch; cols.resize(BoardSize, MaxValue); squares.resize(BoardSize, MaxValue); rows.resize(BoardSize, MaxValue); clear(); // load each square with a value (or leave blank) for (int i = 1; i <= BoardSize; i++) { for (int j = 1; j <= BoardSize; j++) { fin >> ch; // If the read char is not Blank if (ch != '.') setCell(i, j, ch - '0'); // Convert char to int } } } void board::clearCell(const int& i, const int& j) // Sets the value in the cell to blank, updates the conflict list to remove // conflicts with this number in the column, row, and square { if (i >= 1 && i <= BoardSize && j >= 1 && j <= BoardSize) { ValueType tmp = value[i - 1][j - 1] - 1; value[i - 1][j - 1] = Blank; cols[i - 1].at(tmp) = false; rows[j - 1].at(tmp) = false; squares[squareNumber(i, j) - 1].at(tmp) = false; } else throw rangeError("bad value in clearCell"); } void board::setCell(const int& i, const int& j, const ValueType& val) // Sets the value in a cell. Throws exception if bad values // are passed. { if (i >= 1 && i <= BoardSize && j >= 1 && j <= BoardSize && val >= MinValue && val <= MaxValue) { value[i - 1][j - 1] = val; cols[j - 1].at(val - 1) = true; rows[i - 1].at(val - 1) = true; int sqNum(squareNumber(i, j) - 1); squares[sqNum].at(val - 1) = true; } else throw rangeError("bad value in setCell"); } ValueType board::getCell(const int& i, const int& j) const // Returns the value stored in a cell. Throws an exception // if bad values are passed. { if (i >= 1 && i <= BoardSize && j >= 1 && j <= BoardSize) return value[i - 1][j - 1]; else throw rangeError("bad value in getCell"); } bool board::isBlank(const int& i, const int& j) const // Returns true if cell i,j is blank, and false otherwise. { if (i < 1 || i > BoardSize || j < 1 || j > BoardSize) throw rangeError("bad value in setCell"); return (getCell(i, j) == Blank); } void board::print() const // Prints the current board. { for (int i = 1; i <= BoardSize; i++) { if ((i - 1) % SquareSize == 0) { std::cout << " -"; for (int j = 1; j <= BoardSize; j++) std::cout << "---"; std::cout << "-"; std::cout << std::endl; } for (int j = 1; j <= BoardSize; j++) { if ((j - 1) % SquareSize == 0) std::cout << "|"; if (!isBlank(i, j)) std::cout << " " << getCell(i, j) << " "; else std::cout << " "; } std::cout << "|"; std::cout << std::endl; } std::cout << " -"; for (int j = 1; j <= BoardSize; j++) std::cout << "---"; std::cout << "-"; std::cout << std::endl; }
2775a19ab4c22b1ca88b79d8002194a420c72189
[ "Markdown", "C++" ]
4
Markdown
jasonpfi/AlgoProject4a
7b49423d8fb062339372b8935b67d8a6d4ad8383
e181110ef167ee2be638b8092377e01bc5c3b4f5
refs/heads/master
<file_sep># -*- coding: utf-8 -*- #using python 3 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import math import re from sqlalchemy import create_engine import re import pymysql pymysql.install_as_MySQLdb() import numpy as np import pandas as pd score_table = pd.read_csv('E:/scoretable.csv') n_users=np.max(score_table['new_id']) n_movices=int(np.max(score_table['fid'])) indexmax = int(score_table.shape[0]) score_table_len = len(score_table) scorearray = np.zeros((n_users,n_movices)) print('ok') print('ok') for index in range(0,indexmax): row = int(score_table.loc[index]['new_id']-1) column = int( score_table.loc[index]['fid']-1) scorearray[row][column] = score_table.loc[index]['score'] df_s = pd.DataFrame(scorearray) #df_s.to_csv('E:/scorearrayspyder2.csv',index) print('ok') print('ok') l = [ (indexs,i) for indexs in df_s.index for i in range(len(df_s.loc[indexs].values)) if(df_s.loc[indexs].values[i] ==0)] df_location = pd.DataFrame(l)+1 df_location.to_csv('E:/nanlocation.csv',index =None) print('ok') print('ok') from keras.models import model_from_json json_file = open('model629.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights("model629.h5") pred_array = np.zeros((n_users,n_movices)) # for s in range(0,len(df_location)): # # i = df_location.loc[s][0] # # j = df_location.loc[s][1] # # a = i-1 # # b = j-1 # # pred_array[a][b] = model.predict([np.array([i]),np.array([j])]) # # # # df_pred = pd.DataFrame(pred_array) # # df_pred.to_csv('E:/pred.csv',index = None) # # # # print('ok') # # print('ok') # # df_preddata = df_s+df_pred # # df_preddata.to_csv('E:/preddata.csv',index = None) # # print('ok') users=score_table['new_id'].values movices=score_table['fid'].values y=score_table['score'].values pred1 = model.predict([np.array([11]),np.array([1])]) pred2 = model.predict([np.array([users[11]]), np.array([movices[1]])]) pred3 = model.predict([np.array([40]),np.array([1])]) pred4 = model.predict([np.array([users[40]]), np.array([movices[1]])]) print('pred1:',pred1) print('pred2:',pred2) print('pred3:',pred3) print('pred4:',pred4)<file_sep>import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import pandas as pd from sqlalchemy import create_engine import pymysql import pandas.util.testing as tm from scipy import stats import numpy as np import matplotlib.pyplot as plt #pd.set_option('mpl_style','default') #数据从数据库读取 pymysql.install_as_MySQLdb() engine = create_engine( 'mysql+mysqldb://root:root@192.168.10.14:3306/com66nao_cloud?charset=utf8') df1 = pd.read_sql('select user_id as user_truename,train_score as score ,train_time,cogn_task.id as gamename ,cloud_cat.name as firstbrain from user_train_history join cogn_task on cogn_task.id=user_train_history.game_id join cloud_cat on cloud_cat.id=cogn_task.label and cloud_cat.id', engine) df2 = df1[['user_truename','gamename', 'score','train_time']] # 只选取有实际作用的列 #因为在线数据库中有的游戏其实应该是没有上线,一切数值均为0,不应该被纳入考虑,因而删除空值 df3 = df2 [df2['score']>0] df4 = df3[ df3['train_time']>15] #删除哪些游戏时间小于15s的 df4 = df4.dropna() df4['mean_score'] = df4['score']/df4['train_time'] data = df4[['user_truename','mean_score','gamename','score','train_time']] tables1 = pd.pivot_table(data, index='gamename', values='mean_score', aggfunc=lambda x: np.percentile(x,25)-1.5*(np.percentile(x,75)-np.percentile(x,25)))["mean_score"] tables2 = pd.pivot_table(data, index='gamename', values='mean_score', aggfunc=lambda x: np.percentile(x,75)+1.5*(np.percentile(x,75)-np.percentile(x,25)))["mean_score"] pd_tables = pd.DataFrame([tables1,tables2]) pd_tables = pd_tables.T pd_tables.columns = ['lowerlimit','upperlimit'] pd_tables["gamename"] = pd_tables.index score_table = pd.merge(pd_tables,data, on="gamename") score_table1 = score_table[score_table['upperlimit']>score_table['mean_score']] score_table2 = score_table1[score_table1['mean_score']>score_table1['lowerlimit']] listgamename = list(set(list(data['gamename']))) for i in listgamename: singledata = data[data['gamename']== i]['mean_score'] singledata = singledata.reset_index()['mean_score'] df_singledata = singledata.to_frame(name=None) #plt.figure(1) plt.figure p = df_singledata.boxplot() plt.savefig("E:/box_plot/%s.png"%(i)) plt.show() grouped = score_table2['mean_score'].groupby(score_table2['gamename']) des_after = grouped.describe() <file_sep># LIULIUNAO 预测脑能力游戏用户在空值上的得分,并使用训练神经网络模型以期对得分进行评价 <file_sep># -*- coding: utf-8 -*- #using python 3 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import math import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Embedding,Dropout,Dense,Reshape,Merge,Concatenate from sqlalchemy import create_engine import pymysql k=128 #数据预处理,将原始数据划分为6个等级 pymysql.install_as_MySQLdb() engine = create_engine( 'mysql+mysqldb://root:root@192.168.10.14:3306/com66nao_cloud?charset=utf8') df4 = pd.read_sql('select user_id as user_truename,train_score as score ,cogn_task.name as name ,cloud_cat.name as firstbrain from user_train_history join cogn_task on cogn_task.id=user_train_history.game_id join cloud_cat on cloud_cat.id=cogn_task.label', engine) df1 = df4[['user_truename', 'name', 'score']] # 只选取有实际作用的列 #因为在线数据库中有的游戏其实应该是没有上线,一切数值均为0,不应该被纳入考虑,因而删除空值 df5 = df1 [df1>0] df6 = df5.dropna() grouped = df6['score'].groupby([df6['user_truename'], df6['name']]) df2 = grouped.median() df3 = df2.reset_index() old_set=np.unique(df3['user_truename']) old_list=list(old_set) new_id=np.arange(len(old_list)) df3['new_id']=df3['user_truename'].replace(old_list,new_id) df3['new_id']=df3['new_id']+1 print('OK') old_gameset = np.unique(df3['name']) old_gamelist = list(old_gameset) fid = np.arange(len(old_gamelist)) df3['fid'] = df3['name'].replace(old_gamelist,fid) df3['fid'] = df3['fid']+1 print("ok") print('ik') tables1 = pd.pivot_table(df3, index='fid', values='score', aggfunc=lambda x: (np.max(x) - np.min(x)) * 0.90)["score"] tables2 = pd.pivot_table(df3, index='fid', values='score', aggfunc=lambda x: (np.max(x) - np.min(x)) * 0.70)["score"] tables3 = pd.pivot_table(df3, index='fid', values='score', aggfunc=lambda x: (np.max(x) - np.min(x)) * 0.50)["score"] tables4 = pd.pivot_table(df3, index='fid', values='score', aggfunc=lambda x: (np.max(x) - np.min(x)) * 0.30)["score"] tables5 = pd.pivot_table(df3, index='fid', values='score', aggfunc=lambda x: (np.max(x) - np.min(x)) * 0.10)["score"] total_score = pd.DataFrame([tables1, tables2, tables3, tables4, tables5]) final_score = total_score.T final_score.columns = ['a', 'b', 'c', 'd', 'e'] final_score["fid"] = final_score.index score_table = pd.merge(final_score, df3, on="fid") print("ok") score_table.loc[(score_table["score"] < score_table['e']), 'score'] = 6 # score_table.loc[(score_table["score"] >= score_table['e']) & (score_table["score"] < score_table['d']), 'score'] = 5 score_table.loc[(score_table["score"] >= score_table['d']) & (score_table["score"] < score_table['c']), 'score'] = 4 score_table.loc[(score_table["score"] >= score_table['c']) & (score_table["score"] < score_table['b']), 'score'] = 3 score_table.loc[(score_table["score"] >= score_table['b']) & (score_table["score"] < score_table['a']), 'score'] = 2 score_table.loc[(score_table["score"] >= score_table['a']), 'score'] = 1 # 将所有的得分离散化在等级里面 score_table = score_table[['new_id', 'fid', 'score']] # 只选取有实际作用的列 #n数据读取结束 score_table.to_csv('E:/lf/score_table.csv',index = None) n_users=np.max(score_table['new_id']) n_movices=int(np.max(score_table['fid'])) print([n_users,n_movices,len(score_table)]) score_table.to_csv('E:/scoretable.csv',index = None) model1=Sequential() model1.add(Embedding(n_users+1,k,input_length=1)) model1.add(Reshape((k,))) model2=Sequential() model2.add(Embedding(n_movices+1,k,input_length=1)) model2.add(Reshape((k,))) model=Sequential() model.add(Merge([model1,model2],mode='concat'))#然后加入Dropout 和relu 这个非线性变换项,构造多层深度模型。 #model.add(Concatenate([model1, model2])) #x = concatenate([a, b], axis=-1) model.add(Dropout(0.5)) model.add(Dense(k, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(int(k / 4), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(int(k / 16), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(6, activation = 'softmax'))#因为是预测连续变量评分,最后一层直接上线性变化 model.compile(loss='categorical_crossentropy',optimizer='adam') users=score_table['new_id'].values movices=score_table['fid'].values y=score_table['score'].values from keras.utils import np_utils nb_classes = 6 y_train = np_utils.to_categorical(y, nb_classes) from sklearn.model_selection import train_test_split x_train_users, x_test_users,x_train_movices, x_test_movices,y_train, y_test = train_test_split(users, movices, y,test_size=0.2, random_state=None) x_train = [x_train_users,x_train_movices] x_test = [x_test_users,x_test_movices] x = [users,movices] model.fit(x_train,y_train,batch_size=100,epochs=10) print("training is start") model.save_weights('model629.h5') json_string = model.to_json() with open("model629.json", "w") as json_file: json_file.write(json_string) traincost = model.evaluate(x_train,y_train) print('traincost:',traincost) testcost = model.evaluate(x_test,y_test) print('testcost:',testcost) allcost = model.evaluate(x,y) print('allcost:',allcost) #这是总的均方误差,而不是测试集的均方误差 sum =0 predictions = [] for i in range(score_table.shape[0]): predictions.append(model.predict([np.array([score_table['new_id'][i]]), np.array([score_table['fid'][i]])])) sum += (score_table['score'][i] - model.predict([np.array([score_table['new_id'][i]]), np.array([score_table['fid'][i]])])) ** 2 mse = math.sqrt(sum/score_table.shape[0]) print("手算均方误差是",mse) pred1 = model.predict([np.array([10]),np.array([1])]) print('[11,1]的预测值:',[np.array([10]),np.array([1])],' ',pred1) pred2 = model.predict([np.array([score_table['new_id'][0]]), np.array([score_table['fid'][0]])]) print('[11,1]的预测值:',[np.array([10]),np.array([1])],' ',pred2) pred3 = model.predict([np.array([users[10]]),np.array([movices[1]])]) print('[11,1]的预测值:',[np.array([10]),np.array([1])],' ',pred3) pd_predictions = pd.Series(predictions) pd_predictions.to_csv('E:/lf/pd_predictions.csv',index = None) print('ok')
e51165cfecd1c1f15e4fc446c353621c90576c9b
[ "Markdown", "Python" ]
4
Python
zhuanglichun/LIULIUNAO
5e95ad5d22093685aea5daa71dcad3f8011333b9
2b5be735d37f17796ef18e3e15c81a9279f301be
refs/heads/master
<repo_name>trimnac/422-Final-Project<file_sep>/model_creation.R library(e1071) library(car) library(randomForest) library(tree) library(gbm) library(doMC) library(foreach) charity <- read.csv('Dropbox/NU/PREDICT 422/Final/charity.csv') charity$donr = as.factor(charity$donr) data.train = charity[charity$part=='train',!colnames(charity) %in% c('ID','part')] reg.data.train = data.train[data.train$damt > 0,!colnames(data.train) %in% c('donr')] x.train = data.train[,1:20] x.train.mean <- apply(x.train, 2, mean) x.train.sd <- apply(x.train, 2, sd) x.train.std <- t((t(x.train)-x.train.mean)/x.train.sd) #apply(x.train.std, 2, mean) # check zero mean #apply(x.train.std, 2, sd) # check unit sd data.val = charity[charity$part=='valid',!colnames(charity) %in% c('ID','part')] reg.data.val = data.val[data.val$damt > 0,!colnames(data.val) %in% c('donr')] x.val = data.val[,1:20] c.valid = as.integer(data.val[,21]) - 1 c.train = as.integer(data.train[,21]) - 1 y.train <- data.train[c.train==1,22] y.valid <- data.val[c.valid==1,22] data.train.std.c <- data.frame(x.train.std, donr=c.train) # to classify donr data.train.std.y <- data.frame(x.train.std[c.train==1,], damt=y.train) # to predict damt when donr=1 x.valid.std <- t((t(x.val)-x.train.mean)/x.train.sd) # standardize using training mean and sd data.valid.std.c <- data.frame(x.valid.std, donr=c.valid) # to classify donr data.valid.std.y <- data.frame(x.valid.std[c.valid==1,], damt=y.valid) # to predict damt when donr=1 #Logistic Regression GAM variables = c('chld', 'hinc', 'wrat', 'avhv', 'incm', 'inca', 'plow', 'npro', 'tgif', 'lgif', 'rgif', 'tdon', 'tlag', 'agif') best_poly = matrix(nrow=4, ncol=14) for (i in 1:14){ for (j in 1:4){ gam.fit = glm(as.formula(paste('donr~poly(', variables[i], ', ', j, ')')), data=data.train.std.c, family=binomial("logit")) gam.pred = predict(gam.fit, data.valid.std.c, type="response") profit.gam <- cumsum(14.5*c.valid[order(gam.pred, decreasing=T)]-2) best_poly[j,i] = max(profit.gam) } } gam.best.fit = glm(donr~reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + wrat + avhv + incm + plow + npro + tgif + poly(lgif,4) + rgif + poly(tdon, 4) + poly(tlag, 2) + poly(agif, 3), data=data.train.std.c, family=binomial("logit")) #summary(gam.best.fit) gam.best.preds = predict(gam.best.fit, data.valid.std.c, type="response") profit.gam = cumsum(14.5*c.valid[order(gam.best.preds, decreasing=T)]-2) plot(profit.gam) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.gam) # number of mailings that maximizes profits c(n.mail.valid, max(profit.gam)) # report number of mailings and maximum profit cutoff.gam <- sort(gam.best.preds, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid chat.valid.gam <- ifelse(gam.best.preds>cutoff.gam, 1, 0) # mail to everyone above the cutoff table(chat.valid.gam, c.valid) # classification table #Support Vector Machine #WARNING: This code will take a while to execute #svm.tune = tune(svm, donr~.-damt, data=data.train, ranges = list(cost=c(0.001, 0.01, 0.1, # 1, 5, 10), # kernel = c('linear'), # gamma = c(0.5, 1, 2, 3, 4))) #Cost = 0.01, Gamma = 0.5 #svm.best = svm(donr~.-damt, data=data.train, cost=0.01, gamma=0.5, kernel = "linear") #svm.preds = predict(svm.best, data.val) #table(pred = svm.preds, true = data.val$donr) #mean(svm.preds==data.val$donr) #WARNING: This code will take a while to execute set.seed(1) svm.tune2 = tune(svm, donr~.-damt, data=data.train, ranges = list(cost=c(9, 8, 10, 11, 12), kernel = c('radial'), gamma = c(0.011, 0.015, 0.013))) #Cost = 6, gamma = 0.01, kernel = radial 10, 0.011 #svm.best2 = svm.tune2$best.model svm.best2 = svm(donr~.-damt, data=data.train, probability=TRUE, cost = 10, kernel = 'radial', gamma = 0.011) summary(svm.best2) svm.preds2 = predict(svm.best2, data.val, probability = TRUE) table(pred = svm.preds2, true = data.val$donr) mean(svm.preds2==data.val$donr) profit.log1 <- cumsum(14.5*c.valid[order(attr(svm.preds2, "probabilities")[,2], decreasing=T)]-2) plot(profit.log1) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.log1) # number of mailings that maximizes profits c(n.mail.valid, max(profit.log1)) # report number of mailings and maximum profit #Naive Bayes nb.fit = naiveBayes(donr~.-damt, data=data.train, probability=TRUE) nb.preds = predict(nb.fit, data.val[,!colnames(data.val) %in% c('donr','damt')], probability=TRUE) table(pred = nb.preds, true = data.val$donr) mean(nb.preds == data.val$donr) profit.log1 <- cumsum(14.5*c.valid[order(nb.preds, decreasing=T)]-2) plot(profit.log1) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.log1) # number of mailings that maximizes profits c(n.mail.valid, max(profit.log1)) # report number of mailings and maximum profit #Decision Tree set.seed(3) tree.donor = tree(donr~.-damt, data=data.train) cv.donor = cv.tree(tree.donor, FUN=prune.misclass) names(cv.donor) cv.donor prune.donor = prune.misclass(tree.donor, best=15) tree.preds = predict(prune.donor, newdata=data.val, type='vector') table(pred = tree.preds, true = data.val$donr) profit.log1 <- cumsum(14.5*c.valid[order(tree.preds[,2], decreasing=T)]-2) plot(profit.log1) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.log1) # number of mailings that maximizes profits c(n.mail.valid, max(profit.log1)) # report number of mailings and maximum profit #Bagging set.seed(1) bag.fit = randomForest(donr~.-damt, data=data.train, mtry=20, importance=TRUE, probability=TRUE) bag.preds = predict(bag.fit, newdata=data.val, type='prob') table(pred = bag.preds, true = data.val$donr) mean(bag.preds==data.val$donr) profit.log1 <- cumsum(14.5*c.valid[order(bag.preds[,2], decreasing=T)]-2) plot(profit.log1) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.log1) # number of mailings that maximizes profits c(n.mail.valid, max(profit.log1)) # report number of mailings and maximum profit #RandomForest set.seed(1) rf.fit = randomForest(donr~.-damt, data=data.train, mtry=8, probability=TRUE, importance=TRUE) rf.preds = predict(rf.fit, newdata=data.val, type="prob") rf.preds.c = predict(rf.fit, newdata=data.val) table(predict = rf.preds.c, true = data.val$donr) mean(rf.preds==data.val$donr) profit.log1 <- cumsum(14.5*c.valid[order(rf.preds[,2], decreasing=T)]-2) plot(profit.log1) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.log1) # number of mailings that maximizes profits c(n.mail.valid, max(profit.log1)) # report number of mailings and maximum profit registerDoMC(4) #Set the number of cores here foreach(i=1:20)%dopar%{ set.seed(1) fit = randomForest(donr~.-damt, data=data.train, mtry=i, importance=TRUE) preds = predict(fit, newdata=data.val, type='prob') print(i) print(mean(preds==data.val$donr)) profit.log1 <- cumsum(14.5*c.valid[order(preds[,2], decreasing=T)]-2) print(max(profit.log1)) } #Gradient Boosting set.seed(123) gbm.fit = gbm(c.train~.-donr-damt,data=data.train, distribution = 'bernoulli', n.trees = 5500, shrinkage = 0.015, interaction.depth = 1, bag.fraction = 0.7, n.minobsinnode = 42,verbose=F) gbm.preds = predict(gbm.fit, newdata=data.val, n.trees = 5200, type='response') summary(gbm.fit) profit.gbm <- cumsum(14.5*c.valid[order(gbm.preds, decreasing=T)]-2) plot(profit.gbm) # see how profits change as more mailings are made n.mail.valid <- which.max(profit.gbm) # number of mailings that maximizes profits c(n.mail.valid, max(profit.gbm)) # report number of mailings and maximum profit gbm.preds[gbm.preds>=0.5] = 1 gbm.preds[gbm.preds<0.5] = 0 table(pred = gbm.preds, true = c.valid) mean(gbm.preds==c.valid) cutoff.gbm <- sort(gbm.preds, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid chat.valid.gbm <- ifelse(gbm.preds>cutoff.gbm, 1, 0) # mail to everyone above the cutoff table(chat.valid.gbm, c.valid) # classification table n.mail.valid <- which.max(profit.gbm) tr.rate <- .1 # typical response rate is .1 vr.rate <- .5 # whereas validation response rate is .5 adj.test.1 <- (n.mail.valid/n.valid.c)/(vr.rate/tr.rate) # adjustment for mail yes adj.test.0 <- ((n.valid.c-n.mail.valid)/n.valid.c)/((1-vr.rate)/(1-tr.rate)) # adjustment for mail no adj.test <- adj.test.1/(adj.test.1+adj.test.0) # scale into a proportion n.mail.test <- round(n.test*adj.test, 0) # calculate number of mailings for test set cutoff.test <- sort(post.test, decreasing=T)[n.mail.test+1] # set cutoff based on n.mail.test chat.test <- ifelse(post.test>cutoff.test, 1, 0) # mail to everyone above the cutoff table(chat.test) #Find optimal shrinkage #WARNING: This section will take a while to run shrinks = c(0.01, 0.011, 0.012, 0.013, 0.014, 0.015, 0.016, 0.017, 0.018, 0.019, 0.02) foreach(i=shrinks)%dopar%{ set.seed(123) gbm.fit = gbm(c.train~.-donr-damt,data=data.train, distribution = 'bernoulli', n.trees = 5000, shrinkage = i, n.minobsinnode = 43, verbose=F) gbm.preds = predict(gbm.fit, newdata=data.val, n.trees = 5000, type='response') profit.log1 <- cumsum(14.5*c.valid[order(gbm.preds, decreasing=T)]-2) print(i) print(shrinks[i]) print(max(profit.log1)) } #Find optimal trees #WARNING: This section will take a long time to run set.seed(123) gbm.fit = gbm(c.train~.-donr-damt,data=data.train, distribution = 'bernoulli', n.trees = 10000, shrinkage = 0.015, n.minobsinnode = 48, verbose=F) profits = c() start = proc.time() for (i in 1:10000){ if(i %% 1000 == 0){ print(i) print(proc.time() - start) start = proc.time() } gbm.preds = predict(gbm.fit, newdata=data.val, n.trees = i, type='response') profit.log1 <- cumsum(14.5*c.valid[order(gbm.preds, decreasing=T)]-2) profits[i] = max(profit.log1) } #Find optimal minobs minobs = c(40, 41, 42, 43, 44, 45) profits = c() foreach(i=minobs)%dopar%{ set.seed(123) gbm.fit = gbm(c.train~.-donr-damt,data=data.train, distribution = 'bernoulli', n.trees = 5500, shrinkage = 0.015, interaction.depth = 1, bag.fraction=0.7, n.minobsinnode = i, verbose=F) gbm.preds = predict(gbm.fit, newdata=data.val, n.trees = 5200, type='response') profit.log1 <- cumsum(14.5*c.valid[order(gbm.preds, decreasing=T)]-2) profits = max(profit.log1) } #Least Squares Regression lm.fit1 = lm(damt~., data=data.train.std.y) #summary(lm.fit) lm.preds1 = predict(lm.fit1, newdata=data.valid.std.y) mean((reg.data.val$damt - lm.preds1)^2) lm.fit2 = lm(damt~.-inca, data=data.train.std.y) #summary(lm.fit) lm.preds2 = predict(lm.fit2, newdata=data.valid.std.y) mean((reg.data.val$damt - lm.preds2)^2) lm.fit3 = lm(damt~.-inca-wrat, data=data.train.std.y) #summary(lm.fit) lm.preds3 = predict(lm.fit3, newdata=data.valid.std.y) mean((reg.data.val$damt - lm.preds3)^2) #Use this model lm.fit4 = lm(damt~.-inca-wrat-avhv, data=data.train.std.y) summary(lm.fit4) lm.preds4 = predict(lm.fit4, newdata=data.valid.std.y) mean((reg.data.val$damt - lm.preds4)^2) plot(reg.data.val$damt - lm.preds4) lm.fit5 = lm(damt~.-inca-wrat-avhv-tlag, data=data.train.std.y) #summary(lm.fit) lm.preds5 = predict(lm.fit5, newdata=data.valid.std.y) mean((reg.data.val$damt - lm.preds5)^2) plot(reg.data.val$damt - lm.preds5) ncvTest(lm.fit) vif(lm.fit) sqrt(vif(lm.fit)) > 2 qqPlot(lm.fit) #Best Subset library(leaps) predict.regsubsets = function(object, newdata, id, ...){ form = as.formula(object$call[[2]]) mat = model.matrix(form, newdata) coefi = coef(object, id=id) xvars = names(coefi) mat[,xvars]%*%coefi } k = 10 set.seed(1) folds = sample(1:k, nrow(data.train.std.y), replace=TRUE) cv.errors = matrix(NA, k, 20, dimnames = list(NULL, paste(1:20))) for(j in 1:k){ best.fit = regsubsets(damt~.,data=data.train.std.y[folds!=j,], nvmax=20) for(i in 1:20){ pred = predict(best.fit, data.train.std.y[folds==j,], id=i) cv.errors[j,i] = mean((data.train.std.y$damt[folds==j] - pred)^2) } } mean.cv.errors = apply(cv.errors, 2, mean) #outputs 13 as the min reg.best = regsubsets(damt~., data=data.train.std.y, nvmax=20) coef(reg.best, 13) reg.best.lm = lm(damt~ reg3 + reg4 + home + chld + hinc + genf + incm + plow + npro + rgif + tdon + agif, data=data.train.std.y) subset.pred = predict(reg.best.lm, newdata=data.valid.std.y) mean((y.valid - subset.pred)^2) plot(y.valid - subset.pred) #Gradient Boosting Regression set.seed(123) gbm.reg.fit = gbm(damt~.,data=data.train.std.y, distribution = "gaussian", n.trees = 6000, shrinkage = 0.01, interaction.depth = 1, bag.fraction = 0.8, n.minobsinnode = 4, verbose=F) gbm.reg.preds = predict(gbm.reg.fit, newdata=data.valid.std.y, n.trees = 5500) summary(gbm.reg.fit) mean((y.valid - gbm.reg.preds)^2) plot(y.valid - gbm.reg.preds) mpe = c() start = proc.time() for (i in 1:10000){ if(i %% 1000 == 0){ print(i) print(proc.time() - start) start = proc.time() } gbm.preds = predict(gbm.reg.fit, newdata=data.valid.std.y, n.trees = i) mpe[i] = mean((y.valid - gbm.preds)^2) } plot(mpe) mpe2 = c() #started with range of 40:60, keep adjusting until find the min for(i in 1:20){ set.seed(123) gbm.reg.fit = gbm(damt~.,data=data.train.std.y, distribution = "gaussian", n.trees = 5000, shrinkage = 0.01, interaction.depth = 1, n.minobsinnode = i, verbose=F) gbm.reg.preds = predict(gbm.reg.fit, newdata=data.valid.std.y, n.trees = 4250) mpe2[i] = mean((y.valid - gbm.reg.preds)^2) #print(i) } min(mpe2) which.min(mpe2) #Random Forest Regression foreach(i=1:20)%dopar%{ set.seed(1) fit = randomForest(damt~., data=data.train.std.y, mtry=i, importance=TRUE) preds = predict(fit, newdata=data.valid.std.y) mpe = mean((y.valid - preds)^2) print(mpe) } set.seed(1) rf.reg.fit = randomForest(damt~., data=data.train.std.y, mtry=5, importance=TRUE) sort(importance(rf.reg.fit)[,2], decreasing = T) rf.reg.preds = predict(rf.reg.fit, newdata=data.valid.std.y) mean((y.valid - rf.reg.preds)^2) <file_sep>/README.md # 422-Final-Project Model building and Exploratory Data Analysis for Practical Machine Learning Final Project
feb3123176ccd97436e5494b6f77c337a1da13ce
[ "Markdown", "R" ]
2
R
trimnac/422-Final-Project
814a5b1889673313fbc457b233ff2a3c1b783cef
69e619ba4250061d2878426a607c1cc6ba83ce0c
refs/heads/master
<repo_name>npd2020/diploms<file_sep>/a.mulyar/GW/Спектри/10 Fos Ge 10v7/graph.py import matplotlib.pyplot as plt import numpy as np data = np.genfromtxt("res.txt", delimiter=' ', dtype=np.float, skip_header=3) fon = np.genfromtxt("fon.txt", delimiter=' ', dtype=np.float, skip_header=3) plt.yscale('log') plt.plot(data[:,0], (data[:,1]+1)/10000000, "r", label = "Fosgen") plt.plot(fon[:,0], (fon[:,1]+1)/10000000, "k", label = "Background") plt.legend() plt.title('Spectrum') plt.xlabel('Energy (MeV)') plt.ylabel('Counts/neutron') plt.show() <file_sep>/a.mulyar/GW/GWP/src/ActionInitialization.cc #include "ActionInitialization.hh" #include "PrimaryGeneratorAction.hh"//Подключаем обязательный класс //в котором описываются источник начальных частиц /// Обязательный класс, который должен быть объявлен в проекте Geant4 /// Имя класса может быть другим, и он должен наследоваться от /// класса G4VUserActionInitialization /// Конструктор ActionInitialization::ActionInitialization() : G4VUserActionInitialization() {} //Деструктор, ничего не объявляли, поэтому оставим пустым ActionInitialization::~ActionInitialization() {} //Создание источника первичных частиц void ActionInitialization::Build() const { SetUserAction(new PrimaryGeneratorAction);//Задается источник первичных частиц //через обязательный класс PrimaryGeneratorAction } <file_sep>/a.mulyar/GW/GWP/src/RunAction.cc #include "RunAction.hh" #include "PrimaryGeneratorAction.hh" #include "DetectorConstruction.hh" #include "G4RunManager.hh" #include "G4Run.hh" #include "G4AccumulableManager.hh" #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "g4root.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... RunAction::RunAction() : G4UserRunAction(), fEdep(0.) { /* // add new units for dose // const G4double milligray = 1.e-3*gray; const G4double microgray = 1.e-6*gray; const G4double nanogray = 1.e-9*gray; const G4double picogray = 1.e-12*gray; new G4UnitDefinition("milligray", "milliGy" , "Dose", milligray); new G4UnitDefinition("microgray", "microGy" , "Dose", microgray); new G4UnitDefinition("nanogray" , "nanoGy" , "Dose", nanogray); new G4UnitDefinition("picogray" , "picoGy" , "Dose", picogray); // Register accumulable to the accumulable manager G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance(); accumulableManager->RegisterAccumulable(fEdep); accumulableManager->RegisterAccumulable(fEdep2); */ /*auto analysisManager = G4AnalysisManager::Instance(); analysisManager->SetVerboseLevel(1); analysisManager->SetNtupleMerging(true); analysisManager->CreateH1("Edep","Edep in absorber", 100, 0., 3*MeV); analysisManager->CreateNtuple("B4", "Edep and TrackL"); analysisManager->CreateNtupleDColumn("Edep"); analysisManager->FinishNtuple();*/ } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... RunAction::~RunAction() { //delete G4AnalysisManager::Instance(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void RunAction::BeginOfRunAction(const G4Run*) { // inform the runManager to save random number seed /*G4RunManager::GetRunManager()->SetRandomNumberStore(false); auto analysisManager = G4AnalysisManager::Instance(); // Open an output file // G4String fileName = "B1"; analysisManager->OpenFile(fileName);*/ } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void RunAction::EndOfRunAction(const G4Run* run) { /*G4int nofEvents = run->GetNumberOfEvent(); if (nofEvents == 0) return; auto analysisManager = G4AnalysisManager::Instance(); analysisManager->Write(); analysisManager->CloseFile();*/ /* G4int nofEvents = run->GetNumberOfEvent(); if (nofEvents == 0) return; // Merge accumulables G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance(); accumulableManager->Merge(); // Compute dose = total energy deposit in a run and its variance // G4double edep = fEdep.GetValue(); G4double edep2 = fEdep2.GetValue(); G4double rms = edep2 - edep*edep/nofEvents; if (rms > 0.) rms = std::sqrt(rms); else rms = 0.; const B1DetectorConstruction* detectorConstruction = static_cast<const B1DetectorConstruction*> (G4RunManager::GetRunManager()->GetUserDetectorConstruction()); G4double mass = detectorConstruction->GetScoringVolume()->GetMass(); G4double dose = edep/mass; G4double rmsDose = rms/mass; // Run conditions // note: There is no primary generator action object for "master" // run manager for multi-threaded mode. const B1PrimaryGeneratorAction* generatorAction = static_cast<const B1PrimaryGeneratorAction*> (G4RunManager::GetRunManager()->GetUserPrimaryGeneratorAction()); G4String runCondition; if (generatorAction) { const G4ParticleGun* particleGun = generatorAction->GetParticleGun(); runCondition += particleGun->GetParticleDefinition()->GetParticleName(); runCondition += " of "; G4double particleEnergy = particleGun->GetParticleEnergy(); runCondition += G4BestUnit(particleEnergy,"Energy"); }*/ } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void RunAction::AddEdep(G4double edep) { fEdep += edep; }<file_sep>/a.mulyar/GW/GWP/src/DetectorConstruction.cc #include "DetectorConstruction.hh" #include "DetectorSD.hh" #include "G4RunManager.hh" #include "G4SDManager.hh" #include "G4NistManager.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Sphere.hh" #include "G4UnionSolid.hh" //("Box+Cylinder", box, cyl) #include "G4IntersectionSolid.hh" //("Box*Cylinder", box, cyl) #include "G4SubtractionSolid.hh" //("Box-Cylinder", box, cyl) #include "G4MultiUnion.hh" // #include "G4VisAttributes.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4SystemOfUnits.hh" // Конструктор класса объявления материалов и геометрии всей моделируемой системы DetectorConstruction::DetectorConstruction() : G4VUserDetectorConstruction() { } // Деструктор DetectorConstruction::~DetectorConstruction() { } // Функция определения материалов и геометрии всей системы, // должна возвращать физический объем - ссылку на экземпляр класса G4VPhysicalVolume // Геометрию проектировать будем следующую: пучок протонов попадает на мишень // вольфрамовый лист толщиной около 1 мм, а за мишень поставим детектор // таких же размеров, он будет регистрировать что в него попало. G4VPhysicalVolume* DetectorConstruction::Construct() { // Для простоты используем предопределенные в Geant4 материалы // Так объявляется менеджер, из которого можно извлечь // ранее предопределенные материалы G4NistManager* nist = G4NistManager::Instance(); // Опция для включения/выключения проверки перекрытия объемов G4bool checkOverlaps = true; // Envelope parameters G4double env_sizeX = 3*m, env_sizeY = 3*m, env_sizeZ = 3*m; // World(Основна робоча зона) G4double world_sizeX = env_sizeX; G4double world_sizeY = env_sizeY; G4double world_sizeZ = env_sizeZ; G4Material* world_mat = nist->FindOrBuildMaterial("G4_WATER"); G4Box* WorldS = new G4Box("World", //its name 1.2*world_sizeX, 1.2*world_sizeY, 1.2*world_sizeZ); //its size G4LogicalVolume* WorldL = new G4LogicalVolume(WorldS, //its solid world_mat, //its material "World"); //its name G4VPhysicalVolume* WorldPV = new G4PVPlacement(0, //no rotation G4ThreeVector(), //at (0,0,0) WorldL, //its logical volume "World", //its name 0, //its mother volume false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking /////////////////////////////////////////////////////////////////////////////////////////////// /// Земля або досліджуванна речовина(мішень) G4Element* C = nist->FindOrBuildElement("C" , false); G4Element* H = nist->FindOrBuildElement("H" , false); G4Element* Cl = nist->FindOrBuildElement("Cl" , false); G4Element* S = nist->FindOrBuildElement("S" , false); G4Element* O = nist->FindOrBuildElement("O" , false); /* //сірчистий гас G4Material* C4H8Cl2S = new G4Material("C4H8Cl2S", 1.27*g/cm3, 4); C4H8Cl2S->AddElement(C, 4); C4H8Cl2S->AddElement(H, 8); C4H8Cl2S->AddElement(Cl, 2); C4H8Cl2S->AddElement(S, 1); // */ //Фосген G4Material* C4H8Cl2S = new G4Material("C4H8Cl2S", 1.4203*g/cm3, 3); C4H8Cl2S->AddElement(C, 1); C4H8Cl2S->AddElement(O, 1); C4H8Cl2S->AddElement(Cl, 2); // //G4Material* C4H8Cl2S = nist->FindOrBuildMaterial("G4_Ag"); G4ThreeVector pos1 = G4ThreeVector(0, -0.5*env_sizeY, 0*cm); G4Box* GroundS = new G4Box("Ground", //its name 1*m, 1*m, 1*m); //its size G4LogicalVolume* GroundL = new G4LogicalVolume(GroundS, //its solid C4H8Cl2S, //its material "Ground"); //its name /*G4VPhysicalVolume* GroundPV = new G4PVPlacement(0, //no rotation pos1, //at GroundL, //its logical volume "Ground", //its name WorldL, //its mother volume false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * GroundAtt = new G4VisAttributes(G4Colour(1.,1.,0.)); // yellow GroundAtt->SetForceWireframe(true); GroundL->SetVisAttributes(GroundAtt);*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // Алюмінієва преграда(блок) G4double n = 4*cm; G4double TpRMin = 40*cm, TpRMax = 44*cm, TpDz = 30*cm, TpSPhi = 0*deg, TpDPhi = 360.*deg; G4Material* rep_matSS = nist->FindOrBuildMaterial("G4_Al"); G4ThreeVector pos4 = G4ThreeVector(0*cm, 100*cm, 0*cm); G4Box* RepSb = new G4Box("Repperb", TpRMax + 6*cm + 2*n, TpDz+TpRMax/2 + 6*cm + 2*n, TpRMax + 6*cm + 2*n); G4Box* RepSm = new G4Box("Reppers", TpRMax + 2*cm + 2*n, TpDz+TpRMax/2 + 2*cm + 2*n, TpRMax + 2*cm + 2*n); G4SubtractionSolid* sub = new G4SubtractionSolid("RepSb-RepSm", RepSb, RepSm); G4LogicalVolume* RepSSL = new G4LogicalVolume(sub, //its solid rep_matSS, //its material "RepperSS"); //its name G4VPhysicalVolume* RepSSPV = new G4PVPlacement(0, //no rotation pos4, //at RepSSL, //its logical volume "RepperSS", //its name WorldL, //its mother volume (чому не прцює з логічний обєктом WrapperL) false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * RepAttSS = new G4VisAttributes(G4Colour(1.,1.,1.)); // white RepAttSS->SetForceWireframe(true); RepSSL->SetVisAttributes(RepAttSS); /////////////////////////////////////////////////////////////////////////////////////////// // Повітряний блок G4Material* rep_mat = nist->FindOrBuildMaterial("G4_AIR"); G4LogicalVolume* RepL = new G4LogicalVolume(RepSm, //its solid rep_mat, //its material "Repper"); //its name G4VPhysicalVolume* RepPV = new G4PVPlacement(0, //no rotation pos4, //at RepL, //its logical volume "Repper", //its name WorldL, //its mother volume (чому не прцює з логічний обєктом WrapperL) false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * RepAtt = new G4VisAttributes(G4Colour(0.2,0.9,0.1)); // white RepAtt->SetForceWireframe(true); RepL->SetVisAttributes(RepAtt); ////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /*// Джерело G4Box *d = new G4Box("Dj", 1*cm, 1*cm, 1*cm); G4LogicalVolume* RepLl = new G4LogicalVolume(d, //its solid rep_mat, //its material "1"); //its name G4VPhysicalVolume* RepPVl = new G4PVPlacement(0, //no rotation G4ThreeVector(0*cm,-40*cm,0*cm), //at RepLl, //its logical volume "1", //its name WorldL, //its mother volume (чому не прцює з логічний обєктом WrapperL) false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * RepAttl = new G4VisAttributes(G4Colour(0.2,0.9,0.1)); // white RepAttl->SetForceWireframe(false); RepLl->SetVisAttributes(RepAttl);*/ ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// //// Свинцевий захист G4Material* wrapper_mat = nist->FindOrBuildMaterial("G4_Pb"); G4ThreeVector pos2 = G4ThreeVector(0*cm, 0*cm, 0*cm); //G4double TpRMin = 40*cm, TpRMax = 43*cm, TpDz = 26*cm, TpSPhi = 0*deg, TpDPhi = 360.*deg; G4Tubs* WrapperTubusS = new G4Tubs("WrapperTubus", TpRMin, TpRMax, TpDz, TpSPhi, TpDPhi); G4double SpRmin = TpRMin, SpRmax = TpRMax, SpSPhi = 0*deg, SpDPhi = 360.*deg, SpSTheta = 0*deg, SpDTheta = 90.*deg; G4Sphere* WrapperSphereS = new G4Sphere("WrapperSphere", SpRmin, SpRmax, SpSPhi, SpDPhi, SpSTheta, SpDTheta); G4RotationMatrix* rotm = new G4RotationMatrix(); G4ThreeVector position1 = G4ThreeVector(0.*cm,0.*cm,-TpDz + 5*cm); G4ThreeVector position2 = G4ThreeVector(0.*cm,0.*cm,5*cm); G4Transform3D tr1 = G4Transform3D(*rotm,position1); G4Transform3D tr2 = G4Transform3D(*rotm,position2); G4MultiUnion* WrapperU = new G4MultiUnion("Wrapper"); WrapperU->AddNode(*WrapperTubusS,tr1); WrapperU->AddNode(*WrapperSphereS,tr2); WrapperU->Voxelize(); G4LogicalVolume* WrapperL = new G4LogicalVolume(WrapperU, //its solid wrapper_mat, //its material "Wrapper"); //its name G4RotationMatrix* rot = new G4RotationMatrix(); rot->rotateX(M_PI/2.*rad); G4VPhysicalVolume* WrapperPV = new G4PVPlacement(rot, //no rotation pos2, //at WrapperL, //its logical volume "Wrapper", //its name RepL, //its mother volume false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * WrapAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); // red WrapAtt->SetForceWireframe(false); WrapperL->SetVisAttributes(WrapAtt); //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// //// Кадмієв захист G4Material* wrapper_mat2 = nist->FindOrBuildMaterial("G4_Cd"); G4Tubs* WrapperTubusS2 = new G4Tubs("WrapperTubus2", TpRMax, TpRMax + n, TpDz, TpSPhi, TpDPhi); G4double SpRmin2 = TpRMax, SpRmax2 = TpRMax + n; G4Sphere* WrapperSphereS2 = new G4Sphere("WrapperSphere2", SpRmin2, SpRmax2, SpSPhi, SpDPhi, SpSTheta, SpDTheta); G4RotationMatrix* rotm2 = new G4RotationMatrix(); G4ThreeVector position12 = G4ThreeVector(0.*cm,0.*cm,-TpDz + 5*cm); G4ThreeVector position22 = G4ThreeVector(0.*cm,0.*cm,5*cm); G4Transform3D tr12 = G4Transform3D(*rotm2,position12); G4Transform3D tr22 = G4Transform3D(*rotm2,position22); G4MultiUnion* WrapperU2 = new G4MultiUnion("Wrapper2"); WrapperU2->AddNode(*WrapperTubusS2,tr12); WrapperU2->AddNode(*WrapperSphereS2,tr22); WrapperU2->Voxelize(); G4LogicalVolume* WrapperL2 = new G4LogicalVolume(WrapperU2, //its solid wrapper_mat2, //its material "Wrapper2"); //its name G4RotationMatrix* rot2 = new G4RotationMatrix(); rot2->rotateX(M_PI/2.*rad); /*G4VPhysicalVolume* WrapperPV2 = new G4PVPlacement(rot2, //no rotation pos2, //at WrapperL2, //its logical volume "Wrapper2", //its name RepL, //its mother volume false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * WrapAtt2 = new G4VisAttributes(G4Colour(1.,0.5,0.)); WrapAtt2->SetForceWireframe(false); WrapperL2->SetVisAttributes(WrapAtt2);*/ //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// //// <NAME> //G4Element* C = nist->FindOrBuildElement("C" , false); //G4Element* H = nist->FindOrBuildElement("H" , false); G4Material* C31H64 = new G4Material("C31H64", 0.895*g/cm3, 2); C31H64->AddElement(C, 31); C31H64->AddElement(H, 64); G4Tubs* WrapperTubusS3 = new G4Tubs("WrapperTubus3", TpRMax + n, TpRMax + 2*n, TpDz, TpSPhi, TpDPhi); G4double SpRmin3 = TpRMax + n, SpRmax3 = TpRMax + 2*n; G4Sphere* WrapperSphereS3 = new G4Sphere("WrapperSphere3", SpRmin3, SpRmax3, SpSPhi, SpDPhi, SpSTheta, SpDTheta); G4RotationMatrix* rotm3 = new G4RotationMatrix(); G4ThreeVector position13 = G4ThreeVector(0.*cm,0.*cm,-TpDz + 5*cm); G4ThreeVector position23 = G4ThreeVector(0.*cm,0.*cm,5*cm); G4Transform3D tr13 = G4Transform3D(*rotm2,position13); G4Transform3D tr23 = G4Transform3D(*rotm2,position23); G4MultiUnion* WrapperU3 = new G4MultiUnion("Wrapper3"); WrapperU3->AddNode(*WrapperTubusS3,tr13); WrapperU3->AddNode(*WrapperSphereS3,tr23); WrapperU3->Voxelize(); G4LogicalVolume* WrapperL3 = new G4LogicalVolume(WrapperU3, //its solid C31H64, //its material "Wrapper3"); //its name G4RotationMatrix* rot3 = new G4RotationMatrix(); rot3->rotateX(M_PI/2.*rad); /*G4VPhysicalVolume* WrapperPV3 = new G4PVPlacement(rot3, //no rotation pos2, //at WrapperL3, //its logical volume "Wrapper3", //its name RepL, //its mother volume false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * WrapAtt3 = new G4VisAttributes(G4Colour(0.4,0.,0.6)); WrapAtt3->SetForceWireframe(false); WrapperL3->SetVisAttributes(WrapAtt3);*/ //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // Детектор G4Material* detector_mat = nist->FindOrBuildMaterial("G4_Ge"); //G4ThreeVector pos3 = G4ThreeVector(0*cm, 0*env_sizeY, (TpRMin/2)+(TpDz/4)); G4ThreeVector pos3 = G4ThreeVector(0*cm, 0*cm, 0*cm); G4Box* DetectorS = new G4Box("Detector", //its name 0.5*TpRMin, 0.5*TpRMin, 0.5*TpRMin); //its size G4LogicalVolume* DetectorL = new G4LogicalVolume(DetectorS, //its solid detector_mat, //its material "Detector"); //its name G4VPhysicalVolume* DetectorPV = new G4PVPlacement(0, //no rotation pos3, //at DetectorL, //its logical volume "Detector", //its name RepL, //its mother volume (чому не прцює з логічний обєктом WrapperL) false, //no boolean operation 0, //copy number checkOverlaps); //overlaps checking G4VisAttributes * DetAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); // green DetAtt->SetForceWireframe(false); DetectorL->SetVisAttributes(DetAtt); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// //Всегда возвращает физический объем return WorldPV; } void DetectorConstruction::ConstructSDandField() { // Объявление чувствительной области детектора, в которой можно получить подробную // информацию о состоянии и движении частицы // Назовем чувствительную область DetectorSD G4String trackerChamberSDname = "DetectorSD"; // Создаем экземпляр чувствительной области DetectorSD* aTrackerSD = new DetectorSD(trackerChamberSDname); // Передаем указатель менеджеру G4SDManager::GetSDMpointer()->AddNewDetector(aTrackerSD); // Добавляем чувствительный объем ко всем логическим областям с // именем Detector SetSensitiveDetector("Detector", aTrackerSD, true); } <file_sep>/a.mulyar/GW/GWP/src/EventAction.cc #include "EventAction.hh" #include "RunAction.hh" #include "DetectorSD.hh" #include "G4Event.hh" #include "G4RunManager.hh" #include "g4root.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... EventAction::EventAction(RunAction* runAction) : G4UserEventAction(), fRunAction(runAction), fEdep(0.) {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... EventAction::~EventAction() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void EventAction::BeginOfEventAction(const G4Event* event) { fEdep = 0.; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void EventAction::EndOfEventAction(const G4Event* event) { //if (event->GetEventID() % 10 == 0){} // accumulate statistics in run action /* auto analysisManager = G4AnalysisManager::Instance(); analysisManager->FillH1(0, fEdep); analysisManager->FillNtupleDColumn(0, fEdep); analysisManager->AddNtupleRow(); fRunAction->AddEdep(fEdep);*/ } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......<file_sep>/a.mulyar/GW/GWP/include/PrimaryGeneratorAction.hh #ifndef B1PrimaryGeneratorAction_h #define B1PrimaryGeneratorAction_h 1 #include "G4VUserPrimaryGeneratorAction.hh" #include "G4GeneralParticleSource.hh" //загальне джерело частинок #include "G4ParticleGun.hh" #include "globals.hh" class G4GeneralParticleSource; class G4ParticleGun; class G4Event; /// Класс определения источника первичных частиц class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction { public: PrimaryGeneratorAction(); virtual ~PrimaryGeneratorAction(); // Метод из базового класса, задает параметры источника начальных частиц virtual void GeneratePrimaries(G4Event*); private: G4ParticleGun* fParticleGun; // указатель на источник частиц //G4GeneralParticleSource* fGeneralParticleSource; }; #endif <file_sep>/README.md # Дипломні роботи <file_sep>/a.mulyar/GW/Спектри/7/graphs.py import matplotlib.pyplot as plt import numpy as np import math data = np.genfromtxt("res.txt", delimiter=' ', dtype=np.float, skip_header=2) plt.plot(data[:,0], data[:,1], "r", label = "Gas") plt.legend() plt.title('Spectrum') plt.xlabel('Energy (MeV)') plt.ylabel('Counts') plt.show() <file_sep>/a.mulyar/GW/GWP/build/CMakeFiles/example.dir/DependInfo.cmake # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/andriy/Programs/G4W/GW/GWP/example.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/example.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/ActionInitialization.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/ActionInitialization.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/DetectorConstruction.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/DetectorConstruction.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/DetectorSD.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/DetectorSD.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/EventAction.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/EventAction.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/PrimaryGeneratorAction.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/PrimaryGeneratorAction.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/RunAction.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/RunAction.cc.o" "/home/andriy/Programs/G4W/GW/GWP/src/SteppingAction.cc" "/home/andriy/Programs/G4W/GW/GWP/build/CMakeFiles/example.dir/src/SteppingAction.cc.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "G4INTY_USE_QT" "G4INTY_USE_XT" "G4LIB_BUILD_DLL" "G4UI_USE_QT" "G4UI_USE_TCSH" "G4VIS_USE_OPENGL" "G4VIS_USE_OPENGLQT" "G4VIS_USE_OPENGLX" "G4VIS_USE_RAYTRACERX" "QT_CORE_LIB" "QT_GUI_LIB" "QT_OPENGL_LIB" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "/home/andriy/Programs/CLHEP/CLHEP-2.4.1.2-install/lib/CLHEP-2.4.1.2/../../include" "/home/andriy/Programs/Geant4/geant4.10.06-install/include/Geant4" "../include" "/home/andriy/Programs/CLHEP/CLHEP-2.4.1.2-install/include" "/usr/include/qt4/QtGui" "/usr/include/qt4/QtCore" "/usr/share/qt4/mkspecs/default" "/usr/include/qt4" "/usr/include/qt4/QtOpenGL" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>/a.mulyar/GW/GWP/build/graph.py import matplotlib.pyplot as plt import numpy as np data = np.genfromtxt("res.txt", delimiter=' ', dtype=np.float, skip_header=2) fon = np.genfromtxt("fon.txt", delimiter=' ', dtype=np.float, skip_header=2) plt.plot(data[:,0], data[:,1], "r", label = "Gas") plt.plot(fon[:,0], fon[:,1], "k--", label = "Background") plt.legend() plt.title('Spectrum') plt.xlabel('Energy (MeV)') plt.ylabel('Counts') plt.show() <file_sep>/a.mulyar/GW/GWP/include/DetectorConstruction.hh #ifndef DetectorConstruction_h #define DetectorConstruction_h 1 #include "G4VUserDetectorConstruction.hh" #include "globals.hh" class G4VPhysicalVolume; class G4LogicalVolume; class DetectorConstruction : public G4VUserDetectorConstruction { public: //Конструктор, вызывается при создании экземпляра класса //Обычно используется для задания начальных значений и значений по умолчанию //при создании геометрии и материалов DetectorConstruction(); //Деструктор, вызывается при удалении экземпляра класса //Обычно используется для освобождения памяти инициализированных массивов внутри класса virtual ~DetectorConstruction(); //Объявление и создание детекторов и среды virtual G4VPhysicalVolume* Construct(); //Установка чувствительного объема. Когда частица в нем, то в нем извлекается //вся информация о треке и параметрах частицы на каждом шаге моделирования virtual void ConstructSDandField(); G4LogicalVolume* GetScoringVolume() const { return fScoringVolume; } protected: G4LogicalVolume* fScoringVolume; }; #endif <file_sep>/a.mulyar/GW/Спектри/9 Fos NaI 10v7/розбиття.py import matplotlib.pyplot as plt import numpy as np data = np.genfromtxt("res.txt", delimiter=' ', dtype=np.float, skip_header=2) fon = np.genfromtxt("fon.txt", delimiter=' ', dtype=np.float, skip_header=2) np.savetxt('data1.txt', data[:,0], fmt='%.2f') np.savetxt('data2.txt', data[:,1], fmt='%.d') np.savetxt('fon1.txt', fon[:,0], fmt='%.2f') np.savetxt('fon2.txt', fon[:,1], fmt='%.d') <file_sep>/a.mulyar/GW/GWP/src/PrimaryGeneratorAction.cc #include "PrimaryGeneratorAction.hh" // Подключаем необходимы заголовочные файлы #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4Box.hh" #include "G4RunManager.hh" #include "G4ParticleTable.hh" #include "G4ParticleDefinition.hh" #include "G4SystemOfUnits.hh" #include "Randomize.hh" // Класс, в котором описывается положение, тип, энергия, направление вылета // и распределение начальных частиц PrimaryGeneratorAction::PrimaryGeneratorAction() : G4VUserPrimaryGeneratorAction(), fParticleGun(nullptr) { // G4GeneralParticleSource //fGeneralParticleSource = new G4GeneralParticleSource(); // ParticleGun // По умолчанию поставим 1 частицу G4int n_particle = 1; fParticleGun = new G4ParticleGun(n_particle); // Получаем встроеную в Geant4 таблицу частиц G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); // Ищем частицу G4ParticleDefinition* particle = particleTable->FindParticle("neutron"); // Устанавливаем полученную частицу в качестве испускаемого типа начальных частиц в источнике fParticleGun->SetParticleDefinition(particle); // Установка начальной энергии испускаемых частиц fParticleGun->SetParticleEnergy(14.1*MeV); // Встановлюєм позицію істочника fParticleGun->SetParticlePosition(G4ThreeVector(0*cm,-40*cm,0*cm)); // Устанавливаем направление движение частицы по (x,y,z) fParticleGun->SetParticleMomentumDirection(G4ThreeVector(0.,-1.,0.)); } // Деструктор PrimaryGeneratorAction::~PrimaryGeneratorAction() { // удаляем созданный в конструкторе экземпляр класса источника G4ParticleGun delete fParticleGun; //delete fGeneralParticleSource; } void PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) { // Генерируем первичное событие fParticleGun->GeneratePrimaryVertex(anEvent); //fGeneralParticleSource->GeneratePrimaryVertex(anEvent); }
61e81009fe0676f5779d72416845863c18218a76
[ "Markdown", "Python", "CMake", "C++" ]
13
Python
npd2020/diploms
54402012aefa7dad19a366b67ef0f83ca8240122
759dc465cb73760f349f08375873a866b6783fcb
refs/heads/master
<repo_name>sathishalways/billing<file_sep>/application/models/Login_model.php <?php class login_model extends CI_Model{ function __construct(){ parent::__construct(); } public function validate($uname,$pwd){ $this->db->select("id,name,user_name,password,user_type,emp_id,user_access,status"); $this->db->where("user_name",$uname); $this->db->where("password",$pwd); $query = $this->db->get("users"); //$sql = $this->db->get_compiled_select('admin'); //echo $sql; if($query->num_rows() == 1 ) { foreach($query->result() as $rows) { $user_data[] = $rows; } $this->session->set_userdata('login_data',$user_data); return 1; } else { return 0; } } public function update_password($data,$pwd){ $this->db->where('id',$pwd); $this->db->update('users',$data); return $data; } }<file_sep>/application/controllers/old_Pages.php <?php class Pages extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); //$this->load->library('session'); $this->load->model('Prodservicestat_model'); $this->load->model('Productcategory_model'); $this->load->model('Servicecategory_model'); $this->load->model('Servicelocation_model'); $this->load->model('Problemcategory_model'); $this->load->model('Accessories_model'); $this->load->model('Subcategory_model'); $this->load->model('Product_model'); $this->load->model('Customer_model'); $this->load->model('Company_model'); $this->load->model('Employee_model'); $this->load->model('Brand_model'); $this->load->model('Order_model'); $this->load->model('Spare_model'); $this->load->model('Service_model'); $this->load->model('Tax_model'); $this->load->model('quote_review_model'); $this->load->model('quote_in_progress_model'); $this->load->model('quote_approved_model'); $this->load->model('workin_prog_model'); $this->load->model('quality_check_model'); $this->load->model('ready_delivery_model'); $this->load->model('delivery_model'); $this->load->model('Dash_model'); $this->load->model('User_model'); $this->load->model('Report_model'); $this->load->model('Sparereport_model'); $this->load->model('stampingreport_model'); $this->load->model('monthreport_model'); $this->load->model('qc_master_model'); $this->load->model('Labcategory_model'); } public function dash(){ ini_set('max_execution_time', 900); $data1['user_dat'] = $this->session->userdata('login_data'); $data1['user_acc'] = $data1['user_dat'][0]->user_access; $data1['user_type'] = $data1['user_dat'][0]->user_type; /* if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } */ $data1['list']=$this->Dash_model->areawise_count(); $data1['spare_stock_cnt']=$this->Dash_model->spare_stock_cnt(); //$data1['offsite_cnt']=$this->Dash_model->offsite_cnt(); $data1['amc_cnt']=$this->Dash_model->amc_cnt(); //$data1['onsite_cnt']=$this->Dash_model->onsite_cnt(); //$data1['stamping_cnt']=$this->Dash_model->stamping_cnt(); $data1['readyfordelivery_cnt']=$this->Dash_model->readyfordelivery_cnt(); $data1['req_alert_cnt']=$this->Dash_model->req_alert_cnt(); $data1['request_list']=$this->Dash_model->request_list(); $data1['engineer_status']=$this->Dash_model->engineer_status(); $data1['engineer_work_inpro']=$this->Dash_model->engineer_work_inpro(); $data1['engineer_quote_awaiting_approval']=$this->Dash_model->engineer_quote_awaiting_approval(); $data1['engineer_on_hold']=$this->Dash_model->engineer_on_hold(); $data1['engineer_ready_delivery']=$this->Dash_model->engineer_ready_delivery(); $data1['spare_min_alerts']=$this->Dash_model->spare_min_alerts(); $data1['sparelist1'] = $this->Spare_model->sparelist1(); /* $data1['get_min_spares'] = $this->Spare_model->get_min_spares(); foreach($data1['get_min_spares'] as $get_min_spares){ $min_spares[] = $get_min_spares->spare_id; } foreach($data1['sparelist1'] as $sparelist){ if($sparelist->spare_qty <= $sparelist->min_qty){ //echo "<br>".$sparelist->id.'-'.$sparelist->spare_name; if(!empty($min_spares) && in_array($sparelist->id,$min_spares)){ $this->Spare_model->del_min_spares($sparelist->id); } $data_min['spare_id'] = $sparelist->id; $data_min['spare_name'] = $sparelist->spare_name; $data_min['spare_qty'] = $sparelist->spare_qty; $data_min['min_qty'] = $sparelist->min_qty; date_default_timezone_set('Asia/Calcutta'); $data_min['alert_on'] = date("Y-m-d H:i:s"); $this->Spare_model->add_min_spares($data_min); }else{ $this->Spare_model->del_min_spares($sparelist->id); } } */ //$data1['user_dat'] = $this->session->userdata('login_data'); //echo "user_type: ". $data1['user_dat'][0]->user_type; //exit; $this->load->view('templates/header',$data1); $this->load->view('dash',$data1); } public function engg_individual_workinpro_list(){ $id=$this->uri->segment(3); $data1['engg_workinpro_list']=$this->Dash_model->engg_workinpro_list($id); $data1['engg_workinpro_list1']=$this->Dash_model->engg_workinpro_list1($id); //$data1['offsite_listforEmp']=$this->Dash_model->engg_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engg_individual_workinpro_list',$data1); } public function engg_individual_onhold_list(){ $id=$this->uri->segment(3); $data1['engg_onhold_list']=$this->Dash_model->engg_onhold_list($id); $data1['engg_onhold_list1']=$this->Dash_model->engg_onhold_list1($id); //$data1['offsite_listforEmp']=$this->Dash_model->engg_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engg_individual_onhold_list',$data1); } public function engg_individual_awaiting_list(){ $id=$this->uri->segment(3); $data1['engg_awaiting_list']=$this->Dash_model->engg_awaiting_list($id); $data1['engg_awaiting_list1']=$this->Dash_model->engg_awaiting_list1($id); //$data1['offsite_listforEmp']=$this->Dash_model->engg_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engg_individual_awaiting_list',$data1); } public function engg_individual_ready_list(){ $id=$this->uri->segment(3); $data1['engg_ready_list']=$this->Dash_model->engg_ready_list($id); $data1['engg_ready_list1']=$this->Dash_model->engg_ready_list1($id); //$data1['offsite_listforEmp']=$this->Dash_model->engg_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engg_individual_ready_list',$data1); } public function onsite_list(){ $data1['onsite_list']=$this->Dash_model->onsite_list(); $data1['onsite_list1']=$this->Dash_model->onsite_list1(); $data1['service_req_listforEmp']=$this->Dash_model->service_req_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('onsite_list',$data1); } public function offsite_list(){ $data1['offsite_list']=$this->Dash_model->offsite_list(); $data1['offsite_list1']=$this->Dash_model->offsite_list1(); $data1['offsite_listforEmp']=$this->Dash_model->offsite_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('offsite_list',$data1); } public function engg_individual_list(){ $id=$this->uri->segment(3); $data1['engg_list']=$this->Dash_model->engg_list($id); $data1['engg_list1']=$this->Dash_model->engg_list1($id); //$data1['offsite_listforEmp']=$this->Dash_model->engg_listforEmp(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engg_list',$data1); } public function stamping_list(){ $data1['stamping_list']=$this->Dash_model->stamping_list(); $data1['stamping_list1']=$this->Dash_model->stamping_list1(); $data1['stamping_listforEmp']=$this->Dash_model->stamping_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('stamping_list',$data1); } public function Areawise_list(){ $id=$this->uri->segment(3); $data1['Areawise_view']=$this->Dash_model->Areawise_list($id); $data1['Areawise_list1']=$this->Dash_model->Areawise_list1($id); $data1['Areawise_listforEmp']=$this->Dash_model->Areawise_listforEmp($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('areawise_list',$data1); } public function lab_listsss(){ $data1['listss'] = $this->Labcategory_model->labss_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('lab_list',$data1); } public function add_lab(){ //$data1['list']=$this->Customer_model->customer_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_lab'); } public function cust_list(){ $data1['list']=$this->Customer_model->customer_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('cust_list',$data1); } public function add_cust(){ $data1['customer_type']=$this->Customer_model->cust_type_list(); $data1['service_zone']=$this->Customer_model->service_zone_list(); $data1['state_list']=$this->Customer_model->state_list(); $data1['cust_cnt']=$this->Customer_model->cust_cnt(); $data1['lab']=$this->Labcategory_model->labss_list(); if(empty($data1['cust_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['cust_cnt'][0]->id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_cust',$data1); } public function prod_list(){ $data1['list']=$this->Product_model->product_list(); $data1['accessories_list']=$this->Product_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_list',$data1); } public function add_prod(){ $data1['prodcatlist']=$this->Product_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Product_model->prod_sub_cat_dropdownlist(); $data1['brandlists']=$this->Product_model->brandlists(); $data1['accessories_list']=$this->Product_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod',$data1); } public function emp_list(){ $data1['list']=$this->Employee_model->employee_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('emp_list',$data1); } public function add_emp(){ $data1['state_list']=$this->Employee_model->state_list(); $data1['emp_cnt']=$this->Employee_model->emp_cnt(); if(empty($data1['emp_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['emp_cnt'][0]->id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_emp',$data1); } public function service_skill(){ $data1['id']=$this->uri->segment(3); $data1['list']=$this->Employee_model->product_list(); $data1['servicecatlist']=$this->Employee_model->service_cat_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_skill',$data1); } public function comp_list(){ $data1['list']=$this->Company_model->company_list(); $data1['state_list']=$this->Company_model->state_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('comp_list',$data1); } public function prod_service_stat_list(){ $data1['list']=$this->Prodservicestat_model->prod_service_status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_service_stat_list',$data1); } public function add_prod_service_stat(){ //$data1['list']=$this->prodServiceStat_model->customer_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod_service_stat'); } public function prod_cat_list(){ $data1['list']=$this->Productcategory_model->prod_cat_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_cat_list',$data1); } public function add_prod_cat(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod_cat'); } public function prod_subcat_list(){ $data1['list']=$this->Subcategory_model->prod_sub_cat_list(); $data1['droplists']=$this->Subcategory_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_subcat_list',$data1); } public function add_prod_subcat(){ $data1['droplist']=$this->Subcategory_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod_subcat',$data1); } public function service_cat_list(){ $data1['list']=$this->Servicecategory_model->service_cat_list(); //$data1['list1']=$this->Servicecategory_model->service_cat_list1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_cat_list',$data1); } public function add_service_cat(){ $data1['modellist']=$this->Servicecategory_model->modellist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_service_cat',$data1); } public function add_service_charge(){ $data1['modellist']=$this->Servicecategory_model->modellist(); $data1['list']=$this->Servicecategory_model->service_cat_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_service_charge',$data1); } public function service_charge_list(){ $data1['service_charge_list']=$this->Servicecategory_model->service_charge_list(); $data1['service_cat_list']=$this->Servicecategory_model->service_cat_charge_list(); $data1['modellist']=$this->Servicecategory_model->modellist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_charges_list',$data1); } public function service_loc_list(){ $data1['list']=$this->Servicelocation_model->service_location_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_loc_list',$data1); } public function add_service_loc(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_service_loc'); } public function qc_masters(){ $data1['modellist']=$this->qc_master_model->modellist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_qc_master',$data1); } public function qc_masters_list(){ $data1['qc_masters_list']=$this->qc_master_model->qc_masters_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('qc_masters_list',$data1); } public function prob_cat_list(){ $data1['list']=$this->Problemcategory_model->problem_category_list(); $data1['list1']=$this->Problemcategory_model->problem_category_list1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prob_cat_list',$data1); } public function add_prob_cat(){ $data1['modellist']=$this->Problemcategory_model->modellist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prob_cat',$data1); } public function accessories_list(){ $data1['list']=$this->Accessories_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('accessories_list',$data1); } public function add_accessories(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_accessories'); } public function order_list(){ $data1['orderlist']=$this->Order_model->orderlist(); $data1['orderlist1']=$this->Order_model->orderlist1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('order_list',$data1); } public function warranty_pending_claims(){ $data1['warranty_pending_claims']=$this->Service_model->warranty_pending_claims(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('warranty_pending_claims',$data1); } public function amc_list(){ $data1['amclist']=$this->Order_model->amclist(); $data1['amclist1']=$this->Order_model->amclist1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('amc_list',$data1); } public function cmc_list() { $data1['cmclist']=$this->Order_model->cmclist(); $data1['cmclist1']=$this->Order_model->cmclist1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('cmc_list',$data1); } public function rent_list(){ $data1['rentlist']=$this->Order_model->rentlist(); $data1['rentlist1']=$this->Order_model->rentlist1(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('rent_list',$data1); } public function add_order(){ $data1['customerlist']=$this->Order_model->customerlist(); $data1['prodcatlist']=$this->Order_model->prod_cat_dropdownlist(); //$data1['subcatlist']=$this->Order_model->prod_sub_cat_dropdownlist(); ///$data1['brandlist']=$this->Order_model->brandlist(); $data1['modellist']=$this->Order_model->modellist(); $data1['serviceLocList']=$this->Order_model->serviceLocList(); date_default_timezone_set('Asia/Calcutta'); $data1['saledate'] = date("Y-m-d"); $warranty_date = new DateTime("+12 months"); $dd = $warranty_date->format('Y-m-d') . "\n"; $newdate = strtotime ('-1 day' , strtotime ($dd)); $data1['warranty_date'] = date('Y-m-d' , $newdate); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_order',$data1); } public function add_service_req(){ $data1['customerlist']=$this->Service_model->customerlist(); $data1['list_serialnos']=$this->Service_model->list_serialnos(); $data1['servicecat_list']=$this->Service_model->servicecat_list(); $data1['problemlist']=$this->Service_model->problemlist(); $data1['employee_list']=$this->Service_model->employee_list(); $data1['stamping_list']=$this->Service_model->stamping_list(); //$data1['get_categorys']=$this->Service_model->get_categorys(); //$data1['employee_list1']=$this->Service_model->employee_list1(); $data1['accessories_list']=$this->Service_model->accessories_list(); /* $data1['prod_cat_dropdownlist1']=$this->Service_model->prod_cat_dropdownlist1(); $data1['prod_sub_cat_dropdownlist1']=$this->Service_model->prod_sub_cat_dropdownlist1(); $data1['brandlist1']=$this->Service_model->brandlist1(); */ date_default_timezone_set('Asia/Calcutta'); $data1['req_date'] = date("Y-m-d H:i"); $data1['service_cnt']=$this->Service_model->service_cnt(); if(empty($data1['service_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['service_cnt'][0]->request_id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_service_req',$data1); } public function service_req_list(){ error_reporting(0); $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['service_req_list']=$this->Service_model->service_req_list($user_access,$user_type); $data1['service_req_list1']=$this->Service_model->service_req_list1($user_access,$user_type); $data1['service_req_listforEmp']=$this->Service_model->service_req_listforEmp(); $data1['status_list']=$this->Service_model->status_list(); $data1['combine_status_list']=$this->Service_model->combine_status_list(); $data1['preventive_req_lis']=$this->Service_model->preventive_req_list(); foreach($data1['preventive_req_lis'] As $prev_list){ $prenos = $prev_list->prenos; $prenos_cnt = $prev_list->prenos_cnt; //$prev_main = $prev_list->prev_main; if($prev_list->amc_type!=""){ $machine_status = $prev_list->amc_type; }else{ $machine_status = $prev_list->machine_status; } if($prev_list->amc_start_date!=""){ $prev_main_updated = $prev_list->prev_main_updated; }else{ $prev_main_updated = $prev_list->prev_main_updated; } $order_id = $prev_list->order_id; $today = date("Y-m-d"); // Preventive Alerts for 1 Nos if($prenos=='1'){ //echo "IN"; if($prenos_cnt=="0"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 1st month. } if($today == $prev_date){ //echo "DUMMMMMMYY"; if($prenos>$prenos_cnt){ //$data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); $count = $prenos_cnt+1; $data=array( 'prev_main_updated'=>$prev_date, 'prenos_cnt'=>$count ); $this->Service_model->update_preventive($data,$order_id); /* echo "<pre>"; print_r($prev_list); */ $data5['service_p_cnt']=$this->Service_model->service_p_cnt(); if(empty($data5['service_p_cnt'])){ $reqid='00001'; }else{ $cusid = $data5['service_p_cnt'][0]->request_id; $cusid1 = explode("-",$cusid); $dat= $cusid1['1'] + 1; $reqid=sprintf("%05d", $dat); } $data2['request_id'] = "P-".$reqid; $customer_id = $prev_list->customer_id; $data2['cust_name'] = sprintf("%05d", $customer_id); $data2['br_name'] = $prev_list->customer_service_loc_id; $data2['mobile'] = $prev_list->mobile; $data2['email_id'] = $prev_list->email_id; $data2['request_date'] = date('Y-m-d H:i:s', strtotime($prev_date)); $data2['status'] = "0"; $result=$this->Service_model->add_services($data2); $res = sprintf("%05d", $result); if($result){ $data3['request_id']=$res; $data3['serial_no'] = $prev_list->serial_no; $data3['cat_id'] = $prev_list->cat_id; $data3['subcat_id'] = $prev_list->subcat_id; $data3['brand_id'] = $prev_list->brand_id; $data3['model_id'] = $prev_list->model_id; $data3['warranty_date'] = $prev_list->warranty_date; $data3['amc_end_date'] = $prev_list->amc_end_date; $data3['machine_status'] = $machine_status; $data3['service_type'] = $prev_list->machine_status; $data3['zone'] = $prev_list->service_loc_id; $this->Service_model->add_service_details($data3); } } }/* else{ echo "Dummy"; } */ if($today == $prev_main_updated){ $data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); } } // Preventive Alerts for 3 Nos if($prenos=='3'){ if($prenos_cnt=="0"){ $prev_date = date('Y-m-d', strtotime("+3 months", strtotime($prev_main_updated)));// To alert in 3rd month. }else if($prenos_cnt=="1"){ $prev_date = date('Y-m-d', strtotime("+3 months", strtotime($prev_main_updated)));// To alert in 6th month. }else{ $prev_date = date('Y-m-d', strtotime("+3 months", strtotime($prev_main_updated)));// To alert in 9th month. } if($today == $prev_date){ //echo "DUMMMMMMYY"; if($prenos>$prenos_cnt){ //$data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); $count = $prenos_cnt+1; $data=array( 'prev_main_updated'=>$prev_date, 'prenos_cnt'=>$count ); $this->Service_model->update_preventive($data,$order_id); $data5['service_p_cnt']=$this->Service_model->service_p_cnt(); if(empty($data5['service_p_cnt'])){ $reqid='00001'; }else{ $cusid = $data5['service_p_cnt'][0]->request_id; $cusid1 = explode("-",$cusid); $dat= $cusid1['1'] + 1; $reqid=sprintf("%05d", $dat); } $data2['request_id'] = "P-".$reqid; $customer_id = $prev_list->customer_id; $data2['cust_name'] = sprintf("%05d", $customer_id); $data2['br_name'] = $prev_list->customer_service_loc_id; $data2['mobile'] = $prev_list->mobile; $data2['email_id'] = $prev_list->email_id; $data2['request_date'] = date('Y-m-d H:i:s', strtotime($prev_date)); $data2['status'] = "0"; $result=$this->Service_model->add_services($data2); $res = sprintf("%05d", $result); if($result){ $data3['request_id']=$res; $data3['serial_no'] = $prev_list->serial_no; $data3['cat_id'] = $prev_list->cat_id; $data3['subcat_id'] = $prev_list->subcat_id; $data3['brand_id'] = $prev_list->brand_id; $data3['model_id'] = $prev_list->model_id; $data3['warranty_date'] = $prev_list->warranty_date; $data3['amc_end_date'] = $prev_list->amc_end_date; $data3['machine_status'] = $machine_status; $data3['service_type'] = $prev_list->machine_status; $data3['zone'] = $prev_list->service_loc_id; $this->Service_model->add_service_details($data3); } } }/* else{ echo "Dummy"; } */ if($today == $prev_main_updated){ $data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); } } // Preventive Alerts for 6 Nos if($prenos=='6'){ if($prenos_cnt=="0"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 1st month. }else if($prenos_cnt=="1"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 2nd month. }else if($prenos_cnt=="2"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 3rd month. }else if($prenos_cnt=="3"){ $prev_date = date('Y-m-d', strtotime("+2 months", strtotime($prev_main_updated)));// To alert in 5th month. }else if($prenos_cnt=="4"){ $prev_date = date('Y-m-d', strtotime("+2 months", strtotime($prev_main_updated)));// To alert in 7th month. }else{ $prev_date = date('Y-m-d', strtotime("+2 months", strtotime($prev_main_updated)));// To alert in 9th month. } if($today == $prev_date){ //echo "DUMMMMMMYY"; if($prenos>$prenos_cnt){ //$data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); $count = $prenos_cnt+1; $data=array( 'prev_main_updated'=>$prev_date, 'prenos_cnt'=>$count ); $this->Service_model->update_preventive($data,$order_id); $data5['service_p_cnt']=$this->Service_model->service_p_cnt(); if(empty($data5['service_p_cnt'])){ $reqid='00001'; }else{ $cusid = $data5['service_p_cnt'][0]->request_id; $cusid1 = explode("-",$cusid); $dat= $cusid1['1'] + 1; $reqid=sprintf("%05d", $dat); } $data2['request_id'] = "P-".$reqid; $customer_id = $prev_list->customer_id; $data2['cust_name'] = sprintf("%05d", $customer_id); $data2['br_name'] = $prev_list->customer_service_loc_id; $data2['mobile'] = $prev_list->mobile; $data2['email_id'] = $prev_list->email_id; $data2['request_date'] = date('Y-m-d H:i:s', strtotime($prev_date)); $data2['status'] = "0"; $result=$this->Service_model->add_services($data2); $res = sprintf("%05d", $result); if($result){ $data3['request_id']=$res; $data3['serial_no'] = $prev_list->serial_no; $data3['cat_id'] = $prev_list->cat_id; $data3['subcat_id'] = $prev_list->subcat_id; $data3['brand_id'] = $prev_list->brand_id; $data3['model_id'] = $prev_list->model_id; $data3['warranty_date'] = $prev_list->warranty_date; $data3['amc_end_date'] = $prev_list->amc_end_date; $data3['machine_status'] = $machine_status; $data3['service_type'] = $prev_list->machine_status; $data3['zone'] = $prev_list->service_loc_id; $this->Service_model->add_service_details($data3); } } }/* else{ echo "Dummy"; } */ if($today == $prev_main_updated){ $data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); } } // Preventive Alerts for 12 Nos if($prenos=='12'){ if($prenos_cnt=="0"){ //echo "IINNN";exit; $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 1st month. }else if($prenos_cnt=="1"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 2nd month. }else if($prenos_cnt=="2"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 3rd month. }else if($prenos_cnt=="3"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 4th month. }else if($prenos_cnt=="4"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 5th month. }else if($prenos_cnt=="5"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 6th month. }else if($prenos_cnt=="6"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 7th month. }else if($prenos_cnt=="7"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 8th month. }else if($prenos_cnt=="8"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 9th month. }else if($prenos_cnt=="9"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 10th month. }else{ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 11th month. } if($today == $prev_date){ //echo "DUMMMMMMYY"; if($prenos>$prenos_cnt){ //$data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); $count = $prenos_cnt+1; $data=array( 'prev_main_updated'=>$prev_date, 'prenos_cnt'=>$count ); $this->Service_model->update_preventive($data,$order_id); $data5['service_p_cnt']=$this->Service_model->service_p_cnt(); if(empty($data5['service_p_cnt'])){ $reqid='00001'; }else{ $cusid = $data5['service_p_cnt'][0]->request_id; $cusid1 = explode("-",$cusid); $dat= $cusid1['1'] + 1; $reqid=sprintf("%05d", $dat); } $data2['request_id'] = "P-".$reqid; $customer_id = $prev_list->customer_id; $data2['cust_name'] = sprintf("%05d", $customer_id); $data2['br_name'] = $prev_list->customer_service_loc_id; $data2['mobile'] = $prev_list->mobile; $data2['email_id'] = $prev_list->email_id; $data2['request_date'] = $prev_date; $data2['status'] = "0"; $result=$this->Service_model->add_services($data2); $res = sprintf("%05d", $result); if($result){ $data3['request_id']=$res; $data3['serial_no'] = $prev_list->serial_no; $data3['cat_id'] = $prev_list->cat_id; $data3['subcat_id'] = $prev_list->subcat_id; $data3['brand_id'] = $prev_list->brand_id; $data3['model_id'] = $prev_list->model_id; $data3['warranty_date'] = $prev_list->warranty_date; $data3['amc_end_date'] = $prev_list->amc_end_date; $data3['machine_status'] = $machine_status; $data3['service_type'] = $prev_list->machine_status; $data3['zone'] = $prev_list->service_loc_id; $this->Service_model->add_service_details($data3); } } }/* else{ echo "Dummy"; } */ if($today == $prev_main_updated){ $data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); } } // Preventive Alerts for 5 Nos if($prenos=='5'){ if($prenos_cnt=="0"){ $prev_date = date('Y-m-d', strtotime("+1 months", strtotime($prev_main_updated)));// To alert in 1st month. }else if($prenos_cnt=="1"){ $prev_date = date('Y-m-d', strtotime("+2 months", strtotime($prev_main_updated)));// To alert in 3rd month. }else if($prenos_cnt=="2"){ $prev_date = date('Y-m-d', strtotime("+3 months", strtotime($prev_main_updated)));// To alert in 6th month. }else if($prenos_cnt=="3"){ $prev_date = date('Y-m-d', strtotime("+3 months", strtotime($prev_main_updated)));// To alert in 9th month. }else{ $prev_date = date('Y-m-d', strtotime("+2 months", strtotime($prev_main_updated)));// To alert in 11th month. } if($today == $prev_date){ //echo "DUMMMMMMYY"; if($prenos>$prenos_cnt){ //$data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); $count = $prenos_cnt+1; $data=array( 'prev_main_updated'=>$prev_date, 'prenos_cnt'=>$count ); $this->Service_model->update_preventive($data,$order_id); $data5['service_p_cnt']=$this->Service_model->service_p_cnt(); if(empty($data5['service_p_cnt'])){ $reqid='00001'; }else{ $cusid = $data5['service_p_cnt'][0]->request_id; $cusid1 = explode("-",$cusid); $dat= $cusid1['1'] + 1; $reqid=sprintf("%05d", $dat); } $data2['request_id'] = "P-".$reqid; $customer_id = $prev_list->customer_id; $data2['cust_name'] = sprintf("%05d", $customer_id); $data2['br_name'] = $prev_list->customer_service_loc_id; $data2['mobile'] = $prev_list->mobile; $data2['email_id'] = $prev_list->email_id; $data2['request_date'] = $prev_date; $data2['status'] = "0"; $result=$this->Service_model->add_services($data2); $res = sprintf("%05d", $result); if($result){ $data3['request_id']=$res; $data3['serial_no'] = $prev_list->serial_no; $data3['cat_id'] = $prev_list->cat_id; $data3['subcat_id'] = $prev_list->subcat_id; $data3['brand_id'] = $prev_list->brand_id; $data3['model_id'] = $prev_list->model_id; $data3['warranty_date'] = $prev_list->warranty_date; $data3['amc_end_date'] = $prev_list->amc_end_date; $data3['machine_status'] = $machine_status; $data3['service_type'] = $prev_list->machine_status; $data3['zone'] = $prev_list->service_loc_id; $this->Service_model->add_service_details($data3); } } }/* else{ echo "Dummy"; } */ if($today == $prev_main_updated){ $data1['preventive_req_list']=$this->Service_model->preventive_req_list1($prev_main_updated); } } } $this->load->view('templates/header',$data1); $this->load->view('service_req_list',$data1); } public function quote_in_progress_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['service_req_list']=$this->quote_in_progress_model->service_req_list($user_access,$user_type); $data1['service_req_list1']=$this->quote_in_progress_model->service_req_list1(); $data1['service_req_listforEmp']=$this->quote_in_progress_model->service_req_listforEmp(); $data1['status_list']=$this->quote_in_progress_model->status_list(); $data1['combine_status_list']=$this->quote_in_progress_model->combine_status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quote_in_progress_list',$data1); } public function quote_review(){ $data1['quote_review_req_list']=$this->quote_review_model->quote_review_req_list(); $data1['service_req_list1']=$this->quote_review_model->service_req_list1(); $data1['service_req_listforEmp']=$this->quote_review_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->quote_review_model->service_req_listforProb(); //$data1['combine_status_list']=$this->Service_model->combine_status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quote_review',$data1); } public function quote_approved(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['quote_approved_list']=$this->quote_approved_model->quote_approved_list($user_access,$user_type); $data1['service_req_list1']=$this->quote_approved_model->service_req_list1(); $data1['service_req_listforEmp']=$this->quote_approved_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->quote_approved_model->service_req_listforProb(); //$data1['combine_status_list']=$this->Service_model->combine_status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quote_approved_list',$data1); } public function quote_review_view(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quote_review_view'); } public function workin_prog_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; $emp_id = $data1['user_dat'][0]->emp_id; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } if(isset($user_type) && $user_type=='7' && isset($emp_id) && $emp_id!="0"){ $data1['workin_prog_list']=$this->workin_prog_model->workin_prog_listbyempid($emp_id); }else{ $data1['workin_prog_list']=$this->workin_prog_model->workin_prog_list($user_access,$user_type); } //$data1['workin_prog_list']=$this->workin_prog_model->workin_prog_list($user_access,$user_type); $data1['service_req_list1']=$this->workin_prog_model->service_req_list1(); $data1['service_req_listforEmp']=$this->workin_prog_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->workin_prog_model->service_req_listforProb(); $data1['service_req_listforserviceCat']=$this->workin_prog_model->service_req_listforserviceCat(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('workin_prog_list',$data1); } public function comp_engg_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; $emp_id = $data1['user_dat'][0]->emp_id; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } if(isset($user_type) && $user_type=='7' && isset($emp_id) && $emp_id!="0"){ $data1['workin_prog_list']=$this->workin_prog_model->comp_engg_byempid($emp_id); }else{ $data1['workin_prog_list']=$this->workin_prog_model->comp_engg_list($user_access,$user_type); } $data1['service_req_list1']=$this->workin_prog_model->service_req_list1(); $data1['service_req_listforEmp']=$this->workin_prog_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->workin_prog_model->service_req_listforProb(); $data1['service_req_listforserviceCat']=$this->workin_prog_model->service_req_listforserviceCat(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('comp_engg_list',$data1); } public function quality_check_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['workin_prog_list']=$this->quality_check_model->quality_check_list($user_access,$user_type); $data1['service_req_list1']=$this->quality_check_model->service_req_list1(); $data1['service_req_listforEmp']=$this->quality_check_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->quality_check_model->service_req_listforProb(); $data1['service_req_listforserviceCat']=$this->quality_check_model->service_req_listforserviceCat(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quality_check_list',$data1); } public function ready_delivery_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['ready_delivery_list']=$this->ready_delivery_model->ready_delivery_list($user_access,$user_type); $data1['service_req_list1']=$this->ready_delivery_model->service_req_list1(); $data1['service_req_listforEmp']=$this->ready_delivery_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->ready_delivery_model->service_req_listforProb(); $data1['service_req_listforserviceCat']=$this->ready_delivery_model->service_req_listforserviceCat(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('ready_delivery_list',$data1); } public function sparerequest(){ $data1['get_spare_request'] = $this->Spare_model->get_spare_request(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('sparerequest',$data1); } public function workin_prog_view(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('workin_prog_view'); } public function delivered_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } $data1['delivery_list']=$this->delivery_model->delivery_list($user_access,$user_type); $data1['service_req_list1']=$this->delivery_model->service_req_list1(); $data1['service_req_listforEmp']=$this->delivery_model->service_req_listforEmp(); $data1['service_req_listforProb']=$this->delivery_model->service_req_listforProb(); $data1['service_req_listforserviceCat']=$this->delivery_model->service_req_listforserviceCat(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('delivered_list',$data1); } public function delivered_view(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('delivered_view'); } public function add_spare(){ $data1['sparelist']=$this->Spare_model->sparelist(); $data1['sparelist1']=$this->Spare_model->sparelist1(); $data1['getmodels']=$this->Spare_model->getmodels(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_spare',$data1); } public function spare_stock(){ $data1['spare_stock']=$this->Spare_model->sparelist1(); $data1['sparelist_engg']=$this->Spare_model->sparelist_engg(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spare_stock',$data1); } public function add_new_stock(){ $data1['modellist']=$this->Spare_model->modellist(); $data1['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_new_stock',$data1); } public function expiry_list(){ //$date1 = date('Y-m-d'); //$data1['expiry_list']=$this->Order_model->expiry_list($date1); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('expiry_list'); } public function expiry_closed(){ $data1['expiry_closed']=$this->Order_model->expiry_closed(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('expiry_closed',$data1); } public function add_brand(){ $data1['prodcatlist']=$this->Brand_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Brand_model->prod_sub_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_brand',$data1); } public function brandList(){ $data1['brand_list']=$this->Brand_model->brand_list(); $data1['catlist']=$this->Brand_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Brand_model->prod_sub_cat_dropdownlist(); //$data1['droplists']=$this->Brand_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('brandList',$data1); } public function add_tax(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_tax'); } public function tax_list(){ $data1['tax_list']=$this->Tax_model->tax_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('tax_list',$data1); } public function add_spare_engineers(){ $data1['customerlist']=$this->Spare_model->customerlist(); $data1['spare_list']=$this->Spare_model->spare_list_engineers(); $data1['engg_list']=$this->Spare_model->engineer_list(); $data1['reqview']=$this->Spare_model->reqlist(); $data1['cust_cnt']=$this->Customer_model->cust_cnt(); if(empty($data1['cust_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['cust_cnt'][0]->id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spare_engineers',$data1); } public function sparereceipt(){ $data1['receipt'] = $this->Spare_model->getspareengg(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spareengreceipt',$data1); } public function spare_purchase_order(){ date_default_timezone_set('Asia/Calcutta'); $data1['todaydate'] = date("d-m-Y H:i:s"); $data1['comp_info'] = $this->Spare_model->get_compinfo(); $data1['spare_list']=$this->Spare_model->spare_list_engineers(); $data1['tax_list']=$this->Spare_model->tax_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spare_purchase_order',$data1); } public function purchase_orders(){ $data1['get_purchase_orders'] = $this->Spare_model->get_purchase_orders(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('purchase_orders',$data1); } public function min_spare_alerts(){ $data1['get_min_spares'] = $this->Spare_model->get_min_spares(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('min_spare_alerts',$data1); } public function cust_type(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_cust_type'); } public function cust_type_list(){ $data1['cust_type_list']=$this->Customer_model->cust_type_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('cust_type_list',$data1); } public function report_list(){ $m_data['model']=$this->Report_model->modellist(); $m_data['product']=$this->Report_model->procatlist(); //$m_data['custom']=$this->Report_model->custlist(); $m_data['engineer']=$this->Report_model->engnamelist(); $m_data['status_list']=$this->Report_model->status_list(); $m_data['area_list']=$this->Report_model->area_list(); $m_data['brand_list']=$this->Report_model->brand_list(); $m_data['service_zone']=$this->Report_model->zonelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('report_view',$m_data); } public function sparereport_list(){ $m_data['enggname_list']=$this->Report_model->engnamelist(); $m_data['sparename_list']=$this->Report_model->sparenamelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('sparereport_list',$m_data); } public function sparepurchase_list(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('sparepurchase_list'); } public function agingreport(){ $m_data['model']=$this->Report_model->modellist(); $m_data['product']=$this->Report_model->procatlist(); $m_data['custom']=$this->Report_model->custlist(); $m_data['engineer']=$this->Report_model->engnamelist(); $m_data['zone']=$this->Report_model->zonelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('agingreport_list',$m_data); } public function revenuereport() { $m_data['model']=$this->Report_model->modellist(); $m_data['product']=$this->Report_model->procatlist(); //$m_data['custom']=$this->Report_model->custlist(); $m_data['engineer']=$this->Report_model->engnamelist(); $m_data['status_list']=$this->Report_model->status_list(); $m_data['area_list']=$this->Report_model->area_list(); $m_data['brand_list']=$this->Report_model->brand_list(); $m_data['service_zone']=$this->Report_model->zonelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('revenuereport_list',$m_data); } public function purchase_report() { $m_data['model']=$this->Report_model->modellist(); $m_data['product']=$this->Report_model->procatlist(); //$m_data['custom']=$this->Report_model->custlist(); $m_data['location_list']=$this->Report_model->location_list(); $m_data['service_zone']=$this->Report_model->zonelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('purchase_report',$m_data); } public function service_mach_report() { $m_data['model']=$this->Report_model->modellist(); $m_data['product']=$this->Report_model->procatlist(); $m_data['cust_type_list']=$this->Report_model->cust_type_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_mach_report',$m_data); } public function expiry_list1(){ //$date1 = date('Y-m-d'); //$data1['expiry_list']=$this->Order_model->expiry_list($date1); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('expiry_list1'); } public function sparecharge_list(){ //$m_data['enggname_list']=$this->Report_model->engnamelist(); $m_data['sparename_list']=$this->Report_model->sparenamelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('sparecharge_list',$m_data); } public function engineerreport_list(){ $m_data['enggname_list']=$this->Report_model->engnamelist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engineerreport_list',$m_data); } public function engineer_servicereport_list(){ $m_data['enggname_list']=$this->Report_model->engnamelist(); $m_data['status_list']=$this->Report_model->engg_status_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('engineer_servicereport_list',$m_data); } public function stampingreport_list(){ $m_data['employee']=$this->Report_model->emp_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('stampingreport',$m_data); } public function monthlyreport_list(){ //$m_data['employee']=$this->stampingreport_model->emp_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('monthlyreport_list'); } public function serial_list() { $data1['serial_list']=$this->Report_model->get_serial(); $data1['model']=$this->Report_model->modellist(); $data1['customer']=$this->Report_model->custlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('serialreport_list'); } public function customerreport_list(){ $data1['zone']=$this->Report_model->service_zone_list(); $data1['customer_type']=$this->Report_model->cust_type_list(); $data1['product']=$this->Report_model->product_list(); //$m_data['employee']=$this->stampingreport_model->emp_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('customerreport_list',$data1); } public function add_user_cate(){ $data1['get_categories']=$this->User_model->get_categories(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_user_cate',$data1); } public function user_cate_list(){ $data1['get_users']=$this->User_model->get_users(); $data1['get_categories']=$this->User_model->get_categories(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header', $data1); $this->load->view('user_cate_list', $data1); } } <file_sep>/application/controllers/Tax.php <?php class tax extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Tax_model'); } public function add_tax(){ $tax_name=$this->input->post('tax_name'); $percentage=$this->input->post('percentage'); $c=$tax_name; $count=count($c); for($i=0; $i<$count; $i++) { if($tax_name[$i]!=""){ $data1 = array('tax_name' => $tax_name[$i], 'tax_percentage' => $percentage[$i]); $result=$this->Tax_model->add_tax($data1); } else{ echo "<script>alert('Please Enter Tax');window.location.href='".base_url()."pages/tax_list';</script>"; } } if(isset($result)){ echo "<script>alert('Tax Added Successfully!!!');window.location.href='".base_url()."pages/tax_list';</script>"; } } public function update_tax(){ $id=$this->input->post('id'); $data=array( 'tax_name'=>$this->input->post('tax_name'), 'tax_percentage'=>$this->input->post('tax_percent') ); $s = $this->Tax_model->update_tax_info($data,$id); } public function update_default(){ $id=$this->input->post('id'); $data=array( 'tax_default'=>$this->input->post('tax_default') ); $s = $this->Tax_model->update_tax_default($data,$id); } public function del_tax(){ $id=$this->input->post('id'); $s = $this->Tax_model->del_tax_info($id); } public function check_tax() { $data = $this->input->post('tax'); //echo $data;exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Tax_model->checktaxname($data))); } public function Inactive_tax_list(){ //$id=$this->input->post('id'); //$this->Customer_model->del_customer_type($id); $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Tax_model->update_tax_list($data,$id); // echo "<script>alert('Customer Type Inactive');window.location.href='".base_url()."';</script>"; //redirect('pages/tax_list'); } public function active_cust_type(){ //$id=$this->input->post('id'); //$this->Customer_model->del_customer_type($id); $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Tax_model->update_status_customer1($data,$id); // echo "<script>alert('Customer Type Inactive');window.location.href='".base_url()."';</script>"; } public function add_taxrow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_tax',$data); } }<file_sep>/application/views/add_cust_type.php <style> .tableadd tr td input { width:234px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 2px; padding-left: 10px; margin-left: 13px; } .tableadd tr td input { height: 21px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .btn { display: inline-block; padding: 0px 0px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } </style> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($(".firstname").val()==""){ $("#lname1").text("Enter Customer Type").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $(".firstname").keyup(function(){ if($(this).val()==""){ $("#lname1").show(); } else{ $("#lname1").hide(); } }) }); </script> <script> $(document).ready(function(){ $('#addRowBtn1').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/add_custtyperow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $(document).on("keyup","#UserName1", function(){ var timer1; clearTimeout(timer1); timer1 = setTimeout(brand1, 3000); }); //alert("hii"); function brand1(){ var id=$("#UserName1").val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/custtype_validation", data: datastring, cache: false, success: function(data) { //alert(data); if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Customer Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#UserName1').val(''); return false; } } }); } }); </script> <style> body{background-color:#fff;} .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } .waves-light { text-transform:capitalize !important; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Customer Type</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/add_customer_type" method="post"> <table id="myTable" class="tableadd"> <div class="col-md-3 col-sm-6 col-xs-12"> <label><font color="red">*</font>Customer Type</label> <input type="text" name="cust_type[]" id="UserName1" class="firstname" maxlength="30"> <div class="fname" id="lname1" style="color:red"></div> </div> <a class="link" id="addRowBtn1"><i class="fa fa-plus-square" aria-hidden="true" style="margin-top: 30px;color:#5f3282;"></i></a> </table> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action" style="padding: 7px 10px 10px 10px; margin-left: 20px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> <input type="hidden" id="countid" value="1"> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/controllers/Employee.php <?php class Employee extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Employee_model'); } public function add_employee(){ $eid=$this->input->post('emp_id'); $chk_emp=$this->Employee_model->check_emp($eid); if(empty($chk_emp)){ $data['emp_id']=$this->input->post('emp_id'); $data['emp_name']=$this->input->post('emp_name'); $data['emp_designation']=$this->input->post('emp_designation'); //echo "Hello: ".$this->input->post('emp_stamping'); /* if($this->input->post('emp_stamping')=='1'){ $data['emp_stamping'] = '1'; }else{ $data['emp_stamping'] = '0'; } */ $data['emp_mobile']=$this->input->post('emp_mobile'); $data['emp_email']=$this->input->post('emp_email'); $data['emp_edu']=$this->input->post('emp_edu'); $data['emp_exp']=$this->input->post('emp_exp'); $data['doj']=$this->input->post('doj'); $data['emp_addr']=$this->input->post('emp_addr'); $data['emp_addr1']=$this->input->post('emp_addr1'); $data['emp_city']=$this->input->post('emp_city'); $data['emp_state']=$this->input->post('emp_state'); $data['emp_pincode']=$this->input->post('emp_pincode'); $zone=$this->input->post('zone'); //print_r($zone);exit; for($r=0;$r<count($zone);$r++){ $zonee[]=$zone[$r]; } $zonename=implode(',',$zonee); //echo $zonename;exit; //print_r(implode(',',$zonee));exit; $data['service_zone']=$zonename; $data2['city']=$this->input->post('emp_city'); $this->Employee_model->add_city($data2); $result=$this->Employee_model->add_emp($data); $res = sprintf("%05d", $result); if($result){ redirect(base_url().'pages/service_skill/'.$res); } } } public function add_service_skill(){ //echo "<pre>";print_r($_POST); $ids=$this->input->post('ids'); $ser_skill_empid=$this->input->post('empid'); $ser_skill_pcategory=$data['p_category']=$this->input->post('p_category'); $ser_skill_subcategory=$data['sub_category']=$this->input->post('sub_category'); $ser_skill_brand=$data['brand']=$this->input->post('brand'); $ser_skill_pmodel=$data['p_model']=$this->input->post('p_model'); $data['service_cat']=$this->input->post('service_cat'); $c=$ser_skill_pcategory; $count=count($c); $i=0; foreach($ids as $idd){ $data['service_cat']['cat'] = $this->input->post('service_cat'.$idd); //$service_category = implode(",",$data['service_cat']['cat']); if (is_array($data['service_cat']['cat'])){ $service_category = implode(",",$data['service_cat']['cat']); }else{ $service_category=""; } $data1 =array(); $data1[] = array( 'empid' => $ser_skill_empid, 'p_category' => $ser_skill_pcategory[$i], 'sub_category' => $ser_skill_subcategory[$i], 'brand' => $ser_skill_brand[$i], 'p_model' => $ser_skill_pmodel[$i], 'service_category'=>$service_category ); $result=$this->Employee_model->add_service($data1); $i++; } if($result){ redirect(base_url().'pages/emp_list'); } } public function update_employee(){ $id=$this->uri->segment(3); $data['list']=$this->Employee_model->getemployeebyid($id); $data['empservicelist']=$this->Employee_model->getemployeeserviceskillbyid($id); $data['service_zone_list']=$this->Employee_model->service_zone_list(); $data['state_list']=$this->Employee_model->state_list(); $data['plist']=$this->Employee_model->product_list(); $data['servicecatlist']=$this->Employee_model->service_cat_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_emp_list',$data); } public function edit_employee(){ ini_set('max_input_vars', 3000); /* if($this->input->post('emp_stamping')=='1'){ $stamps = '1'; }else{ $stamps = '0'; } */ $zone=$this->input->post('zone'); //print_r($zone);exit; for($r=0;$r<count($zone);$r++){ $zonee[]=$zone[$r]; } $zonename=implode(',',$zonee); $data=array( 'emp_id'=>$this->input->post('emp_id'), 'emp_name'=>$this->input->post('emp_name'), 'emp_designation'=>$this->input->post('emp_designation'), 'emp_mobile'=>$this->input->post('emp_mobile'), 'emp_email'=>$this->input->post('emp_email'), 'emp_edu'=>$this->input->post('emp_edu'), 'emp_exp'=>$this->input->post('emp_exp'), 'doj'=>$this->input->post('doj'), 'emp_addr'=>$this->input->post('emp_addr'), 'emp_addr1'=>$this->input->post('emp_addr1'), 'emp_city'=>$this->input->post('emp_city'), 'emp_state'=>$this->input->post('emp_state'), 'emp_pincode'=>$this->input->post('emp_pincode'), 'service_zone'=>$zonename ); $id=$this->input->post('empid'); $data3['city']=$this->input->post('emp_city'); $this->Employee_model->add_city($data3); $this->Employee_model->update_employee($data,$id); $ser_skill_empid=$this->input->post('empid'); $ids=$this->input->post('ids'); $ser_skill_pcategory=$data1['p_category']=$this->input->post('p_category'); $ser_skill_subcategory=$data1['sub_category']=$this->input->post('sub_category'); $ser_skill_brand=$data1['brand']=$this->input->post('brand'); $ser_skill_pmodel=$data1['p_model']=$this->input->post('p_model'); $data1['service_cat']=$this->input->post('service_cat'); $this->Employee_model->delete_employee_service_skill($ser_skill_empid); $c=$ser_skill_pcategory; $count=count($c); $i=0; foreach($ids as $idd){ $data1['service_cat']['cat'] = $this->input->post('service_cat'.$idd); if (is_array($data1['service_cat']['cat'])){ $service_category = implode(",",$data1['service_cat']['cat']); }else{ $service_category=""; } $data1 =array(); $data1[] = array( 'empid' => $ser_skill_empid, 'p_category' => $ser_skill_pcategory[$i], 'sub_category' => $ser_skill_subcategory[$i], 'brand' => $ser_skill_brand[$i], 'p_model' => $ser_skill_pmodel[$i], 'service_category'=>$service_category ); $result=$this->Employee_model->add_service($data1,$idd); $i++; } echo "<script>alert('Employee Updated Successfully!!!');window.location.href='".base_url()."pages/emp_list';</script>"; } public function get_city(){ $id=$this->input->post('keyword');//echo $id; exit; //$data['city_list']=$this->Employee_model->get_cities($id); //$this->load->view('city_list',$data); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Employee_model->get_cities($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_employee(){ $id=$this->input->post('id'); $s = $this->Employee_model->del_emp($id); } public function mobile_validation() { //print_r($_POST); exit; $mobile= $this->input->post('id'); $this->output->set_content_type("application/json")->set_output(json_encode($this->Employee_model->mobile_validation($mobile))); } }<file_sep>/application/views/expiry_closed.php <script> function DelStatus(id){ var r=confirm("Are you sure want to delete?"); if (r==true) { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>order/del_order', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ window.location = "<?php echo base_url(); ?>pages/expiry_closed"; alert("Order Deleted Successfully!!!"); } }); } } </script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 8px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; border:1px solid #dbd0e1 !important; /*background-color: white;*/ } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; /*color: #303f9f;*/ background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} a{ color:#522276; } a:hover{ color:#522276; } a:active{ color:#522276; } a:focus{ color:#522276; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Chargeable List</h2> <a href="<?php echo base_url(); ?>pages/add_order"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Sales" style="position: relative;float: right;bottom: 27px;right: 22px;"></i></a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th class="hidden">ID</th> <!--<th>Customer ID</th>--> <th>S.No</th> <th>Customer Name</th> <!--<th>Branch</th>--> <!--<th>Type Of Customer</th>--> <th>Model</th> <th>Serial No.</td> <th>Purchase Date</th> <th>Warranty Date</th> <th>AMC Date</th> <th>Location</th> <th style="width: 8% !important;">Action</th> </tr> </thead> <tbody> <?php $i=1; foreach($expiry_closed As $key){?> <tr> <td class="hidden"><?php echo $key->id;?></td> <!--<td><?php echo $key->customer_id; ?></td>--> <td><?php echo $i; ?></td> <td><?php echo $key->company_name; ?></td> <td><?php echo $key->model; ?></td> <td><?php echo $key->serial_no;?></td> <td><?php echo $key->purchase_date; ?></td> <td><?php if($key->warranty_date!=""){echo $key->warranty_date;}elseif($key->prev_main!=""){echo $key->prev_main;}//$key->warranty_date; ?></td> <td><?php if($key->amc_type!=""){echo $key->amc_end_date;} ?></td> <td><?php echo $key->service_loc; ?></td> <td><a href="<?php echo base_url(); ?>order/update_order/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a> <a href="<?php echo base_url(); ?>order/view_order/<?php echo $key->id; ?>" title="View" style="padding-right:10px;" ><i class="fa fa-eye fa-2x"></i></a> <a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a> </td> </tr> <?php $i++; } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/brand_add.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link href="js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type='text/javascript' src='js/addrow.js'></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { border-radius:5px; /* margin-bottom: 25px !important;*/ } .tableadd tr td input { width: 215px; } .tableadd { margin-bottom:35px; } .tableadd tr td label { font-weight:bold; } </style> </head> <body> <div id="loader-wrapper"> <!-- <div id="loader"></div> --> <div class="loader-section section-left"></div> <div class="loader-section section-right"></div> </div> <header id="header" class="page-topbar"> <?php include('header.php'); ?> </header> <div id="main"> <div class="wrapper"> <?php include('menu.php'); ?> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Add Product Brand Name</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form > <table id="myTable" class="tableadd"> <tr><td><label>Category Name</label></td><td><label>Sub-Category Name</label></td><td><label>Brand Name</label></td></tr> <tr> <td> <select > <option value="">---Select---</option> <option value="Motorola">Air Conditioner</option> <option value="<NAME>">Television</option> <option value="Nokia">Digital Camera</option> <option value="Apple">Mobile Phone</option> <option value="Samsung">Cash Counting Machine</option> <option value="Samsung">Washing Machine</option> </select></td><td> <select > <option value="">---Select---</option> <option value="Motorola">SubCategory 1</option> <option value="<NAME>">SubCategory 2</option> <option value="Nokia">SubCategory 3</option> <option value="Apple">SubCategory 4</option> <option value="Samsung">SubCategory 5</option> <option value="Samsung">SubCategory 6</option> </select></td> <td><input type="text" value="" name=""></td> </tr> </table> <a class="link" href='' onclick='$("<tr><td><select ><option value=\"\">---Select---</option><option value=\"Motorola\">Air Conditioner</option><option value=\"<NAME>\">Television</option> <option value=\"Nokia\">Digital Camera</option><option value=\"Apple\">Mobile Phone</option><option value=\"Samsung\">Cash Counting Machine</option><option value=\"Samsung\">Washing Machine</option></select></td><td><select ><option value=\"\">---Select---</option><option value=\"\">SubCategory 1</option><option value=\"\">SubCategory 2</option> <option value=\"\">SubCategory 3</option><option value=\"\">SubCategory 4</option><option value=\"\">SubCategory 5</option><option value=\"\">SubCategory 6</option></select></td> <td><input type=\"text\" value=\"\" name=\"\"></td></tr>").appendTo($("#myTable")); return false;'>Add SubCategory</a><button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="js/materialize.js"></script> <script type="text/javascript" src="js/prism.js"></script> <script type="text/javascript" src="js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> </body> </html><file_sep>/application/models/Stampingreportmodel.php <?php class Report_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } }<file_sep>/application/views/pdf_view.php <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-right:20px; } .link:hover { color:black; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 170px; margin: auto auto 35px; } h6 { font-weight: bold; font-size: 16px; margin: 0px; border-bottom: 1px solid gray; width: 145px; margin-top:2%; } #rowadd { border: 1px solid #055E87 !important; background: #093F88 none repeat scroll 0% 0% !important; padding: 6px; border-radius: 5px; color: #FFF; font-weight: bold; font-family: calibri; font-size: 17px; margin-left: 47%; } .tableadd tr td{ height:40px; } .right p { line-height:5px; font-size: 12px; } .right h1 { line-height:5px; } .toaddress h4 { line-height:5px; } .toaddress p { line-height: 5px; margin-left: 2%; } .toaddress { margin-bottom: 25px; margin-top: 20px; } .subject { /*margin-left:30px;*/ } .box{ display: none; box-shadow:none !important; } .comprehensive { display:block; } .message p { /*text-indent: 30px;*/ text-align:justify; } .message p.dear { text-indent: 0px; } input { border: 1px solid #093F88; border-radius: 3px; } table tr td { width:150px; height:30px; } table tr td.dot { width:50px; } table tr td.bank { width:350px; } table tr td.bank .address { margin-right:20px; } table { margin-left: 10%; } b { text-decoration:underline; } .service { width:400px; } .service b { font-weight:normal; text-decoration:none; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="comprehensive"){ $(".box").not(".comprehensive").hide(); $(".comprehensive").show(); } if($(this).attr("value")=="service_only"){ $(".box").not(".service_only").hide(); $(".service_only").show(); } }); }); </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("#fromdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#todate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#startdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#enddate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }//]]> </script> <section id="content"> <div class="container"> <div class="section"> <div id="reportheader" > <div class="left" style="float:left;width:20%;"> <img src="../../assets/images/maxsell-logo1.png" style="width:190px; margin-top: 14px;"> </div> <div class="right" style="float:right;width:79%; text-align:center;"> <h1 class="headingprint breadcrumbs-title" style="font-size:18px;">Arihant Marketing</h1> <p>10, Gowdia Mutt Road,Royapettah,Chennai - 600014,Tamilnadu, India</p> <p>Tel:+91 44 2813 1159 / 69, Fax:+91 44 2813 2111</p> </div> <div style="height:13%;border-bottom:1px dashed gray; "></div> </div> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>createpdf/pdf" method="post" name="frmServiceStatus"> <div id="errorBox"></div> <?php error_reporting(0); $servername = "localhost"; $username = "srscales_srscalesuser"; $password = "<PASSWORD>"; $dbname = "srscales_serviceEff"; $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT ord.id,cust.customer_name,cust.customer_id,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ser_loc.service_loc, ( CASE WHEN ordt.warranty_date!='' THEN 'Warranty' WHEN ordt.prev_main!='' THEN 'Preventive' WHEN ordt.paid!='' THEN 'Paid' ELSE 1 END) AS machine_status FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE ord.id ='$id'"); while($res = mysql_fetch_array($qry)){ $customer_id = $res['customer_id']; $customer_name = $res['customer_name']; $model = $res['model']; $purchase_date = $res['purchase_date']; $warranty_date = $res['warranty_date']; $service_loc = $res['service_loc']; $machine_status = $res['machine_status']; } ?> <!--<table class="tableadd"> <tr> <td><label>Customer Name</label></td><td><input type="text" name="cust_name" class="email" value="<?php echo $customer_name; ?>"><input type="hidden" name="orderid" class="email" value="<?php echo $id; ?>"><input type="hidden" name="custid" class="email" value="<?php echo $customer_id; ?>"></td><td><label>Machine Status</label></td><td><input type="text" name="machine_status" id="machine_status" class="adress" value="<?php echo $machine_status; ?>"></td> </tr> <tr> <td><label>Machine Model</label></td><td><input type="text" name="model" class="email" value="<?php echo $model; ?>"></td><td><label>Charge</label></td><td><input type="text" name="charge" class="email" value=""></td> </tr> <tr> <td><label>AMC From date</label></td><td><input type="text" name="amc_frmdate" id="fromdate" class="date"></td><td><label>AMC To date</label></td><td><input type="text" name="amc_todate" id="todate" class="date"></td> </tr> </table>--> <p style="float:right;">Date:24/11/2015</p> <div class="toaddress"> <b>To:</b> <div> <p>Customer Name</p> <p>Address 1</p> <p>Address 2</p> </div> </div> <div class="subject"> <p><b>Attention:</b> Mr.Contact Name</p> <p><b>Sub:</b> AMC for <input type="text" name="" class="" value="" placeholder="Product">-<input type="text" name="" class="" value="" placeholder="Model No"> Purchased on <input type="text" id="fromdate" class="date" value="" ></p> </div> <div class="message"> <p class="dear"><b>Dear Sir/Madam:</b></p> <p>We thank you for your continued patronage to our products.It has been our pleasure to serve you and we always endeavour to put our best foot forward, which serving you.We hope that we have been able to satisfy your requirements.</p> <p>In order to maintain the above instruction prime condition for your use, we hereby extend our AMC services for <input type="text" name="" class="" value=""></p> <p>The current service contract expires on <input type="text" id="todate" class="date" value="">. We recommend that you renew service contract, which will prevent operation failure and also wear & tear of the instrument. Details of the AMC package are as follows:</p> <table> <tr> <td><label>Service Type</label></td><td class="dot">:</td><td class="service"><input type="radio" name="type" class="" checked="checked" value="comprehensive"><b>Comprehensive</b><input type="radio" name="type" class="" value="service_only"><b>Service Only</b></td> </tr> <tr> <td><label>Service Cost</label></td><td class="dot">:</td><td><input type="text" name="" class="" value=""></td> </tr> <tr> <td><label>AMC Start Date</label></td><td class="dot">:</td><td><input type="text" name="" class="" value="" id="startdate"></td> </tr> <tr> <td><label>AMC End Date</label></td><td class="dot">:</td><td><input type="text" name="" class="" value="" id="enddate"></td> </tr> <tr> <td><label>No of preventive maintenance</label></td><td class="dot">:</td><td><input type="text" name="" class="" value="" id="enddate"></td> </tr> </table> <p>Please confirm the AMC Quotation by return email and remit the AMC charges to the bank as follows:</p> <table> <tr> <td><label>Bank Name</label></td><td class="dot">:</td><td><input type="text" name="" class="" value=""></td> </tr> <tr> <td><label>Bank Address & City</label></td><td class="dot">:</td><td class="bank"><input type="text" name="" class="address" value="" ><input type="text" name="" class="city" value="" ></td> </tr> <tr> <td><label>IFSC (RTGS)</label></td><td class="dot">:</td><td><input type="text" name="" class="" value="" id="enddate"></td> </tr> <tr> <td><label>A/C No</label></td><td class="dot">:</td><td><input type="text" name="" class="" value="" id="enddate"></td> </tr> </table> <table></table> </div> <p class="dear"><b>Terms & Conditions:</b></p> <ul class="comprehensive box"> <li>This is covers all services including Spare parts replacement and its cost along with conveyances & services charges.</li> <li>Only machine will be covered under AMC .Online UPS , Isolation transformer and battery service will not be covered.</li> <li>Preventive maintenance appointment will be scheduled as per our Engineers/Maintenance plan.</li> </ul> <ul class="service_only box"> <li>This is covers all services no spare parts replacement and its cost along with conveyances & services charges.</li> <li>Only machine will be covered under AMC .Online UPS , Isolation transformer and battery service will not be covered.</li> <li>Preventive maintenance appointment will be scheduled as per our Engineers/Maintenance plan.</li> </ul> <br/><br/> <button class="btn cyan waves-effect waves-light " type="submit" id="rowadd">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!-- <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script>--> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> </body> </html><file_sep>/application/views_bkMarch_0817/expiry_list1.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url() ?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('export', 'W3C Example Table')"> <img src="<?php echo base_url() ?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <?php $h=0; $count=0; ?> <style> body{background-color:#fff;} table.display { margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Warranty Expiring Report</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="export" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>S.No</th> <th>Customer Name</th> <th>Branch</th> <th>Model</th> <th>Serial No.</th> <th>Purchase Date</th> <th>Warranty Date</th> <th>Preventive Maintenance End Date</th> <th>Location</th> <!--<th>Action</th>--> <!--<th>Action</th>--> </tr> </thead> <tbody> <?php error_reporting(0); $servername = "localhost"; $username = "syndinzg_service"; $password = "<PASSWORD>"; $dbname = "syndinzg_service"; /* $servername = "localhost"; $username = "root"; $password = ""; $dbname = "srscales"; */ /* $servername = "localhost"; $username = "sellejyp_servmax"; $password = "<PASSWORD>"; $dbname = "sellejyp_service_maxsell"; */ $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT ord.id,cust.customer_name,cust.company_name ,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ordt.amc_type,ordt.serial_no,ser_loc.service_loc, csl.branch_name, csl.id As csl_id FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join customer_service_location As csl ON csl.id=ord.customer_service_loc_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE (datediff(ordt.warranty_date, date(now())) <= 30 and datediff(ordt.warranty_date, date(now())) >= 0 and ordt.amc_end_date='' and ordt.paid='') or (datediff(ordt.prev_main, date(now())) <= 30 and datediff(ordt.prev_main, date(now())) >= 0 and ordt.amc_end_date='' and ordt.paid='') or (datediff(ordt.amc_end_date, date(now())) <= 30 and datediff(ordt.amc_end_date, date(now())) >= 0 and ordt.paid='')"); $i=1; while($res = mysql_fetch_array($qry)) { ?> <tr> <td><?php echo $i; ?></td> <td><?php echo $res['company_name'];?><input type="hidden" name="order_id" id="order_id" value="<?php echo $res['id'];?>"></td> <td><?php echo $res['branch_name'];?></td> <td><?php echo $res['model']; ?></td> <td><?php echo $res['serial_no']; ?></td> <td><?php if($res['purchase_date']!=""){echo date("d-m-Y", strtotime($res['purchase_date']));} ?></td> <td><?php if($res['warranty_date']!=""){echo date("d-m-Y", strtotime($res['warranty_date']));} ?></td> <td><?php if($res['prev_main']!=""){echo date("d-m-Y", strtotime($res['prev_main']));} ?></td> <td><?php echo $res['service_loc'];?></td> <!--<td><a href="<?php echo base_url(); ?>createpdf/pdf/<?php echo $res['id'];?>" target="_blank">AMC Quotation</a></td>--> <!--<td><a class="fancybox-manual-b" href="javascript:;" id="amcquote_<?php echo $res['id'].'-'.$res['csl_id'];?>">AMC Quotation</a></td>--> <!--<td class="options-width"> <a href="#" style="padding-left:15px;" ><i class="fa fa-floppy-o fa-2x"></i></a> </td>--> </tr> <?php $i++; } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); $(document).ready(function() { $(".fancybox-manual-b").click(function() { //alert($("#order_id").val()); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var orderid = arr['1']; //alert(orderid); $.fancybox.open({ href : '<?php echo base_url(); ?>createpdf/pdf_view/'+orderid, type : 'iframe', padding : 5 }); }); }); </script> <script> $(document).ready(function(){ $('[id^="stats_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split('-'); var orderid = arr['0']; var amc_type = arr['1']; if(amc_type=="Comprehensive" || amc_type=="serviceonly"){ $.fancybox.open({ href : '<?php echo base_url(); ?>order/update_amc_type/'+orderid+'/'+amc_type, type : 'iframe', padding : 5 }); } if(amc_type=="Close"){ var status = 'paid'; var data_String; data_String = 'id='+orderid+'&status='+status; $.post('<?php echo base_url(); ?>order/update_stats',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Product Closed"); //$('#actaddress').val(data.Address1), }); } }); }); </script> </body> </html><file_sep>/application/views_bkMarch_0817/customerreport_data.php <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <style> table.display { margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } </style> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url() ?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('example', 'W3C Example Table')"> <img src="<?php echo base_url() ?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="example" class="responsive-table display" cellspacing="0" > <thead> <tr> <th>S.No</th> <th>Customer Name</th> <th>Type Of Customer</th> <th>Contact Name</th> <th>Mobile</th> <th>Email ID</th> <th>Address</th> <th>Address1</th> <th>City</th> <th>Zone</th> </tr> </thead> <tbody> <?php if(!empty($customerreport)) { $i=1; foreach($customerreport as $row) { ?> <tr> <td><?php echo $i;?></td> <td><?php echo $row->company_name;?></td> <td><?php echo $row->customertype;?></td> <td><?php echo $row->customer_name;?></td> <td><?php echo $row->mobile;?></td> <td><?php echo $row->email_id;?></td> <td><?php echo $row->address;?></td> <td><?php echo $row->address1;?></td> <td><?php echo $row->city;?></td> <td><?php echo $row->service_loc;?></td> </tr> <?php $i++; } } else { echo "<h4 align='center'>No Data Available</h4>"; } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script><file_sep>/application/views/pdfform.php <?php tcpdf(); $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $obj_pdf->SetCreator(PDF_CREATOR); $title = "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 Arihant Maxsell Technologies Pvt Ltd"; $obj_pdf->SetTitle($title); $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING); $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $obj_pdf->SetDefaultMonospacedFont('helvetica'); $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $obj_pdf->SetFont('helvetica', '', 9); $obj_pdf->setFontSubsetting(false); $obj_pdf->AddPage(); // we can have any view part here like HTML, PHP etc /* $servername = "localhost"; $username = "root"; $password = ""; $dbname = "service"; $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT ord.id,cust.customer_name,cust.customer_id,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ser_loc.service_loc, ( CASE WHEN ordt.warranty_date!='' THEN 'Warranty' WHEN ordt.prev_main!='' THEN 'Preventive' WHEN ordt.paid!='' THEN 'Paid' ELSE 1 END) AS machine_status FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE ord.id ='$orderid'"); */ /* while($res = mysql_fetch_array($qry)){ $customer_id = $res['customer_id']; $customer_name = $res['customer_name']; $model = $res['model']; $purchase_date = $res['purchase_date']; $warranty_date = $res['warranty_date']; $service_loc = $res['service_loc']; $machine_status = $res['machine_status']; } */ //exit; $content = '<html> <head> <title>AMC Quotation</title> <style> .tablewidth { width:70%; } .tablewidth tr td { line-height:20px; border:1px solid gray; text-indent:5px; } </style> </head> <body> <h1 style="text-align:center;font-size:12px; ">AMC Quotation</h1> <p style="text-align:right;">Date:'.$today_date.'</p> <b>To:</b> <p>'.$cust_name.'</p> <p>'.$cust_addr.' '.$cust_addr1.'</p> <p>'.$city.'</p> <p>'.$email_id.'</p> <p><b>Attention: </b>'.$salutation.''.$cont_name.'</p> <p><b>Sub:</b> AMC for '.$product_name.' - '.$model.' - '.$serialno.' Warranty / AMC Expiry date '.$fromdate.'</p> <p class="dear"><b>Dear Sir/Madam:</b></p> <p>We thank you for purchasing Maxsell Products. We recommend you to renew AMC service which prevents from operation failure and also wear and tear of the spare parts in the machine.</p> <p>In order to maintain the above instruction prime condition for your use, we hereby extend our AMC services for '.$product_name1.'; </p> <p>The current service contract expires on '.$todate.'. We recommend that you renew service contract, which will prevent operation failure and also wear & tear of the instrument. Details of the AMC package are as follows:</p> <table class="tablewidth"> <tr> <td><label>Service Type</label></td><td class="service">'.$type.'</td> </tr> <tr> <td><label>Service Cost</label></td><td>Rs.'.$Service_Cost.'</td> </tr> <tr> <td><label>AMC Start Date</label></td><td>'.$amc_start_date.'</td> </tr> <tr> <td><label>AMC End Date</label></td><td>'.$amc_end_date.'</td> </tr> <tr> <td><label>No of preventive maintenance</label></td><td>'.$prev_nos.'</td> </tr> </table> <p>Please confirm the AMC Quotation by return email and remit the AMC charges to the bank as follows:</p> <table class="tablewidth"> <tr> <td><label>Bank Name</label></td><td>'.$bank_name.'</td> </tr> <tr> <td><label>Bank Address & City</label></td><td class="bank">'.$bank_addr.'</td> </tr> <tr> <td><label>IFSC (RTGS)</label></td><td>'.$ifsc.'</td> </tr> <tr> <td><label>A/C No</label></td><td>'.$acc_no.'</td> </tr> </table> <table></table> <p class="dear"><b>Terms & Conditions:</b></p> <ul> <li>Work will be carried out during our normal business hours.(10.00AM to 6.00PM).</li> <li>If Service AMC is undertaken , Spare parts will not be covered under this contract and rest of the terms & conditions is applicable.</li> <li>Any urgent attention for service may require will be dealt with as promptly as possible upon receipt of service request at our local office or written intimation in the effect.</li> <li>Preventive maintenance will be provided at the convenience of the company with prior appointment from the party. If for any reason the party is unable to get the service done the party cannot claim back the service as part of contract.</li> <li>Based on the contract opted for, equipment are covered under maintenance contract but the replacement of spares will be on charges basis (service contract) if the same is required to be replaced as a result of misuse ,neglect, burglary, fire theft or accidental damage however caused. Our liability shall cease, if the equipment or any part thereof is tampered with or otherwise opened by person other than our duly authorized personnel. Our decision in the matter as to whatever there has been any misuse of instrument of whether replacement of any part has been necessitate as a result of fair wear shall be final.</li> <li>The premium paid here shall cover all traveling & any other expenses of our technician and supervisory staff, However, if the equipment needs workshop attention, then the transportation expenses of the same will be paid by you. </li> <li>You will provide unskilled assistance wherever necessary. Customer must cooperate with Service team in order to render quality of services.</li> <li>Calibration shall be done as and when required for the said instrument. AMC does not cover accessories or ancillary items like Online UPS, Isolation transformer, battery , PC/laptop except for in-built models, printer, scrapping unit , cables, adaptor etc.</li> <li>The old parts sub assemblies which are replaced with new or reconditioned parts become our property.</li> <li>We shall not be responsible for any claims, liabilities in respect of consequential losses of what so ever nature resulting either from malfunctioning of the equipment or whatsoever.</li> <li>We shall not be liable for any effect of consequence resulting from any act of God or War, riot not Civil commotion or otherwise beyond our power and control.</li> <li>Any disputes or differences arising between us in the interpretation or implementation of the terms herein or touching any matter connected therewith will be subject to the jurisdiction of Madras Court.</li> <li>Only instrument which is in Good Operating condition will enter into contract . Others will be treated as per paid service scheme.</li> <li>If Customer requires Re-installation of the instrument , the respective charges will be claimed irrespective of the instrument covered under the contract (Applicable only for Laser Marker & Gold Testing Machine). For Equipments under AMC customer must inform when the equipment is moved. If moved without any proper information then Company is not responsible for damages, working limitations or whatever. And AMC will be void in such cases. </li> <li>Company is only obliged to inspect & service the defective equipment . However , customers wants day extension of engineer in such cases customer must pay – accommodation , conveyance , food , DA as per the company norms.</li> <li>Service tax & Vat Tax if applicable extra shall be charged.</li> <li>We use only OEM Parts and service will be provided by skilled & factory trained engineer.</li> <li>The AMC Contract is non-transferable.</li> </ul> <p><b>Products: Cash Counting Machine</b><br> Direct No : 044-40470007<br> Mobile No : 9094488995<br> Email Id : <EMAIL> </p> <p>Products: Gold Testing Machine<br> Direct no : 044-40470005<br> Email id : <EMAIL> </p> </body> </html>'; ob_end_clean(); $obj_pdf->writeHTML($content, true, false, true, false, ''); //$obj_pdf->Output('"'.$cust_name.'".pdf', 'I'); $obj_pdf->Output('serviceEff_maxsell/assets/pdf/amc_quotation/'.$cust_name.'_'.$ord_id.'.pdf', 'F'); ?><file_sep>/application/views/search_list.php <script> function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>order/del_order', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/order_list"; } alert("Order deleted"); } }); }); } </script> <!--<script> $(document).ready(function(){ $("#search").change(function(){ alert("search"); var datastring='search='+$("#search").val(); //alert(datastring); $.ajax({ type: "post", url: "<?php echo base_url(); ?>order/search_list", cache: false, data:datastring, success: function(data){ alert(data); //$('#finalResult').html(""); $('.display').append(data); }, }); }); }); </script>--> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276; font-size:12px; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; border: 1px solid #dbd0e1 !important; /*background-color: white;*/ } thead { border-bottom: 1px solid #ccc; border: 1px solid #ccc; color: #fff; background:#6c477d; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } h1, .h1, h2, .h2, h3, .h3 { margin-top: 20px; margin-bottom: 10px; } hr { margin-top: 0px !important; } a{ color: #522276 !important; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Search List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addsale.png" title="Add Sales" style="width:24px;height:24px;">Add Sales</button>--> <!--<a href="<?php echo base_url(); ?>pages/add_order" style="position: relative; bottom: 27px;left: 88%;"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Sales"></i></a>--> <!--<input type="text" name="search" id="search" style="position: relative; bottom: 27px;left: 78%;"/>--> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead><?php foreach($orderlist1 as $key1){ foreach($orderlist as $key){ if($key->order_id==$key1->id){?> <tr> <th class="hidden">id</th> <th style="width:9% !important">Customer ID</th> <th style="width:16% !important">Customer Name</th> <th>Branch</th> <th style="width:11% !important">Type Of Customer</th> <th style="width:16% !important">Products</th> <th style="width:3% !important">Serial_NO</th> <th style="width:7% !important">Sale Date</th> <?php if($key->warranty_date != ''){ ?> <th style="width:9% !important">Warranty Date</th> <?php } ?> <?php if($key->amc_end_date != ''){ ?> <th style="width:9% !important">AMC Date</th> <?php } ?> <?php if($key->cmc_end_date != ''){ ?> <th style="width:9% !important">CMC Date</th> <?php } ?> <?php if($key->rent_date != ''){ ?> <th style="width:9% !important">Rent Date</th> <?php } ?> <?php if($key->warranty_date!="" ||$key->rent_type!="" ){?> <th style="width:9% !important">Machine status</th> <?php }?> <th>Location</th> <th>Action</th> </tr> </thead><?php } } } ?> <tbody><?php foreach($orderlist1 as $key1){?> <tr> <td class="hidden"><?php echo $key1->id; ?></td> <td><?php echo $key1->customer_id; ?></td> <td style="width:223px; !important"><?php echo $key1->company_name; ?></td> <td style="width:65px;"><?php echo $key1->branch_name; ?></td> <td><?php echo $key1->type; ?></td> <td style="width:16% !important"> <ul class="quantity1"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php echo $key->model; ?></li> <?php } } ?> </ul> </td> <td style="width:3% !important"><?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?><?php echo $key->serial_no; ?><?php } } ?></td> <td style="text-align:left;"> <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php echo date("d-m-Y", strtotime($key->purchase_date)); ?></li> <?php } } ?> </ul> </td> <?php if($key->warranty_date!=""){ ?> <td style="width:120px;text-align:left;" > <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php if($key->warranty_date!=""){echo date("d-m-Y", strtotime($key->warranty_date));} ?></li> <?php } } ?> </ul> </td><?php } ?> <?php if($key->amc_end_date!=""){ ?> <td style="width:120px;text-align:left;" > <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php if($key->amc_end_date!=""){echo date("d-m-Y", strtotime($key->amc_end_date));} ?></li> <?php } } ?> </ul> </td><?php } ?> <?php if($key->cmc_end_date!=""){ ?> <td style="width:120px;text-align:left;" > <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php if($key->cmc_end_date!=""){echo date("d-m-Y", strtotime($key->cmc_end_date));} ?></li> <?php } } ?> </ul> </td><?php } ?> <?php if($key->rent_date!=""){ ?> <td style="width:120px;text-align:left;" > <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php if($key->rent_date!=""){echo date("d-m-Y", strtotime($key->rent_date));} ?></li> <?php } } ?> </ul> </td><?php } ?> <?php if($key->warranty_date!="" || $key->rent_type!="" ){?> <td style="width:143px;"> <ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php if($key->warranty_date!=""){ echo "Warranty"; }elseif($key->rent_type=='syndicate') { echo "Syndicate"; }elseif($key->rent_type=='distributor') { echo "Local Distributor"; }elseif($key->rent_type=='chargeble') { echo "Chargeable"; } ?></li> <?php } } ?> </ul> </td><?php }?> <td style="width:106px;"><ul class="quantity"> <?php foreach($orderlist as $key){ if($key->order_id==$key1->id){ ?> <li><?php echo $key->service_loc; ?></li> <?php } } ?> </ul></td> <td class="options-width"> <a href="<?php echo base_url(); ?>order/update_order/<?php echo $key1->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a> <a href="<?php echo base_url(); ?>order/view_order/<?php echo $key1->id; ?>" title="View" style="padding-right:10px;" ><i class="fa fa-eye fa-2x"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key1->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr><?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/custom.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/piklor.js"></script> <script src="<?php echo base_url(); ?>assets/js/handlers.js"></script> </body> </html><file_sep>/application/controllers/Customer.php <?php class customer extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Customer_model'); $this->load->model('Order_model'); } public function view_sales($idd) { $data['list']=$this->Customer_model->getcustomersalesbyid($idd); $this->load->view('view_sales',$data); } public function add_customer(){ $mobile = $this->input->post('mobile'); $check_cust = $this->Customer_model->check_cust($mobile); if(empty($check_cust)){ $data['customer_name']=$this->input->post('company_name'); $data['state']=$this->input->post('state'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['address']=$this->input->post('address'); $data['city']=$this->input->post('city'); $data['pincode']=$this->input->post('pincode'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $result=$this->Customer_model->add_customer($data); echo "<script>alert('Customer Added Successfully!!!');window.location.href='".base_url()."pages/cust_list';</script>"; }else{ echo "<script>alert('Customer already exists!!!');window.location.href='".base_url()."pages/add_cust';</script>"; } } public function edit_customer(){ $id = $this->input->post('cust_id'); $data['customer_name']=$this->input->post('company_name'); $data['state']=$this->input->post('state'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['address']=$this->input->post('address'); $data['city']=$this->input->post('city'); $data['pincode']=$this->input->post('pincode'); date_default_timezone_set('Asia/Calcutta'); $data['updated_on'] = date("Y-m-d H:i:s"); $this->Customer_model->update_customer($data,$id); echo "<script>alert('Customer Updated Successfully!!!');window.location.href='".base_url()."pages/cust_list';</script>"; } public function update_customer(){ $id=$this->uri->segment(3); $data['state_list']=$this->Order_model->state_list(); $data['list']=$this->Customer_model->getcustomerbyid($id); $this->load->view('templates/header'); $this->load->view('edit_cust',$data); } public function update_cust_list(){ $id=$this->uri->segment(3); $data['list']=$this->Customer_model->getcustomertypebyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_cust_type',$data); } public function update_cust_list1(){ $id=$this->uri->segment(3); $data['list']=$this->Customer_model->getcustomertypebyid1($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $$this->load->view('tax_list',$data); } public function edit_customer_type(){ $cust_typeid = $this->input->post('cust_typeid'); $data=array( 'type'=>$this->input->post('cust_type') ); $this->Customer_model->update_customer_type($data,$cust_typeid); echo "<script>alert('Customer Type Updated Successfully!!!');window.location.href='".base_url()."pages/cust_type_list';</script>"; } function delete_status() { $currentElemID = $this->input->post('currentElemID'); $this->Customer_model->delete_brand_status($currentElemID); } //view public function view_customer() { $id=$this->uri->segment(3); $data['list']=$this->Customer_model->getcustomerbyid($id); $data['list1']=$this->Customer_model->getcustservicelocationbyid($id); $data['lablist']=$this->Customer_model->getlablistbyid($id); $data['customer_type']=$this->Customer_model->cust_type_list(); $data['service_zone']=$this->Customer_model->service_zone_list(); $data['pincode_list']=$this->Customer_model->pincode_list(); $data['state_list']=$this->Customer_model->state_list(); //echo "<pre>";print_r($data);exit; $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('view_customer',$data); } public function addrow(){ $data['count']=$this->input->post('countid'); $data['zoneid']=$this->input->post('zoneid'); $data['zone_coverage'] = $this->input->post('zone_coverage'); $data['state_list']=$this->Customer_model->state_list(); $data['service_zone']=$this->Customer_model->service_zone_list(); //echo "Count: ".$data['count']; //$data['customerlist']=$this->Service_model->customerlist(); //$data['list_serialnos']=$this->Service_model->list_serialnos(); //$data['servicecat_list']=$this->Service_model->servicecat_list(); //$data['problemlist']=$this->Service_model->problemlist(); //$data['employee_list']=$this->Service_model->employee_list(); $this->load->view('add_cust_row',$data); } public function del_customer(){ $id=$this->input->post('id'); $data['flag']="Deleted"; //print_r($data);exit; $this->Customer_model->delete_customer_service_loc($id,$data); $result = $this->Customer_model->del_customers($id,$data); } public function Inactive_cust_type(){ //$id=$this->input->post('id'); //$this->Customer_model->del_customer_type($id); $id=$this->input->post('id'); echo $id; $data=array( 'status'=>'1' ); $s = $this->Customer_model->update_status_customer($data,$id); //echo "<script>alert('Customer Type Inactive');window.location.href='".base_url()."';</script>"; } public function active_cust_type(){ //$id=$this->input->post('id'); //$this->Customer_model->del_customer_type($id); $id=$this->input->post('id'); // echo $id; $data=array( 'status'=>'0' ); //print($data); $s = $this->Customer_model->update_status_customer1($data,$id); //echo "<script>alert('Customer Type Inactive');window.location.href='".base_url()."';</script>"; } public function custtype_validation() { $product_id = $this->input->post('id'); //echo $product_id; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Customer_model->custtype_validation($product_id))); } public function custtype_validation1() { $product_id = $this->input->post('id'); //echo $product_id; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Customer_model->custtype_validation1($product_id))); } public function category_validation1() { $product_id = $this->input->post('id'); //echo $product_id; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Customer_model->custtype_validation($product_id))); } public function add_custtyperow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_custtype',$data); } }<file_sep>/application/views/sparecharge_list.php <style> body{background-color:#fff;} table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } </style> <?php //print_r($enggname_list);exit;?> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare Charge List</h2> <hr> <form action="<?php echo base_url(); ?>report/getcharge_list" method="post"> <tr> <td><label>From Date:</label></td><td><input type="text" name="from" class="date"></td> <td><label>To Date:</label></td><td><input type="text" name="to" class="date"></td> <!--<td><label>Engineer Name:</label></td> <td><select name="engineer" > <option value="">---select---</option> <?php foreach($enggname_list as $eng) {?> <option value="<?php echo $eng->id;?>"><?php echo $eng->emp_name;?></option><?php } ?></select></td><br><br><br>--> <td><label>Spare Name:</label></td> <td><select name="spare"> <option value="">--select--</option> <?php foreach($sparename_list as $spare) {?> <option value="<?php echo $spare->id;?>"><?php echo $spare->spare_name;?></option><?php } ?> </select> </td><br><br> <td><label>Machine Status:</label></td> <td><select name="sersite"> <option value="">--select--</option> <option value="Chargeable">Chargeable</option> <option value="Warranty">Warranty</option> <option value="Preventive">Preventive</option> <option value="Comprehensive">Comprehensive</option> <option value="Serviceonly">Serviceonly</option> </select> </td><br> <input type="submit" name="search" id="search" value="Search" class="submit_button" > </tr> </form> <!--DataTables example--> <br> </div> </div> </section> </div> </div> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ $(document).ready(function(){//alert("hfhh"); $(".date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); });//]]> </script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> </body> </html> <file_sep>/application/views_bkMarch_0817/edit_prod_sub_cat.php <style> .tableadd input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 3px; /* padding-left: 10px; */ margin-left: 13px; } .tableadd input { height: 21px !important; margin-top: 11px; margin-right: -242px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width:103%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Sub-Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>subcategory/edit_sub_category" method="post"> <table id="myTable" class="tableadd"> <?php foreach($list as $key){ ?> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Contact Name</label> <select id= "pro_cat" name="pro_cat"> <option value="">---Select---</option> <?php foreach($droplists as $dkey){ if($dkey->id==$key->pro_catid){ ?> <option selected="selected" value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } } ?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category Name</label> <input type="text" name="sub_catname" class="model" value="<?php echo $key->subcat_name; ?>"><input type="hidden" name="subcatid" class="model" value="<?php echo $key->prosubcat_id; ?>"> </div> <!--<tr><td><label>Category Name</label></td><td><label>Sub-Category Name</label></td></tr> <tr> <td> <select id= "pro_cat" name="pro_cat"> <option value="">---Select---</option> <?php foreach($droplists as $dkey){ if($dkey->id==$key->pro_catid){ ?> <option selected="selected" value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } } ?> </select> </td> <td><input type="text" name="sub_catname" class="model" value="<?php echo $key->subcat_name; ?>"><input type="hidden" name="subcatid" class="model" value="<?php echo $key->prosubcat_id; ?>"></td> </tr>--> <?php } ?> </table> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> </body> </html><file_sep>/application/views/spare_stock.php <head> <style> .ui-state-default { background:#6c477d; color:#fff; border: 3px solid #fff !important; font-size: 12px; /*border-bottom:1px solid #000;*/ } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; border: 1px solid #522276 !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } select { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ label > input[type=text] { background-color: transparent; border: 1px solid #522276; font-size: 12px; border-radius: 7; width: 55% !important; font-size: 1.5 rem; margin: 0 0 3px 0; padding: 5px; box-shadow: #522276; /* -webkit-box-sizing: content-box; */ -moz-box-sizing: content-box; /* box-sizing: content-box; */ /* transition: all .3s; */ height: 12px; } input[type=text] { background-color: transparent; border: 0px solid #522276; font-size: 12px; border-radius: 7; width: 55% !important; font-size: 1.5 rem; margin: 0 0 3px 0; padding: 5px; box-shadow: #522276; /* -webkit-box-sizing: content-box; */ -moz-box-sizing: content-box; /* box-sizing: content-box; */ /* transition: all .3s; */ height: 12px; } input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 6px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} .ui-widget-header { border: 1px solid white; background: white; height: 35px; } .ui-state-default { font-size: 13px !important; font-weight: bold; } .ui-state-default .ui-icon { float: right; } .ui-button { min-width: 1.5em; padding: 0.5em 1em; margin-left: 10px !important; text-align: center; background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%); } .dataTables_paginate{ float:right; } .dataTables_info{ float:left; } /* input, textarea, .uneditable-input { margin-left: 940px; margin-top: -68px; } */ .dataTables_length{ float: left; margin-left: 0px; } .dataTables_filter{ float:right; } label { display: block; margin-bottom: 34px; margin-left: 25px; } .dtable {display:none} .dtable_custom_controls {display:none;position: absolute;z-index: 50;margin-left: 5px;margin-top:1px} .dtable_custom_controls .dataTables_length {width:auto;float:none} .dataTables_filter input{ border:1px solid #ccc; } .dataTables_paginate > span > a{ color: #000 !important; border: 0px solid #cacaca !important; /*background-color: #fff;*/ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); /*background: linear-gradient(to bottom, #DBD0E1 0%, #522276 100%) !important;*/ background: transparent !important; opacity: 1; } .dataTables_paginate > span > a.ui-state-disabled{ color: #333 !important; border: 1px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important; opacity:1; } .dataTables_paginate > .previous{ color: #fff !important; border: 0px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); /*background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important;*/ background: transparent !important; opacity: 1; } .dataTables_paginate > .previous.ui-state-disabled{ color: #333 !important; border: 1px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important; opacity:1; } .dataTables_paginate > .next{ color: #000 !important; border: 0px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); /*background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important;*/ background: transparent !important; opacity: 1; } .dataTables_paginate > .next.ui-state-disabled{ color: #333 !important; border: 1px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important; opacity:1; } .dataTables_paginate > .first{ color: #000 !important; border: 0px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); /*background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important;*/ background: transparent !important; opacity: 1; } .dataTables_paginate > .first.ui-state-disabled{ color: #333 !important; border: 1px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important; opacity:1; } .dataTables_paginate > .last{ color: #000 !important; border: 0px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); /*background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important;*/ background: transparent !important; opacity: 1; } .dataTables_paginate > .last.ui-state-disabled{ color: #333 !important; border: 1px solid #cacaca !important; background-color: #fff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc)); background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%); background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%) !important; opacity:1; } a:hover{ cursor:pointer; color:#000; } a{ color:#522276; } </style> <style> /*select{width:200px;}*/ thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } input[readonly] { border:none; } .data{ border: 1px solid #522276 !important; width: 25% !important; margin-right:4px !important; } .data1{ border: 1px solid #522276 !important; width: 20% !important; margin-right:4px !important; } .date { border: 1px solid gray !important; width: 32% !important; margin-right:4px !important; } .fancybox-opened{ width:1035px !important; } .fancybox-inner{ width:1030px !important; } </style> <!--<style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; border: 1px solid #522276 !important; } th { padding: 0px; text-align: center; font-size: 12px; border: 1px solid #522276 !important; /* background-color: #DBD0E1 !important; */ } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=text]{ background-color: transparent; border: none; width: 100%; font-size: 12px; margin: 0 0 -2px 0; padding: 5px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} .fancybox-inner{ width:1020px !important; } .fancybox-wrap{ width:1030px !important; } </style>--> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <!-- Add jQuery library --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery-1.10.1.min.js"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var jq= jQuery.noConflict(); jq(document).ready(function() { jq("#fancybox-manual-b").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); jq.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popup', type : 'iframe', padding : 5 }); }); jq("#fancybox-manual-bc").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); jq.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popupminus', type : 'iframe', padding : 5 }); }); /*$("#fancybox-manual-purchase").click(function() { alert("test"); //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); $.fancybox.open({ href : '<?php echo base_url(); ?>Spare/view_purchase', type : 'iframe', padding : 5 }); });*/ }); </script> <script> function clickPopup(idd) { //alert("test"); //var sitename = $("#sitename_"+idd).val(); jq.fancybox.open({ href : '<?php echo base_url(); ?>spare/view_purchase/'+idd, type : 'iframe', padding : 5 }); } </script> </head> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare Stock</h2> <hr> <!--DataTables example--> <div id="table-datatables" style="width:90%; margin-left:5%;"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div style="float: right; height:50px; "> <a id="fancybox-manual-b" href="javascript:;" style="margin-right: 20px;"><img src="<?php echo base_url(); ?>assets/images/spare_add1.png" alt="materialize logo"></a> <a id="fancybox-manual-bc" href="javascript:;"><img src="<?php echo base_url(); ?>assets/images/spare_delete1.png" alt="materialize logo"></a> </div> <table id="data-table-simple" class="dtable responsive-table display" cellspacing="0" style=" margin-top:2%;"> <thead> <tr><th class="hidden">id</th> <th>Spare Name</th> <th>Stock In Hand</th> <th>Spare With Engineers</th> <th>Used Spare</th> </tr> </thead> <tbody> <?php foreach($spare_stock as $sparekey){ $sdf=$sparekey->id;?> <tr> <td class="hidden"><?php echo $sparekey->id; ?></td> <td><input type="text" value="<?php echo $sparekey->spare_name; ?>" class="" name="spare_name" id="spare_name" readonly></td> <td><a onclick="clickPopup('<?php echo $sdf;?>')"> <input type="text" value="<?php echo $sparekey->spare_qty; ?>" class="" name="total_spare" id="total_spare_<?php echo $sparekey->id; ?>" readonly></a></td> <td><input type="text" value="<?php echo $sparekey->eng_spare; ?>" class="" name="engg_spare" id="engg_spare_<?php echo $sparekey->id; ?>" readonly></td> <td><input type="text" value="<?php echo $sparekey->used_spare; ?>" class="" name="used_spare" id="used_spare_<?php echo $sparekey->id; ?>" readonly></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <!--<script type='text/javascript'>//<![CDATA[ $(document).ready(function () { $('#data-table-simple').dataTable({ "order": [[0,"desc"]], "aoColumns": [ { "sType": "cust-txt" }, { "sType": "cust-txt" }, { "sType": "cust-txt" }, { "sType": "cust-txt" } ]}); }); </script>--> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script>--> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script>--> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { /* * Find and assign actions to filters */ $.fn.dataTableExt.afnFiltering = new Array(); var oControls = $('.dtable').prevAll('.dtable_custom_controls:first').find(':input[name]'); oControls.each(function() { var oControl = $(this); //Add custom filters $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { if ( !oControl.val() || !oControl.hasClass('dtable_filter') ) return true; for ( i=0; i<aData.length; i++ ) if ( aData[i].indexOf(oControl.val()) != -1 ) return true; return false; }); }); options = { "sDom" : 'R<"H"lfr>t<"F"ip<', "bProcessing" : true, "bJQueryUI" : true, "bStateSave" : false, "iDisplayLength" : 8, "aLengthMenu" : [[8, 25, 50, -1], [8, 25, 50, "All"]], "sPaginationType" : "full_numbers", "aoColumnDefs": [{ 'bSortable': true, 'aTargets': [ 0,7,9 ] }], // "ordering": false, //"ordering": [[ 2, "false" ]], "aoColumnDefs": [ { 'bSortable': true, 'aTargets': [ 0 ] } ], "aaSorting" : [[ 0, "asc" ]], "fnDrawCallback" : function(){ //Without the CSS call, the table occasionally appears a little too wide $(this).show().css('width', '100%'); //Don't show the filters until the table is showing $(this).closest('.dataTables_wrapper').prevAll('.dtable_custom_controls').show(); }, /*"fnStateSaveParams": function ( oSettings, sValue ) { //Save custom filters oControls.each(function() { if ( $(this).attr('name') ) sValue[ $(this).attr('name') ] = $(this).val().replace('"', '"'); }); return sValue; },*/ "fnStateLoadParams" : function ( oSettings, oData ) { //Load custom filters oControls.each(function() { var oControl = $(this); $.each(oData, function(index, value) { if ( index == oControl.attr('name') ) oControl.val( value ); }); }); return true; } }; var oTable = $('.dtable').dataTable(options); //var table = $('#example').dataTable(); // Perform a filter oTable.fnSort( [ [0,'desc'] ] ); //oTable.fnSort( [ [0,'desc'] ] ); /* * Trigger the filters when the user interacts with them */ oControls.each(function() { $(this).change(function() { //Redraw to apply filters oTable.fnDraw(); }); }); oTable.fnFilter(''); // oTable.fnFilter(''); // Remove all filtering oTable.fnFilterClear(); }); </script> </body> </html><file_sep>/application/models/Brand_model.php <?php class Brand_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_brands($data){ $this->db->insert('brands',$data); return true; } public function checkbrandname($user) { $this->db->select('brand_name'); $this->db->from('brands'); $this->db->where_in('brand_name',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function brand_list(){ $this->db->select("id As br_id, brand_name, status",FALSE); $this->db->from('brands'); //$this->db->join('prod_category', 'prod_category.id=brands.cat_id'); //$this->db->join('prod_subcategory', 'prod_subcategory.id=brands.subcat_id'); $this->db->order_by('id', 'DESC'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getbrandbyid($id){ $this->db->select("id As br_id, brand_name",FALSE); $this->db->from('brands'); //$this->db->join('prod_category', 'prod_category.id=brands.cat_id'); //$this->db->join('prod_subcategory', 'prod_subcategory.id=brands.subcat_id'); $this->db->where('id', $id); $this->db->order_by('id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $query = $this->db->get(); return $query->result(); } public function getsub_cat($id){ $query = $this->db->get_where('prod_subcategory', array('prod_category_id' => $id)); return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function update_cat($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_subcat($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_brandname($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_status_brand($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_status_brand1($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function del_brands($id){ $this->db->where('id',$id); $this->db->delete('brands'); } public function brand_validation($brand) { $this->db->where('brand_name',$brand); $this->db->from('brands'); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $numrow = $query->num_rows(); } }<file_sep>/application/views/edit_prod_list.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"> <style> body{background-color:#fff;} #errorBox { color:#F00; } .tableadd1 select { border: 1px solid #000; background-image:none; border-radius: 2px; width: 100%; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .limitedNumbChosen { width: 100%; } .chosen-container { width: 100% !important; } .chosen-container-multi .chosen-choices { border: 1px solid #ccc; } textarea.materialize-textarea { overflow: auto; padding: 3px; resize: none; min-height: 10rem; } .chosen-container-multi .chosen-choices li.search-field input[type=text] { color: #333; } select { border: 1px solid #ccc !important; } .star{ color:#ff0000; font-size:15px; } .btn{text-transform:none !important;} </style> <script> $(function(){ //alert("test"); $("button").click(function(event){ //alert("clcl"); if($("#product_name").val()==""){ $("#proderror").text("Enter the Product Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } if($("#category").val()==""){ $("#caterror").text("Please select the Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#subcategory").val()==""){ $("#subcaterror").text("Please select the Sub-Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#brand").val()==""){ $("#branderror").text("Please select the Brand Name").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#model").val()==""){ $("#modelerror").text("Enter the Model Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } /*if($(".limitedNumbChosen").find("option:selected").length < 1){ $("#infoerror").text("Please select the Addtional Information").show().css({ 'font-size':'12px', 'color':'#ff0000' }); }*/ }); $("#product_name").keyup(function(){ if($(this).val()==""){ $("#proderror").show(); } else{ $("#proderror").fadeOut('slow'); } }); $("#category").change(function(){ if($(this).val()==""){ $("#caterror").show(); } else{ $("#caterror").fadeOut('slow'); } }); $("#subcategory").change(function(){ if($(this).val()==""){ $("#subcaterror").show(); } else{ $("#subcaterror").fadeOut('slow'); } }); $("#brand").change(function(){ if($(this).val()==""){ $("#branderror").show(); } else{ $("#branderror").fadeOut('slow'); } }); $("#model").keyup(function(){ if($(this).val()==""){ $("#modelerror").show(); } else{ $("#modelerror").fadeOut('slow'); } }); $(".limitedNumbChosen").change(function(){ if($(this).val()==""){ $("#infoerror").show(); } else{ $("#infoerror").fadeOut('slow'); } }); }); /*function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var product_name = document.frmProd.product_name.value, category = document.frmProd.category.value, subcategory = document.frmProd.subcategory.value, model = document.frmProd.model.value; if( product_name == "" ) { document.frmProd.product_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the product name"; return false; } if( category == "" ) { document.frmProd.category.focus() ; document.getElementById("errorBox").innerHTML = "enter the category name"; return false; } if( subcategory == "" ) { document.frmProd.subcategory.focus() ; document.getElementById("errorBox").innerHTML = "enter the sub category name"; return false; } if( model == "" ) { document.frmProd.model.focus() ; document.getElementById("errorBox").innerHTML = "enter the model"; return false; } }*/ </script> <script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { //alert("hi"); $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> /* $(document).ready(function() { $("#subcategory").change(function() { $("#brand > option").remove(); var subcatid=$(this).val(); categoryid = $("#category").val(); //alert("Subcat: "+id+"Cat:" +category); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/get_brand", data: dataString, cache: false, success: function(data) { $('#brand').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data); $('#brand').append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); }); */ </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Edit Product Details</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Product/edit_product" method="post" name="frmProd"> <!--onsubmit="return frmValidate()" --> <?php foreach($list as $key){?> <div id="errorBox"></div> <table class="tableadd" style="width: 75%;"> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Product Name <span class="star">*</span></label> <input type="text" name="model" id="model" class="prod-model" value="<?php echo $key->model; ?>" maxlength="80"> <div id="modelerror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category <span class="star">*</span></label> <select name="category" id="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ if($pcatkey->id==$key->category){ ?> <option selected="selected" value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } } ?> </select> <div id="caterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category <span class="star">*</span></label> <select name="subcategory" id="subcategory"> <option value="">---Select---</option> <?php foreach($subcatlist as $psubcatkey){ if($psubcatkey->id==$key->subcategory){ ?> <option selected="selected" value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } else {?> <option value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } } ?> </select> <div id="subcaterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Stock</label> <input type="text" name="stock_qty" id="stock_qty" class="prod-name" maxlength="80" value="<?php echo $key->stock_qty; ?>" readonly> </div> </div> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Enter Stock</label> <input type="text" name="stock_qty1" id="stock_qty1" class="prod-name" maxlength="80" value=""> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Description</label> <textarea type="text" name="description" id="description" class="materialize-textarea" maxlength="150"><?php echo $key->description; ?></textarea><input name="product_id" value="<?php echo $key->id; ?>" type="hidden"> </div> </div> <!--<tr> <td><label>Product Name</label></td><td><input type="text" name="product_name" id="product_name" class="" value="<?php echo $key->product_name; ?>"></td> </tr> <tr> <td ><label>Category</label></td><td style="width:200px;"> <select name="category" id="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ if($pcatkey->id==$key->category){ ?> <option selected="selected" value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td ><label>Sub-Category</label></td><td style="width:200px;"> <select name="subcategory" id="subcategory"> <option value="">---Select---</option> <?php foreach($subcatlist as $psubcatkey){ if($psubcatkey->id==$key->subcategory){ ?> <option selected="selected" value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } else {?> <option value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td ><label>Brand Name</label></td><td style="width:200px;"> <select name="brand" id="brand"> <option value="">---Select---</option> <?php foreach($brandlist as $brandskey){ if($brandskey->id==$key->brand){ ?> <option selected="selected" value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } else {?> <option value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td><label>Model</label></td><td><input type="text" name="model" id="model" class="" value="<?php echo $key->model; ?>"></td> </tr> <tr> <td><label>Description</label></td><td><textarea type="text" name="description" id="description" class="materialize-textarea" ><?php echo $key->description; ?></textarea></td> </tr>--> </table> <table class="tableadd1 tableadd" style="width: 75%;"> <!--<tr> <td><label >Additional Information</label></td> <td> <select name="addlinfo[]" multiple> <option value="">---Select---</option> <?php foreach($accessories_list as $acckey1){ if (in_array($acckey1->accessory, $addl)){ ?> <option selected="selected" value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } else{?> <option value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } }?> </select> </td> </tr>--> <!--<tr> <td><input type="checkbox" class="" name="addlinfo[]" value="charger" <?php if (in_array("charger", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="DataCable" <?php if (in_array("DataCable", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Battery" <?php if (in_array("Battery", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Headset" <?php if (in_array("Headset", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Cover" <?php if (in_array("Cover", $addl)){ ?> checked='checked'<?php } ?>></td> </tr>--> <tr> <td style="padding-top: 25px;"> <button class="btn cyan waves-effect waves-light " type="submit" >Submit</button> </td> </tr> </table> </div> <?php } ?> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } $(".limitedNumbChosen").chosen({ placeholder_text_multiple: "---Select---" }) .bind("chosen:maxselected", function (){ window.alert("You reached your limited number of selections which is 2 selections!"); }); $(".prod-name").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9. ]/g,'') ); }); $(".prod-model").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9. ]/g,'') ); }); $("textarea").removeClass("materialize-textarea"); $("textarea").css({ 'height':'100px', 'overflow-y':'auto', 'overflow-x':'hidden' }); </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views_bkMarch_0817/engg_list.php <script> $(document).ready(function(){ $('[id^="service_status_"]').change(function(){//alert("hiisss"); var id = $(this).val(); //alert(id); var arr = id.split(','); var statusid = arr['0']; var reqid = arr['1']; var data_String; data_String = 'statusid='+statusid+'&reqid='+reqid; $.post('<?php echo base_url(); ?>service/update_service_status',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Service status changed"); //$('#actaddress').val(data.Address1), }); }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Engineer's Request List</h4> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Request Id</th> <th>Customer Name</th> <th>Product Name</th> <th>Machine Status</th> <th>Requested Date</th> <th>Assign To</th> <th>Site</th> <th>Location</th> </tr> </thead> <!-- <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot>--> <tbody> <?php foreach($engg_list as $key){?> <tr> <td><a href="<?php echo base_url(); ?>service/update_service_req/<?php echo $key->id; ?>"><?php echo $key->request_id; ?></a></td> <td><?php echo $key->customer_name; ?></td> <td><?php foreach($engg_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->model;} } ?></td> <td><?php foreach($engg_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?></td> <td><?php echo $key->request_date; ?></td> <td><?php echo $key->emp_name; ?></td> <td><?php foreach($engg_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->site; } } ?></td> <td><?php foreach($engg_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->service_loc; } } ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/add_qc_master_row.php <tr> <td style="padding:10px 0;"><input type="text" name="qc_param[]" id="qc_param-<?php echo $count; ?>"></td> <td style="padding:10px 0;"><input type="text" name="qc_value[]" id="qc_value-<?php echo $count; ?>"></td> </tr><file_sep>/application/views_bkMarch_0817/ready_delivery_view.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $(' <tr><td> <select> <option>---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn1", "click", function(){ var vals = $('#spare_tot').val(); var idd=$(this).closest(this).attr('id'); // alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); //alert($('#amt'+ctid).val()); var vals = $('#spare_tot').val(); vals -= Number($('#amt'+ctid).val()); //alert(vals); $('#spare_tot').val(vals); var tax_amt = (vals * $('#tax_type').val()) / 100; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); if(warran=='Preventive' || warran=='Warranty' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); //alert(Total_amount); $('#total_amt').val(Total_amount); } $(this).closest("tr").remove(); }); }); });//]]> </script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).val()=="3"){ $(".box").not(".ready").hide(); $(".ready").show(); } else if($(this).val()=="4"){ $(".box").not(".delivery").hide(); $(".delivery").show(); } else if($(this).attr("value")=="blue"){ $(".box").not(".blue").hide(); $(".blue").show(); } else{ $(".box").hide(); } }); }).change(); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1+'&modelid='+modelid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#table11').append(result); } }); }); }); </script> <style> .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td select { width: 210px !important; } .tableadd2 tr td select { width: 165px; } .tableadd tr td label{ width: 180px !important; font-weight: bold; font-size: 13px; } .box{ padding: 20px; display: none; margin-top: 20px; box-shadow:none !important; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Ready For Delivery View</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>ready_delivery/edit_quotereview" method="post" name="frmServiceStatus"> <?php foreach($getQuoteByReqId as $key){ if(isset($key->problem)){ $problem_data = explode(",",$key->problem); } ?> <table class="tableadd"> <tr> <td><label>Request ID</label>:</td><td><input type="text" name="reque_id" class="" value="<?php echo $key->request_id; ?>" readonly></td> <td><label>Customer Name</label>:</td><td><input type="text" name="cust_name" class="" value="<?php echo $key->customer_name; ?>" readonly><input type="hidden" name="cust_mobile" class="" value="<?php echo $key->mobile; ?>" readonly></td> </tr> <tr> <td><label>Branch Name</label>:</td><td><input type="text" name="br_name" class="" value="<?php echo $key->branch_name; ?>" readonly></td> <td><label>Address</label>:</td><td><?php echo $key->address.' '.$key->address1; ?></td> </tr> <tr> <td><label>Product Name</label>:</td><td><input type="text" name="p_name" class="" value="<?php echo $key->model; ?>" readonly><input type="hidden" name="modelid" id="modelid" class="" value="<?php echo $key->modelid; ?>"><input type="hidden" name="req_id" id="req_id" class="" value="<?php echo $req_id; ?>"></td> <td><label>Date Of Purchase</label>:</td><td><input type="text" name="purchase_date" class="date" value="<?php echo $key->purchase_date; ?>" readonly></td> </tr> <tr> <td><label>Warranty End Date</label>:</td><td><?php echo $key->warranty_date; ?></td> <td><label>Date Of Request</label>:</td><td><?php echo $key->request_date; ?></td> </tr> <tr> <td><label>Location</label>:</td><td><input type="text" name="serviceloc" class="" value="<?php echo $key->service_loc; ?>" readonly></td> <td><label>Problem</label>:</td><td><?php if(!empty($problemlist1)){ foreach($problemlist1 as $problemlistkey1){ if (in_array($problemlistkey1->id, $problem_data)){ echo '<br/>'.$prob_category = $problemlistkey1->prob_category; }} }else{ echo $prob_category =""; } ?></td> </tr> <tr> <td><label>Machine Status</label>:</td><td><input type="text" name="machine_status" class="" value="<?php echo $key->machine_status; ?>" readonly></td> <td><label>Blanket Approval</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->blank_app; ?>" readonly></td> </tr> <!--<tr> <td><label >Status</label>:</td><td><input type="text" name="" class="" value="<?php foreach($status_listForquoteInpro as $statuskey){echo $statuskey->status;} ?>" readonly></td> </tr>--> </table> <?php } ?> <table id="table11" class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>Spare Name</td> <td>Quantity</td> <td>Amount</td> </tr> <tr> <?php if(!empty($spareIds)){ foreach($spareIds as $key3){ foreach($key3 as $key4){ $usedspare[] = $key4->used_spare; $stockspare[] = $key4->spare_qty; $salesprice[] = $key4->sales_price; } } }//exit; $tot_spare_amt = 0; if(!empty($spare_amtt)){ //print_r($spare_amtt); foreach($spare_amtt as $spareAmt_key){ $tot_spare_amt += $spareAmt_key; } } $i = 0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ $tax_amt11 = $i;}else{foreach($getTaxDefaultInfo as $taxKey){ $tax_amt11 = ($tot_spare_amt * $taxKey->tax_percentage) / 100; }} } foreach($getServiceCatbyID as $ServiceKey){ if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ $labor_chrg = $i;}else{ $labor_chrg = $ServiceKey->service_charge;}} if(isset($getservicecharge)){ $labor_chrg = $getservicecharge;} if($WarranKey->machine_status=="Chargeable"){ $conchrg = $key->concharge;}else{$conchrg = $i;} if(isset($tot_spare_amt) || isset($tax_amt11) || isset($labor_chrg) || isset($conchrg) ){ $tottt = $tot_spare_amt+$tax_amt11+$labor_chrg+$conchrg; } $count='0'; foreach($getQuoteReviewSpareDetByID as $ReviewDetKey2){ ?> <tr> <td><input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="<?php if(!empty($usedspare[$count])){echo $usedspare[$count];}?>"><input type="hidden" name="spare_tbl_id[]" id="spare_tbl_id<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->id;?>"> <?php foreach($spareListByModelId1 as $sparekey1){ if($sparekey1->id==$ReviewDetKey2->spare_id){ echo $sparekey1->spare_name; } } ?> </td> <td><?php echo $ReviewDetKey2->spare_qty; ?></td> <td><?php echo $ReviewDetKey2->amt; ?></td> </tr> <?php $count++; } ?> </tr> </table> <!--<a id="addMoreRows" style="background: rgb(179, 179, 179) none repeat scroll 0% 0% !important; padding: 10px; color: white; border-radius:5px;">Add Row</a>--> <?php foreach($getQuoteReviewDetByID1 as $ReviewDetKey1){ ?> <table class="tableadd"> <tr> <td><label>Spare Tax Amount</label>:</td><td> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Preventive'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?><?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Chargeable'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <input type="text" name="spare_tax" id="spare_tax" class="" value="<?php $i = 0; if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{foreach($getTaxDefaultInfo as $taxKey){ echo $tax_amt = ($tot_spare_amt * $taxKey->tax_percentage) / 100; }}?>" readonly><input type="hidden" name="tax_type" id="tax_type" class="" value="<?php foreach($getTaxDefaultInfo as $taxKey){ echo $taxKey->tax_percentage; }?>" ></td><td><label>Spare Total Charges</label>:</td><td><input type="text" name="spare_tot" id="spare_tot" class="" value="<?php if(isset($tot_spare_amt)){echo $tot_spare_amt;} ?>" readonly></td> </tr> <tr> <td><label>Labour Charges</label>:</td><td><input type="text" name="labourcharge" id="labourcharge" class="" value="<?php foreach($getServiceCatbyID as $ServiceKey){if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{echo $ServiceKey->service_charge;}} if(isset($getservicecharge)){echo $getservicecharge;} ?>" readonly></td><td><label>Conveyance Charges</label>:</td><td><input type="text" name="concharge" id="concharge" class="" value="<?php if($WarranKey->machine_status=="Chargeable"){echo $key->concharge;}else{echo $i;} ?>" readonly></td> </tr> <tr> <td><label>Total Amount</label>:</td><td><input type="text" name="total_amt" id="total_amt" class="" value="<?php if((isset($ReviewDetKey1->pending_amt) && $ReviewDetKey1->pending_amt!="0") || (isset($ReviewDetKey1->disc_amt) && $ReviewDetKey1->disc_amt!="0") || (isset($ReviewDetKey1->plus_amt) && $ReviewDetKey1->plus_amt!="0")){echo $ReviewDetKey1->total_amt; }else{echo $tottt;}?>" readonly><input type="hidden" name="total_amt1" id="total_amt1" class="" value="<?php if((isset($ReviewDetKey1->pending_amt) && $ReviewDetKey1->pending_amt!="0") || (isset($ReviewDetKey1->disc_amt) && $ReviewDetKey1->disc_amt!="0") || (isset($ReviewDetKey1->plus_amt) && $ReviewDetKey1->plus_amt!="0")){echo $ReviewDetKey1->total_amt; }else{echo $tottt;}?>" ></td> <td><label>Discount Amount</label>:</td><td><input type="text" name="disc_amt" id="disc_amt" class="minus1" value="" ><input type="hidden" name="disc_amt1" id="disc_amt1" class="" value="<?php echo $ReviewDetKey1->disc_amt; ?>" ></td> </tr> <tr> <td><label>Add Amount</label>:</td><td><input type="text" name="plus_amt" id="plus_amt" class="plus1" value="" ><input type="hidden" name="plus_amt1" id="plus_amt1" class="" value="<?php echo $ReviewDetKey1->plus_amt; ?>" ></td> <td><label><b>Payment mode: </b></label></td> <td> <select name="payment_mode"> <option value="">---Select---</option> <option value="Cash" <?php if(isset($ReviewDetKey1->payment_mode) && $ReviewDetKey1->payment_mode=="Cash"){?> selected="selected" <?php } ?>>Cash</option> <option value="Cheque" <?php if(isset($ReviewDetKey1->payment_mode) && $ReviewDetKey1->payment_mode=="Cheque"){?> selected="selected" <?php } ?>>Cheque</option> </select> </td> </tr> <tr> <td><label><b>CMR Paid</b></label></td> <td><input type="text" name="service_cmr_paid" id="service_cmr_paid" class="" value=""><input type="hidden" name="service_cmr_paid1" id="service_cmr_paid1" class="" value="<?php if(isset($ReviewDetKey1->cmr_paid)){echo $st = $ReviewDetKey1->cmr_paid;}else{ echo $st = '0'; } ?>"></td> <td><label><b>Pending Amount</b></label></td> <td><input type="text" name="service_pending_amt" id="service_pending_amt" class="" value="<?php if(isset($ReviewDetKey1->pending_amt)){echo $ReviewDetKey1->pending_amt;} ?>"><input type="hidden" name="service_pending_amt1" id="service_pending_amt1" class="" value="<?php if(isset($ReviewDetKey1->pending_amt)){echo $ReviewDetKey1->pending_amt;} ?>"></td> </tr> <tr> <td><label >Status</label></td> <?php foreach($get_status as $get_statusKey){ $stat = $get_statusKey->status;}?> <td> <select name="status"> <option value="3">---Select---</option> <?php foreach($status_listForreadydel as $qcstatuskey){ if($qcstatuskey->id==$stat){ ?> <option selected="selected" value="<?php echo $qcstatuskey->id; ?>"><?php if($qcstatuskey->id=='1'){ echo "Work InProgress";}else{echo $qcstatuskey->status;} ?></option> <?php } else {?> <option value="<?php echo $qcstatuskey->id; ?>"><?php if($qcstatuskey->id=='1'){ echo "Work InProgress";}else{echo $qcstatuskey->status;} ?></option> <?php } } ?> </select> </td> </tr> <tr class="ready box"> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="delivery_date" id="datetimepicker7" value="<?php if(isset($ReviewDetKey1->delivery_date) && $ReviewDetKey1->delivery_date!=""){ echo $ReviewDetKey1->delivery_date; } ?>" ></td> </tr> <tr class="ready box"> <td><label>Comments</label>:</td><td><input type="text" name="comment_ready" class="" value="<?php if(isset($ReviewDetKey1->comments) && $ReviewDetKey1->comments!=""){echo $ReviewDetKey1->comments;} ?>" ></td> </tr> <tr class="delivery box"> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="delivery_date1" id="datetimepicker8" value="<?php echo $ReviewDetKey1->delivery_date; ?>" ></td> </tr> <tr class="delivery box"> <td><label>Comments</label>:</td><td><input type="text" name="comment_deliver" class="" value="<?php if(isset($ReviewDetKey1->comments) && $ReviewDetKey1->comments!=""){echo $ReviewDetKey1->comments;} ?>" ></td> </tr> <tr class="delivery box"> <td><label>Assign To</label>:</td><td><input type="text" name="assign_to" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->emp_name; }?>" readonly><input type="hidden" name="assign_to_id" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->id; }?>" readonly></td> </tr> <tr class="ready"> <td><label>Emp Pts</label>:</td><td><input type="text" name="emp_pts" value="<?php if(isset($ReviewDetKey1->emp_pts) && $ReviewDetKey1->emp_pts!="0"){echo $ReviewDetKey1->emp_pts; }else{echo "0";}?>"></td> </tr> </table> <table class="tableadd"> <tr> <td><label>Notes</label>:</td><td><textarea type="text" name="notes" id="notes" class="materialize-textarea"><?php if($ReviewDetKey1->notes!=""){echo $ReviewDetKey1->notes;}else{foreach($getQuoteByReqId as $notekey){echo $notekey->notes;}} ?></textarea></td> </tr> </table> <?php } ?> <input type="hidden" name="countid" id="countid" class="" value="<?php echo $count; ?>" > <table class="tableadd" style="margin-top: 25px;"> <tr > <td > <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button>&nbsp;<a class="btn cyan waves-effect waves-light " onclick="history.go(-1);">Exit </a> <!--<a id="addRowBtn" class="delivery box" href="<?php echo base_url(); ?>ready_delivery/print_request/<?php echo $req_id; ?>" style="background: rgb(5, 94, 135) none repeat scroll 0% 0% !important; padding: 10.4px !important; color: #FFF !important; border-radius: 5px !important; margin-left: 20px !important;" target="_blank">Print Invoice</a> --> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }); }); }//]]> </script> <script> $('.spare_qty').keyup(function() { //alert($('#tax_type').val()); //alert("fdgvdfgfd"); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); //var qty = $(this).val(); // var actual_qty = $('#spare_qty1'+ctid).val(); if(parseInt($(this).val()) != ""){ if(parseInt($(this).val()) > parseInt($('#spare_qty1'+ctid).val())){ alert("Qty is only: "+ $('#spare_qty1'+ctid).val() + " nos. So please enter below that."); }else{ var cal_amt = parseInt($(this).val()) * parseInt($('#amt1'+ctid).val()); $('#amt'+ctid).val(cal_amt); } } var vals = 0; $('input[name="amt[]"]').each(function() { //alert("dsd"); //alert($(this).val()); vals += Number($(this).val()); //alert(val); $('#spare_tot').val(vals); }); var tax_amt = (vals * $('#tax_type').val()) / 100; if(warran=='Preventive' || warran=='Warranty' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); //alert(Total_amount); $('#total_amt').val(Total_amount); } //$('input[name="res"]').val(val); }); </script> <script> $('#cmr_paid').keyup(function() { var pending_amt_val = $('#pending_amt1').val(); //alert(pending_amt_val); var cmr_paid = $( this ).val(); var pending_amt = parseInt(pending_amt_val) - parseInt(cmr_paid); $('#pending_amt').val(pending_amt); }); </script> <script> $(document).ready(function(){ $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999-19-39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('#datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker8').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker9').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker10').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker11').datetimepicker({ onChangeDateTime:logic, onShow:logic }); }); </script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $('#plus_amt').keyup(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; } else{ var disc_amt = $( this ).val(); //alert(disc_amt); if(disc_amt){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) + parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); }else{ var total_amt = $('#total_amt1').val(); //alert(total_amt); $('#total_amt').val(total_amt); $('#service_pending_amt').val(total_amt); $('#service_pending_amt1').val(total_amt); } } }); $('#disc_amt').keyup(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; } else{ var disc_amt = $( this ).val(); //alert(disc_amt); if(disc_amt){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) - parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); }else{ var total_amt = $('#total_amt1').val(); //alert(total_amt); $('#total_amt').val(total_amt); $('#service_pending_amt').val(total_amt); $('#service_pending_amt1').val(total_amt); } } }); $('#service_cmr_paid').keyup(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; }else{ var service_pending_amt_val = $('#service_pending_amt1').val(); //alert(pending_amt_val); var service_cmr_paid = $( this ).val(); if(service_cmr_paid){ var service_pending_amt = parseInt(service_pending_amt_val) - parseInt(service_cmr_paid); $('#service_pending_amt').val(service_pending_amt); }else{ $('#service_pending_amt').val(service_pending_amt_val); } } }); $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('disc_amt').value!=""){ alert("enter discount or addition amt"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus_amt').value!=""){ alert("enter discount or addition amt"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); </script> </body> </html><file_sep>/application/views/edit_spare_purchase_order.php <head> <style> input[type=text]:-moz-read-only { /* For Firefox */ background-color: #eee; } input[type=text]:read-only { background-color: #eee; } .btn { text-transform:none !important; } .purchasedetail { /* position: relative; */ /* top: -63px; */ /* left: 50px; */ } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script> <style> .delRowBtn{ background: #055E87 none repeat scroll 0% 0% !important; color:#fff; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { border: 1px solid #6b4289; text-align: center; } .tableadd1 tr { height: 50px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:white; } .tableadd1 tr { height: 35px; } .tableadd1 tr td.plus { padding-top: 14px; } .tableadd1 tr td.plus input { width:70px; } .tableadd1 tr td input { height:25px; border-radius: 3px; padding-left: 10px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:black; } #errorBox{ color:#F00; } input[id=basicamount]{ width: 100px; border: 1px solid #ccc; border-radius: 2px; padding: 5px; float:right; position: relative; top: -55px; left: -193px; } input[id=cst]{ width: 100px; border: 1px solid #ccc; border-radius: 2px; padding: 5px; float:right; position: relative; top: -61px; left: -193px; } input[id=freight]{ width: 100px; border: 1px solid #ccc; border-radius: 2px; padding: 5px; float:right; position: relative; top: -56px; left: -81px; } input[id=totalamount]{ width: 100px; border: 1px solid #ccc; border-radius: 2px; padding: 5px; float:right; position: relative; top: -52px; left: 30px; } .tableadd tr td input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 5px; padding-left: 10px; } .rowadd{cursor:pointer;} .select2-drop { width: 100%; margin-top: -1px; position: absolute !important; z-index: 9999; top: 100%; background: #fff; color: #000; border: 1px solid #aaa; border-top: 0; border-radius: 0 0 4px 4px; -webkit-box-shadow: 0 4px 5px rgba(0, 0, 0, .15); box-shadow: 0 4px 5px rgba(0, 0, 0, .15); } </style> <script> $(document).ready(function(){ $( "form" ).submit(function( event ) { if ( $( "#to_name" ).val() === "" ) { $( "#errorbox1" ).text( "Enter the Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'19px','font-size':'10px'}); event.preventDefault(); } if ( $( "#to_addr" ).val() === "" ) { $( "#errorbox2" ).text( "Enter the Address" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#to_cont_name" ).val() === "" ) { $( "#errorbox3" ).text( "Enter the Contact Person " ).show().css({'color':'#ff0000','position':'relative','bottom':'19px','font-size':'10px'}); event.preventDefault(); } if ( $( "#to_cont_no" ).val() === "" ) { $( "#errorbox4" ).text( "Enter the Contact No." ).show().css({'color':'#ff0000','position':'relative','bottom':'19px','font-size':'10px'}); event.preventDefault(); } if ( $( "#spare_name-0" ).val() === "" ) { $( "#errorbox5" ).text( "Select the Item Name" ).show().css({'color':'#ff0000','position':'relative','font-size':'10px'}); event.preventDefault(); } if ( $( ".spare_qty" ).val() === "" ) { $( "#errorbox6" ).text( "Enter the Quantity" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#sr_no" ).val() === "" ) { $( "#errorbox7" ).text( "Enter the Serial No." ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(document).ready(function(){ var regemail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; var regemail1=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; $('#pi,#tin').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z0-9]/g,'') ); }); $('#to_cont_no,#cont_no,#sr_no,.spare_qty').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('input:text[id="to_cont_mail"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z0-9@. ]/g,'') ); }); $('input:text[id="mailv"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z0-9@. ]/g,'') ); }); $('input:text[id="cont_name"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z]/g,'') ); }); $('#from_cont_mail').change(function(){ var email1=$(this).val(); if(!regemail1.test(email1)){ alert("Invalid Email"); $(this).val(""); $(this).focus(); return false; } }); $('#to_cont_no').change(function(){ if($(this).val().length<10){ alert("Mobile Number must be atleast 10 digit"); $(this).val(""); $(this).focus(); return false; } }); $('#cont_no').change(function(){ if($(this).val().length<10){ alert("Mobile Number must be atleast 10 digit"); $(this).val(""); $(this).focus(); return false; } }); }); </script> <script> $(document).ready(function(){ $("#to_name").keyup(function(){ if($(this).val()==""){ $("#errorbox1").show(); } else{ $("#errorbox1").hide(); } }); $("#to_addr").keyup(function(){ if($(this).val()==""){ $("#errorbox2").show(); } else{ $("#errorbox2").hide(); } }); $("#to_cont_name").keyup(function(){ if($(this).val()==""){ $("#errorbox3").show(); } else{ $("#errorbox3").hide(); } }); $("#to_cont_no").keyup(function(){ if($(this).val()==""){ $("#errorbox4").show(); } else{ $("#errorbox4").hide(); } }); $("#spare_name-0").change(function(){ if($(this).val()==""){ $("#errorbox5").show(); } else{ $("#errorbox5").hide(); } }); $(".spare_qty").keyup(function(){ if($(this).val()==""){ $("#errorbox6").show(); } else{ $("#errorbox6").hide(); } }); $("#sr_no").keyup(function(){ if($(this).val()==""){ $("#errorbox7").show(); } else{ $("#errorbox7").hide(); } }); }); </script> <script> $(document).ready(function(){ var regemail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; $('#to_cont_mail').change(function(){ var email1=$(this).val(); if(!regemail.test(email1)){ alert("Invalid Email"); $(this).val(""); $(this).focus(); return false; exit; } }); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow_purchase_order", data: datastring, cache: false, success: function(result) { //alert(result); // $('#table1').append(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; // alert(vl); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ var check=data.purchase_price; //alert(check); if(check !=0) { $('#rate-'+vl).val(data.purchase_price) }else{ $('#rate-'+vl).val('') } }); } }); }); }); </script> </head> <section id="content"> <div class="container"> <form action="<?php echo base_url(); ?>Spare/update_purchase_order" method="post" name="frmSpareEng" autocomplete="off"> <div class="section"> <h2>Edit Spares Purchase Order</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <div class="col-md-12 tableadd" id="addtable" style="width:1100px;"> <div id="errorBox"></div> <?php foreach($comp_info as $comkey){ ?> <div class="col-md-3"> <div><label><b>From,</b></label></div> <div><label>Company Name </label></div> <div><input type="text" name="comp_name" id="comp_name" value="<?php echo $comkey->name; ?>"></div> <div><label>Address </label></div> <div><textarea name="addr" id="addr" maxlength="250"><?php echo $comkey->addr1.' '.$comkey->addr2; ?></textarea></div> <div><label>Contact Person </label></div> <div><input type="text" name="cont_name" id="cont_name" value="Sandhya" maxlength="50"></div> <div><label>Contact No.</label></div> <div> <input type="text" name="cont_no" id="cont_no" value="" maxlength="15"></div> <div><label>Mail ID </label></div> <div> <input type="text" name="" id="from_cont_mail" value=""></div> </div> <?php } ?> <?php foreach($get_purchase_ordersbyid as $vendorkey){ ?> <div class="col-md-3"> <div><label><b>To,</b></label></div> <div><label>Vendor Name </label><span style="color:red;">*</span></div> <div><input type="text" name="to_name" id="to_name" maxlength="50" value="<?php echo $vendorkey->to_name; ?>"><span style="color:red;" id="errorbox1"></span></div> <!--<input type="text" name="vendor_name" id="vendor_name" value="">--> <div><label>Address </label><span style="color:red;">*</span></div> <div><textarea name="to_addr" maxlength="250" id="to_addr"><?php echo $vendorkey->to_addr; ?></textarea><span style="color:red;" id="errorbox2"></span></div> <!--<textarea name="vendor_addr" id="vendor_addr"></textarea>--> <div><label>Contact Person </label><span style="color:red;">*</span></div> <div><input type="text" class="cperson" name="to_cont_name" id="to_cont_name" maxlength="50" value="<?php echo $vendorkey->to_cont_name; ?>"><span style="color:red;" id="errorbox3"></span></div> <!--<input type="text" name="vendor_cont_name" id="vendor_cont_name" value="">--> <div><label>Contact No. </label><span style="color:red;">*</span></div> <div><input type="text" name="to_cont_no" id="to_cont_no" value="<?php echo $vendorkey->to_cont_no; ?>" maxlength="15"><span style="color:red;" id="errorbox4"></span></div> <!--<input type="text" name="vendor_cont_no" id="vendor_cont_no" value="">--> <div><label>Mail ID </label></div> <div><input type="text" name="to_cont_mail" id="to_cont_mail" value="<?php echo $vendorkey->to_cont_mail; ?>"></div> <!--<input type="text" name="vendor_mail" id="vendor_mail" value="">--> </div> <?php } ?> <?php foreach($get_purchase_ordersbyid as $key2){ ?> <div class="tableadd tableleft col-md-3" id="addtable" > <div></div> <div><label>Date </label></div> <div><input type="text" id="datepicker" name="todaydate" class="purchasedetail" value="<?php echo $key2->todaydate;?>"><input type="hidden" name="po_id" id="po_id" value="<?php echo $key2->id; ?>"></div> <div><label>P.I / Ref No. </label></div> <div><input type="text" name="refno" class="pipurchasedetail" maxlength="25" value="<?php echo $key2->refno;?>" id="pi"></div> <div><label>TIN / CST No. </label></div> <div><input type="text" name="cst_no" class="cstpurchasedetail" maxlength="25" value="<?php echo $key2->cst_no;?>" id="tin"></div> </div> <?php } ?> </div> <div style="margin: 30px 0px;"> <table id="table1" class="tableadd1" style="width:100%;"> <tr style="background: rgb(112, 66, 139) none repeat scroll 0% 0%"><td><label>SI. No.</label><span style="color:red;">*</span></td> <td><label>Part Number & Item Name</label><span style="color:red;">*</span></td> <td><label>Qty</label><span style="color:red;">*</span></td> <td><label>Rate per Unit</label></td> <td><label>Total Amount</label></td></tr> <?php $i=0;foreach($get_purchase_orders_sparesbyid as $sparekey){ ?> <tr> <td class="plus"><input type="text" class="sino" name="sr_no[]" id="sr_no" value="<?php echo $sparekey->sr_no;?>" maxlength="5"><br><span style="color:red;"id="errorbox7"></td> <td><select name="spare_name[]" id="spare_name-0" class="chosen-select form-control spare_name"> <option value="">---Select---</option> <?php foreach($spare_list as $sparekey1){ if($sparekey1->id==$sparekey->spare_name){?> <option selected="selected" value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name; ?></option> <?php } else{?> <option value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name; ?></option> <?php } }?> </select><br><span style="color:red;"id="errorbox5"></td> <td class="plus"><input type="text" name="spare_qty[]" id="spare_qty-0" class="spare_qty" value="<?php if($sparekey->spare_qty !=0){ echo $sparekey->spare_qty;}?>" maxlength="5"><br><span style="color:red;"id="errorbox6"></td> <td class="plus"><input type="text" name="rate[]" id="rate-0" value="<?php if($sparekey->rate !=0){ echo $sparekey->rate;}?>" readonly></td> <td class="plus"><input type="text" name="spare_tot[]" id="spare_tot-0" style="width:100px" value="<?php if($sparekey->spare_tot !=0){echo $sparekey->spare_tot;}?>" readonly></td> <?php if($i==0){?> <td style="border:none !important;"> <a id="addMoreRows" class="rowadd " ><i class="fa fa-plus-square" style="color:#70428b;"></i></a></td> <?php }else{?> <td style="border:none !important;"> <a onclick="$(this).closest('tr').remove();" ><i class="fa fa-trash" style="color:#70428b;"></i></a></td> <?php }?> </tr> <?php $i++; } ?> </table> <br> <?php foreach($get_purchase_ordersbyid as $key3){ ?> <div class="col-md-6" style=" float: right; margin-right:-123px;"> <div><label style="margin-left: 51px;">Basic Amount</label></div><br> <div><input type="text" name="basicamount" id="basicamount" class="bamount" value="<?php if($key3->basicamount !=0){echo $key3->basicamount; }?>" readonly></div> <div><label style="margin-left: 51px;"> <select name="cst1" id="cst1" class="cst1"> <?php foreach($tax_list as $taxkey){ if($taxkey->tax_name!="" && isset($taxkey->tax_name)){ if($taxkey->id==$key3->tax_id){ ?> <option selected='selected' value="<?php echo $taxkey->id.'-'.$taxkey->tax_percentage; ?>"><?php echo $taxkey->tax_name.'@'.$taxkey->tax_percentage; ?></option> <?php } else{ ?> <option value="<?php echo $taxkey->id.'-'.$taxkey->tax_percentage; ?>"><?php echo $taxkey->tax_name.'@'.$taxkey->tax_percentage; ?></option> <?php }}}?> </select> </label></div><br> <div><input type="text" name="cst" id="cst" class="bamount" value="<?php if($key3->cst !=0){ echo $key3->cst;} ?>" readonly></div> <div><label style="margin-left: 51px;">Freight</label></div><br> <div><input type="text" name="freight" id="freight" class="freight" value="<?php if($key3->freight !=0){echo $key3->freight; }?>" maxlength="10"></div> <div><label style="margin-left: 51px;">Total Amount</label></div><br> <div><input type="text" name="totalamount" id="totalamount" class="bamount" value="<?php if($key3->totalamount !=0){echo $key3->totalamount; }?>" maxlength="10" readonly><input type="hidden" name="totalamount1" id="totalamount1" class="bamount" value="<?php echo $key3->totalamount; ?>"> <?php } ?> <input type="hidden" name="countid" id="countid" class="" value="0"> </div> </div> <br><br> </div> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> <p><b>Imp Note:</b> Minimum order value should be Rs. 3000/- for spare parts.</p> <p><b>Note:</b> If Shipping address is different form above address pls mention here.</p> <?php foreach($get_purchase_ordersbyid as $key4){ ?> <!--<p><b>Address:</b> <textarea name="spec_addr" col="5" rows="5" class="form-control" style="width:280px;position:relative;left:70px;top:-23px"><?php echo $key4->spec_addr; ?></textarea></p> <p><b>Any Specific instruction:</b> <textarea name="spec_ins" col="5" rows="5" class="form-control" style="width:280px;position:relative;left:175px;top:-23px"><?php echo $key4->spec_ins; ?></textarea></p><br><br>--> <div class="col-md-12"> <div class="col-md-3" style="margin-right: 87px;"> <div><b>Address:</b></div> <div><textarea name="spec_addr" col="5" rows="5" class="form-control" style="width:280px;"><?php echo $key4->spec_addr; ?></textarea></p></div> </div> <div style="col-md-3"> <div><b>Any Specific instruction:</b></div> <div><textarea name="spec_ins" col="5" rows="5" class="form-control" style="width:280px;"><?php echo $key4->spec_ins; ?></textarea></div> </div> </div> <?php } ?> <p><b>Terms and Conditions:</b><br> <ol> <li>Payment 100% Advance Payment by DD/ Cash in our HDFC Bank account in favor of Arihant Marketing</li> <li>If "C" form not received on date, interest @24% per annum will be charged from the actual amount.</li> <li>All disputes subject to jurisdication of Chennai Courts.</li> <li>Kindly fill your order form with Part Name No clearly and send to concern person.</li> <li>For Parts under warranty compulsory send faulty spares for getting replacement of new; with m/c serial no, wherever applicable.</li> <li>Order processing will take minimum 2-3 working days.</li> <li>No orders will be processsed if PO value is less than Rs 3000/-</li> <li>Chick for stock availability before placing order.</li> <li>Payment details must be sent for timely dispatch.</li> </ol> </div> <br><br> <a href="<?php echo base_url(); ?>Spare/print_purchase_order/<?php echo $key2->id; ?>" class="btn cyan waves-effect waves-light" style="right: -11px; height: 38px; width: 163px; font-size: 13px;" target="_blank">Print Purchase Order</a> <button class="btn cyan waves-effect waves-light" type="submit" name="action" style="float:left;position: relative;left: 0px; width: 100px;">Submit</button> <br><br><br><br> </section> </div> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery-ui.css"> <script src="<?php echo base_url(); ?>assets/js/jquery-ui.min.js"></script> <!--<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script> <script> $(function(){ $("#datepicker").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: "1950:2055" }); }) </script> <script> $('.spare_qty').keyup(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('-'); var ctid = arr['1']; if(parseInt($(this).val()) && parseInt($('#rate-'+ctid).val())){ //alert("hello"); var cal_amt = parseInt($(this).val()) * parseInt($('#rate-'+ctid).val()); if(cal_amt !=0){ $('#spare_tot-'+ctid).val(cal_amt); }else{ $('#spare_tot-'+ctid).val(''); } }else{ $('#spare_tot-'+ctid).val(''); } var vals = 0; $('input[name="spare_tot[]"]').each(function() { //alert("dsd"); //alert($(this).val()); vals += Number($(this).val()); //alert(val); if(vals !=0){ $('#basicamount').val(vals); }else{ $('#basicamount').val(''); } }); var cst1 = $('#cst1').val(); var cst1_arr = cst1.split('-'); var tax_type = cst1_arr[1]; var tax_amt = (vals * tax_type) / 100; //var tax_amt = (vals * 14.5) / 100; if(tax_amt !=0){ $('#cst').val(tax_amt); }else{ $('#cst').val(''); } var freight_amt = $('#freight').val(); var total_spare_charge = $('#basicamount').val(); if(parseInt($('#freight').val())){ var Total_amount = parseInt(tax_amt) + parseInt(total_spare_charge) + parseInt(freight_amt); //alert(Total_amount); if(parseInt(Total_amount)){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); }else{ $('#totalamount').val(''); $('#totalamount1').val(''); } }else{ var Total_amount = parseInt(tax_amt) + parseInt(total_spare_charge); //alert(Total_amount); if(parseInt(Total_amount)){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); }else{ $('#totalamount').val(''); $('#totalamount1').val(''); } } }); $('#cst1').change(function() { var tax_name1 = $(this).val(); var tax_name1_arr = tax_name1.split('-'); var tax_name = tax_name1_arr[1]; var basicamount= $('#basicamount').val(); var tax_amt = (basicamount * tax_name) / 100; $('#cst').val(tax_amt); var freight_amt = $('#freight').val(); if(parseInt($('#freight').val())){ var Total_amount = parseInt(basicamount) + parseInt(tax_amt) + parseInt(freight_amt); //alert(Total_amount); if(Total_amount){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); }else{ $('#totalamount').val(''); $('#totalamount1').val(''); } }else{ var Total_amount = parseInt(basicamount) + parseInt(tax_amt); //alert(Total_amount); if(Total_amount){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); }else{ $('#totalamount').val(''); $('#totalamount1').val(''); } } }); </script> <script> $('.freight').keyup(function() { var freight_amt = $(this).val(); var totalamount = $('#totalamount1').val(); if(parseInt($(this).val())){ var Totall_amount = parseInt(freight_amt) + parseInt(totalamount); //alert("1"); //alert(Totall_amount); if(parseInt(Totall_amount)){ $('#totalamount').val(Totall_amount); }else{ $('#totalamount').val(''); } }else{ if(parseInt(totalamount)){ //alert(totalamount); $('#totalamount').val(totalamount); }else{ $('#totalamount').val(''); } } }); </script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css"> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function() { $(".spare_name").select2(); /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); $(".freight,.spare_qty,.sino").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9 ]/g,"")); }); $(".cperson").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z ]/g,"")); }); </script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>customer/add_quickforspares/'+id, type : 'iframe', padding : 5 }); } </script> <script> function setSelectedUser(customer_name,cust_idd,spare_rowid) { //alert("JII"); $('#custtest_'+spare_rowid).val(customer_name); $('#cust_id_'+spare_rowid).val(cust_idd); } </script> </body> </html><file_sep>/application/views/add_prob_cat.php <style> #addMoreRows{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color:#49186d; } .delRowBtn{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 0px 4px 4px 4px; border-radius: 5px; color: white; height:30px; } </style> <script> $(function(){ $( "#product" ).click(function( event ) { if ( $( "#prob_cat_name1" ).val() === "" ) { $( "#prob_cat_name_error1" ).text( "Enter the Problem Category Name" ).show().css({ 'color':'#ff0000', 'font-size':'10px' }); event.preventDefault(); } if ( $( "#model1" ).val() === "" ) { $( "#model_error1" ).text( "Please choose the model" ).show().css({ 'color':'#ff0000', 'font-size':'10px' }); event.preventDefault(); } if ( $( "#prob_code1" ).val() === "" ) { $( "#prob_code_error1" ).text( "Enter the Problem Category Code" ).show().css({ 'color':'#ff0000', 'font-size':'10px' }); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#prob_cat_name1").keyup(function(){ if($(this).val()==""){ $("#prob_cat_name_error1").show(); } else{ $("#prob_cat_name_error1").hide(); } }); $("#model1").change(function(){ if($(this).val()==""){ $("#model_error1").show(); } else{ $("#model_error1").hide(); } }); $("#prob_code1").keyup(function(){ if($(this).val()==""){ $("#prob_code_error1").show(); } else{ $("#prob_code_error1").hide(); } }); $("#prob_code1,#prob_cat_name1").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9 ]/g,'') ); }); }); </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $(document).on("click","#addMoreRows", function(){ //alert("ddssss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>problemcategory/addrow", data: datastring, cache: false, success: function(result) { // alert(result); $('#myTable > tbody').append(result); } }); }); }); </script> <script> $(function() { $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }) </script> <!--<script> $(document).ready(function(){ $('#prob_code1').change(function(){ var prob_code=$(this).val(); //alert(prob_code); var datastring='code='+prob_code; $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkCode", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ $('#name_error').html('Problem Code already Exist!').show(); $('#prob_code1').val(''); } else if(data==0) { $('#name_error').hide(); } } }); }); }); </script> --> <script> $(document).ready(function(){ $(document).on("keyup","#prob_cat_name1", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ //$('#prob_cat_name1').change(function(){ var prob_code=$('#prob_cat_name1').val(); var model=$('#model1').val(); //alert(prob_code); var datastring='code='+model+'&problem='+prob_code; //alert(datastring); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkproblem", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ //alert("hiii"); $('#prob_cat_name_error1').html('Problem Category Name Already Exist!').show().css({'color':'#ff0000','font-size':'10px'}); $('#prob_cat_name1').val(''); } else { $('#prob_cat_name_error1').hide(); } } }); } }); </script> <style> .btn{text-transform:none !important;} .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } body{background-color:#fff;} table{ margin-bottom:15px; } table, th, td { border: 1px solid #522276; border-collapse: collapse; } th, td { padding: 5px 15px; } table, td:last-child{ border:0px; } thead { border-bottom: 0px solid #d0d0d0; background-color: #dbd0e1; border: 0px solid #055E87; color: #522276; } select { border: 1px solid #ccc !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { border:1px solid #ccc; margin: 0 0 0px 0; height: 2.9rem; } .link{ cursor:pointer; color:#fff; font-weight:bold; } .link:hover{ cursor:pointer; color:#fff; font-weight:bold; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Problem Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>problemcategory/add_prob_category" method="post"> <table id="myTable"> <thead> <tr> <th>Problem Code<span class="star" style="color:red">*</span></th> <th style="width:30%">Model<span class="star"style="color:red">*</span></th> <th>Problem Category Name<span class="star"style="color:red">*</span></th> <th>Description</th> </tr> </thead> <tbody> <tr> <td> <input type="text" name="prob_code[]" id="prob_code1" class="prob_cate" maxlength="50"> <div id="prob_code_error1" style="color:red"></div> <div id="name_error1" style="color:red"></div> </td> <td> <select name="model[]" id="model1"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="dpt_error1" style="color:red;"></div> <div id="model_error1" style="color:red;"></div> </td> <td> <input type="text" name="prob_cat_name[]" id="prob_cat_name1" class="prob_cate" maxlength="50"> <div id="hname1" style="color:red;"></div> <div id="prob_cat_name_error1" style="color:red"></div> </td> <td> <textarea name="p_description[]" type="text" id="p_description1" value="" /></textarea> </td> <input type="hidden" id="countid" value="1"> <td> <a class="link" id="addMoreRows"><i class="fa fa-plus-square" aria-hidden="true"></i></a> </td> </tr> </tbody> </table> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action" id="product" style="color:#fff;">Submit</button> </form> </div> </div> </div> <div class="col-md-1"> </div> </div> </div> </div> </section> </div> </div> <script> $(document).on("change","#model", function(){ var category=$("#cate").val(); var model = $(this).find("option:selected").attr("value"); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>problemcategory/add_prob_category', data: { category:category, model:model, }, success: function (data) { if(data == 0){ $('#dpt_error1').fadeOut('slow'); } else{ $('#dpt_error1').text('Brand Name Already Exist').show().delay(1000).fadeOut(); $('#model').val(''); return false; } } }); }); </script> </body> </html><file_sep>/application/views/view_qc_model.php <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="http://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script src="http://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" ></script> <style> h2 { color: #000; font-family: 'Source Sans Pro',sans-serif; } table.dataTable tbody th, table.dataTable tbody td { padding: 3px 10px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; color: #000; font-size: 13px; } table.dataTable tbody tr:nth-child(even) {background: #f9f9f9} table.dataTable tbody tr:nth-child(odd) {background: #eaeaea} table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 8px !important; border: 1px solid #522276 !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; /*color: #303f9f;*/ background:#6c477d; color:#fff; } input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } h2{ color: #6C217E; } </style> </head> <body> <div class="container"> <h2>Service Charge List</h2> <table cellpadding="1" cellspacing="1" id="detailTable"> <thead> <tr> <th>Model</th> <th>Charge</th> </tr> </thead> <tbody> <?php foreach($getqcparametersbyid1 as $res_key){?> <tr> <td> <?php echo $res_key->qc_param; ?>"</td> <td><?php echo $res_key->qc_value;?></td> </tr> <?php } ?> </tbody> </table> </div> <script> $(document).ready(function() { $('#detailTable').DataTable(); }); </script> </body> </html><file_sep>/application/views_bkMarch_0817/brand_list.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link href="js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="js/plugins/data-tables/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <style> table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } </style> </head> <body> <div id="loader-wrapper"> <!-- <div id="loader"></div> --> <div class="loader-section section-left"></div> <div class="loader-section section-right"></div> </div> <header id="header" class="page-topbar"> <?php include('header.php'); ?> </header> <div id="main"> <div class="wrapper"> <?php include('menu.php'); ?> <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Product Brand List</h4> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" cellspacing="0" style="width:70%; margin-top:2%;"> <thead> <tr> <td>Category Name</td> <td>Sub-Category Name</td> <td>Brand Name</td> <td>Action</td> </tr> </thead> <tbody> <tr> <td><input type="text" value="Air Conditioner" class="" name=""></td> <td><input type="text" value="Subcategory 1" class="" name=""></td> <td><input type="text" value="Brand 1" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> <tr> <td><input type="text" value="Television" class="" name=""></td> <td><input type="text" value="SubCategory 2" class="" name=""></td> <td><input type="text" value="Brand 2" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> <tr> <td><input type="text" value="Digital Camera" class="" name=""></td> <td><input type="text" value="SubCategory 3" class="" name=""></td> <td><input type="text" value="Brand 3" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> <tr> <td><input type="text" value="Mobile Phone" class="" name=""></td> <td><input type="text" value="SubCategory 4" class="" name=""></td> <td><input type="text" value="Brand 4" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> <tr> <td><input type="text" value="Cash Counting Machine" class="" name=""></td> <td><input type="text" value="SubCategory 5" class="" name=""></td> <td><input type="text" value="Brand 5" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> <tr> <td><input type="text" value="Washing Machine" class="" name=""></td> <td><input type="text" value="SubCategory 6" class="" name=""></td> <td><input type="text" value="Brand 6" class="" name=""></td> <td class="options-width"> <a href="#" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i class="fa fa-trash-o fa-3x"></i></a> </td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="js/plugins.js"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/controllers/Productcategory.php <?php class Productcategory extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Productcategory_model'); } public function add_prod_category(){ $cat_name=$this->input->post('cat_name'); $c=$cat_name; $count=count($c); for($i=0; $i<$count; $i++) { if($cat_name[$i]!=""){ $data1 = array('product_category' => $cat_name[$i]); $result=$this->Productcategory_model->add_prod_cat($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_prod_cat';alert('Please enter Product Category');</script>"; } */ } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/prod_cat_list';alert('Product Category Added Successfully!!!');</script>"; } } public function update_prod_category(){ $id=$this->uri->segment(3); $data['list']=$this->Productcategory_model->getprodcatbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_prod_cat',$data); } public function edit_prod_category(){ $user=array('product_category'=>$this->input->post('cat_name')); $catid=$this->input->post('catid'); $data=array( 'product_category'=>$this->input->post('cat_name') ); $s = $this->Productcategory_model->update_prod_cat($data,$catid); echo "<script>alert('Product Category Updated Successfully!!!');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function update_status_prod_category(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Productcategory_model->update_status_prod_cat($data,$id); echo "<script>alert('Product Category made Inactive');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function update_status_prod_category1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Productcategory_model->update_status_prod_cat1($data,$id); echo "<script>alert('Product Category made active');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function category_validation() { $product_id = $this->input->post('p_id'); //echo $product_id; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Productcategory_model->category_validation($product_id))); } public function add_prodrow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_prod',$data); } }<file_sep>/application/models/Ready_delivery_model.php <?php class ready_delivery_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function ready_delivery_list($user_access,$user_type){ if($user_type=="1"){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.active_req, customers.customer_name",FALSE); $this->db->from('service_request'); $this->db->join('quote_review', 'quote_review.req_id=service_request.id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request.active_req', '0'); $this->db->where_in('service_request.status', array('3')); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); }else{ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.active_req, customers.customer_name",FALSE); $this->db->from('service_request'); $this->db->join('quote_review', 'quote_review.req_id=service_request.id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request.active_req', '0'); $this->db->where_in('service_request.status', array('3')); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } public function service_req_list1(){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request.id, service_request.active_req, service_request_details.machine_status, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->where('service_request.active_req', '0'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforEmp(){ $this->db->select("service_request_details.request_id, service_request.id, service_request.active_req, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforEmp1($id){ $this->db->select("service_request_details.request_id, service_request.id, service_request.active_req, employee.emp_name, employee.id",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->where('service_request.active_req', '0'); $this->db->where('service_request_details.request_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforProb(){ $this->db->select("service_request_details.request_id, service_request.id, service_request.active_req, problem_category.prob_category",FALSE); $this->db->from('service_request_details'); $this->db->join('problem_category', 'problem_category.id = service_request_details.problem'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->where('service_request.active_req', '0'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforserviceCat(){ $this->db->select("service_request_details.request_id, service_request.id, service_request.active_req, service_category.service_category",FALSE); $this->db->from('service_request_details'); $this->db->join('service_category', 'service_category.id = service_request_details.service_cat'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->where('service_request.active_req', '0'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_details($id){ $this->db->select("*",FALSE); $this->db->from('stamping_details'); $this->db->where('req_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function status_listForStampingworkInpro(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $this->db->where_in('id', array('4')); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_stamping_details($data,$id){ $this->db->where('req_id',$id); $this->db->update('stamping_details',$data); } public function log_stamping_details($data){ $this->db->insert('log_stamping',$data); } public function get_stamping_details($reqid){ $this->db->select("*",FALSE); $this->db->from('stamping_details'); $this->db->where('req_id', $reqid); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_quotereview1($data,$id){ $this->db->where('req_id',$id); $this->db->update('quote_review',$data); } public function getWarrantyInfo($id){ $this->db->select("id, machine_status",FALSE); $this->db->from('service_request_details'); //$this->db->join('order_details', 'order_details.serial_no = service_request_details.serial_no'); $this->db->where('request_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function status_listForquoteInpro(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $this->db->where_in('id', array('3')); $query = $this->db->get(); return $query->result(); } public function status_listForreadydel(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $this->db->where_in('id', array('1','2','4')); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_status($id){ $this->db->select("service_request.status",FALSE); $this->db->from('service_request'); $this->db->join('quote_review', 'quote_review.req_id = service_request.id'); $this->db->where('service_request.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function add_quotereview($data){ $this->db->insert('quote_review',$data); } public function add_quotereview_spares($data1){ $this->db->insert_batch('quote_review_spare_details',$data1); } /*public function getQuoteReviewDetByID($id){ $this->db->select("quote_review.status",FALSE); $this->db->from('quote_review'); // $this->db->join('quote_review_spare_details', 'quote_review_spare_details.request_id = quote_review.req_id'); $this->db->where('quote_review.req_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); }*/ public function getQuoteReviewDetByID1($id){ $this->db->select("quote_review.spare_tax, quote_review.spare_tot, quote_review.labourcharge, quote_review.concharge, quote_review.total_amt, quote_review.delivery_date, quote_review.model_id, quote_review.notes, quote_review.comments, quote_review.cust_feed, quote_review.disc_amt, quote_review.pending_amt, quote_review.cmr_paid, quote_review.payment_mode, quote_review.plus_amt, quote_review.emp_pts",FALSE); $this->db->from('quote_review'); // $this->db->join('quote_review_spare_details', 'quote_review_spare_details.request_id = quote_review.req_id'); $this->db->where('quote_review.req_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result()); return $query->result(); } public function log_service_payment_details($data){ $this->db->insert('log_service_payment_details',$data); } public function getQuoteReviewSpareDetByID($id){ $this->db->select("quote_review_spare_details.id, quote_review_spare_details.spare_id, quote_review_spare_details.spare_qty, quote_review_spare_details.amt",FALSE); $this->db->from('quote_review_spare_details'); //$this->db->join('quote_review_spare_details', 'quote_review_spare_details.request_id = quote_review.req_id'); $this->db->where('quote_review_spare_details.request_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function log_stampings($id){ $this->db->select("*",FALSE); $this->db->from('log_onhold_stamping'); //$this->db->join('order_details', 'order_details.serial_no = service_request_details.serial_no'); $this->db->where('req_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getQuoteByReqId($id){ $this->db->select("customers.customer_name, customers.mobile, customers.company_name, customer_service_location.branch_name, customer_service_location.mobile As cust_mobile, customer_service_location.address, customer_service_location.address1, products.model, products.id As modelid, service_request_details.warranty_date, service_request.request_id, service_request.request_date, service_request.id As req_id, service_request_details.machine_status, service_request_details.notes, service_request_details.assign_to, service_request_details.blank_app, service_request_details.service_cat, service_request_details.problem, service_request_details.accepted_engg_id, service_location.service_loc, service_location.concharge ,order_details.purchase_date, order_details.serial_no, service_request.status",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id = service_request_details.request_id'); $this->db->join('customers', 'customers.id = service_request.cust_name'); $this->db->join('customer_service_location', 'customer_service_location.id = service_request.br_name'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->join('order_details', 'order_details.serial_no = service_request_details.serial_no'); $this->db->where('service_request_details.request_id', $id); $this->db->group_by('service_request_details.request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->row());exit; return $query->result(); } public function getProbforQuoteByReqId($id){ $this->db->select("problem_category.id, problem_category.prob_category",FALSE); $this->db->from('service_request_details'); $this->db->join('problem_category', 'problem_category.id = service_request_details.problem'); $this->db->where('service_request_details.request_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->row());exit; return $query->result(); } public function getServiceCatbyID($service_service_cat, $service_modelid){ $this->db->select("service_charge.id, service_charge.service_charge, service_category.service_category",FALSE); $this->db->from('service_charge'); $this->db->join('service_category', 'service_category.id = service_charge.service_cat_id'); //$this->db->join('service_charge', 'service_charge.service_cat_id = service_request_details.service_cat'); $this->db->where('service_charge.service_cat_id', $service_service_cat); $this->db->where('service_charge.model', $service_modelid); $query = $this->db->get(); // echo $this->db->last_query(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_stats($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function update_quotereview($data,$id){ $this->db->where('req_id',$id); $this->db->update('quote_review',$data); } public function delete_quote_review($id){ $this->db->where('request_id',$id); $this->db->delete('quote_review_spare_details'); } public function status_list(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $query = $this->db->get(); return $query->result(); } public function spareListByModelId($modelid){ $this->db->select("spares.id, spares.spare_name, spares.spare_qty, spares.used_spare, spares.sales_price",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.model_id', $modelid); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsparedetbyid($id){ $this->db->select("spares.id, spares.spare_name, spares.spare_qty, spares.used_spare, spares.stock_spare, spares.sales_price",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spares.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsparedetForEditbyid($id){ $this->db->select("id, spare_name, spare_qty, used_spare, sales_price",FALSE); $this->db->from('spares'); //$this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spares.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsparebyid($id){ $query = $this->db->get_where('spares', array('id' => $id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getupspare($where){ $query = $this->db->get_where('petty_spare', $where); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function updatepspare($n_data,$where) { /* $this->db->where('spare_id',$id); return $this->db->update('petty_spare',$p_data); */ $qry = $this->db->update_string('petty_spare', $n_data, $where); $this->db->query($qry); } public function getTaxDefaultInfo(){ $query = $this->db->get_where('tax_details', array('tax_default' => '1')); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_spare_balance($data){ // $this->db->where('id',$id); $this->db->update_batch('spares',$data,'id'); } public function customerlist(){ $this->db->select("id, customer_id, customer_name, customer_type, mobile, email_id",FALSE); $this->db->from('customers'); $query = $this->db->get(); return $query->result(); } public function list_serialnos(){ $this->db->select("serial_no",FALSE); $this->db->from('order_details'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_list(){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqbyid($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.mobile, service_request.email_id, customers.customer_name, customers.id As cust_id",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqDetailsbyid($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.serial_no, service_request_details.warranty_date, service_request_details.service_type, service_request_details.service_cat, service_request_details.zone, service_request_details.problem, service_request_details.assign_to, service_request_details.received, service_request_details.machine_status, prod_category.id As catid, prod_subcategory.id As subcatid, brands.id As brandid, products.id As modelid, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model, service_location.service_loc, service_location.id As locid",FALSE); $this->db->from('service_request_details'); $this->db->join('prod_category', 'prod_category.id = service_request_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = service_request_details.subcat_id'); $this->db->join('brands', 'brands.id = service_request_details.brand_id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getserviceEmpbyid($id){ $this->db->select("service_request_details.assign_to, employee.id As emp_id, employee.emp_name ",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function servicecat_list(){ $this->db->select("id,service_category ",FALSE); $this->db->from('service_category'); $query = $this->db->get(); return $query->result(); } public function problemlist(){ $this->db->select("id,prob_category ",FALSE); $this->db->from('problem_category'); $query = $this->db->get(); return $query->result(); } public function employee_list(){ $this->db->select("id, emp_id, emp_name",FALSE); $this->db->from('employee'); $query = $this->db->get(); return $query->result(); } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $query = $this->db->get(); return $query->result(); } public function brandlist(){ $this->db->select("id, cat_id, subcat_id, brand_name",FALSE); $this->db->from('brands'); $query = $this->db->get(); return $query->result(); } public function serviceLocList(){ $this->db->select("id, service_loc",FALSE); $this->db->from('service_location'); $query = $this->db->get(); return $query->result(); } public function get_branch($id){ $query = $this->db->get_where('customer_service_location', array('customer_id' => $id)); return $query->result(); } public function getsub_cat($id){ $query = $this->db->get_where('prod_subcategory', array('prod_category_id' => $id)); return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function get_brands($categoryid,$subcatid){ $query = $this->db->get_where('brands', array('cat_id' => $categoryid, 'subcat_id' => $subcatid)); return $query->result(); } public function get_models($categoryid,$subcatid,$brandid){ $query = $this->db->get_where('products', array('category' => $categoryid, 'subcategory' => $subcatid, 'brand' => $brandid)); return $query->result(); } public function orderlist1(){ $this->db->select("orders.id, customers.customer_name,customers.customer_type",FALSE); $this->db->from('orders'); $this->db->join('customers', 'customers.id=orders.customer_id'); $this->db->order_by('orders.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_service_request($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function delete_serv_req_details($id){ $this->db->where('request_id',$id); $this->db->delete('service_request_details'); } public function delete_orders($id){ $this->db->where('id',$id); $this->db->delete('orders'); } }<file_sep>/application/views/expiry_list.php <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 8px !important; border: 1px solid #522276 !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 5px; border: 1px solid #522276 !important; } th { padding: 5px; text-align: center; font-size: 12px; border: 1px solid #dbd0e1 !important; /*background-color: white;*/ } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; /*color: #303f9f;*/ background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Expiring Contract List</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th class="hidden" >id</th> <!--<th>Customer ID</th>--> <th>S.No</th> <th>Customer Name</th> <th>Branch</th> <th>Mobile</th> <th>Product Name</th> <th>Model</th> <th>Serial No.</th> <th>Purchase Date</th> <th>Warranty Date</th> <th>Preventive Maintenance End Date</th> <th>Location</th> <th>Action</th> <!--<th>Action</th>--> <!--<th>Action</th>--> </tr> </thead> <tbody> <?php error_reporting(0); /* $servername = "localhost"; $username = "root"; $password = ""; $dbname = "syndinzg_service"; */ $servername = "localhost"; $username = "syndinzg_service"; $password = "<PASSWORD>"; $dbname = "syndinzg_service"; $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT ord.id,cust.customer_name,cust.company_name ,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ordt.amc_type,ser_loc.service_loc, csl.branch_name, csl.id As csl_id,ordt.serial_no,cust.customer_id, ordt.rent_type FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join customer_service_location As csl ON csl.id=ord.customer_service_loc_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE (datediff(ordt.warranty_date, date(now())) <= 30 and datediff(ordt.warranty_date, date(now())) >= 0 and ordt.amc_end_date='' and ordt.paid='') or (datediff(ordt.prev_main, date(now())) <= 30 and datediff(ordt.prev_main, date(now())) >= 0 and ordt.amc_end_date='' and ordt.paid='') or (datediff(ordt.amc_end_date, date(now())) <= 30 and datediff(ordt.amc_end_date, date(now())) >= 0 and ordt.paid='')ORDER BY ord.id DESC"); $i=1; //$res = mysql_fetch_array($qry); if(mysql_fetch_array($qry)!=''){ while($res = mysql_fetch_array($qry)) {?> <tr> <td class="hidden"><?php echo $res['id'];?></td> <!--<td ><?php echo $res['customer_id'];?></td>--> <td><?php echo $i;?></td> <td><?php echo $res['company_name'];?><input type="hidden" name="order_id" id="order_id" value="<?php echo $res['id'];?>"></td> <td><?php echo $res['branch_name'];?></td> <td><?php echo $res['mobile'];?></td> <td><?php echo $res['product_name'];?></td> <td><?php echo $res['model']; ?></td> <td><?php echo $res['serial_no']; ?></td> <td><?php if($res['purchase_date']!=""){echo date("d-m-Y", strtotime($res['purchase_date']));} ?></td> <td><?php if($res['warranty_date']!=""){echo date("d-m-Y", strtotime($res['warranty_date']));} ?></td> <td><?php if($res['prev_main']!=""){echo date("d-m-Y", strtotime($res['prev_main']));} ?></td> <td><?php echo $res['service_loc'];?></td> <td class="options-width" style="width: 130px;"> <select name="stats[]" id="stats_<?php echo $res['id']; ?>"> <option value="">----Select-----</option> <?php //if($res['warranty_date']!=""){?> <!--<option <?php //if($res['amc_type']=='Out of Warranty'){?>selected="selected"<?php //}?> value="<?php //echo $res['id'].'- Out of Warranty'; ?>"><?php //echo "Out of Warranty"; ?></option>--> <?php //} ?> <?php //if($res['prev_main']!=""){?> <!--<option <?php //if($res['amc_type']=='Out of Preventive Maintenance'){?>selected="selected"<?php //}?> value="<?php //echo $res['id'].'- Out of Preventive Maintenance'; ?>"><?php //echo "Out of Preventive Maintenance"; ?></option>--> <?php //} ?> <option <?php if($res['amc_type']=='Comprehensive'){?>selected="selected"<?php }?> value="<?php echo $res['id'].'-Comprehensive'; ?>"><?php echo "Comprehensive AMC"; ?></option> <option <?php if($res['amc_type']=='serviceonly'){?>selected="selected"<?php }?> value="<?php echo $res['id'].'-serviceonly'; ?>"><?php echo "Service Only"; ?></option> <option <?php if($res['rent_type']=='syndicate'){?>selected="selected"<?php }?> value="<?php echo $res['id'].'-syndicate'; ?>"><?php echo "Rental By Syndicate"; ?></option> <option <?php if($res['rent_type']=='distributor'){?>selected="selected"<?php }?> value="<?php echo $res['id'].'-distributor'; ?>"><?php echo "By Sub or local Distributor"; ?></option> <option <?php if($res['amc_type']=='closed'){?>selected="selected"<?php }?> value="<?php echo $res['id'].'-Close'; ?>">Paid</option> </select> </td> <!--<td><a href="<?php echo base_url(); ?>createpdf/pdf/<?php echo $res['id'];?>" target="_blank">AMC Quotation</a></td>--> <!--<td><a class="fancybox-manual-b" href="javascript:;" id="amcquote_<?php echo $res['id'].'-'.$res['csl_id'];?>">AMC Quotation</a></td>--> <!--<td class="options-width"> <a href="#" style="padding-left:15px;" ><i class="fa fa-floppy-o fa-2x"></i></a> </td>--> </tr> <?php $i++; }}else{ ?> <tr><td align="center" colspan="12"><?php echo "<h5 align='center'>No Data Available</h5>"; ?></td></tr> <?php }?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script> $(document).ready(function(){ $('[id^="stats_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split('-'); var orderid = arr['0']; var amc_type = arr['1']; alert(id+'-'+amc_type); if(amc_type=="Comprehensive" || amc_type=="serviceonly"){ $.fancybox.open({ href : '<?php echo base_url(); ?>order/update_amc_type/'+orderid+'/'+amc_type, type : 'iframe', padding : 5, afterClose: function () { // USE THIS IT IS YOUR ANSWER THE KEY WORD IS "afterClose" parent.location.reload(true); alert('Update Successfully!!!'); } }); } if(amc_type=="syndicate" || amc_type=="distributor"){ $.fancybox.open({ href : '<?php echo base_url(); ?>order/update_amc_type/'+orderid+'/'+amc_type, type : 'iframe', padding : 5, afterClose: function () { // USE THIS IT IS YOUR ANSWER THE KEY WORD IS "afterClose" parent.location.reload(true); alert('Update Successfully!!!'); } }); } if(amc_type=="Close"){ var status = 'paid'; var data_String; data_String = 'id='+orderid+'&status='+status; $.post('<?php echo base_url(); ?>order/update_stats',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Product Closed"); //$('#actaddress').val(data.Address1), }); } }); }); </script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); $(document).ready(function() { $(".fancybox-manual-b").click(function() { //alert($("#order_id").val()); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var orderid = arr['1']; //alert(orderid); $.fancybox.open({ href : '<?php echo base_url(); ?>createpdf/pdf_view/'+orderid, type : 'iframe', padding : 5 }); }); }); </script> </body> </html><file_sep>/application/controllers/Prodservicestat.php <?php class Prodservicestat extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Prodservicestat_model'); } public function add_prod_service_status(){ $cname=$this->input->post('status_name'); $c=$cname; $count=count($c); for($i=0; $i<$count; $i++) { if($cname[$i]!=""){ $data1 = array('prod_service_status' => $cname[$i]); $result=$this->Prodservicestat_model->add_prod_ser_stat($data1); } else{ echo "<script>window.location.href='".base_url()."pages/add_prod_service_stat';alert('Please enter Product Service Status');</script>"; } } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/prod_service_stat_list';alert('Product Service Status added');</script>"; } } public function update_prod_service_status(){ $id=$this->input->post('id'); $data=array( 'prod_service_status'=>$this->input->post('status_name') ); $s = $this->Prodservicestat_model->update_prod_ser_stat($data,$id); } public function del_prod_service_status(){ $id=$this->input->post('id'); $s = $this->Prodservicestat_model->del_prod_ser_stat($id); } public function update_customerstep2(){ // $id1=$this->input->post('customer_id'); /* $data['full_name']=$this->input->post('fullname'); $data['short_name']=$this->input->post('shortname'); $data['nature_of_customer']=$this->input->post('nature_of_customer'); $data['customer_category']=$this->input->post('customer_category'); $data['company_name1']=$this->input->post('company_name1'); $data['designation']=$this->input->post('designation'); $data['mobile']=$this->input->post('mobile'); $data['email']=$this->input->post('email'); $data['qualification']=$this->input->post('qualification'); $data['dob']=$this->input->post('dob'); $data['age']=$this->input->post('age'); $data['marital_status']=$this->input->post('marital_status'); $data['comments']=$this->input->post('comments'); */ $data=array( 'full_name'=>$this->input->post('fullname'), 'short_name'=>$this->input->post('shortname'), 'nature_of_customer'=>$this->input->post('nature_of_customer'), 'customer_category'=>$this->input->post('customer_category'), 'company_name1'=>$this->input->post('company_name1'), 'designation'=>$this->input->post('designation'), 'mobile'=>$this->input->post('mobile'), 'email'=>$this->input->post('email'), 'qualification'=>$this->input->post('qualification'), 'dob'=>$this->input->post('dob'), 'age'=>$this->input->post('age'), 'marital_status'=>$this->input->post('marital_status'), 'comments'=>$this->input->post('comments'), ); $id=$this->input->post('customer_id'); $cname=$data1['company_name']=$this->input->post('company_name'); $cmobile=$data1['company_mobile']=$this->input->post('company_mobile'); $cemail=$data1['company_email']=$this->input->post('company_email'); $caddress=$data1['company_address']=$this->input->post('company_address'); $ccity=$data1['company_city']=$this->input->post('company_city'); $cstate=$data1['company_state']=$this->input->post('company_state'); $cpincode=$data1['company_pincode']=$this->input->post('company_pincode'); //$count=count($data1['company_name']); //$data1=""; $c=$cname; $count=count($c); $con_address=$data2['contact_address']=$this->input->post('contact_address'); $con_city=$data2['contact_city']=$this->input->post('contact_city'); $con_state=$data2['contact_state']=$this->input->post('contact_state'); $con_pincode=$data2['contact_pincode']=$this->input->post('contact_pincode'); $this->master_model->update_customer($data,$id); $count1=count($con_address); //echo "<script>alert($c);</script>"; $data1 =array(); for($i=0; $i<$count; $i++) { $data1[] = array( 'company_name' => $cname[$i], 'company_mobile' => $cmobile[$i], 'company_email' => $cemail[$i], 'company_address' => $caddress[$i], 'company_city' => $ccity[$i], 'company_state' => $cstate[$i], 'company_pincode' => $cpincode[$i], 'customer_id'=>$id, ); } $data2=array(); for($i=0; $i<$count1; $i++){ $data2[]=array( 'contact_address'=>$con_address[$i], 'contact_city'=>$con_city[$i], 'contact_state'=>$con_state[$i], 'contact_pincode'=>$con_pincode[$i], 'customer_id'=>$id, ); } // $this->load->helper('url'); $this->master_model->delete_customer_corporate($id); $this->master_model->add_customer_company($data1); $this->master_model->delete_customer_contact($id); $result=$this->master_model->add_customer_contact($data2); if($result) echo "<script> alert('update success'); window.location.href='".base_url()."pages/customer_list'; </script>"; } public function delete_customer($id){ $this->master_model->delete_customer($id); $this->master_model->delete_customer_corporate($id); $result = $this->master_model->delete_customer_contact($id); if($result){ echo "<script> alert('Customer deleted'); window.location.href='".base_url()."pages/customer_list'; </script>"; } } //company public function add_company(){ $data=array( 'company_main_id'=>$this->input->post('company_id'), 'full_name'=>$this->input->post('full_name'), 'short_name'=>$this->input->post('short_name'), 'address'=>$this->input->post('address'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'mobile'=>$this->input->post('mobile'), 'phone'=>$this->input->post('phone'), 'company_email'=>$this->input->post('company_email'), 'lead_email'=>$this->input->post('lead_email'), 'manager_email'=>$this->input->post('manager_email'), ); $result=$this->master_model->add_company($data); if($result){ echo "<script> alert('Company added'); window.location.href='".base_url()."pages/company_list'; </script>"; } } public function update_company(){ $id=$this->uri->segment(3); $data['list']=$this->master_model->getcompanybyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('master/edit_company',$data); $this->load->view('templates/footer'); } public function update_companystep2(){ $data=array( 'company_main_id'=>$this->input->post('company_main_id'), 'full_name'=>$this->input->post('full_name'), 'short_name'=>$this->input->post('short_name'), 'address'=>$this->input->post('address'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'mobile'=>$this->input->post('mobile'), 'phone'=>$this->input->post('phone'), 'company_email'=>$this->input->post('company_email'), 'lead_email'=>$this->input->post('lead_email'), 'manager_email'=>$this->input->post('manager_email'), ); $id=$this->input->post('company_id'); $result=$this->master_model->update_company($data,$id); if($result){ echo "<script> alert('company edited success'); window.location.href='".base_url()."pages/company_list'; </script>"; } } }<file_sep>/application/models/Stampingreport_model.php <?php class Stampingreport_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function emp_list(){ $this->db->select("id, emp_name",FALSE); $this->db->from('employee'); $this->db->order_by('emp_name','asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } function getstamping_report($from_date,$to_date) { $query=$this->db->query("select stamp.req_id,cust.customer_name,cust.mobile,cust.land_ln,cust.state,cust.city,service.created_on,stamp.agn_charge,stamp.conveyance,stamp.cmr_paid,det.site,stat.state from stamping_details as stamp left join service_request as service on service.id=stamp.req_id left join service_request_details as det on det.request_id=service.id left join customers as cust on cust.id=service.cust_name left join state as stat on stat.id=cust.state where det.site='Stamping' AND service.created_on BETWEEN '$from_date' AND '$to_date 23:59:59.993' "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } function request_count() { $this->db->select('req_id',false); $this->db->from('stamping_details'); //$this->db->where('employee_id',$emp_id); $query=$this->db->get(); return $query->num_rows(); } }<file_sep>/application/views/sparerequest.php <style> #select_value { height: 33px; width: 210px; border:1px solid #055E87; border-image: none; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; border-radius: 0px; margin: 0px; box-sizing: border-box; -moz-appearance: none; } table.display th,td { padding:10px; border:1px solid #ccc; } table.dataTable tbody td{ padding: 8px 10px !important; border: 1px solid #522276 !important; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } select { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=text]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } a{ color:#522276; } a:hover{ color:#522276; } a:active{ color:#522276; } a:focus{ color:#522276; } .form-control { border:none; } </style> <script> function DelStatus(id){ var spareid = $("#spareid_"+id).val(); var reqid = $("#reqid_"+id).val(); var qty = $("#qty_"+id).val(); var auto_cnt = $("#auto_cnt_"+id).val(); var dataString = 'id='+id+'&spareid='+spareid+'&reqid='+reqid+'&qty='+qty+'&auto_cnt='+auto_cnt; var r=confirm("Are you sure want to delete"); if (r==true) { $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/del_spare_to_enggs", data: dataString, cache: false, success: function(data) { window.location = "<?php echo base_url(); ?>pages/sparereceipt"; alert("Spare to engineer deleted"); } }); } } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare Requests</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <br/> <div class='dtable_custom_controls'> <div class='dataTables_wrapper'> <div class='ui-toolbar'> <div class='dataTables_length'> </div> </div> </div> </div> <table id="data-table-simple" class="dtable responsive-table display" cellspacing="0"> <thead> <tr> <th class="hidden">Request Id</th> <th>Request ID</th> <th>Requested Date</th> <th>Customer Name</th> <th>Engineer Name</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($get_spare_request as $key){?> <tr> <td class="hidden"><?php echo $key->request_id; ?></td> <td><?php echo $key->request_id; ?></td> <td style="text-align:left;"><?php echo $key->request_date;?></td> <td><?php echo $key->company_name;?></td> <td><?php echo $key->emp_name;?></td> <td class="options-width"> <a href="#" style="padding-left:15px;" onclick='brinfo("<?php echo $key->reid.'-'.$key->empid.'-'.$key->cust_id; ?>")'><i class="fa fa-floppy-o fa-2x"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <style> .dtable {display:none} .dtable_custom_controls {display:none;position: absolute;z-index: 50;margin-left: 5px;margin-top:1px} .dtable_custom_controls .dataTables_length {width:auto;float:none} .ui-widget-header { border: 1px solid white; background: white;} .ui-state-default { background: #6c477d; border: 3px solid #055E87; color: #fff; font-size: 12px; } .ui-state-default .ui-icon { float: right; } .ui-button { min-width: 1.5em; padding: 0.5em 1em; margin-left: 10px !important; text-align: center; } /*.ui-state-default { background:#6c477d; color:#fff; font-size: 12px; }*/ /* table.dataTable thead th{ background-color: #DBD0E1 !important; color: #522276 !important; } */ table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } .cyan:hover { background-color: transparent !important; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { /* * Find and assign actions to filters */ $.fn.dataTableExt.afnFiltering = new Array(); var oControls = $('.dtable').prevAll('.dtable_custom_controls:first').find(':input[name]'); oControls.each(function() { var oControl = $(this); //Add custom filters $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { if ( !oControl.val() || !oControl.hasClass('dtable_filter') ) return true; for ( i=0; i<aData.length; i++ ) if ( aData[i].indexOf(oControl.val()) != -1 ) return true; return false; }); }); options = { "sDom" : 'R<"H"lfr>t<"F"ip<', "bProcessing" : true, "bJQueryUI" : true, "bStateSave" : false, "iDisplayLength" : 8, "aLengthMenu" : [[8, 25, 50, -1], [8, 25, 50, "All"]], "sPaginationType" : "full_numbers", "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [ 0,7,9 ] }], // "ordering": false, //"ordering": [[ 2, "false" ]], "aoColumnDefs": [ { 'bSortable': false, 'aTargets': [ 0 ] } ], "aaSorting" : [[ 0, "asc" ]], "fnDrawCallback" : function(){ //Without the CSS call, the table occasionally appears a little too wide $(this).show().css('width', '100%'); //Don't show the filters until the table is showing $(this).closest('.dataTables_wrapper').prevAll('.dtable_custom_controls').show(); }, /*"fnStateSaveParams": function ( oSettings, sValue ) { //Save custom filters oControls.each(function() { if ( $(this).attr('name') ) sValue[ $(this).attr('name') ] = $(this).val().replace('"', '"'); }); return sValue; },*/ "fnStateLoadParams" : function ( oSettings, oData ) { //Load custom filters oControls.each(function() { var oControl = $(this); $.each(oData, function(index, value) { if ( index == oControl.attr('name') ) oControl.val( value ); }); }); return true; } }; var oTable = $('.dtable').dataTable(options); //var table = $('#example').dataTable(); // Perform a filter oTable.fnSort( [ [0,'desc'] ] ); //oTable.fnSort( [ [0,'desc'] ] ); /* * Trigger the filters when the user interacts with them */ oControls.each(function() { $(this).change(function() { //Redraw to apply filters oTable.fnDraw(); }); }); oTable.fnFilter(''); // oTable.fnFilter(''); // Remove all filtering oTable.fnFilterClear(); }); </script> <!-- materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(idd){ //alert(idd); var arr = idd.split('-'); var id = arr['0']; var empid = arr['1']; var custid = arr['2']; //alert(custid); $.fancybox.open({ href : '<?php echo base_url(); ?>Spare/update_spare_req/'+id+'/'+empid+'/'+custid, type : 'iframe', padding : 5, }); } </script> </body> </html><file_sep>/application/views/add_spare_row.php <tr> <td> <select name="model[]" id="model-<?php echo $count; ?>" class="model"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="errorBox1<?php echo $count; ?>" style="color:red;text-align:left;margin-left: 12px;"></div> </td> <td><input type="text" name="category_name" id="category_name-<?php echo $count; ?>" readonly><input type="hidden" name="category[]" id="category-<?php echo $count; ?>" readonly></td> <td><input type="text" name="subcategory_name" id="subcategory_name-<?php echo $count; ?>" readonly><input type="hidden" name="subcategory[]" id="subcategory-<?php echo $count; ?>" readonly></td> <td><input type="text" name="brand_name" id="brand_name-<?php echo $count; ?>" readonly><input type="hidden" name="brandname[]" id="brandname-<?php echo $count; ?>" readonly> </td> <td style="background:#fff;border:none;"> <a class="delRowBtn btn btn-primary" style="border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white;height: 30px;margin-left:10px;"><i class="fa fa-trash" style="line-height: 0px;"></i></a> </td> </tr> <script> $(document).ready(function(){ $('.model').change(function(){//alert("ddddd"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; //alert(id); var dataString = 'modelno='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_productinfobyid", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#category_name-'+vl).val(data.product_category), $('#category-'+vl).val(data.category), $('#subcategory_name-'+vl).val(data.subcat_name), $('#subcategory-'+vl).val(data.subcategory), $('#brand_name-'+vl).val(data.brand_name), $('#brandname-'+vl).val(data.brand) }); } }); }); }); </script> <script> $(document).ready(function(){ //alert("hii"); $("#register").click(function(){ //alert("hiiiiii"); //var count=<?php echo $count; ?>; //alert(count); //alert($( "#model-<?php echo $count; ?>" ).val()); if ( $( "#model-<?php echo $count; ?>" ).val() == "" ) { $( "#errorBox1<?php echo $count; ?>" ).text( " Select the Model" ).show().css({'color':'#ff0000','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(document).ready(function(){ //alert("sdf"); $("#model-<?php echo $count; ?>").change(function(){ $("#errorBox1<?php echo $count; ?>").hide(); }); }); </script> <!--<script> $(document).ready(function(){ /*$("select").change(function() {//alert("hiii"); $("select").find('option').prop("disabled",fale); var selectedItem = $(this).val(); if (selectedItem) { $("select").children('option[value="' + selectedItem + '"]').prop('disabled', true); } }); */ $(document).on('change', 'select', function() { // $('option[value="disabled"]').prop('disabled', false); $(this).addClass('exception'); $('select').children('option[value="' + this.value + '"]').remove(); $(this).removeClass('exception'); }); }); $(document).ready(function() { $(document).on('change','select',function(){ //alert("hiii"); $(this).addClass('exception'); $('option[value="' + this.value + '"]:not(.exception *)').remove(); $(this).removeClass('exception'); }); }); </script> <script> /*$("select").change(function() { alert("hii"); var arr=[]; $("select option:selected").each(function() { arr.push($(this).val()); }); $("option").filter(function() { $(this).addClass('exception'); return $.inArray($(this).val(),arr)>-1; }).attr("disabled","disabled"); $(this).removeClass('exception'); });*/ $('select').change(function() { alert("hiii"); var myOpt = []; $("select").each(function () { myOpt.push($(this).val()); }); $("select").each(function () { $(this).find("option").prop('hidden', false); var sel = $(this); $.children.each(myOpt, function(key, value) { if((value != "") && (value != sel.val())) { sel.find("option").filter('[value="' + value +'"]').prop('hidden', true); } }); }); }); </script>--><file_sep>/application/controllers/Problemcategory.php <?php class problemcategory extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Problemcategory_model'); } public function add_prob_category(){ $prob_cat_name=$this->input->post('prob_cat_name'); $prob_code=$this->input->post('prob_code'); $model=$this->input->post('model'); $p_description=$this->input->post('p_description'); $c=$prob_cat_name; $count=count($c); for($i=0; $i<$count; $i++) { if($prob_cat_name[$i]!=""){ $data1 = array('prob_category' => $prob_cat_name[$i], 'model' => $model[$i], 'prob_code'=>$prob_code[$i], 'prob_description'=>$p_description[$i]); $result=$this->Problemcategory_model->add_problem_category($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_prob_cat';alert('Please enter Problem Category');</script>"; } */ } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/prob_cat_list';alert('Problem Category Added Successfully!!!');</script>"; } } public function update_prob_cat(){ $id=$this->uri->segment(3); $data['list']=$this->Problemcategory_model->getprobcatbyid($id); $data['modellist']=$this->Problemcategory_model->modellist(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_probcat_list',$data); } public function update_prob_category(){ $id=$this->input->post('prob_catid'); $c = $this->input->post('prob_code'); $model = $this->input->post('model'); $p_description = $this->input->post('p_description'); $cname = $this->input->post('prob_cat_name'); $count=count($c); for($i=0; $i<$count; $i++) { if($c[$i]!=""){ $this->db->select("*",FALSE); $this->db->from('problem_category'); $this->db->where('prob_code', $c[$i]); $query = $this->db->get(); $totnum = $query->num_rows(); if($totnum>0) { $data1 = array('prob_category' => $cname[$i], 'model' => $model[$i], 'prob_description'=>$p_description[$i]); $s = $this->Problemcategory_model->update_prob_cat($data1,$id); } else { $data1 = array('prob_category' => $cname[$i], 'model' => $model[$i], 'prob_code'=>$c[$i], 'prob_description'=>$p_description[$i]); $result=$this->Problemcategory_model->add_problem_category($data1); } //$data1 = array('prob_category' => $prob_cat_name[$i], 'model' => $model[$i], 'prob_code'=>$prob_code[$i], 'prob_description'=>$p_description[$i]); //$result=$this->Problemcategory_model->add_problem_category($data1); } } // $data=array('prob_category'=>$this->input->post('prob_cat_name'), 'model'=>$this->input->post('model')); // $s = $this->Problemcategory_model->update_prob_cat($data,$id); echo "<script>window.location.href='".base_url()."pages/prob_cat_list';alert('Problem Category Updated Successfully!!!');</script>"; } public function del_prob_category(){ $id=$this->input->post('id'); $s = $this->Problemcategory_model->del_prob_cat($id); } public function addrow(){ $data['count']=$this->input->post('countid'); $data['modellist']=$this->Problemcategory_model->modellist(); $this->load->view('problemaddrow',$data); } public function category_validation() { $category=$this->input->post('category'); $model=$this->input->post('model'); $this->Problemcategory_model->category_validation($category,$model); } public function checkCode() { $code=$this->input->post('code'); $this->Problemcategory_model->code_validation($code); } public function checkproblem() { $model= $this->input->post('code'); $problem= $this->input->post('problem'); //echo $model; echo $problem; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Problemcategory_model->problem_validation($problem,$model))); } }<file_sep>/application/views_bkMarch_0817/add_service_charge_row.php <!--<tr> <td> <select id="spare_name_<?php echo $count; ?>" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> </select> </td> <td><input type="text" name="qty[]"><input type="hidden" name="spare_qty1[]" id="spare_qty1_<?php echo $count; ?>"><input type="hidden" name="used_spare1[]" id="used_spare1_<?php echo $count; ?>"><input type="hidden" name="purchase_price1[]" id="purchase_price1_<?php echo $count; ?>"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_<?php echo $count; ?>"></td> <td><input type="text" name="purchase_date[]"></td> <td><input type="text" name="purchase_price[]"></td> <td><input type="text" name="invoice_no[]"></td> <td><input type="text" name="reason[]"></td> <td style="border:none;"><button class="delRowBtn" >Delete</button></td> </tr>--> <tr> <td><select name="model[]" class="eng_spare_name" id="model-<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select></td><td class="plus"><input type="text" name="service_charge[]" id="service_charge-<?php echo $count; ?>" class="plus1"><a class="delRowBtn btn btn-primary fa fa-trash" style="position: relative;right: 10px;"></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(<?php echo $count; ?>)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('minus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('plus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <style> .delRowBtn{ background: transparent !important; border: transparent !important; color:#337ab7 !important; } .delRowBtn:hover{ background: transparent !important; border: transparent !important; color: #337ab7 !important; } .delRowBtn:focus{ background-color: transparent !important; border-color: transparent !important; color: #337ab7 !important; } .z-depth-1-half, .btn:hover, .btn-large:hover, .btn-floating:hover { box-shadow: none !important; } .plus1{ position: relative; right: 9px; } </style> <file_sep>/application/controllers/Report.php <?php class report extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Report_model'); } //service report function get_customer_name() { $a=array(); if($this->input->post('site') <> ''){ $a[]="req.site= '".$this->input->post('site')."' AND "; } if($this->input->post('model') <> ''){ $a[]="pro.id= '".$this->input->post('model')."' AND "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $a[]="service_request.created_on between '".$this->input->post('from')."' and '".$this->input->post('to')."' and "; } $wh= 'where '.substr(implode('',$a),0,-5); //print_r($wh);exit; //$from_date = $this->input->post('from'); //$to_date = $this->input->post('to'); //$site = $this->input->post('site'); $data['modellist']=$this->Report_model->modellist(); //$model = $this->input->post('model'); $data['report'] = $this->Report_model->get_report($wh); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('report_cust_list',$data); } //sparepurchase public function getpurchase() { $a=array(); if($this->input->post('spare') <> ''){ $a[]="engg.spare_id= ".$this->input->post('spare')." and "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $a[]="engg.purchase_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } //$wh= 'where '.substr(implode('',$a),0,-5); $wh= 'where ' .substr(implode('',$a),0,-5); $m_data['purchase'] = $this->Report_model->get_purchase($wh); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; //print_r($m_data['purchase']);exit; $this->load->view('templates/header',$data); $this->load->view('sparepurchase',$m_data); } //spare report function get_engineer_name() { $a=array(); if($this->input->post('spare') <> ''){ $a[]="spares.id= ".$this->input->post('spare')." and "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $a[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } //$wh= 'where '.substr(implode('',$a),0,-5); $wh= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$a),0,-5); $m_data['enggname_list']=$this->Report_model->engnamelist(); $m_data['sparename_list']=$this->Report_model->sparenamelist(); $m_data['sparereport'] = $this->Report_model->get_sparereport($wh); $data['user_dat'] = $this->session->userdata('login_data'); //echo "<pre>"; //print_r($m_data['sparereport']);exit; $this->load->view('templates/header',$data); $this->load->view('sparereport_engg_list',$m_data); } //sparecharge list public function getcharge_list() { $b=array(); if($this->input->post('spare') <> ''){ $b[]="spa.id= ".$this->input->post('spare')." and "; } /* if($this->input->post('site') <> ''){ $b[]="service.site= '".$this->input->post('site')."' AND "; } */ if($this->input->post('sersite') <> ''){ $b[]="service.machine_status= '".$this->input->post('sersite')."' AND "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $b[]="req.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."' and "; } $whxg= 'where '.substr(implode('',$b),0,-5); //print_r($whxg); $data['name']=$this->Report_model->getsparecharge_list($whxg); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('sparechargereport_data',$data); } //spare engineer public function get_engineerdate() { $b=array(); if($this->input->post('name') <> ''){ $b[]="emp.id= ".$this->input->post('name')." and "; } if($this->input->post('sname') <> ''){ $b[]="engg.spare_id= ".$this->input->post('sname')." and "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $b[]="engg.engineer_date between '".$this->input->post('from')."' and '".$this->input->post('to')."' and "; } //$whxg= 'where '.substr(implode('',$b),0,-5); $whxg= 'where req.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); /*$engg_from=$this->input->post('from'); $engg_to=$this->input->post('to'); $name=$this->input->post('name');*/ $data['name']=$this->Report_model->get_engineerreport($whxg); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('enggreport_data',$data); } //Engineer Report public function get_engineerreport() { $b=array(); if($this->input->post('name')!=''){ $b[]="service_request_details.assign_to= ".$this->input->post('name')." and "; } if($this->input->post('work_status')!=''){ $b[]="service_request.status= ".$this->input->post('work_status')." and "; } if($this->input->post('from')!="" && $this->input->post('to')!=""){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."' and "; } /* if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."' and "; } if($this->input->post('from')<> '' && $this->input->post('to')<> ''){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993 ' and "; }*/ //$whxg= 'where '.substr(implode('',$b),0,-5); $whxg= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); $data['name']=$this->Report_model->get_engineerreport1($whxg); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('enggreport1_data',$data); } //stamping report function get_stamping() { $from_date = $this->input->post('from'); $to_date = $this->input->post('to'); $employee = $this->input->post('employee'); //echo $employee;exit; $data['report'] = $this->Report_model->getstamping_report($from_date,$to_date); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('stampingreport_data',$data); } //stamping Monthly report function get_monthreport() { $from_date = $this->input->post('from'); $to_date = $this->input->post('to'); $data['month'] = $this->Report_model->getstampingmonth_report($from_date,$to_date); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('monthreport_data',$data); } function get_customerreport() { $b=array(); if($this->input->post('customer_type') <> ''){ $b[]="customer_type.id= ".$this->input->post('customer_type')." and "; } if($this->input->post('zone') <> ''){ $b[]="loc.id= '".$this->input->post('zone')."' and "; } if($this->input->post('cal_ref') <> ''){ $b[]="customers.cal_ref= '".$this->input->post('cal_ref')."' and "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')){ $b[]="customers.created_on between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993 ' and "; } $whxg= 'where '.substr(implode('',$b),0,-5); $data['customerreport'] = $this->Report_model->getcustomer_report($whxg); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('customerreport_data',$data); } function get_agingreport() { $from = $this->input->post('from'); $to = $this->input->post('to'); $range = $this->input->post('range'); //$sersite = $this->input->post('sersite'); $r = explode('-',$range); $r1 = $r[0]; $r2 = $r[1]; $model = $this->input->post('model'); $customer = $this->input->post('customer'); $category = $this->input->post('product'); $emp = $this->input->post('employee'); $zone = $this->input->post('zone'); /* $date = date('Y-m-d'); $b=array(); if(!empty($this->input->post('sersite'))){ $b[]="service.site= '".$this->input->post('sersite')."' AND "; } if(!empty($this->input->post('model'))){ $b[]="pro.id= ".$this->input->post('model')." AND "; } if(!empty($this->input->post('customer'))){ $b[]="cust.id= ".$this->input->post('customer')." AND "; } if(!empty($this->input->post('product'))){ $b[]="cate.id= ".$this->input->post('product')." AND "; } if(!empty($this->input->post('employee'))){ $b[]="emp.id= ".$this->input->post('employee')." AND "; } if(!empty($this->input->post('zone'))){ $b[]="zone.id= ".$this->input->post('zone')." AND "; } $range = $this->input->post('range'); $r = explode('-',$range); $r1 = $r[0]; $r2 = $r[1]; $from = $this->input->post('from'); // echo $from;exit; // $diff34 = dateDiff ($date,$from); //$days = $diff34->d; // echo $diff34;exit; //$dat = date('Y-m-d',strtotime($from.'+'.$range.'days')); if(!empty($this->input->post('from')) and !empty($date)){ $b[]="req.request_date >= '".$this->input->post('from')."' between '".$r1."' and '".$r2."' and "; } $whxg= 'where '.substr(implode('',$b),0,-5); //print_r($whxg);exit; //$data['agingreport'] = $this->Report_model->getaging_report($category,$zone,$emp,$customer,$model,$from,$dat); $data['agingreport'] = $this->Report_model->getaging_report($whxg);*/ $data['agingreport'] = $this->Report_model->getaging_report($from,$r1,$r2,$model,$customer,$category,$emp,$zone); $data['category'] = $this->Report_model->getprob_category(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('chargereport_data',$data); } //revenue report public function get_revenuereport1() { $b=array(); /* if($this->input->post('sersite')!=""){ $b[]="service_request_details.machine_status= '".$this->input->post('sersite')."' AND "; } */ $b[]="service_request.status= '3' AND "; if($this->input->post('spare_status')=="w_spare"){ $b[]="quote_review_spare_details.spare_id!= '0' AND "; }else{ $b[]="quote_review_spare_details.spare_id = 0 AND "; } if($this->input->post('area_wise')!=""){ $b[]="customer_service_location.area= '".$this->input->post('area_wise')."' AND "; } if($this->input->post('brand_name')!=""){ $b[]="service_request_details.brand_id= '".$this->input->post('brand_name')."' AND "; } if($this->input->post('model')!=""){ $b[]="service_request_details.model_id= '".$this->input->post('model')."' AND "; } if($this->input->post('prod_category')!=""){ $b[]="service_request_details.cat_id= '".$this->input->post('prod_category')."' AND "; } if($this->input->post('zone')!=""){ $b[]="service_request_details.zone= '".$this->input->post('zone')."' AND "; } if($this->input->post('problem')!=""){ $b[]="service_request_details.problem= '".$this->input->post('problem')."' AND "; } if($this->input->post('from')!="" && $this->input->post('to')!=""){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } //$whxg= 'where '.substr(implode('',$b),0,-5); $whxg= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); $data['revenuereport'] = $this->Report_model->getrevenue1_report($whxg); //$data1['status']= $this->Report_model->getstatus(); $data['spare_status'] = $this->input->post('spare_status'); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('revenuereport1_data',$data); } //service report updated public function get_revenuereport() { $b=array(); /* if($this->input->post('sersite')!=""){ $b[]="service_request_details.machine_status= '".$this->input->post('sersite')."' AND "; } */ if($this->input->post('work_status')!=""){ $b[]="service_request.status= '".$this->input->post('work_status')."' AND "; } if($this->input->post('site')!=""){ $b[]="service_request_details.site= '".$this->input->post('site')."' AND "; } if($this->input->post('area_wise')!=""){ $b[]="customer_service_location.area= '".$this->input->post('area_wise')."' AND "; } if($this->input->post('brand_name')!=""){ $b[]="service_request_details.brand_id= '".$this->input->post('brand_name')."' AND "; } if($this->input->post('model')!=""){ $b[]="service_request_details.model_id= '".$this->input->post('model')."' AND "; } if($this->input->post('prod_category')!=""){ $b[]="service_request_details.cat_id= '".$this->input->post('prod_category')."' AND "; } if($this->input->post('zone')!=""){ $b[]="service_request_details.zone= '".$this->input->post('zone')."' AND "; } if($this->input->post('problem')!=""){ $b[]="service_request_details.problem= '".$this->input->post('problem')."' AND "; } if($this->input->post('from')!="" && $this->input->post('to')!=""){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } $whxg= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); //$whxg= 'where service_request.active_req = '.'0'; $data['revenuereport'] = $this->Report_model->getrevenue_report($whxg); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('revenuereport_data',$data); } //preventive maintanance Report public function get_preventivereport() { $b=array(); if($this->input->post('ename')!=""){ $b[]="service_request_details.accepted_engg_id= '".$this->input->post('ename')."' AND "; } if($this->input->post('work_status')!=""){ $b[]="service_request.status= '".$this->input->post('work_status')."' AND "; } if($this->input->post('site')!=""){ $b[]="service_request_details.site= '".$this->input->post('site')."' AND "; } if($this->input->post('area_wise')!=""){ $b[]="customer_service_location.area= '".$this->input->post('area_wise')."' AND "; } if($this->input->post('brand_name')!=""){ $b[]="service_request_details.brand_id= '".$this->input->post('brand_name')."' AND "; } if($this->input->post('model')!=""){ $b[]="service_request_details.model_id= '".$this->input->post('model')."' AND "; } if($this->input->post('prod_category')!=""){ $b[]="service_request_details.cat_id= '".$this->input->post('prod_category')."' AND "; } if($this->input->post('zone')!=""){ $b[]="service_request_details.zone= '".$this->input->post('zone')."' AND "; } if($this->input->post('problem')!=""){ $b[]="service_request_details.problem= '".$this->input->post('problem')."' AND "; } if($this->input->post('from')!="" && $this->input->post('to')!=""){ $b[]="service_request.request_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } //$b[]="service_request_details.service_type='Preventive'AND"; $whxg= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); //$whxg= 'where service_request.active_req = '.'0'; $data['preventivereport'] = $this->Report_model->getpreventive_report($whxg); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('preventive_report_data',$data); } //Service Machines Report public function get_ser_machreport() { if($this->input->post('from')!=""){ $from = $this->input->post('from'); }else{ $from = ''; } if($this->input->post('to')!=""){ $to = $this->input->post('to'); }else{ $to = ''; } if($this->input->post('model')!=""){ $model = $this->input->post('model'); }else{ $model = ''; } if($this->input->post('prod_category')!=""){ $prod_category = $this->input->post('prod_category'); }else{ $prod_category = ''; } if($this->input->post('sersite')!=""){ $machine_status = $this->input->post('sersite'); }else{ $machine_status = ''; } if($this->input->post('cust_type')!=""){ $cust_type = $this->input->post('cust_type'); }else{ $cust_type = ''; } if($this->input->post('cust_name')!=""){ $cust_name = $this->input->post('cust_name'); }else{ $cust_name = ''; } if($this->input->post('service_zone')!=""){ $service_zone = $this->input->post('service_zone'); }else{ $service_zone = ''; } $data['get_sermachine_report'] = $this->Report_model->get_sermachine_report($from,$to,$model,$prod_category,$machine_status,$cust_type,$cust_name,$service_zone); $data['spare_statusm'] = $this->input->post('sersite'); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('sermachinereport_data',$data); } //serial report public function get_serialreport() { $b = array(); if($this->input->post('serialname') <> '') { $b[]="det.serial_no= '".$this->input->post('serialname')."' AND "; } if($this->input->post('customer_name') <> '') { $b[]="customers.id= ".$this->input->post('customer_name')." AND "; } if($this->input->post('model_name') <> '') { $b[]="products.id= ".$this->input->post('model_name')." AND "; } if(($this->input->post('from') <> '') and ($this->input->post('to') <> '')) { $b[]="order_details.purchase_date between '".$this->input->post('from')."' and '".$this->input->post('to')."23:59:59.993' and "; } $whxg= 'where '.substr(implode('',$b),0,-5); //print_r($whxg);exit; $data['list'] = $this->Report_model->getserial_report($whxg); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('serailreport_data',$data); } public function get_serialByStatus() { $id=$this->uri->segment(3); $data['serial'] = $this->Report_model->getpopup_list($id); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('serailpopup_data',$data); } public function all_spare(){ $from=$this->input->post('from'); $to=$this->input->post('to'); $data1['engspareqty']=$this->Report_model->engspareqty(); $data1['sparelist']=$this->Report_model->sparelist(); $data1['sparelist1']=$this->Report_model->sparelist1($from,$to); //$data1['sparelist_engg']=$this->Spare_model->sparelist_engg(); //$data1['getmodels']=$this->Spare_model->getmodels(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('all_spare_report_list',$data1); } }<file_sep>/application/views/view_history.php <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="http://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script src="http://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" ></script> <style> h2 { color: #000; font-family: 'Source Sans Pro',sans-serif; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; border: 1px solid #522276 !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #522276 !important; background-color:#DBD0E1 !important; } .dataTables_wrapper .dataTables_length { float: left; padding-top: 10px; } ul li{ list-style:none; display:inline-block; margin:5px 5px 0px; background:#DBD0E1; color:#522276 !important; padding:5px 25px; width:180px; border-top-left-radius:5px; border-top-right-radius:5px; } ol, ul { margin-top: 0; margin-bottom: 0px; } /*table.dataTable tbody tr:nth-child(even) {background: #f9f9f9} table.dataTable tbody tr:nth-child(odd) {background: #eaeaea}*/ </style> </head> <body> <?php //print_r($history_notes); ?> <div class="container"> <h2>History View</h2> <ul> <li><a class="a">Coordinator Notes</a></li> <li><a class="b">Customer Remarks</a></li> <li><a class="c">Engineer Notes</a></li> <li><a class="d">Engineer Solution</a></li> </ul> <div style="border:1px solid #ccc"> <table cellpadding="1" cellspacing="1" id="detailTable" class="first"> <thead> <tr> <th>ID</th> <th>Request ID</th> <th>Notes</th> <th>Updated On</th> </tr> </thead> <tbody> <?php foreach($history_conotes as $key){ $sddd = $key->created_on; ?> <tr> <td><?php echo $key->id; ?></td> <td><?php echo $key->req_id; ?></td> <td><?php echo $key->co_notess; ?></td> <td><?php echo $sddd; ?></td> </tr> <?php } ?> </tbody> </table> </div> <div style="border:1px solid #ccc"> <table cellpadding="1" cellspacing="1" id="detailTable1" class="second"> <thead> <tr> <th>ID</th> <th>Request ID</th> <th>Notes</th> <th>Updated On</th> </tr> </thead> <tbody> <?php foreach($history_remark as $key){ $sddd = $key->created_on; ?> <tr> <td><?php echo $key->id; ?></td> <td><?php echo $key->req_id; ?></td> <td><?php echo $key->cust_remark; ?></td> <td><?php echo $sddd; ?></td> </tr> <?php } ?> </tbody> </table> </div> <div style="border:1px solid #ccc"> <table cellpadding="1" cellspacing="1" id="detailTable2" class="third"> <thead> <tr> <th>ID</th> <th>Request ID</th> <th>Notes</th> <th>Updated On</th> </tr> </thead> <tbody> <?php foreach($history_engnotess as $key){ $sddd = $key->created_on; ?> <tr> <td><?php echo $key->id; ?></td> <td><?php echo $key->req_id; ?></td> <td><?php echo $key->eng_notess; ?></td> <td><?php echo $sddd; ?></td> </tr> <?php } ?> </tbody> </table> </div> <div style="border:1px solid #ccc"> <table cellpadding="1" cellspacing="1" id="detailTable3" class="fourth"> <thead> <tr> <th>ID</th> <th>Request ID</th> <th>Solution</th> <th>Updated On</th> </tr> </thead> <tbody> <?php foreach($history_sol as $key){ $sddd = $key->created_on; ?> <tr> <td><?php echo $key->id; ?></td> <td><?php echo $key->req_id; ?></td> <td><?php echo $key->cust_solution; ?></td> <td><?php echo $sddd; ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> <script> $(document).ready(function() { $('#detailTable').DataTable({ "pagingType": "full_numbers" } ); $('#detailTable1').DataTable({ "pagingType": "full_numbers" } ); $('#detailTable2').DataTable({ "pagingType": "full_numbers" } ); $('#detailTable3').DataTable({ "pagingType": "full_numbers" } ); $("#detailTable1_wrapper, #detailTable2_wrapper, #detailTable3_wrapper").hide(); $(".a").click(function(){ $("#detailTable_wrapper").show(); $("#detailTable1_wrapper, #detailTable2_wrapper, #detailTable3_wrapper").hide(); }); $(".b").click(function(){ $("#detailTable1_wrapper").show(); $("#detailTable_wrapper, #detailTable2_wrapper, #detailTable3_wrapper").hide(); }); $(".c").click(function(){ $("#detailTable2_wrapper").show(); $("#detailTable1_wrapper, #detailTable_wrapper, #detailTable3_wrapper").hide(); }); $(".d").click(function(){ $("#detailTable3_wrapper").show(); $("#detailTable1_wrapper, #detailTable2_wrapper, #detailTable_wrapper").hide(); }); }); </script> </body> </html><file_sep>/application/models/Quote_in_progress_model.php <?php class quote_in_progress_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_services($data){ $this->db->insert('service_request',$data); return $this->db->insert_id(); } public function add_service_details($data1){ $this->db->insert('service_request_details',$data1); } public function get_customerdetails($id){ $query = $this->db->get_where('customers', array('id' => $id)); return $query->result(); } public function customerlist(){ $this->db->select("id, customer_id, customer_name, customer_type, mobile, email_id",FALSE); $this->db->from('customers'); $query = $this->db->get(); return $query->result(); } public function list_serialnos(){ $this->db->select("serial_no",FALSE); $this->db->from('order_details'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_orderdetails($id){ $this->db->select("prod_category.id As catid, prod_subcategory.id As subcatid, brands.id As brandid, products.id As modelid, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model, order_details.warranty_date, service_location.service_loc, service_location.id As locid",FALSE); $this->db->from('order_details'); $this->db->join('prod_category', 'prod_category.id = order_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = order_details.subcat_id'); $this->db->join('brands', 'brands.id = order_details.brand_id'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); //$this->db->order_by('order_details.order_id', 'asc'); $this->db->where('order_details.serial_no', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_list($user_access,$user_type){ if($user_access=="nonstamping_user"){ $query = $this->db->query("SELECT service_request.id, service_request.request_id, service_request.request_date, customers.customer_name from service_request as service_request inner join customers as customers ON customers.id=service_request.cust_name inner join service_request_details as service_request_details ON service_request_details.request_id=service_request.id where (service_request.status IN(5,8) and service_request_details.assign_to!='' and (service_request_details.site='Service Center' or service_request_details.site='Customer Site')) ORDER BY service_request.id ASC"); //echo "<pre>";print_r($query->result());exit; return $query->result(); }elseif($user_type=="1"){ //$this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name",FALSE); //$this->db->from('service_request'); //$this->db->join('customers', 'customers.id=service_request.cust_name'); //$this->db->join('service_request_details', 'service_request_details.request_id=service_request.id'); //$this->db->where_in('service_request.status', array('5','8')); //$this->db->where('service_request_details.assign_to!=', ''); //$this->db->where_in('service_request_details.site', 'Service Center'); //$this->db->order_by('service_request.id', 'asc'); //$query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; //return $query->result(); $query = $this->db->query("SELECT service_request.id, service_request.request_id, service_request.request_date, customers.customer_name from service_request as service_request inner join customers as customers ON customers.id=service_request.cust_name inner join service_request_details as service_request_details ON service_request_details.request_id=service_request.id where (service_request.status IN(5,8) and service_request_details.assign_to!='' and (service_request_details.site='Service Center' or service_request_details.site='Customer Site')) ORDER BY service_request.id ASC"); //echo "<pre>";print_r($query->result());exit; return $query->result(); }else{ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('service_request_details', 'service_request_details.request_id=service_request.id'); $this->db->where_in('service_request_details.site', ''); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } public function service_req_list1(){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); //$this->db->join('prod_category', 'prod_category.id = order_details.cat_id'); //$this->db->join('prod_subcategory', 'prod_subcategory.id = order_details.subcat_id'); //$this->db->join('brands', 'brands.id = order_details.brand_id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->join('employee', 'employee.id = service_request_details.assign_to'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforEmp(){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function status_list(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $query = $this->db->get(); return $query->result(); } public function combine_status_list(){ $this->db->select("service_request.id, service_request.status",FALSE); $this->db->from('service_request'); //$this->db->join('quote_review', 'quote_review.req_id=service_request.id'); //$this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqbyid($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.mobile, service_request.email_id, customers.customer_name, customers.id As cust_id",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqDetailsbyid($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.serial_no, service_request_details.warranty_date, service_request_details.service_type, service_request_details.service_cat, service_request_details.zone, service_request_details.problem, service_request_details.assign_to, service_request_details.received, service_request_details.machine_status, service_request_details.site, prod_category.id As catid, prod_subcategory.id As subcatid, brands.id As brandid, products.id As modelid, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model, service_location.service_loc, service_location.id As locid",FALSE); $this->db->from('service_request_details'); $this->db->join('prod_category', 'prod_category.id = service_request_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = service_request_details.subcat_id'); $this->db->join('brands', 'brands.id = service_request_details.brand_id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getserviceEmpbyid($id){ $this->db->select("service_request_details.assign_to, employee.id As emp_id, employee.emp_name ",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function servicecat_list(){ $this->db->select("id,service_category",FALSE); $this->db->from('service_category'); $query = $this->db->get(); return $query->result(); } public function problemlist(){ $this->db->select("id,prob_category ",FALSE); $this->db->from('problem_category'); $query = $this->db->get(); return $query->result(); } public function employee_list(){ $this->db->select("id, emp_id, emp_name",FALSE); $this->db->from('employee'); $query = $this->db->get(); return $query->result(); } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $query = $this->db->get(); return $query->result(); } public function brandlist(){ $this->db->select("id, cat_id, subcat_id, brand_name",FALSE); $this->db->from('brands'); $query = $this->db->get(); return $query->result(); } public function serviceLocList(){ $this->db->select("id, service_loc",FALSE); $this->db->from('service_location'); $query = $this->db->get(); return $query->result(); } public function get_branch($id){ $query = $this->db->get_where('customer_service_location', array('customer_id' => $id)); return $query->result(); } public function getsub_cat($id){ $query = $this->db->get_where('prod_subcategory', array('prod_category_id' => $id)); return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function get_brands($categoryid,$subcatid){ $query = $this->db->get_where('brands', array('cat_id' => $categoryid, 'subcat_id' => $subcatid)); return $query->result(); } public function get_models($categoryid,$subcatid,$brandid){ $query = $this->db->get_where('products', array('category' => $categoryid, 'subcategory' => $subcatid, 'brand' => $brandid)); return $query->result(); } public function orderlist1(){ $this->db->select("orders.id, customers.customer_name,customers.customer_type",FALSE); $this->db->from('orders'); $this->db->join('customers', 'customers.id=orders.customer_id'); $this->db->order_by('orders.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_service_request($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function update_service_status($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function delete_serv_req_details($id){ $this->db->where('request_id',$id); $this->db->delete('service_request_details'); } public function delete_orders($id){ $this->db->where('id',$id); $this->db->delete('orders'); } }<file_sep>/application/models/Labcategory_model.php <?php class labcategory_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); $this->load->helper('array'); } public function add_lab_cat($data1){ $query= $this->db->insert('lab_tech',$data1); return true; } public function checkusername($user) { $this->db->select('lab_name'); $this->db->from('lab_tech'); $this->db->where_in('lab_name',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function labss_list() { $this->db->select('*'); $this->db->from('lab_tech'); $this->db->order_by('id','desc'); $query=$this->db->get(); return $query->result(); } public function getlabbyid($id) { $this->db->select('*'); $this->db->from('lab_tech'); $this->db->where('id',$id); $this->db->order_by('id','desc'); $query=$this->db->get(); return $query->result(); } public function update_lab($data,$id){ $this->db->where('id',$id); $this->db->update('lab_tech',$data); } public function update_status_prod_cat($data,$id){ $this->db->where('id',$id); $this->db->update('lab_tech',$data); } public function update_status_prod_cat1($data,$id){ $this->db->where('id',$id); $this->db->update('lab_tech',$data); } public function category_validation($product_id) { $query = $this->db->get_where('lab_tech', array('lab_name' => $product_id)); return $numrow = $query->num_rows(); } } ?><file_sep>/application/views/add_emp.php <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(function(){ $('[name="cand_no"]').on('change', function() { // Not checking for Invalid input if (this.value != '') { var val = parseInt(this.value, 10); var rows = $('#studentTable tr'), rowCnt = rows.length - 1; // Allow for header row if (rowCnt > val) { for (var i = rowCnt; i > val; i--) { rows[i].remove(); } } if (rowCnt < val) { for (var i = 0; i < val - rowCnt; i++) { // Clone the Template var $cloned = $('.template tbody').clone(); // For each Candidate append the template row $('#studentTable tbody').append($cloned.html()); } } } }); });//]]> </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; //var regemail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; var emp_id = document.frmEmp.emp_id.value, emp_name = document.frmEmp.emp_name.value, emp_mobile = document.frmEmp.emp_mobile.value, emp_email = document.frmEmp.emp_email.value, emp_edu = document.frmEmp.emp_edu.value, zone = document.frmEmp.zone.value; if( emp_id == "" ) { document.frmEmp.emp_id.focus() ; document.getElementById("errorBoxid").innerHTML = "Enter the employee id"; $( "#errorBoxid" ).css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); return false; } if( emp_name == "" ) { document.frmEmp.emp_name.focus() ; document.getElementById("errorBoxName").innerHTML = "Enter the Employee Name"; return false; } if( emp_mobile == "" ) { document.frmEmp.emp_mobile.focus() ; document.getElementById("errorBoxMobile").innerHTML = "Enter the Mobile Number"; return false; } if( emp_email == "" ) { document.frmEmp.emp_email.focus() ; document.getElementById("errorBoxEmail").innerHTML = "Enter the Email ID"; return false; } if( emp_edu == "" ) { document.frmEmp.emp_edu.focus() ; document.getElementById("errorBoxQualification").innerHTML = "Enter the Educational Qualification"; return false; } if( zone == "" ) { document.frmEmp.zone.focus() ; document.getElementById("errorBoxServiceZone").innerHTML = "Enter the Zone"; return false; } } </script> <script> $(function(){ $( "form" ).submit(function( event ) { //alert("fgh"); if ( $( "#company" ).val() === "" ) { $( "#company_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( ".city" ).val() === "" ) { $( "#errorBox_city" ).text( "Enter the City" ).show(); event.preventDefault(); } }); }); </script> <!--<script>///////////////////////////////////character & number validation/////////////////////////////////////////// $(document).ready(function(){ $('#emp_name').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('#emp_designation').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('.city').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('#emp_qualification').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z ./-_,]+$/,'') ); }); $('#emp_address').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z ./-_,]+$/,'') ); }); $('#emp_address1').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z ./-_,]+$/,'') ); }); $('#mobile').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#mobile').change(function(){ if($(this).val().length<10){ $( "#errorBoxMobile" ).text( "Phone Number must be atleast 10 digit" ).show(); return false; $(this).focus(); } }); $('#pincode').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); }); </script>--> <!--<script> $(document).ready(function(){ var regemail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/; $('#emp_email').change(function(){ var email1=$(this).val(); if(!regemail.test(email1)){ $( "#errorBoxEmail" ).text( "Invalid Email Address" ).show(); $(this).val(""); $(this).focus(); return false; } }); }); </script>--> <script> $(document).ready(function(){ $("#emp_name").keyup(function(){ if($(this).val()==""){ $("#errorBoxName").show(); } else{ $("#errorBoxName").hide(); } }); $("#mobile").keyup(function(){ if($(this).val()==""){ $("#errorBoxMobile").show(); } else{ $("#errorBoxMobile").hide(); $("#errorBoxMobile1").html(''); } }); $("#emp_email").keyup(function(){ if($(this).val()==""){ $("#errorBoxEmail").show(); } else{ $("#errorBoxEmail").hide(); } }); $("#emp_qualification").keyup(function(){ if($(this).val()==""){ $("#errorBoxQualification").show(); } else{ $("#errorBoxQualification").hide(); } }); $("#zone").change(function(){ if($(this).val()==""){ $("#errorBoxServiceZone").show(); } else{ $("#errorBoxServiceZone").hide(); } }); $(".city").keyup(function(){ if($(this).val()==""){ $("#errorBox_city").show(); } else{ $("#errorBox_city").hide(); } }); }); </script> <style> body{background-color:#fff;} #studentTable .skill td { background: #055E87 none repeat scroll 0% 0%; border: 1px solid #B3B3B3; padding: 8px; color: #FFF; } #studentTable tr td { border: 1px solid #B3B3B3; text-align: center; padding: 10px; } #studentTable tr td select { width: 106px; height: 33px; border-width: medium medium 1px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color #055E87; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; margin: 0px 3px; box-sizing: border-box; -moz-appearance: none; border-radius: 5px; } #studentTable tr td select:focus { border:1px solid #055E87; } input.number { border-radius:5px; } #errorBox{ color:#F00; font-size: 12px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } input[readonly]{background-color: #eee;} </style> <style> .btn{text-transform:none !important;} .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list { float: left; list-style: none; margin: 0; padding: 0; width: 246px; height: 125px; overflow-y: auto; overflow-x: hidden; position: relative; bottom: 15px; border: 1px solid #2196F3; border-top: gray; } #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} #suggesstion-box{ position: absolute; z-index: 3; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>New Employee</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Employee/add_employee" method="post" name="frmEmp" onsubmit="return frmValidate()" autocomplete="off"> <div id="errorBox"></div> <div class="tableadd"> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Employee ID&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_id" class="" value="<?php echo "ENG".$cnt; ?>" readonly> </div> <div class="col-md-3"> <label>Employee Name&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_name" id="emp_name" class="alpha" maxlength="50"> <div id="errorBoxName" style="color:red; font-size: 10px; bottom:1px; margin-top: -13px;"></div> </div> <div class="col-md-3"> <label>Designation</label> <input type="text" name="emp_designation" id="emp_designation" class="alpha" maxlength="80"> </div> <div class="col-md-3"> <label>Mobile&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_mobile" id="mobile" class="numeric" maxlength="15"> <div id="errorBoxMobile" style="color:red; font-size: 10px; margin-top:-14px;"></div> <div id="errorBoxMobile1" style="color:red; font-size: 10px; margin-top:10px;"></div> </div> </div> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Email ID&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_email" id="emp_email" class="email"> <div id="errorBoxEmail" style="color:red;font-size: 10px; margin-top:-4px; "></div> </div> <div class="col-md-3"> <label>Educational Qualification&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_edu" id="emp_qualification" class="alphanumericdotspace" maxlength="50"> <div id="errorBoxQualification" style="color:red;font-size: 10px; margin-top: -13px;"></div> </div> <div class="col-md-3"> <label>Experience</label> <input type="text" name="emp_exp" class="alphanumericdotspace" maxlength="8"> </div> <div class="col-md-3"> <label>Date of Joining</label> <input type="text" name="doj" class="date" maxlength="10"> </div> </div> <!--<div class="col-md-12"> <div class="col-md-3"><label>Stampings</label></div><div class="col-md-3"><input type="checkbox" name="emp_stamping" class="" value="1"></div> </div>--> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Address</label> <input type="text" name="emp_addr" id="emp_address" class="alphanumericaddress" maxlength="150"> <div id="errorBoxAddress"></div> </div> <div class="col-md-3"> <label>Address 1</label> <input type="text" name="emp_addr1" id="emp_address1" class="alphanumericaddress" maxlength="150"> <div id="errorBoxAddress1"></div> </div> <!--<div class="col-md-3"> <label>City</label> <input type="text" name="emp_city" id="search-box" class="city alpha" maxlength="80"> <div id="suggesstion-box" ></div> <div id="errorBoxCity"></div> </div>--> <div class="col-md-3 col-sm-6 col-xs-12 "> <label for="tags">City<span style="color:red;">*</span></label> <input type="text" name="emp_city" id="tags" class="city" maxlength="100"> <!--<div id="suggesstion-box" ></div>--> <div id="errorBox_city" style="color:red;font-size:10px;margin-top:-16px;"></div> </div> <div class="col-md-3"> <label>State</label> <select name="emp_state" id="emp_state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } ?> </select> <div id="errorBoxState"></div> </div> </div> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Pincode</label> <input type="text" name="emp_pincode" id="pincode" class="numeric" maxlength="6"> <div id="errorBoxPincode"></div> </div> <div class="col-md-3"> <label>Service Zone&nbsp;<span style="color:red;">*</span></label> <select name="zone[]" id="zone" class="zone_validate" multiple="multiple" style="width:230px;"> <option value="">---Select---</option> <?php foreach($service_zone_list as $zoneKey){?> <option value="<?php echo $zoneKey->id; ?>"><?php echo $zoneKey->service_loc; ?></option> <?php }?> </select> <div id="errorBoxServiceZone" style="color:red;font-size: 10px; "></div> </div> </div> </div> <!--<table class="tableadd1"> <tr> <td><label style="font-weight: bold;">Service Skills</label></td><td></td> </tr> <tr> <th><label>Category</label></th><th><label>Sub-category</label></th> <th><label>Model</label></th><th><label>Installation</label></th><th><label>AMC</label></th><th><label>General</label></th><th><label>Major</label></th><th><label>Extra Fitting</label></th> </tr> <tr> <td><input type="text" class="" name=""></td> <td><input type="text" class="" name=""></td><td><input type="text" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td> </tr> <tr> <td style="padding-top: 25px;"> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> </td> </tr> </table>--> <!--<label style="font-weight: bold; font-size: 15px; color: black;padding-top:10px; padding-bottom:10px;">Service Skills:</label> <p> <label style="font-weight: bold; font-size: 13px; color: black; width: 230px;">Enter No Of Service</label> <label><input name="cand_no" type="text" placeholder="Enter Number" style="width: 405px;" class="number"/></label> <div class="clear"></div> </p> <div class="cand_fields"> <table id="studentTable" width="630" border="0"> <tr class="skill"> <td>Category</td> <td>Sub-category</td> <td>Model</td> <td>Installation</td> <td>AMC</td> <td>General</td> <td>Major</td> <td>Extra Fitting</td> </tr> <tr> <td style="width:200px;"> <select > <option value="">---Select---</option> <option value="Motorola">Air Conditioner</option> <option value="<NAME>">Television</option> <option value="Nokia">Digital Camera</option> <option value="Apple">Mobile Phone</option> <option value="Samsung">Cash Counting Machine</option> <option value="Samsung">Washing Machine</option> </select> </td> <td style="width:200px;"> <select > <option value="">---Select---</option> <option value="Motorola">Subcategory 1</option> <option value="<NAME>">Subcategory 2</option> <option value="Nokia">Subcategory 3</option> <option value="Apple">Subcategory 4</option> <option value="Samsung">Subcategory 5</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Model 1</option> <option value="<NAME>">Model 2</option> <option value="Nokia">Model 3</option> <option value="Apple">Model 4</option> <option value="Samsung">Model 5</option> </select> </td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> </tr> </table> </div> <div class="template" style="display: none"> <table > <tr> <td > <select > <option value="">---Select---</option> <option value="Motorola">Air Conditioner</option> <option value="<NAME>">Television</option> <option value="Nokia">Digital Camera</option> <option value="Apple">Mobile Phone</option> <option value="Samsung">Cash Counting Machine</option> <option value="Samsung">Washing Machine</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Subcategory 1</option> <option value="<NAME>">Subcategory 2</option> <option value="Nokia">Subcategory 3</option> <option value="Apple">Subcategory 4</option> <option value="Samsung">Subcategory 5</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Model 1</option> <option value="<NAME>">Model 2</option> <option value="Nokia">Model 3</option> <option value="Apple">Model 4</option> <option value="Samsung">Model 5</option> </select> </td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> </tr> </table> href="<?php echo base_url(); ?>pages/service_skill" </div>--> <!--<a class="btn cyan waves-effect waves-light " type="submit" name="action" style="margin-top: 25px;">Add Service Skill <i class="fa fa-arrow-right"></i> </a>--> <button class="btn cyan waves-effect waves-light " type="submit" >Add Service Skill </button> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(function(){ var regeditmail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.(com|org|net|co.in|in|mil|edu|gov|gov.in))$/; $(".alpha").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z. ]/g,"")); }); $(".numeric").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9]/g,"")); }); $(".alphanumericdotspace").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9. ]/g,"")); }); $(".alphanumericaddress").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $(".email").on("change", function(){ if(!regeditmail.test($(".email").val())){ $("#errorBoxEmail").text("Invalid Email ID!").show().css({ "font-size":"10px", "color":"#ff0000", "position":"relative", "bottom":"10px" }); $(this).val(""); } }); $('#mobile').change(function(){ if($(this).val().length<10){ $( "#errorBoxMobile" ).text( "Phone Number must be atleast 10 digit" ).show().css({ "font-size":"10px", "color":"#ff0000", "position":"relative", "margin-top":"-10px" }); $(this).val(""); return false; $(this).focus(); } }); $('#pincode').change(function(){ if($(this).val().length<6){ $( "#errorBoxPincode" ).text( "Pincode Number must be atleast 6 digit" ).show().css({ "font-size":"10px", "color":"#ff0000", "position":"relative", "bottom":"10px" }); $(this).val(""); return false; $(this).focus(); } }); $('#pincode').keyup(function(){ $( "#errorBoxPincode" ).hide(); }); }); </script> <script> $( function() { var available_cities = []; //alert($(this).val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>Employee/get_city", data:'keyword='+$(this).val(), success: function(data) { $.each(data, function(index, data){ available_cities.push(data.city); }); } }); $( "#tags" ).autocomplete({ source: available_cities }); } ); </script> <script> $(document).ready(function(){ $(document).on("keyup","#mobile", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var id=$("#mobile").val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Employee/mobile_validation", data: datastring, cache: false, success: function(data) { if(data == 0){ $('#errorBoxMobile').html(''); } else{ $('#errorBoxMobile1').html('Mobile Number Already Exist!').show(); $('#mobile').val(''); return false; } } }); } }); </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 999-9999'); $('#mobile').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script>--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> $("#zone").select2(); </script> </body> </html><file_sep>/application/controllers/Login.php <?php class Login extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('login_model'); } public function index($msg = NULL){ $data['msg']=$msg; $this->load->view('index',$data); } public function process(){ $uname=$this->input->post('email'); $pwd=$this->input->post('password'); $validate = $this->login_model->validate($uname,$pwd); if($validate == 0 ) { $msg='<font color=red>Invalid email and/or password.</font>'; $this->index($msg); } else { $data1['user_dat'] = $this->session->userdata('login_data'); $usertype = $data1['user_dat'][0]->user_type; if($usertype=='7'){ redirect(base_url().'pages/workin_prog_list'); }else{ redirect(base_url().'pages/dash'); } //$data1['user_acc'] = $data1['user_dat'][0]->user_access; //$data1['user_type'] = $data1['user_dat'][0]->user_type; } } public function change_pass() { $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_password'); } public function update_password() { $pwd=$this->input->post('changeid'); $pwdd=$this->input->post('brand_name2'); $pwddd=$this->input->post('brand_name3'); if($pwdd==$pwddd) { $data=array( 'password'=>$<PASSWORD> ); $s = $this->login_model->update_password($data,$pwd); if($s) { redirect('login/logout'); } } } public function logout(){ $this->session->sess_destroy(); redirect('login'); } }<file_sep>/application/views_bkMarch_0817/emp_list.php <script> function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Employee/del_employee', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/emp_list"; } alert("Employee deleted"); } }); }); } </script> <style> .ui-state-default { background: #fff !important; border: 3px solid #fff !important; color: #303f9f !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=text]{ background-color: transparent; border:none; border-radius: 7; width: 55% !important; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <section id="content"> <div class="container-fluid"> <div class="section"> <!-- <h4 class="header" style="display:inline-block; height: 36px; background: #FFF; margin-bottom: -20px; padding: 10px;border:1px solid #055E87; border-bottom:none;">Employee List</h4> <a href="employee_add.php" style="border:1px solid #055E87;padding: 15px; border-bottom:none; margin-left:-5px;padding-bottom: 2px;">NEW EMPLOYEE</a>--> <h2>Employee List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addemployee.png" title="Add Employee" style="width:24px;height:24px;">Add Employee</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Employee" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Emp ID</th> <th>Emp Name</th> <th>Designation</th> <th>Mobile</th> <th>Email</th> <th>City</th> <th>State</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($list as $key){?> <tr> <td><?php echo $key->emp_id; ?></td> <td><?php echo $key->emp_name; ?></td> <td><?php echo $key->emp_designation; ?></td> <td><?php echo $key->emp_mobile; ?></td> <td><?php echo $key->emp_email; ?></td> <td><?php echo $key->emp_city; ?></td> <td><?php echo $key->state; ?></td> <td class="options-width" style="text-align:center;"> <a href="<?php echo base_url(); ?>Employee/update_employee/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/search_list1.php <script> function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>order/del_order', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/order_list"; } alert("Order deleted"); } }); }); } </script> <script> $(document).ready(function(){ $("#search").change(function(){ //alert("search"); var datastring='search='+$("#search").val(); var avail=$("#available").remove(); //var a=$('#bodyd').hide(); //var ava=$("#bodyd").remove(); //alert(datastring); $.ajax({ type: "post", url: "<?php echo base_url(); ?>order/search_list", cache: false, data:datastring, success: function(data){ if(data.length=='0'){ //alert("sdsds"); $('#bodyd').append("<tr id='available'><td colspan='10' align='center'><h4 align='center'>No Data Available</h4></td></tr>"); }else{ $.each(data, function(index, data){ var val=data.warranty_date; var datavalue=''; var value=''; if(val !='') { value ="Warranty"; }else { value="Chargeable"; } datavalue=value; //alert(data.serial_no.length); if(data.serial_no.length>0){ //alert("3rrr"); $('#bodyd').append("<tr id='available'><td>"+data.customer_id+"</td><td>"+data.company_name+"</td><td>"+data.branch_name+"</td><td>"+data.type+"</td><td>"+data.model+"</td><td>"+data.serial_no+"</td><td>"+data.purchase_date+"</td><td>"+datavalue+"</td><td>"+data.service_loc+"</td><td><a href='<?php echo base_url(); ?>order/update_order/"+data.oid+"'>Edit</a> <a href='#' onclick='brinfo1("+data.oid+")'>View</a></td></tr>"); } }); } }, }); }); });/*"<tr><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th><th>"+id+"</th></tr>"*/ </script> <style> .input-group-btn:last-child>.btn, .input-group-btn:last-child>.btn-group { margin-left: 4px !important; height: 38px; } .fa { font-size: 16px !important; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #522276; font-size:12px; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } table, th, td { border: 1px solid #ccc; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; border: 1px solid #dbd0e1 !important; /*background-color: white;*/ } thead { border-bottom: 1px solid #ccc; border: 1px solid #ccc; color: #fff; background:#6c477d; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } /* Ends Here */ input[type=text]{ margin: 0 0 15px 0; padding: 1px; border: 1px solid #ccc; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; border-radius: 6px; } h1, .h1, h2, .h2, h3, .h3 { margin-top: 20px; margin-bottom: 10px; } hr { margin-top: 0px !important; } a{ color: #522276 !important; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } #sicon{ cursor:pointer; } #available{ align:center; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <div class="col-md-12"> <h2>Search List</h2> <hr> <!--<div class="col-md-offset-4 col-md-3"> <input type="text" name="search" id="search" class="form-control" maxlength="40" placeholder="Search Serial No." AUTOCOMPLETE = "off" style="font-size: 12px;"/> <span style="position: relative; float: right; top: -42px; "><i class="fa fa-search" id="sicon"></i> </span> </div>--> </div> <div class="row"> <div class="col-md-offset-4 col-xs-6 col-md-4"> <div class="input-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Search Serial No." AUTOCOMPLETE = "off" /> <div class="input-group-btn"> <button class="btn btn-primary" type="submit"> <span class="glyphicon glyphicon-search"></span> </button> </div> </div> </div> </div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table class="table table-border display" > <thead id="head"> <tr> <th class="hidden">id</th> <th >Customer ID</th> <th >Customer Name</th> <th>Branch</th> <th>Type Of Customer</th> <th >Products</th> <th>Serial No.</th> <th >Sale Date</th> <!--<th style="width:9% !important">Warranty Date</th>--> <th >Machine status</th> <th>Location</th> <th>Action</th> </tr> </thead> <tbody id="bodyd" > <tr id="available"><td colspan="14"><?php echo "<h4 align='center'>No Data Available</h4>"; ?></td></tr> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/custom.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/piklor.js"></script> <script src="<?php echo base_url(); ?>assets/js/handlers.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('#search').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); /*$('#search').click( function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $('#bodyd').hide(); });*/ }); </script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo1(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>Order/pm_service_status/'+id, type : 'iframe', padding : 5, 'width' : 800, 'height' : 675, 'autoScale' : false, 'onComplete' : function(){ $.fancybox.resize(); } }); } </script> </body> </html><file_sep>/application/views/workin_prog_viewbk16august17.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); var i=1; $("#addRowBtn").click(function(){ $(' <tr><td> <select id="sparename_'+i+'"> <option value="">---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> <div class="spare-error'+i+'"></div> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); $("#resgister").click(function(event){ //alert("test"); if($("#sparename_"+i).find("option:selected").attr("value")==""){ alert("inside if"); $(".spare-error"+i).text("Please choose any one spare").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } }); i++; }); $(document.body).delegate(".delRowBtn1", "click", function(){ var vals = $('#spare_tot').val(); var idd=$(this).closest(this).attr('id'); // alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); //alert($('#amt'+ctid).val()); var vals = $('#spare_tot').val(); vals -= Number($('#amt'+ctid).val()); //alert(vals); $('#spare_tot').val(vals); var tax_amt = (vals * $('#tax_type').val()) / 100; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); if(warran=='Preventive' || warran=='Warranty' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); $('#total_amt1').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); //alert(Total_amount); $('#total_amt').val(Total_amount); } $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(function(){ // alert('ddddddddd'); $(".eng_notess").hide(); $(".cust_solution").hide(); if($("#notes_alle").find("option:selected").attr("value")=="cust_solution"){ $(".cust_solution").show(); } else { $(".cust_solution").hide(); } if($("#notes_alle").find("option:selected").attr("value")=="eng_notess"){ $(".eng_notess").show(); } else { $(".eng_notess").hide(); } $("#notes_alle").change(function(){ if($(this).find("option:selected").attr("value")=="cust_solution"){ $(".cust_solution").show(); //$("#cust_remark").val(""); $("#eng_notess").val(""); } else{ $(".cust_solution").hide(); } if($(this).find("option:selected").attr("value")=="eng_notess"){ $(".eng_notess").show(); $(".cust_solution").hide(); $("#cust_solution").val(""); //$("#eng_notes").val(""); } else{ $(".eng_notess").hide(); } }); }); </script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).val()=="3"){ $(".box").not(".ready").hide(); $(".ready").show(); } else if($(this).val()=="4"){ $(".box").not(".delivery").hide(); $(".delivery").show(); } else if($(this).val()=="9"){ $(".box").not(".onhold").hide(); $(".onhold").show(); } else if($(this).attr("value")=="blue"){ $(".box").not(".blue").hide(); $(".blue").show(); } else if($(this).val()=="eng_notess"){ $(".box").not(".eng_notess").hide(); $(".eng_notess").show(); } else if($(this).val()=="cust_solution"){ $(".box").not(".cust_solution").hide(); $(".cust_solution").show(); } else{ $(".box").hide(); } }); }).change(); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1+'&modelid='+modelid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#table11').append(result); } }); }); }); </script> <style> .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td select { width: 210px !important; } .tableadd2 tr td select { width: 165px; margin-bottom: 15px; } .tableadd2 tr.back td { background: #6c477d !important; border: 1px solid #6c477d !important; color: #fff; padding: 8px; } .tableadd tr td label{ width: 180px !important; font-weight: bold; font-size: 13px; } .breadcrumbs-title { font-size: 1.8rem; line-height: 5.804rem; margin: 0 0 0; color:#6C217E; font-weight:bold; } .box{ padding: 20px; display: none; margin-top: 20px; box-shadow:none !important; } .box1{ display: none; } .rating label { font-weight: normal; padding-right: 5px; } .rating li { display: inline; } input[type=text], input[type=textarea], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: auto; } [type="radio"]:not(:checked), [type="radio"]:checked { position:relative; } [type="radio"] + label:before, [type="radio"] + label:after { } [type="radio"] + label:before, [type="radio"] + label:after { content: ''; position: absolute; left: 0; top: 0; margin: 4px; width: 16px; height: 16px; display:none; z-index: 0; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; } [type="radio"]:not(:checked) + label, [type="radio"]:checked + label { position: relative; padding-left: 5px; cursor: pointer; display: inline-block; height: 25px; line-height: 25px; font-size: 14px; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; } .tableadd { padding: 0px; } /*.addressdiv, .toggleaddress { display: none; }*/ @media only screen and (min-width: 301px){ .xdsoft_datetimepicker .xdsoft_datepicker.active+.xdsoft_timepicker { margin-top: 41px !important; margin-bottom: 3px; } .xdsoft_datetimepicker .xdsoft_datepicker { width: 154px !important; float: left; margin-left: 8px; } } @media only screen and (max-width: 350px){ .headerDivider { border-left:1px solid #c5c5c5 !important; border-right:1px solid #c5c5c5 !important; height:25px !important; position: absolute !important; top:102px !important; left: 40px !important; } .toggleaddress { display: none; } } .fa { margin-right: 15px; } input[type=radio] { margin-left: 10px; margin-right: 2px; } .col-md-2, .col-md-1 { padding:0px; } .headerDivider { border-left:1px solid #c5c5c5; border-right:1px solid #c5c5c5; height:25px; position: absolute; top:73px; left: 280px; } textarea { width: 100%; height: auto !important; background-color: transparent; } .noresize{ resize: none; } .linkaddress { cursor: pointer; } #errorBox{ color:#F00; } .tableadd2 tr td input { margin: 10px; height: 30px; } @media only screen and (max-width: 380px) { td { padding: 3px !important; } a { padding: 3px !important; } select { width: 100px !important; } .tableadd2 tr td input { border-radius: 5px; height: 33px; margin-top: 17px; width: 50px; margin-left: 3px; margin-right: 3px; } .tableadd2 tr td select { padding: 0 30px 0 0; } } @media only screen and (max-width: 768px) and (min-width: 240px){ ol, ul { margin-top: 0; margin-bottom: 0 !important; } } .cyan { background-color: #6c477d !important; width: 7%; } label.appendfont{ border:none !important; font-size: 0.85em !important; } span.pagerefresh{ color: #6c477d !important; } input:read-only{ background:#eee; } textarea:read-only{ background:#eee; } .header-buttons{ width: 190px; position: relative; left: 320px; } select{ width:84%; } input[type=text], input[type=textarea], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: 100%; } </style> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id = $(this).val(); //alert("spareid: "+id); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1'+ctid).val(data.spare_qty), $('#amt1'+ctid).val(data.sales_price), $('#used_spare'+ctid).val(data.used_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $( ".pagerefresh" ).click(function() { location.reload(true); }); }); </script> <script> function frmValidate(){ if(document.frmworkinpro.eng_ack.checked=false) { // document.frmworkinpro.eng_ack.focus() ; document.getElementById("errorBox").innerHTML = "Please your give your ack"; return false; } } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <div class="header-buttons pull-right"><a class="btn cyan waves-effect waves-light" onclick="history.go(-1);" style="width:19%;margin-right:10px;height:29px;padding:3px 7px;"><span class="fa fa-arrow-left" data-toggle="tooltip" title="Back"></span></a> <div class="headerDivider"></div><span class="fa fa-refresh pagerefresh" data-toggle="tooltip" title="Refresh"></span></div> <h5 class="breadcrumbs-title">Completed by Engineer</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div> <form action="<?php echo base_url(); ?>work_inprogress/edit_quotereview" method="post" name="frmworkinpro" onsubmit="return frmValidate()"> <div id="errorBox"></div> <?php //print_r($getQuoteByReqId); foreach($getQuoteByReqId as $key){ if(isset($key->problem)){ $problem_data = explode(",",$key->problem); } ?> <?php if($key->accepted_engg_id!="0"){ $get_emp_by_id = $this->workin_prog_model->get_emp_by_id($key->accepted_engg_id); $emp_namess = $get_emp_by_id[0]->emp_name; $emp_idss = $get_emp_by_id[0]->id; }else{ $emp_namess = ''; $emp_idss = '0'; } $assign = $key->assign_to; $ass_too = explode(",",$assign); //print_r($ass_too); ?> <input type="hidden" name="assignn_to" id="assignn_to" value="<?php if($key->accepted_engg_id!="0"){echo $key->accepted_engg_id;}else{echo "0"; } ?>"> <div class="tableadd col-md-12"> <?php if($key->status!='16' && $key->eng_ack!='accept'){ ?> <div class="col-md-12" style="padding-left:30px;padding-bottom:10px"> <div class="col-md-2"><label style="margin-bottom:0px">Acknowledgement<span style="color:red">*</span></label></div> <div class="col-md-1"><input type="radio" name="eng_ack" value="accept" <?php if($key->eng_ack=='accept' && $key->eng_ack!=''){?>checked='checked'<?php }?> >Accept</div> <div class="col-md-1"><input type="radio" name="eng_ack" value="reject" <?php if($key->eng_ack=='reject' && $key->eng_ack!=''){?>checked='checked'<?php }?>>Reject</div> <div class="col-md-1"><input type="radio" name="eng_ack" value="later" <?php if($key->eng_ack=='later' && $key->eng_ack!=''){?>checked='checked'<?php }?>>Later</div> </div> <?php } ?> <!--<div class="col-md-6">--> <div class="col-md-12"> <div class="col-md-3"> <label>Request ID:</label> <input type="text" name="reque_id" class="" value="<?php echo $key->request_id; ?>" readonly > </div> <div class="col-md-3"> <label>Customer Name:</label> <input type="text" name="cust_name" class="" value="<?php echo $key->company_name; ?>" readonly><input type="hidden" name="cust_mobile" class="" value="<?php echo $key->mobile; ?>" readonly> </div> <div class="col-md-3"> <label>Branch Name:</label> <input type="text" name="br_name" class="" value="<?php echo $key->branch_name; ?>" readonly> </div> <div class="col-md-3"> <label>Contact Name:</label> <input type="text" name="cont_name" class="" value="<?php echo $key->contact_name; ?>" readonly> </div> <input type="hidden" value="<?php echo $key->email_id;?>" name="email"> </div> <div class="col-md-12"> <div class="col-md-3 addressdiv"> <div class="addresslabel"><a class="linkaddress">Address</a></div> <div class="toggleaddress"><textarea class="noresize materialize-textarea" cols="22" rows="1" readonly><?php echo $key->address.' '.$key->address1; ?></textarea></div> </div> <div class="col-md-3"> <label>Mobile:</label> <input type="text" name="cust_mobile1" class="" value="<?php echo $key->cust_mobile; ?>" readonly> </div> <div class="col-md-3"> <label>Landline:</label> <input type="text" name="land_line" class="" value="<?php echo $key->landline; ?>" readonly> </div> <!--<div class="col-md-6 col-sm-3"><label>Address:</label></div> <div class="col-md-6 col-sm-3"><textarea class="noresize materialize-textarea" cols="22" rows="2"><?php echo $key->address.' '.$key->address1; ?></textarea></div>--> <div class="col-md-3"> <label>Model:</label> <input type="text" name="p_name" class="" value="<?php echo $key->model; ?>" readonly><input type="hidden" name="modelid" id="modelid" class="" value="<?php echo $key->modelid; ?>"> <input type="hidden" name="req_id" id="req_id" class="" value="<?php echo $req_id; ?>"> </div> </div> <div class="col-md-12"> <?php if($key->serial_no=='serial_no') {?> <div class="col-md-3"> <label>Serial No.:</label> <input type="text" name="serial_no" value="update sr no" readonly> <input type="hidden" name="order_row_id" value="<?php echo $key->order_row_id; ?>" readonly> </div> <div class="col-md-3"> <label>Batch No.:</label> <input type="text" name="batch_no" value="batch no" readonly> </div> <?php } ?> <?php if($key->serial_no!='serial_no') {?> <div class="col-md-3"> <label>Serial No.:</label> <input type="text" name="serial_no" value="<?php echo $key->serial_no; ?>"> <input type="hidden" name="order_row_id" value="<?php echo $key->order_row_id; ?>"> </div> <div class="col-md-3"> <label>Batch No.:</label> <input type="text" name="batch_no" value="<?php echo $key->batch_no; ?>"> </div> <div class="col-md-3"> <label>Addl Engineer Name: </label> <input type="text" name="addl_engg" class="" value="<?php foreach($service_req_listforaddlEmp1 as $AddlEmpkey){echo $AddlEmpkey->emp_name;} ?>" readonly> <input type="hidden" value="<?php foreach($service_req_listforaddlEmp1 as $roww){ if($roww->id==""){ echo ""; }else {echo $roww->id;} }?>" name="eng_name"> </div> <?php } ?> <?php if($user_type!='7'){?> <div class="col-md-3"> <label>Date Of Purchase:</label> <input type="text" name="purchase_date" class="date" value="<?php echo $key->purchase_date; ?>" readonly> </div> <!--</div> <div class="col-md-6">--> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Warranty End Date:</label> <input type="text" name="warranty_date" value="<?php echo $key->warranty_date; ?>" readonly> </div> <?php } ?> <div class="col-md-3"> <label>Date Of Request:</label> <input type="text" name="request_date" value="<?php echo $key->request_date; ?>" readonly> </div> <div class="col-md-3"> <label>Problem:</label> <input type="text" value="<?php if(!empty($problemlist1)){ foreach($problemlist1 as $problemlistkey1){ if (in_array($problemlistkey1->id, $problem_data)){ echo $prob_category = $problemlistkey1->prob_category; }} }else{ echo $prob_category =""; } ?>" readonly> </div> <div class="col-md-3"> <label>Machine Status:</label> <input type="text" name="machine_status" class="" value="<?php echo $key->machine_status; ?>" readonly> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Blanket Approval:</label> <input type="text" name="" class="" value="<?php echo $key->blank_app; ?>" readonly> </div> <div class="col-md-3"> <label>Area:</label> <input type="text" name="area_name" class="" value="<?php echo $key->area_name; ?>" readonly> </div> <div class="col-md-3"> <label>Pincode:</label> <input type="text" name="pincode" class="" value="<?php echo $key->pincode; ?>" readonly> </div> <div class="col-md-3"> <label>Location:</label> <input type="text" name="serviceloc" class="" value="<?php echo $key->service_loc; ?>" readonly> </div> </div> <div class="col-md-12"> </div> <!--</div> --> </div> <?php } ?> <?php if(!empty($get_qc_parameters_details)){ foreach($get_qc_parameters_details as $qcp_key){ $qc_master_ids[] = $qcp_key->qc_master_id; } }else{ $qc_master_ids[] = ''; } $qc_models = $this->workin_prog_model->get_qc_params($key->modelid); if(!empty($qc_models)){?> <h5 class="breadcrumbs-title">QC</h5> <table class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>QC Parameters</td> <td>Actual value</td> <td>Result value</td> </tr> <?php foreach($qc_models as $qc_key){ ?> <tr> <td><?php echo $qc_key->qc_param; ?></td> <td><?php echo $qc_key->qc_value; ?></td> <?php if(in_array($qc_key->id, $qc_master_ids) && !empty($qc_master_ids)){ $qc_models = $this->workin_prog_model->get_qc_params_det($qc_key->id,$req_id); ?> <td><input type="text" name="res_qc_value[]" id="res_qc_value" value="<?php echo $qc_models[0]->result_qc_value; ?>">&nbsp; <input type="hidden" name="qc_param_id[]" id="qc_param_id" value="<?php echo $qc_models[0]->qc_master_id; ?>"></td> <?php } else{?> <td><input type="text" name="res_qc_value[]" id="res_qc_value" value="">&nbsp; <input type="hidden" name="qc_param_id[]" id="qc_param_id" value="<?php echo $qc_key->id; ?>"></td> <?php } ?> </tr> <?php } ?> </table> <?php } ?> <h5 class="breadcrumbs-title">Spare Info</h5> <div class="table-responsive"> <table id="table11" class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>Spare Name<span style="color:red">*</span></td> <td>Quantity<span style="color:red">*</span></td> <td>Amount<span style="color:red">*</span></td> <td>Status</td> <td>Warranty Claim Status</td> <?php if($key->accepted_engg_id==$emp_id){?> <td style="width:50px;background: none;border: 0px"><a id="addMoreRows" style="padding: 10px;color: #000; border-radius:5px; cursor:pointer;"><span class="fa fa-plus" style="margin-right: 0px;"></span></a></td> <?php } ?> </tr> <?php if(!empty($spareIds)){ foreach($spareIds as $key3){ foreach($key3 as $key4){ $usedspare[] = $key4->used_spare; $stockspare[] = $key4->spare_qty; $salesprice[] = $key4->sales_price; } } }//exit; $count='0'; foreach($getQuoteReviewSpareDetByID as $ReviewDetKey2){ ?> <tr> <td><input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="<?php if(!empty($usedspare[$count])){echo $usedspare[$count];} ?>"> <input type="hidden" name="spare_tbl_id[]" id="spare_tbl_id<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->id;?>"> <select name="spare_name[]" id="sparename_<?php echo $count; ?>" class="spare_name"> <option value="0">---Select---</option> <?php foreach($spareListByModelId1 as $sparekey1){ if($sparekey1->id==$ReviewDetKey2->spare_id){ ?> <option selected="selected" value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name.' - '.$sparekey1->part_no; ?></option> <?php } else {?> <option value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name.' - '.$sparekey1->part_no; ?></option> <?php } } ?> </select> <div class="spare-error<?php echo $count; ?>"></div> <?php if(isset($ReviewDetKey2->warranty_claim_status) && $ReviewDetKey2->warranty_claim_status=='to_claim'){?> <div class="appendtr1<?php echo $count; ?>" id="appendtr11-<?php echo $count; ?>"> <label class="form-control appendfont">Description of Failure</label> <textarea name="desc_failure[]" id="desc_failure" value="" class="noresize"><?php echo $ReviewDetKey2->desc_failure;?></textarea> </div> <?php } ?> <?php if($ReviewDetKey2->warranty_claim_status!='to_claim'){?> <div class="appendtr" id="appendtr11-<?php echo $count; ?>"> <label class="form-control appendfont">Description of Failure</label> <textarea name="desc_failure[]" id="desc_failure" value="" class="noresize"></textarea> </div> <?php } ?> <div name="error_sparename" id="error_sparename"></div> </td> <td><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->spare_qty; ?>" class="spare_qty"><input type="hidden" value="<?php if(!empty($stockspare[$count])){echo $stockspare[$count];}?>" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""> <?php if(isset($ReviewDetKey2->warranty_claim_status) && $ReviewDetKey2->warranty_claim_status=='to_claim'){?> <div class="appendtr1<?php echo $count; ?>" id="appendtr12-<?php echo $count; ?>"> <label class="form-control appendfont">Why &amp; When did it occur?</label> <textarea name="why_failure[]" id="why_failure" value="" class="noresize"><?php echo $ReviewDetKey2->why_failure;?></textarea> </div> <?php } ?> <?php if($ReviewDetKey2->warranty_claim_status!='to_claim'){?> <div class="appendtr" id="appendtr12-<?php echo $count; ?>"> <label class="form-control appendfont">Why &amp; When did it occur?</label> <textarea name="why_failure[]" id="why_failure" value="" class="noresize"></textarea> </div> <?php } ?> <div name="error_quantity" id="error_sparename"></div> </td> <td><input type="text" value="<?php echo $ReviewDetKey2->amt; ?>" name="amt[]" id="amt<?php echo $count; ?>" class="amout" readonly><input type="hidden" value="<?php if(!empty($salesprice[$count])){echo $salesprice[$count];}?>" name="amt1" id="amt1<?php echo $count; ?>" class=""> <?php if(isset($ReviewDetKey2->warranty_claim_status) && $ReviewDetKey2->warranty_claim_status=='to_claim'){?> <div class="appendtr1<?php echo $count; ?>" id="appendtr13-<?php echo $count; ?>"> <label class="form-control appendfont">Corrective Action</label> <textarea name="correct_action[]" id="correct_action" value="" class="noresize"><?php echo $ReviewDetKey2->correct_action;?></textarea> </div> <?php } ?> <?php if($ReviewDetKey2->warranty_claim_status!='to_claim'){?> <div class="appendtr" id="appendtr13-<?php echo $count; ?>"> <label class="form-control appendfont">Corrective Action</label> <textarea name="correct_action[]" id="correct_action" value="" class="noresize"></textarea> </div> <?php } ?> <div name="error_amount" id="error_sparename"></div> </td> <td><?php if($ReviewDetKey2->approval_status!=''){echo $ReviewDetKey2->approval_status;}else{echo "unapproved";} ?></td> <td> <select name="warranty_claim_status[]" class="warranty_claim_status" id="warranty_claim_status-<?php echo $count; ?>"> <option value="">---select---</option> <option value="to_claim" <?php if(isset($ReviewDetKey2->warranty_claim_status) && $ReviewDetKey2->warranty_claim_status=='to_claim'){?>selected='selected'<?php } ?>>To claim</option> </select> </td> <?php if($key->accepted_engg_id==$emp_id){?> <td style="border:none;"><a class="delRowBtn1" style="font-size:20px;color: #000" id="delRowBtn1_<?php echo $count; ?>"><span class="fa fa-trash-o" style="margin-right: 0px"></span></a></td> <?php } ?> </tr> <?php $count++; } ?> </table> </div> <?php //print_r($getQuoteReviewDetByID1); foreach($getQuoteReviewDetByID1 as $ReviewDetKey1){ ?> <div class="tableadd col-md-12"> <!--<div class="col-md-6"> </div>--> <?php if($user_type!='7'){?> <div class="col-md-6"> <div class="col-md-6"> <label>Ratings:</label> </div> <div class="col-md-6"> <ul class="rating"> <li><label><input class="rate" type="radio" name="rating" <?php if(isset($ReviewDetKey1->rating) && $ReviewDetKey1->rating=='1'){?>checked='checked'<?php }?> value="1">Satisfied</label></li> <li><label><input class="rate" type="radio" name="rating" <?php if(isset($ReviewDetKey1->rating) && $ReviewDetKey1->rating=='2'){?>checked='checked'<?php }?> value="2">Good</label></li> <li><label><input class="rate" type="radio" name="rating" <?php if(isset($ReviewDetKey1->rating) && $ReviewDetKey1->rating=='3'){?>checked='checked'<?php }?> value="3">Very Good</label></li> <li><label><input class="rate" type="radio" name="rating" <?php if(isset($ReviewDetKey1->rating) && $ReviewDetKey1->rating=='4'){?>checked='checked'<?php }?> value="4">Excellent</label></li> </ul> </div> <div class="tableadd col-md-6"> <label style="margin-left:20px;">Coordinator Instructions:</label> </div> <div class="tableadd col-md-6"> <textarea type="text" name="notes" id="notes" cols="25" rows="3" class="materialize-textarea"><?php if($ReviewDetKey1->notes!=""){echo $ReviewDetKey1->notes;}else{foreach($getQuoteByReqId as $notekey){echo $notekey->notes;}} ?></textarea> </div> <div class="tableadd col-md-6"> <label style="margin-left:20px;">Coordinator Instructions:</label> </div> <div class="tableadd col-md-6"> <?php if($ReviewDetKey1->notes!=""){echo $ReviewDetKey1->notes;}else{foreach($getQuoteByReqId as $notekey){echo $notekey->notes;}} ?> </div> </div> <?php } ?> <div class="col-md-6"> <?php if($user_type!='7'){?> <div class="col-md-6"><label>Spare Tax Amount:</label></div> <div class="col-md-6"> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='AMC'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Rental'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Chargeable'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='CMC'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ ?><input type="hidden" name="amc_typ" id="amc_typ" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <input type="text" name="spare_tax" id="spare_tax" class="" value="<?php $s=$ReviewDetKey1->spare_tax; if($s!=0){echo $s;}?>" readonly> <input type="hidden" name="tax_type" id="tax_type" class="" value="<?php foreach($getTaxDefaultInfo as $taxKey){ echo $taxKey->tax_percentage; }?>" ></div> <div class="col-md-6"><label>Spare Total Charges:</label></div> <div class="col-md-6"><input type="text" name="spare_tot" id="spare_tot" class="" value="<?php if($ReviewDetKey1->spare_tot !=0){echo $ReviewDetKey1->spare_tot;} ?>" readonly></div> <!-- <div class="col-md-6"><label>Labour Charges:</label></div> <div class="col-md-6"><input type="text" name="labourcharge" id="labourcharge" class="" value="<?php //foreach($getServiceCatbyID as $ServiceKey){if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Rental' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{echo $ServiceKey->service_charge;}} if(isset($getservicecharge)){echo $getservicecharge;} ?>" readonly></div> --> <div class="col-md-6"><label>Labour Charges:</label></div> <div class="col-md-6"><input type="text" name="labourcharge" id="labourcharge" class="" value="<?php foreach($getServiceCatbyID as $ServiceKey){if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Rental' || $WarranKey->machine_status=='CMC' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{echo $ServiceKey->service_charge;}} if(isset($getservicecharge)){if($getservicecharge!=0){echo $getservicecharge;}} ?>" readonly></div> <div class="col-md-6"><label>Conveyance Charges:</label></div> <div class="col-md-6"><input type="text" name="concharge" id="concharge" class="" value="<?php if($WarranKey->machine_status=="Chargeable"){echo $key->concharge;}else{if($i!=0){echo $i;}} ?>" readonly></div> <div class="col-md-6"><label>Total Amount:</label></div> <div class="col-md-6"><input type="text" name="total_amt" id="total_amt" class="" value="<?php if($ReviewDetKey1->total_amt !=0){ echo $ReviewDetKey1->total_amt; }?>" readonly><input type="hidden" name="total_amt1" id="total_amt1" class="" value="<?php echo $ReviewDetKey1->total_amt; ?>" ></div> <?php } ?> <div class="col-md-6"><label>Status</label></div> <?php foreach($get_status as $get_statusKey){ $stat = $get_statusKey->status;}?> <?php if($job_done=='completed'){?> <input type="hidden" name="job_done" value="<?php echo $job_done; ?>"> <div class="col-md-5"> <?php if($user_type=='7'){?> <select name="status" <?php if($key->accepted_engg_id!=$emp_id){?>disabled<?php } ?>> <option value="16">---Select---</option> <?php foreach($status_listForEmpLogin as $empstatuskey){ if($empstatuskey->id==$stat){ ?> <option selected="selected" value="<?php echo $empstatuskey->id; ?>"><?php echo $empstatuskey->status; ?></option> <?php } else {?> <option value="<?php echo $empstatuskey->id; ?>"><?php echo $empstatuskey->status; ?></option> <?php } } ?> </select> <?php }else{?> <select name="status" <?php if($key->accepted_engg_id!=$emp_id){?>disabled<?php } ?>> <option value="16">---Select---</option> <?php foreach($status_listForworkInpro as $workinprostatuskey){ if($workinprostatuskey->id==$stat){ ?> <option selected="selected" value="<?php echo $workinprostatuskey->id; ?>"><?php echo $workinprostatuskey->status; ?></option> <?php } else {?> <option value="<?php echo $workinprostatuskey->id; ?>"><?php echo $workinprostatuskey->status; ?></option> <?php } } ?> </select> <?php } ?> </div> <?php } else{ ?> <div class="col-md-5"> <?php if($user_type=='7'){ ?> <select name="status" <?php if($key->accepted_engg_id!=$emp_id){?>disabled<?php } ?>> <option value="1">---Select---</option> <?php foreach($status_listForEmpLogin as $empstatuskey){ if($empstatuskey->id==$stat){ ?> <option selected="selected" value="<?php echo $empstatuskey->id; ?>"><?php echo $empstatuskey->status; ?></option> <?php } else {?> <option value="<?php echo $empstatuskey->id; ?>"><?php echo $empstatuskey->status; ?></option> <?php } } ?> </select> <?php }else{?> <select name="status" <?php if($key->accepted_engg_id!=$emp_id){?>disabled<?php } ?>> <option value="1">---Select---</option> <?php foreach($status_listForworkInpro as $workinprostatuskey){ if($workinprostatuskey->id==$stat){ ?> <option selected="selected" value="<?php echo $workinprostatuskey->id; ?>"><?php echo $workinprostatuskey->status; ?></option> <?php } else {?> <option value="<?php echo $workinprostatuskey->id; ?>"><?php echo $workinprostatuskey->status; ?></option> <?php } } ?> </select> <?php } ?> </div> <?php } ?> </div> </div> <div class="tableadd col-md-12"> <div class="col-md-6" style="padding:0px;"> <?php if(isset($ReviewDetKey1->onhold_date) && $ReviewDetKey1->onhold_date!=""){?> <div> <div class="col-md-6"><label>Previous holds:</label></div> <div class="col-md-6"><?php $s=1; foreach($get_log_onholds as $log_hold_key){ if(isset($log_hold_key->on_hold) && $log_hold_key->on_hold!=""){ echo "<br/>".$s.'. '.$log_hold_key->onhold_reason.' - '.$log_hold_key->on_hold; } $s++; } ?> </div> </div> <?php } ?> <div class="ready box"> <div class="col-md-6"><label>Date Of Delivery:</label></div> <div class="col-md-6"><input type="text" name="delivery_date" id="datetimepicker7" value="<?php echo $ReviewDetKey1->delivery_date; ?>" ></div> </div> <div class="ready box"> <div class="col-md-6"><label>Comments:</label></div> <div class="col-md-6"><input type="text" name="comment_ready" class="" value="Delivered" ></div> </div> <div class="delivery box"> <div class="col-md-6"><label>Date Of Delivery:</label></div> <div class="col-md-6"><input type="text" name="delivery_date1" id="delivery_date1" value="<?php echo $ReviewDetKey1->delivery_date; ?>" ></div> </div> <div class="delivery box"> <div class="col-md-6"><label>Comments:</label></div> <div class="col-md-6"><input type="text" name="comment_deliver" class="" value="Delivered" ></div> </div> <div class="delivery box"> <div class="col-md-6"><label>Assign To:</label></div> <div class="col-md-6"><input type="text" name="assign_to" class="" value="<?php echo $emp_namess; ?>" readonly><input type="text" name="assign_to_id" class="" value="<?php echo $emp_idss; ?>" readonly></div> </div> <div class="onhold box"> <div class="col-md-6"><label>Date of On-Hold:</label></div> <div class="col-md-6"><input type="text" name="on_hold" class="date" value="<?php echo $req_date; ?>" ></div> <div class="col-md-6"><label>On Hold Reason:</label></div> <div class="col-md-6"><textarea type="text" name="onhold_reason" id="onhold_reason" cols="25" rows="3" class="materialize-textarea"></textarea></div> </div> <div style="margin-left:30px;margin-top:15px;"> </div> </div> </div> <!--<?php //if($user_type!='7'){?> worked on 05-08-2017 <div class="tableadd col-md-12"> </div> <?php //} ?> <?php //if($user_type=='7'){?> <div class="tableadd col-md-12"> </div> <?php //} ?>--> <div class="tableadd col-md-12"> <input type="hidden" name="usrtyp" id="usrtyp" value="<?php echo $user_type;?>"> <input type="hidden" name="usrlogid" id="usrlogid" value="<?php echo $user_id;?>"> <?php if($user_type=='7') {?> <div class="col-md-3"> <label>Notes:</label> </div> <a id="<?php echo $ReviewDetKey1->req_id; ?>" href="javascript:;">Click here to view history</a> <?php } ?> <div class="col-md-3"> <?php if($user_type=='7') {?> <select name="reporttyt" id="notes_alle" <?php if($key->accepted_engg_id!=$emp_id){?>disabled<?php } ?>> <option value="eng_notess"<?php if(($ReviewDetKey1->eng_notess!='') && ($ReviewDetKey1->cust_solution=='')){?>selected='selected'<?php } ?>> Engineer Notes</option> <option value="cust_solution"<?php if(($ReviewDetKey1->eng_notess=='') && ($ReviewDetKey1->cust_solution!='')){?>selected='selected'<?php } ?>> Engineer Solution</option> </select> <?php } ?> <div class="eng_notess box"> <div class="tableadd col-md-3"><textarea type="text" name="eng_notess" id="eng_notess" cols="25" rows="3" class="materialize-textarea"> <?php if($ReviewDetKey1->eng_notess!=""){echo $ReviewDetKey1->eng_notess;} ?></textarea> </div> </div> <div class="cust_solution box"> <div class="tableadd col-md-3"><textarea type="text" name="cust_solution" id="cust_solution" cols="25" rows="3" class="materialize-textarea"> <?php if($ReviewDetKey1->cust_solution!=""){echo $ReviewDetKey1->cust_solution;} ?></textarea> </div> </div> </div> </div> <?php if($user_type=='1') {?> <div class="col-md-12"> <div class="col-md-3"> <label>Engineer Notes & Solution:</label> </div> <div class="col-md-3"> <a id="<?php echo $ReviewDetKey1->req_id; ?>" href="javascript:;">Click here to view history</a> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Customer Remarks </label> </div> <div class="col-md-3"> <div class="tableadd col-md-3"><textarea type="text" name="cust_remarkk" id="cust_remarkk" cols="25" rows="3" class="materialize-textarea"> <?php if($ReviewDetKey1->cust_remark!=""){echo $ReviewDetKey1->cust_remark;} ?></textarea> </div> </div> </div> <?php } ?> <script> $(document).ready(function() { //alert("nquwe"); $("#<?php echo $ReviewDetKey1->req_id; ?>").click(function() { $.fancybox.open({ href : '<?php echo base_url(); ?>work_inprogress/view_history/<?php echo $ReviewDetKey1->req_id; ?>/<?php echo $user_type;?>/<?php echo $emp_idss;?>', type : 'iframe', padding : 5 }); }); }); </script> <?php } ?> <input type="hidden" name="countid" id="countid" class="" value="<?php echo $count; ?>" > <table class="tableadd" style="margin-top: 25px;"> <tr> <td> <?php if($key->accepted_engg_id==$emp_id){?><button class="btn cyan waves-effect waves-light " type="submit" name="action" id="resgister">Submit <i class="fa fa-arrow-right"></i> </button>&nbsp;<?php } ?><a class="btn cyan waves-effect waves-light " onclick="history.go(-1);">Exit </a> </td> </tr> </table> </div> </form> </div> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }); }); }//]]> </script> <script type="text/javascript"> $(document).ready(function(){ $('.appendtr').hide(); $(".warranty_claim_status").change(function(){ var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert("HII: "+vl); var warran_val = $("#warranty_claim_status-"+vl).val(); //alert("test: "+warran_val); if(warran_val=="to_claim"){ $("#appendtr11-"+vl).show(); $("#appendtr12-"+vl).show(); $("#appendtr13-"+vl).show(); } if(warran_val==""){ $("#appendtr11-"+vl).hide(); $("#appendtr12-"+vl).hide(); $("#appendtr13-"+vl).hide(); } }); }); </script> <script> $('.spare_qty').keyup(function() { //alert($('#tax_type').val()); //alert("fdgvdfgfd"); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); //var qty = $(this).val(); // var actual_qty = $('#spare_qty1'+ctid).val(); if(parseInt($(this).val())!="" && $(this).val()!=""){ if(parseInt($(this).val()) > parseInt($('#spare_qty1'+ctid).val())){ alert("Qty is only: "+ $('#spare_qty1'+ctid).val() + " nos. So please enter below that."); $('#spareqty_0').val(''); }else{ var cal_amt = parseInt($(this).val()) * parseInt($('#amt1'+ctid).val()); if(parseInt(cal_amt)){ $('#amt'+ctid).val(cal_amt); } } }else{ //alert("else"); $('#amt'+ctid).val(''); } var vals = 0; $('input[name="amt[]"]').each(function() { //alert("dsd"); //alert($(this).val()); vals += Number($(this).val()); //alert(val); $('#spare_tot').val(vals); }); var tax_amt = (vals * $('#tax_type').val()) / 100; if(warran=='Preventive' || warran=='Warranty' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); $('#total_amt1').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); //alert(Total_amount); $('#total_amt').val(Total_amount); } //$('input[name="res"]').val(val); }); </script> <script> $('#cmr_paid').keyup(function() { var pending_amt_val = $('#pending_amt1').val(); //alert(pending_amt_val); var cmr_paid = $( this ).val(); var pending_amt = parseInt(pending_amt_val) - parseInt(cmr_paid); $('#pending_amt').val(pending_amt); }); $('#service_cmr_paid').keyup(function() { var service_pending_amt_val = $('#service_pending_amt1').val(); //alert(pending_amt_val); var service_cmr_paid = $( this ).val(); if(service_cmr_paid){ var service_pending_amt = parseInt(service_pending_amt_val) - parseInt(service_cmr_paid); $('#service_pending_amt').val(service_pending_amt); }else{ $('#service_pending_amt').val(service_pending_amt_val); } }); $('#disc_amt').keyup(function() { var disc_amt = $( this ).val(); if(disc_amt){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) - parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); }else{ var total_amt = $('#total_amt1').val(); $('#total_amt').val(total_amt); $('#service_pending_amt').val(total_amt); $('#service_pending_amt1').val(total_amt); } }); </script> <script> $(document).ready(function(){ $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999-19-39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('#datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#delivery_date1').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#on_hold1').datetimepicker({ onChangeDateTime:logic, onShow:logic }); }); </script> <script> $(document).ready(function(){ $('.addresslabel').click(function() { $('.toggleaddress').toggle(); }); $("#resgister").click(function(event){ //alert("test"); if($("#sparename_<?php echo $count; ?>").find("option:selected").attr("value")==0){ alert("inside if"); $(".spare-error<?php echo $count; ?>").text("Please choose any one spare").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } }); }); </script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> </body> </html><file_sep>/application/models/Order_model.php <?php class Order_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_orders($data){ $this->db->insert('orders',$data); return $this->db->insert_id(); } public function add_order_details($data1){ $this->db->insert('order_details',$data1); } public function order_list(){ $query = $this->db->query('SELECT orders.id, orders.order_id, orders.grand_total, orders.amt_paid, orders.amt_pending, orders.purchase_date, customers.customer_name FROM orders as orders INNER JOIN customers as customers ON customers.id = orders.customer_id'); return $query->result(); } public function getorderbyid($id){ $query = $this->db->query("SELECT * FROM orders WHERE id=$id"); return $query->result(); } public function getCustDetails($id){ $query = $this->db->query("SELECT customer_name FROM customers WHERE id=$id"); return $query->row(); } public function getorderDetailsbyid($id){ $query = $this->db->query("SELECT * FROM order_details WHERE order_id=$id"); return $query->result(); } public function get_customerById($id){ $query = $this->db->query("SELECT customers.*, state.state as st_name FROM customers as customers INNER JOIN state as state ON state.id = customers.state WHERE customers.id=$id"); return $query->result(); } public function update_orders($data,$id){ $this->db->where('id',$id); $this->db->update('orders',$data); return true; } public function update_order_details($data,$id){ $this->db->where('id',$id); $this->db->update('order_details',$data); return true; } public function bill_cnt(){ $this->db->select("order_id",FALSE); $this->db->from('orders'); $this->db->order_by('order_id', 'desc'); $this->db->limit(1); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function state_list(){ $query = $this->db->query('SELECT * FROM state'); return $query->result(); } public function update_stock_in_hand($qty,$pid){ $this->db->query("UPDATE products SET stock_qty = stock_qty - $qty WHERE id = $pid", FALSE); //echo $this->db->last_query(); } public function update_used_qty($qty,$pid){ $this->db->query("UPDATE products SET used_qty = used_qty + $qty WHERE id = $pid", FALSE); // echo $this->db->last_query(); } }<file_sep>/application/views/check_invoice_type.php <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> #errorBox{ color:#F00; text-align: center; } .fancybox-inner{ height:100px !important; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; border: 1px solid gray; height: 27px; } .dropdown-content { display:none; } #table1 { margin-top:10px; width:100%; border-collapse: collapse; } #table1 tr { height:40px; } #table1 tr td { border:1px solid gray; text-align:center; } span { margin-right: 25px; } #table1 tr td input { width:120px; border: 1px solid gray; height: 27px; } #table1 tr td select { width:120px; border: 1px solid gray; height: 27px; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 114px; margin: auto auto 35px; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; position: relative; top: 10px; } .color { background: rgb(5, 94, 135) none repeat scroll 0% 0%; color: white; height: 30px !important; } .rowadd{ cursor:pointer; } </style> <script> function frmValidate(){ if((document.getElementById("print_invoice").checked == false) && (document.getElementById("print_invoice1").checked == false)) { document.getElementById("print_invoice").focus(); document.getElementById("errorBox").innerHTML = "Check any button to print invoice"; return false; } } </script> <section id="content"> <div class="container"> <div class="section"> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-10"> <form action="<?php echo base_url(); ?>delivery/print_bills" method="post" name="invoice_chk_frm" onsubmit="return frmValidate()"> <?php if($sitename!='Stamping'){?> <table class="spare_table" style="margin-top: 20px;width: 60%;"> <input type="hidden" id="req_id" name="req_id" value="<?php echo $id; ?>"> <tr><td style="padding-bottom: 30px; padding-left: 60px;"><label><input type="radio" id="print_invoice" class="print_invoice" name="print_invoice" value="with_spare"><span class="spare_charge">With Spare charges</span></label> </td><div id="errorBox"></div></tr> <tr> <td style="padding-bottom: 30px; padding-left: 60px;"><label><input type="radio" id="print_invoice1" class="print_invoice" name="print_invoice" value="without_spare"><span class="spare_charge">Without Spare charges</span></label></td> </tr> <tr> <td style="padding-bottom: 30px; padding-left: 60px;"><button class="btn cyan waves-effect waves-light rowadd" type="submit" name="action">Submit<i class="fa fa-arrow-right"></i></button></td> </tr> </table> <?php } ?> </div> </form> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr><td> <select id="spare_name" class="spare_name" name="spare_name[]"><option value="">---Select---</option> </select></td><td><input type="text" name="qty[]"></td><td><input type="text" name="purchase_date[]"></td><td><input type="text" name="purchase_price[]"></td><td><input type="text" name="invoice_no[]"></td><td style="border:none;"><button class="delRowBtn" >Delete</button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js"></script> <script> $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999/19/39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('.datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); </script> </body> </html><file_sep>/application/models/Prodservicestat_model.php <?php class Prodservicestat_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_prod_ser_stat($data){ $this->db->insert('service_status',$data); return true; } public function prod_service_status_list(){ $this->db->select("id,prod_service_status",FALSE); $this->db->from('service_status'); $query = $this->db->get(); return $query->result(); } public function update_prod_ser_stat($data,$id){ $this->db->where('id',$id); echo $this->db->update('service_status',$data);exit; } public function del_prod_ser_stat($id){ $this->db->where('id',$id); $this->db->delete('service_status'); } }<file_sep>/billing.sql -- phpMyAdmin SQL Dump -- version 4.0.4.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Dec 22, 2018 at 07:34 PM -- Server version: 5.5.32 -- PHP Version: 5.4.19 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 */; -- -- Database: `billing` -- CREATE DATABASE IF NOT EXISTS `billing` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `billing`; -- -------------------------------------------------------- -- -- Table structure for table `accessories` -- CREATE TABLE IF NOT EXISTS `accessories` ( `id` int(10) NOT NULL AUTO_INCREMENT, `accessory` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `accessories` -- INSERT INTO `accessories` (`id`, `accessory`) VALUES (1, 'Accessories 1'); -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE IF NOT EXISTS `admin` ( `admin_id` int(10) NOT NULL AUTO_INCREMENT, `user` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`admin_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`admin_id`, `user`, `email`, `password`) VALUES (1, 'admin', '<EMAIL>', 'welcome'); -- -------------------------------------------------------- -- -- Table structure for table `brands` -- CREATE TABLE IF NOT EXISTS `brands` ( `id` int(10) NOT NULL AUTO_INCREMENT, `brand_name` varchar(100) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `brands` -- INSERT INTO `brands` (`id`, `brand_name`, `status`) VALUES (1, 'STAGO', 1), (2, 'test', 0), (3, 'ssss', 0), (4, 'sssssds', 0); -- -------------------------------------------------------- -- -- Table structure for table `city` -- CREATE TABLE IF NOT EXISTS `city` ( `id` int(10) NOT NULL AUTO_INCREMENT, `city` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=246 ; -- -- Dumping data for table `city` -- INSERT INTO `city` (`id`, `city`) VALUES (1, 'MUMBAI'), (2, 'PUNE'), (3, 'KOLHAPUR'), (4, 'AHMEDNAGAR'), (5, 'MUNDRA'), (6, 'SANGLI'), (7, 'SOLAPUR'), (8, 'AURANGABAD'), (9, 'AHMEDNAGAR'), (10, 'BARSHI'), (11, 'NASHIK'), (12, 'AKOLA'), (13, 'Dader(MH)'), (14, 'JABALPUR'), (15, 'BHILAI'), (16, 'DHAMTARI'), (17, 'Satna'), (18, 'GWALIOR'), (19, 'INDORE'), (20, 'BHUBANESWAR'), (21, 'PATNA'), (22, 'UJJAIN'), (23, 'CHITRAKOOT'), (24, 'BHOPAL'), (25, 'AGRA'), (26, 'GORAKHPUR'), (27, 'MEERUT'), (28, 'ALLAHABAD'), (29, 'LUCKNOW'), (30, 'HALDWANI'), (31, 'VARANASI'), (32, 'MIRZAPUR'), (33, 'SAHARANPUR'), (34, 'AZAMGARH'), (35, 'NOIDA'), (36, 'GHAZIABAD'), (37, 'AGRA'), (38, 'MURADABAD'), (39, 'ALIGARH'), (40, 'HALDWANI'), (41, '<NAME>'), (42, 'Chennai'), (43, 'Coimbatore'), (44, 'Trichy'), (45, 'Pondichery'), (46, 'JODHPUR'), (47, 'KARAULI'), (48, 'KEKARI'), (49, 'KISHANGARH'), (50, 'KOTA'), (51, 'KOTPUTLI'), (52, 'NAGAUR'), (53, 'NASIRABAD'), (54, 'NATHDWARA'), (55, 'RAJSAMAND'), (56, 'SIKAR'), (57, 'SIROHI'), (58, 'SUJANGARH'), (59, 'TONK'), (60, 'UDAIPUR'), (61, 'AJMER'), (62, 'ALWAR'), (63, 'BALOTARA'), (64, 'BARAN'), (65, 'BEAWAR'), (66, 'BHARATPUR'), (67, 'BHILWARA'), (68, 'BIKANER'), (69, 'BUNDI'), (70, 'CHURU'), (71, 'DAUSA'), (72, 'DHAULPUR'), (73, 'DIDWANA'), (74, 'DUNGARPUR'), (75, 'GANGAPUR CITY'), (76, 'HANUMANGARH'), (77, 'JAIPUR'), (78, 'JHALAWAR'), (79, 'JHUNJHUNU'), (80, 'Belgaum'), (81, 'Bangalore'), (82, 'HYDERABAD'), (83, 'Secunderabad.'), (84, 'vijaywada'), (85, 'VISAKHAPATTANAM '), (86, 'Motihari'), (87, 'Darbhanga'), (88, 'Raipur'), (89, 'Dehradun'), (90, 'Anuppur'), (91, 'Umariya'), (92, 'Shahdol'), (93, 'Jhanshi'), (94, 'Kanpur'), (95, 'Baswara'), (96, 'Etawa'), (97, 'AZAMGARH'), (98, 'KARIMNAGAR'), (99, 'Chennai'), (100, 'Bangalore'), (101, 'Chennai'), (102, 'Chennai'), (103, 'VARANASI'), (104, 'GORAKHPUR'), (105, 'LUCKNOW'), (106, 'BHILWARA'), (107, 'MUMBAI'), (108, 'MUMBAI'), (109, 'AURANGABAD'), (110, 'PUNE'), (111, 'SAGAR'), (112, 'MEERUT'), (113, 'BHOPAL'), (114, 'Chennai'), (115, 'Lucknow'), (116, ''), (117, 'Chennai'), (118, 'Lucknow'), (119, ''), (120, ''), (121, ''), (122, 'Mumbai'), (123, ''), (124, ''), (125, 'VARANASI'), (126, ''), (127, 'GORAKHPUR'), (128, 'SAHARANPUR'), (129, 'LUCKNOW'), (130, 'BAREILLY'), (131, 'ALLAHABAD'), (132, 'ALLAHABAD'), (133, 'JAUNPUR'), (134, 'ALIGARH'), (135, 'GORAKHPUR'), (136, '<NAME>'), (137, 'GHAZIABAD'), (138, 'HAPUR'), (139, 'Patna'), (140, 'Kanpur'), (141, 'Bhopal'), (142, 'Kanpur'), (143, 'AGRA'), (144, 'Bhopal'), (145, 'bhadohi'), (146, 'MAU'), (147, 'LUCKNOW'), (148, 'GONDA'), (149, 'FIROZABAD'), (150, 'MATHURA'), (151, 'FARRUKHABAD'), (152, 'KAUSHAMBI'), (153, 'FATEHPUR'), (154, 'PRATAPGARH'), (155, 'BANDA'), (156, 'BALLIA'), (157, 'Hyderabad'), (158, 'Hyderabad'), (159, 'Hyderabad'), (160, 'Hyderabad'), (161, 'AZAMGARH'), (162, 'SONBHADRA'), (163, 'VARANASI'), (164, 'DEORIA'), (165, 'MEERUT'), (166, 'Hyderabad'), (167, 'Bangalore'), (168, 'ALIGARH'), (169, 'BULANDSHAHAR'), (170, 'Kanpur'), (171, 'Etawa'), (172, 'BAHRAICH'), (173, 'Etawa'), (174, 'VARANASI'), (175, 'MEERUT'), (176, '<NAME>'), (177, 'AMROHA'), (178, 'RAMPUR'), (179, 'LUCKNOW'), (180, 'Jhanshi'), (181, 'KUSHINAGAR'), (182, 'MUMBAI'), (183, 'LUCKNOW'), (184, 'HAMIRPUR'), (185, 'MORADABAD'), (186, 'RAIBARLI'), (187, 'BIJNOR'), (188, 'LALITPUR'), (189, 'SAMLI'), (190, 'Bangalore'), (191, 'Chennai'), (192, 'BHILWARA'), (193, 'MUMBAI'), (194, 'MUMBAI'), (195, 'LUCKNOW'), (196, 'KOLHAPUR'), (197, 'SANGLI'), (198, 'SANGLI'), (199, 'Bangalore'), (200, 'TIRUPPUR'), (201, 'HYDERABAD'), (202, 'Chennai'), (203, 'KOLHAPUR'), (204, 'MANGALORE'), (205, 'GWALIOR'), (206, 'JAIPUR'), (207, 'LUCKNOW'), (208, 'KOTA'), (209, 'KARAD'), (210, 'Coimbatore'), (211, 'Bangalore'), (212, 'UDAIPUR'), (213, 'KOTA'), (214, 'BELAPUR'), (215, 'Hyderabad'), (216, 'Hyderabad'), (217, 'MUMBAI'), (218, 'MUMBAI'), (219, 'MUMBAI'), (220, 'tambaram'), (221, 'PUNE'), (222, 'CHITRAKOOT'), (223, 'Chennai'), (224, 'Chennai'), (225, 'Patna'), (226, 'CHITRAKOOT'), (227, 'CHITRAKOOT'), (228, 'Chennai'), (229, 'Bhopal'), (230, 'Chennai'), (231, 'Chennai'), (232, 'chennai'), (233, 'Chennai'), (234, 'KOLHAPUR'), (235, 'Chennai'), (236, 'MUMBAI'), (237, ''), (238, ''), (239, 'MUMBAI'), (240, ''), (241, 'Pondichery'), (242, 'CHITRAKOOT'), (243, 'MATHURA'), (244, 'PATNA'), (245, 'Chennai'); -- -------------------------------------------------------- -- -- Table structure for table `company_details` -- CREATE TABLE IF NOT EXISTS `company_details` ( `id` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `mobile` int(20) NOT NULL, `phone` varchar(20) NOT NULL, `comp_email` varchar(100) NOT NULL, `mgr_email` varchar(100) NOT NULL, `addr1` varchar(250) NOT NULL, `addr2` varchar(250) NOT NULL, `city` varchar(100) NOT NULL, `state` varchar(100) NOT NULL, `pincode` int(10) NOT NULL, `service_tax` varchar(100) NOT NULL, `pan` varchar(100) NOT NULL, `vat_no` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `company_details` -- INSERT INTO `company_details` (`id`, `name`, `mobile`, `phone`, `comp_email`, `mgr_email`, `addr1`, `addr2`, `city`, `state`, `pincode`, `service_tax`, `pan`, `vat_no`) VALUES (1, 'Syndicate Diagnostics', 123456790, '', '', '<EMAIL>', 'NO 127B,1ST FLOOR,BR<NAME>,PURASAWALKAM,CHENNAI-07', '', 'Chennai', '31', 600007, '', '1111111111', ''); -- -------------------------------------------------------- -- -- Table structure for table `co_notess` -- CREATE TABLE IF NOT EXISTS `co_notess` ( `id` int(255) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `co_notess` varchar(500) NOT NULL, `usrr_id` int(10) NOT NULL, `created_on` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ; -- -- Dumping data for table `co_notess` -- INSERT INTO `co_notess` (`id`, `req_id`, `co_notess`, `usrr_id`, `created_on`) VALUES (1, 3870, 'new notes', 1, '2017-06-17 16:59:00'), (2, 3870, 'test notes', 1, '2017-06-17 17:10:58'), (3, 3870, 'wwwwwwwwww', 1, '2017-06-17 17:12:45'), (4, 3971, 'testing instructions new', 1, '2017-06-20 13:12:46'), (5, 3978, 'aaaaaaaaaaaaaaa', 1, '2017-06-28 18:30:56'), (6, 3996, 'sads', 1, '2017-06-29 11:10:24'), (7, 3994, 'sdfdsfdsf', 1, '2017-06-29 11:13:57'), (8, 3997, 'asasasa', 1, '2017-06-29 11:19:00'), (9, 3998, 'kkkkkkkkkkkkkkkkkkkkk', 1, '2017-06-29 11:28:48'), (10, 22, 'ggggggggggg', 1, '2017-07-01 15:38:48'), (11, 1, 'PHOTOMETRIC CALIBRATION ISSUE', 1, '2017-07-03 14:23:24'), (12, 30, 'test', 1, '2017-07-12 11:05:35'), (13, 25, 'sssssssssssss', 1, '2017-07-12 11:14:59'), (14, 25, 'sssssssssssss', 1, '2017-07-12 11:24:42'), (15, 25, 'sssssssssssss', 1, '2017-07-12 11:54:20'), (16, 33, 'test notes new', 1, '2017-07-12 12:05:46'), (17, 36, 'first notes', 18, '2017-07-12 16:45:45'), (18, 37, 'eeeeeeeeeeeeeeee', 18, '2017-07-12 16:54:54'), (19, 37, 'eeeeeeeeeeeeeeee', 18, '2017-07-12 17:00:00'), (20, 38, 'wwwwwwwwwwwwww', 18, '2017-07-12 17:04:12'), (21, 39, 'second notes', 18, '2017-07-12 17:22:35'), (22, 39, 'second notes', 18, '2017-07-12 17:23:29'), (23, 40, 'test notess test notessss', 18, '2017-07-12 17:40:13'), (24, 40, 'test notess test notessss', 18, '2017-07-12 17:41:03'), (25, 1, 'PHOTOMETRIC CALIBRATION ISSUE', 9, '2017-07-17 13:40:40'), (26, 48, 'CLEAN PDR HOME SENSOR ', 1, '2017-07-17 14:27:30'), (27, 46, 'LLD cable issue replaced the same', 8, '2017-07-17 14:29:06'), (28, 44, 'Mapping issue ,done mapping ', 5, '2017-07-17 14:32:09'), (29, 51, 'Routine maintenance', 13, '2017-07-20 20:58:39'), (30, 57, 'Routine maintenance', 13, '2017-07-24 14:26:37'), (31, 56, 'Routine Maintenance', 13, '2017-07-24 14:26:54'), (32, 61, 'Routine Maintenance', 13, '2017-07-26 13:04:05'), (33, 33, 'test notes new', 18, '2017-07-26 13:04:28'), (34, 25, 'sssssssssssss', 18, '2017-07-26 13:05:28'), (35, 3, 'Machine sifted to apollo specialty.replaced EPROM latest.Need to get payment', 13, '2017-07-26 13:05:52'), (36, 36, 'first notes', 18, '2017-07-29 15:46:31'), (37, 62, 'Problem with FVIII calibration they found error in 3rd and 4th dilution', 5, '2017-07-31 13:41:32'), (38, 69, 'sdfsdfds', 18, '2017-08-03 10:24:19'), (39, 76, 'routine maintenance', 13, '2017-08-03 14:26:53'), (40, 75, 'Routine Maintenance', 13, '2017-08-03 14:27:08'), (41, 67, 'System stuck', 14, '2017-08-04 12:33:13'), (42, 86, 'Routine maintenance', 13, '2017-08-08 12:47:44'), (43, 2, 'BUBBLE FORMS IN NEEDLE NO. 1 TUBING', 7, '2017-08-10 16:36:36'), (44, 95, 'test notes entry', 18, '2017-08-10 17:47:07'), (45, 95, 'test notes entry', 18, '2017-08-10 17:47:16'), (46, 106, 'PM&CAL', 10, '2017-08-24 15:38:16'), (47, 135, 'maintenance', 13, '2017-09-19 14:31:22'), (48, 134, 'maintenance routine', 13, '2017-09-19 14:31:45'), (49, 146, 'PM&CAL', 9, '2017-09-21 13:11:47'), (50, 289, 'this is test data. please ignore it', 18, '2017-12-30 12:18:55'), (51, 290, 'asfasdfasfasf', 26, '2018-02-08 13:32:22'), (52, 291, 'asfasfdsafasfasfasfasfsafsafsafasfsafsa', 26, '2018-02-08 17:14:29'), (53, 292, 'ssssssssssssss', 26, '2018-02-13 16:41:33'), (54, 296, 'sasdssdadsssas', 26, '2018-02-14 14:13:05'); -- -------------------------------------------------------- -- -- Table structure for table `customers` -- CREATE TABLE IF NOT EXISTS `customers` ( `id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT, `customer_name` varchar(100) NOT NULL, `mobile` varchar(50) NOT NULL, `email_id` varchar(50) NOT NULL, `address` varchar(250) NOT NULL, `city` varchar(100) NOT NULL, `state` varchar(100) NOT NULL, `pincode` int(20) NOT NULL, `created_on` varchar(100) NOT NULL, `updated_on` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `customers` -- INSERT INTO `customers` (`id`, `customer_name`, `mobile`, `email_id`, `address`, `city`, `state`, `pincode`, `created_on`, `updated_on`) VALUES (00001, 'Vijayakumar', '999899899', '', 'No.22, Gangai Nagar', 'Patna', '5', 800021, '2018-10-10 19:33:46', '2018-10-11 12:51:45'), (00002, 'Ramesh', '9840289188', '', 'No.21 Palavanthangal', 'Coimbatore', '31', 600054, '2018-10-11 12:52:26', '2018-10-11 12:52:44'), (00003, 'Rakesh', '4569874125', '', 'fdafdasdf24234', 'Chennai', '31', 600021, '2018-10-12 18:32:30', '2018-10-12 18:32:30'), (00004, 'Arjun', '2323232323', '', '12, Nowroji Road, Kilpauk, Chennai', 'Chennai', '31', 232323, '2018-10-12 18:36:15', '2018-10-16 11:22:33'), (00005, 'Karthick', '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', '31', 500012, '2018-10-17 15:24:38', '2018-10-22 15:42:03'); -- -------------------------------------------------------- -- -- Table structure for table `customer_labtech` -- CREATE TABLE IF NOT EXISTS `customer_labtech` ( `id` int(10) NOT NULL AUTO_INCREMENT, `customer_id` varchar(255) NOT NULL, `lab_name` varchar(255) NOT NULL, `lab_value` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=118 ; -- -- Dumping data for table `customer_labtech` -- INSERT INTO `customer_labtech` (`id`, `customer_id`, `lab_name`, `lab_value`) VALUES (1, '325', '', ''), (2, '327', '', ''), (3, '329', '', ''), (4, '331', '', ''), (5, '332', '', ''), (6, '333', '', ''), (7, '334', '', ''), (8, '335', '', ''), (9, '336', '', ''), (10, '337', '', ''), (11, '338', '', ''), (12, '340', '', ''), (13, '342', '', ''), (14, '343', '', ''), (15, '344', '', ''), (16, '345', '', ''), (17, '346', '', ''), (18, '347', '', ''), (19, '348', '', ''), (20, '349', '', ''), (21, '350', '', ''), (22, '351', '', ''), (23, '352', '', ''), (24, '353', '', ''), (25, '354', '', ''), (26, '355', '', ''), (27, '356', '', ''), (28, '357', '', ''), (29, '358', '', ''), (30, '359', '', ''), (31, '360', '', ''), (32, '361', '', ''), (33, '362', '', ''), (34, '363', '', ''), (35, '364', '', ''), (36, '365', '', ''), (37, '366', '', ''), (38, '367', '', ''), (39, '368', '', ''), (40, '369', '', ''), (41, '370', '', ''), (42, '371', '', ''), (43, '372', '', ''), (44, '373', '', ''), (45, '374', '', ''), (46, '375', '', ''), (47, '376', '', ''), (48, '377', '', ''), (49, '378', '', ''), (50, '379', '', ''), (51, '380', '', ''), (52, '381', '', ''), (53, '382', '', ''), (54, '383', '', ''), (55, '384', '', ''), (56, '385', '', ''), (57, '386', '', ''), (58, '387', '', ''), (59, '388', '', ''), (60, '389', '', ''), (61, '390', '', ''), (62, '391', '', ''), (63, '392', '', ''), (64, '00071', '', ''), (65, '393', '', ''), (66, '394', '', ''), (67, '395', '', ''), (68, '396', '', ''), (69, '397', '', ''), (70, '398', '', ''), (71, '399', '', ''), (72, '400', '', ''), (73, '401', '', ''), (74, '402', '', ''), (75, '403', '', ''), (76, '404', '', ''), (77, '405', '', ''), (78, '406', '', ''), (79, '407', '', ''), (80, '00407', '', ''), (81, '408', '', ''), (82, '00020', '', ''), (83, '00021', '', ''), (84, '00021', '', ''), (85, '409', '', ''), (86, '410', '', ''), (87, '411', '', ''), (88, '412', '', ''), (89, '413', '', ''), (90, '414', '', ''), (91, '00017', '', ''), (92, '00034', '', ''), (93, '00017', '', ''), (94, '00017', '', ''), (95, '415', '', ''), (96, '416', '', ''), (97, '417', '', ''), (98, '00417', '', ''), (99, '418', '', ''), (100, '419', '', ''), (101, '00415', '', ''), (102, '00415', '', ''), (103, '420', '', ''), (104, '00420', '', ''), (105, '00419', '', ''), (106, '421', '', ''), (107, '422', '', ''), (108, '423', '', ''), (109, '424', '', ''), (110, '427', '', ''), (111, '00427', '', ''), (112, '428', '', ''), (113, '429', '', ''), (114, '00429', '', ''), (115, '00420', '', ''), (116, '00419', '', ''), (117, '00423', '', ''); -- -------------------------------------------------------- -- -- Table structure for table `customer_noperday_history` -- CREATE TABLE IF NOT EXISTS `customer_noperday_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cust_id` int(11) NOT NULL, `no_perday` int(11) NOT NULL, `user_id` int(11) NOT NULL, `create_on` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `customer_noperday_history` -- INSERT INTO `customer_noperday_history` (`id`, `cust_id`, `no_perday`, `user_id`, `create_on`) VALUES (1, 429, 8, 1, '2018-02-20'), (2, 429, 3, 1, '2018-02-20'), (3, 420, 0, 1, '2018-06-29'), (4, 419, 0, 1, '2018-06-29'), (5, 423, 0, 1, '2018-06-29'); -- -------------------------------------------------------- -- -- Table structure for table `customer_service_location` -- CREATE TABLE IF NOT EXISTS `customer_service_location` ( `id` int(10) NOT NULL AUTO_INCREMENT, `customer_id` int(10) NOT NULL, `branch_name` varchar(100) NOT NULL, `landline` varchar(100) NOT NULL, `address` varchar(250) NOT NULL, `address1` varchar(250) NOT NULL, `city` varchar(100) NOT NULL, `state` varchar(100) NOT NULL, `pincode` int(20) NOT NULL, `area` int(255) NOT NULL, `service_zone_loc` int(10) NOT NULL, `zone_coverage` varchar(100) NOT NULL, `contact_name` varchar(100) NOT NULL, `designation` varchar(100) NOT NULL, `mobile` varchar(50) NOT NULL, `email_id` varchar(100) NOT NULL, `created_on` varchar(100) NOT NULL, `updated_on` varchar(100) NOT NULL, `user_id` int(10) NOT NULL, `flag` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=465 ; -- -- Dumping data for table `customer_service_location` -- INSERT INTO `customer_service_location` (`id`, `customer_id`, `branch_name`, `landline`, `address`, `address1`, `city`, `state`, `pincode`, `area`, `service_zone_loc`, `zone_coverage`, `contact_name`, `designation`, `mobile`, `email_id`, `created_on`, `updated_on`, `user_id`, `flag`) VALUES (1, 1, 'Apollo Specialty Hospital', '?044 2433 4455', 'Cenatoph Road,Teyanampet,Chennai', '', 'Chennai', 'Tamil Nadu', 600035, 1, 8, '', 'Mr Deva', 'Senior Technician', '9841313358', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (2, 2, 'Apollo Main Hospital', '91-44-28290200', 'Greams Rd,Chennai', '', 'Chennai', 'Tamil Nadu', 600006, 96, 8, '', 'Mr Madhu', 'Senior Technician', '9884057732', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (3, 3, 'Nungambakam', '4442925553', 'Nungambkkam,Chennai', '', 'Chennai', 'Tamil Nadu', 600034, 97, 8, '', 'Mr.Jeyapalan', 'Senior Technician', '9566275789', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (4, 4, 'Vadapalani', '044 4921 1455', 'vadapalani,Chennai', '', 'Chennai', 'Tamil Nadu', 600026, 98, 8, '', 'Mr Ayal', 'Senior Technician', '9884050521', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (5, 5, 'Chetpet', '044 4227 1001', 'Chetepet,Chennai', '', 'Chennai', 'Tamil Nadu', 600031, 99, 8, '', 'Mrs Shoby', 'Senior Technician', '9840605384', '', '2017-05-31', '2017-05-31', 1, ''), (6, 6, 'Kilpauk Branch', '4426412096', 'PH rd,Chennai', '', 'Chennai', 'Tamil Nadu', 600010, 100, 8, '', 'Ms.Priya', 'Senior Technician', '9962474499', '', '2017-05-31', '2017-05-31', 1, ''), (7, 7, '<NAME>', '', '<NAME>,Chennai', '', 'Chennai', 'Tamil Nadu', 600040, 101, 8, '', 'Dr shiva', 'pathologist', '9841429606', '', '2017-05-31', '2017-05-31', 1, ''), (8, 8, 'CMC V', '', 'Vellore', '', 'Vellore', 'Tamil Nadu', 632009, 108, 9, '', 'Mr singh', 'Senior Technician', '9994780672', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (9, 9, 'Adyar', '', 'adyar,chennai', '', 'Chennai', 'Tamil Nadu', 600020, 102, 8, '', 'Mr Jones', 'Admin', '9941623477', '', '2017-05-31', '2017-05-31', 1, ''), (10, 10, 'Chitoor', '', 'Chitoor', '', 'Chitoor', '<NAME>', 517219, 109, 10, '', '', '', '085732 83221', '', '2017-05-31', '2017-05-31', 1, ''), (11, 11, 'Pallikaranai', '', 'Perumbakkam,Chennai', '', 'Chennai', 'Tamil Nadu', 600100, 103, 8, '', 'Mr Mohan', 'Senior Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (12, 12, 'Nandanam', '', 'Nandanam,Chennai', '', 'Chennai', 'Tamil Nadu', 600035, 95, 8, '', 'Mrs Jesy', 'Senior Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (13, 13, 'Perambur', '', 'Perambur,Chennai', '', 'Chennai', 'Tamil Nadu', 600023, 105, 8, '', 'Mr rajasekar', 'Senior Technician', '9444200883', '', '2017-05-31', '2017-05-31', 1, ''), (14, 14, 'T nagar', '', 'T nagar ,Chennai', '', 'Chennai', 'Tamil Nadu', 600017, 106, 8, '', 'Dr Srinivasan', 'doctor', '', '', '2017-05-31', '2017-05-31', 1, ''), (15, 15, 'West Mambalam', '', 'Chennai', '', 'Chennai', 'Tamil Nadu', 600033, 107, 8, '', 'Dr chitra', 'doctor', '9884270574', '', '2017-05-31', '2017-05-31', 1, ''), (16, 16, 'PANJAGUTTA', '', 'Mumbai Highway, Punjagutta, Hyderabad', '', 'Hyderabad', 'Telangana', 500082, 110, 11, '', 'Dr <NAME>', 'Pathologist', '9866231933', '', '2017-05-31', '2017-05-31', 1, ''), (17, 17, '<NAME>', '040-60601066', ' Road No 72, Opp. Bharatiya Vidya Bhavan School, Film Nagar, Jubilee Hills', '', 'Hyderabad', 'Telangana', 500033, 111, 11, '', 'Dr vanjakshi', 'HOD (Hematology)', '8106298889', '', '2017-05-31', '2017-05-31', 1, ''), (18, 18, '<NAME>', '040-46999999', 'Virinchi Circle,, Hyderabad,', '', 'Hyderabad', 'Telangana', 500034, 112, 11, '', 'Dr <NAME>', 'Lab Director', '1111111111111', '', '2017-05-31', '2017-05-31', 1, ''), (19, 19, '<NAME>', '040-30418888', 'Road No. 1, Banjara Hills, Hyderabad', '', 'Hyderabad', 'Telangana', 500034, 112, 11, '', 'Dr <NAME>', 'Lab Director', '11111114444444', '', '2017-05-31', '2017-05-31', 1, ''), (20, 20, '<NAME>', '040-23420422', '3-6-16 & 17, Street No. 19, Himayatnagar,', '', 'Hyderabad', 'Telangana', 500029, 113, 11, '', 'Dr Neelamani', 'Lab Director', '123334566300', '', '2017-05-31', '2017-05-31', 1, ''), (21, 21, 'MALAKPET', '', 'Old Malakpet, Nalgonda cross road, Hyderabad', '', 'Hyderabad', 'Telangana', 500036, 114, 11, '', 'Dr <NAME>', 'Pathologist', '9849076574', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (22, 21, 'SOMAJIGUDA', '040-67776754', '<NAME>d, <NAME>, Somajiguda, Hyderabad,', '', 'Hyderabad', 'Telangana', 500082, 110, 11, '', 'Dr Bhuralakshmi', 'HOD (Hematology)', '040-67776754111', '', '2017-05-31', '2017-05-31', 1, ''), (23, 21, 'SECUNDERABAD', '', '<NAME>, <NAME>, <NAME>, Secunderabad, Telangana ', '', 'Secundrabad', 'Telangana', 500003, 0, 11, '', 'Dr Sachin', 'Pathologist', '9963465929', '', '2017-05-31', '2017-05-31', 1, ''), (24, 22, '<NAME>', '', 'Road No.12, Banjara Hills, Hyderabad', '', 'Hyderabad', 'Telangana', 500034, 112, 11, '', 'Dr K<NAME>', 'Lab Director', '9391044414', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (25, 23, 'GACHIBOWLI', '', 'Plot No. 3, Road No. 2, IT & Financial District, Nanakramguda, Gachibowli', '', 'Hyderabad', 'Telangana', 500035, 115, 11, '', 'Dr. <NAME>', 'Pathologist', '9951576644', '', '2017-05-31', '2017-05-31', 1, ''), (26, 24, '<NAME>', '', '<NAME>,', '', 'Hyderabad', 'Telangana', 505417, 116, 11, '', '', '', '8782216380', '', '2017-05-31', '2017-05-31', 1, ''), (27, 25, 'NEHRU PHARMA CITY (SEZ)', '', 'Hospira Health Care India Pvt Ltd,Plot No#117,Jawaharlal Nehru Pharma City,, (SEZ) ,Parawada Mandal, Visakhapatnam, Andhra Pradesh?', '', 'Visakhapatnam', 'Andhra Pradesh', 531019, 135, 12, '', 'Mr. Shankar', 'R&D Incharge', '8374444889', '', '2017-05-31', '2017-05-31', 1, ''), (28, 26, 'TURAKAPALLI', '(040) 23480421', '230/235, Gemome Valley Road, Shamirper, ', '', 'Hyderabad', 'Telangana', 500078, 117, 11, '', 'Mr.k<NAME>', 'lab Incharge', '04023480421', '', '2017-05-31', '2017-05-31', 1, ''), (29, 27, 'CHADERGHAT', '', '16-6-104 to 109, Old Kamal Theater Complex, Opp Niagara Hotel', '', 'Hyderabad', 'Telangana', 500024, 118, 11, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (30, 28, 'KARKANA', '040-44114444', 'Plot No. 203, Vasavinagar, Karkhana', '', 'Hyderabad', 'Telangana', 500015, 119, 11, '', 'Dr Smitha', 'Lab Director', '', '', '2017-05-31', '2017-05-31', 1, ''), (31, 29, '<NAME>', '040-66924444', '4-1-1227, Abids Road, King Koti', '', 'Hyderabad', 'Telangana', 500001, 120, 11, '', 'Dr <NAME>', 'Pathologist', '', '', '2017-05-31', '2017-05-31', 1, ''), (32, 30, 'VISAKHAPATNAM', '0891-2584027', 'Naus<NAME>, Visakhapatnam, Andhra Pradesh', '', 'Visakhapatnam', 'Andhra Pradesh', 530005, 121, 11, '', 'Dr seerat pal', 'Pathologist', '', '', '2017-05-31', '2017-05-31', 1, ''), (33, 31, '<NAME>', '', 'Plot No 73/C & 73/D, Survey No # 52, Saraswathi Nagar Colony, Mansoorabad Village,', '', 'Hyderabad', 'Telangana', 500074, 122, 11, '', 'Mr <NAME>', 'lab Manager', '9100974616', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (34, 31, 'HYDERNAGAR', '', 'Plot No. 1, Opposite Chermas, Hydernagar, Kukatpally', '', 'Hyderabad', 'Telangana', 500072, 123, 11, '', 'Mr <NAME>', 'LabManager', '9100974616', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (35, 32, 'KACHIGUDA', '', 'Plot No.27, KPHB Main Road, Jal Vayu Vihar, Opp Arjun Theatre', '', 'Hyderabad', 'Telangana', 500072, 123, 11, '', 'Dr KVVR Lakshmi', 'Lab Director', '9391044414', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (36, 33, 'MALKAJGIRI', '', 'Makajgiri ', '', 'Hyderabad', 'Telangana', 500015, 119, 11, '', '<NAME>', '', '8283060421', '', '2017-05-31', '2017-05-31', 1, ''), (37, 34, 'KANCHANBAGH', '04024342222', 'DMRL X Road, Kanch<NAME>, Santosh Nagar, ', '', 'Hyderabad', 'Telangana', 500258, 125, 11, '', 'Dr <NAME>', 'HOD (Hematology)', '', '', '2017-05-31', '2017-05-31', 1, ''), (38, 35, '<NAME>', '040-60601066', 'Road No 72, Opp. Bharatiya Vidya Bhavan School, Film Nagar, Jubilee Hills', '', 'Hyderabad', 'Telangana', 500033, 111, 12, '', 'Dr <NAME>', 'Pathologist', '', '', '2017-05-31', '2017-05-31', 1, ''), (39, 36, 'TURAKAPALLI', '', 'Genome Valley Rd, Turkapally,', '', 'Hyderabad', 'Telangana', 500078, 117, 11, '', 'Mr Kalayan', 'R&D Incharge', '7032403133', '', '2017-05-31', '2017-05-31', 1, ''), (40, 37, 'NIZAMPET', '', '#1-2-49/13B, Nizampet Road, Hydernagar, Kukatpally,', '', 'Hyderabad', 'Telangana', 500072, 123, 11, '', 'Mr <NAME>', 'lab Incharge', '8897067733', '', '2017-05-31', '2017-05-31', 1, ''), (41, 38, 'SECUNDERABAD', '', 'Secunderabad,telangana', '', 'Hyderabad', 'Telangana', 500015, 119, 11, '', 'Dr <NAME>', 'HOD (Hematology)', '9948042253', '', '2017-05-31', '2017-05-31', 1, ''), (42, 39, 'GUNTUR', '', 'Collector Office Rd, Nagarampalem, Guntur, Andhra Pradesh?', '', 'Guntur', 'Andhra Pradesh', 522004, 137, 12, '', 'Mr <NAME>', 'lab Incharge', '9703222644', '', '2017-05-31', '2017-05-31', 1, ''), (43, 39, 'VIJAYAWADA', '', 'MG Road, Opposite Indira Gandhi Municipal Stadium, Labbipet,', '', 'vijayawada', 'Andhra Pradesh', 520010, 138, 12, '', 'Dr <NAME>', 'Lab Director', '9490353046', '', '2017-05-31', '2017-05-31', 1, ''), (44, 31, 'VIJAYAWADA', '', 'D.No: 48-10-12/2A, Opp. NTR University of Health Sciences, Vijayawada, Andhra Pradesh?', '', 'vijayawada', 'Andhra Pradesh', 520008, 0, 11, '', 'Mr <NAME>', 'lab Manager', '9100974616', '', '2017-05-31', '2017-05-31', 1, ''), (45, 31, 'KONDAPUR', '', 'Plot No # 32&33 Survey No: 12\nOpp CII , Kondapur, Serilingampally Mandal\nRangareddy District - 500081.', '', 'Hyderabad', 'Telangana', 500081, 0, 11, '', 'Mr <NAME>', 'lab Manager', '9100974616', '', '2017-05-31', '2017-05-31', 1, ''), (46, 31, '<NAME>', '', '<NAME>,secunderabad', '', 'Hyderabad', 'Telangana', 500009, 0, 11, '', 'Mr <NAME>', 'lab Manager', '9100974616', '', '2017-05-31', '2017-05-31', 1, ''), (47, 31, '<NAME>', '', '22, Road No. 4, Karvy Lanes, Banjara Hills, Hyderabad', '', 'Hyderabad', 'Telangana', 500034, 112, 11, '', 'Mr <NAME>', 'lab Manager', '9100974616', '', '2017-05-31', '2017-05-31', 1, ''), (48, 41, 'JAGADAMBHA CENTER', '', 'KGH Down Rd, Near Jagdamba, <NAME>, Visakhapatnam, ', '', 'visakhapatnam', 'Andhra Pradesh', 530002, 128, 11, '', 'Dr Rooplata', 'HOD (Hematology)', '9490132498', '', '2017-05-31', '2017-05-31', 1, ''), (49, 42, 'Rockdale Layout', '', 'Waltair Main Road, Rockdale Layout, Visakhapatnam, ', '', 'visakhapatnam', 'Andhra Pradesh', 530002, 128, 11, '', 'Mr Vamsi', 'Biomedical Engineer', '9014410414', '', '2017-05-31', '2017-05-31', 1, ''), (50, 43, 'SARINILGAMPALLY', '', ' Near <NAME>, Nallagandla, Seri-lingampally, Hyderabad', '', 'Hyderabad', 'Telangana', 500019, 130, 11, '', 'Dr <NAME>', 'HOD (Hematology)', '9866969997', '', '2017-05-31', '2017-05-31', 1, ''), (51, 16, 'PANJAGUTTA', '', 'Mumbai Highway, Punjagutta, Hyderabad', '', 'Hyderabad', 'Telangana', 500082, 110, 11, '', 'Dr Sudheer', '', '8142931082', '', '2017-05-31', '2017-05-31', 1, ''), (52, 17, 'SECUNDERABAD', '', 'Pollicetty Towers, St. John''s Road, Bhagyanagar Colony, Beside Keyes High School, Secunderabad', '', 'Hyderabad', 'Telangana', 500003, 0, 11, '', 'Mr <NAME>', 'lab Incharge', '8106298889', '', '2017-05-31', '2017-05-31', 1, ''), (53, 45, '<NAME>', '', 'Road Number 12, AG Heights, Near Amrutha Valley Apartments, Hyderabad,', '', 'Hyderabad', 'Telangana', 500034, 112, 11, '', 'Dr Sheela', 'HOD (Hematology)', '9618240007', '', '2017-05-31', '2017-05-31', 1, ''), (54, 17, 'Hyderguda', '', 'Plot No. 838, 3-5-836-838/1, Near Old MLA Quarters, Hyderguda, Hyderabad,', '', 'Hyderabad', 'Telangana', 500029, 113, 11, '', 'Mrs Sharda', 'lab Incharge', '9866812828', '', '2017-05-31', '2017-05-31', 1, ''), (55, 46, 'Hyderguda', '', '3-6-282, Opp. Old MLA Quarters, Hyderguda, Hyderabad', '', 'Hyderabad', 'Telangana', 500029, 113, 11, '', 'Dr Kalayani', 'HOD (Hematology)', '9573313499', '', '2017-05-31', '2017-05-31', 1, ''), (56, 47, 'VIJAYAWADA', '', 'NH-5, Soumya Nagar, Tadepalli, Vijayawada,', '', 'vijayawada', 'And<NAME>', 522501, 132, 11, '', 'Mr Uday', 'lab Incharge', '9030439460', '', '2017-05-31', '2017-05-31', 1, ''), (57, 48, 'TURAKAPALLI', '', 'turkapally hyderabad', '', 'Hyderabad', 'Telangana', 500078, 117, 11, '', 'Mr Naresh', 'R&D Incharge', '9966244736', '', '2017-05-31', '2017-05-31', 1, ''), (58, 49, 'IDA,Pashamylaram', '', 'IDA Pashamylaram, Hyderabad', '', 'Hyderabad', 'Telangana', 502307, 133, 11, '', 'Mr Purnachander', 'R&D Incharge', '9391386862', '', '2017-05-31', '2017-05-31', 1, ''), (59, 50, 'MIYAPUR', '', '1-121/1, Survey Nos.66 (Part) & 67(Part) Miyapur, Serilingampally', '', 'Hyderabad', 'Telangana', 500049, 134, 11, '', 'Mr <NAME>', 'R&D Incharge', '9642445479', '', '2017-05-31', '2017-05-31', 1, ''), (60, 17, 'Bannerghatta Road', '', '154/11, Bannerghatta Road, Opposite IIM, Bengaluru,?', '', 'Bangalore', 'Telangana', 560076, 80, 5, '', 'Mr Mani', 'Materials Incharge', '9900654134', '', '2017-05-31', '2017-05-31', 1, ''), (61, 51, 'Sampangiram nagar', '', 'HCG Towers No 8, Kalinga Rao Road, HMT Estate, Sampangiram Nagar, Bengaluru,', '', 'Bangalore', 'Karnataka', 560013, 78, 5, '', 'Dr Renu', 'HOD (Hematology)', '9663827717', '', '2017-05-31', '2017-05-31', 1, ''), (62, 52, 'BG rd', '080 2297 7400', 'Bannerghatta Main Road, Jayanagara 9th Block, Bengaluru, Karnataka', '', 'Bangalore', 'Karnataka', 560069, 79, 5, '', 'sunil', 'Lab Incharge', '9900564277', '', '2017-05-31', '2017-05-31', 1, ''), (63, 53, 'BG rd', '', 'No. 9, TKN Towers, Bannerghatta Road, Bengaluru,?', '', 'Bangalore', 'Karnataka', 560076, 80, 5, '', 'Rajarao', 'Incharge lab', '9535633221', '', '2017-05-31', '2017-05-31', 1, ''), (64, 54, 'Thippasandra', '', 'New Thippasandra Main Road, HAL 3rd Stage, New Thippasandra, Beside Thippasandra Post Office,', '', 'Bangalore', 'Karnataka', 560075, 81, 5, '', 'Samrat', 'lab Manager', '9741051170', '', '2017-05-31', '2017-05-31', 1, ''), (65, 55, 'Yelahanka', '080 2217 6767', 'Venkatala, Near Bagalur Cross, Bellary Rd, Yelahanka, Bengaluru,?', '', 'Bangalore', 'Karnataka', 560064, 82, 5, '', 'admin', 'Admin', '?080 2217 6767', '', '2017-05-31', '2017-05-31', 1, ''), (66, 56, 'MSRIT', '080 4052 8400', 'M S Ramaiah Narayana Heart Centre, Basement, M. S. Ramaiah Memorial Hospital, MSR College Road, MSRIT Post,', '', 'Bangalore', 'Karnataka', 560054, 83, 5, '', 'Abdulla', 'Incharge lab', '9972089942', '', '2017-05-31', '2017-05-31', 1, ''), (67, 57, 'Bellary rd', '080 3399 3939', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', 'Bangalore', 'Karnataka', 560092, 84, 5, '', 'Sumitra', 'hod', '7829889829', '', '2017-05-31', '2017-05-31', 1, ''), (68, 58, 'Lakkasandra', '080 2699 5000', 'Hosur Road, Lakkasandra, Wilson Garden', '', 'Bangalore', 'Karnataka', 560029, 85, 5, '', 'mahesh', 'Incharge lab', '9900566592', '', '2017-05-31', '2017-05-31', 1, ''), (69, 59, 'C block Pathology Lab SGPGI', '', '1 st Floor, C block Pathology Lab SGPGI Lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226014, 19, 2, '', 'DR. seema sharma', '', '9918883214', '', '2017-05-31', '2017-05-31', 1, ''), (70, 59, 'C block Hemtology Lab SGPGI ', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226014, 19, 2, '', 'Narendra', '', '9452243957', '', '2017-05-31', '2017-05-31', 1, ''), (71, 59, '24 hr Lab', '', '1 st Floor, 24 hr Lab SGPGI Lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226014, 19, 2, '', 'dr. natu', '', '9335903344', '', '2017-05-31', '2017-05-31', 1, ''), (72, 60, '<NAME>', '', 'nirala nagar lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226016, 20, 2, '', 'dr m kar', '', '7060771155', '', '2017-05-31', '2017-05-31', 1, ''), (73, 61, '<NAME>', '', 'doiawalla jolly grand dehradun', '', 'Dehradun', 'Uttarakhand', 248016, 21, 2, '', 'DR. VIKASH', '', '9412901682', '', '2017-05-31', '2017-05-31', 1, ''), (74, 62, 'Lucknow', '', 'K 994 (Basement) Aashiana', '', 'LUCKNOW', 'Uttar Pradesh', 206012, 22, 2, '', 'Dr, Deewan', '', '9936507369', '', '2017-05-31', '2017-05-31', 1, ''), (75, 63, 'agra', '', '7 manjila bullding pathology lab moti katra agra', '', 'Agra', 'Uttar Pradesh', 282002, 23, 2, '', 'DR. POOJA', '', '8439233948', '', '2017-05-31', '2017-05-31', 1, ''), (76, 64, 'Azamgarh', '', ' chakrapanpur medical college Azamgarh', '', 'AZAMGARH', 'Uttar Pradesh', 276127, 24, 2, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (77, 65, 'Meerut', '', 'jai bhim nagar medical college Meerut', '', 'MEERUT', 'Uttar Pradesh', 250004, 25, 2, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (78, 66, 'Gomti Nagr', '', '7th floor RMLIMS Vibhuti khand Gomti Nagr LUCKNOW', '', 'LUCKNOW', 'Uttar Pradesh', 226010, 26, 2, '', 'DR. NAMRATA', '', '9452177802', '', '2017-05-31', '2017-05-31', 1, ''), (79, 67, 'VARANASI', '', 'BHU BLOOD BANK, LANKA VARANASI', '', 'VARANASI', 'Uttar Pradesh', 221005, 27, 2, '', 'DR. A K GUPTA', '', '9415389013', '', '2017-05-31', '2017-05-31', 1, ''), (80, 68, 'VARANASI', '', 'LANKA VARANASI', '', 'VARANASI', 'Uttar Pradesh', 221005, 27, 2, '', 'DR. S D SINGH', '', '8423740390', '', '2017-05-31', '2017-05-31', 1, ''), (81, 69, 'chowk', '', 'kgmc Trauma center chowk lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 28, 2, '', 'DR WAHID ALI', '', '9208052893', '', '2017-05-31', '2017-05-31', 1, ''), (82, 70, 'chowk', '', 'CVTS LAB KGMC chowk lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 28, 2, '', 'DR <NAME> ', '', '9208052893', '', '2017-05-31', '2017-05-31', 1, ''), (83, 71, 'Rae Bareli Road', '', 'Graund Floor, blood bank SGPGI Lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226014, 19, 2, '', '<NAME>', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (84, 72, '<NAME> ', '', 'nirala nagar lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226020, 29, 2, '', 'Dr. <NAME>', '', '9628695518', '', '2017-05-31', '2017-05-31', 1, ''), (85, 73, 'VARANASI', '', 'L<NAME>', '', 'VARANASI', 'Uttar Pradesh', 221005, 27, 2, '', 'Dr. S p singh', '', '9452569502', '', '2017-05-31', '2017-05-31', 1, ''), (86, 74, 'allhabad', '', 'nawab yusuf rd civil line station allhabad', '', 'ALLAHABAD', 'Uttar Pradesh', 221001, 30, 2, '', 'Dr. <NAME>', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (87, 75, '<NAME>', '', '6th floor RMLIMS Vibhuti khand <NAME> LUCKNOW', '', 'LUCKNOW', 'Uttar Pradesh', 226010, 26, 2, '', 'DR. NAMRATA', '', '9452177802', '', '2017-05-31', '2017-05-31', 1, ''), (88, 76, ' rampur road', '', ' rampur road haldwani', '', 'HALDWANI', 'Uttarakhand', 263129, 31, 2, '', 'MR. PARMOD', '', '7579174424', '', '2017-05-31', '2017-05-31', 1, ''), (89, 77, 'VARANASI', '', ' BHUIMS Lanka varanasi', '', 'VARANASI', 'Uttar Pradesh', 221005, 27, 2, '', 'DR. <NAME>', '', '8004083306', '', '2017-05-31', '2017-05-31', 1, ''), (90, 78, 'gorakhpur', '', ' NH29 Rajendra nagar blood bank gorakhnath hospital gorakhpur', '', 'GORAKHPUR', 'Uttar Pradesh', 233015, 32, 2, '', 'DR. <NAME>', '', '9044336419', '', '2017-05-31', '2017-05-31', 1, ''), (91, 79, 'ALLHABAD', '', 'MLN MEDICAL COLLEGE CENTRAL LAB GEORGE TOWN ALLHABAD', '', 'ALLAHABAD', 'Uttar Pradesh', 211002, 33, 2, '', 'DR. <NAME>', '', '7388700671', '', '2017-05-31', '2017-05-31', 1, ''), (92, 80, '<NAME>CKNOW', '', 'COMMANA HOSPITAL CANT LUCKNOW', '', 'LUCKNOW', 'Uttar Pradesh', 226021, 34, 2, '', '<NAME>', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (93, 81, 'jankipuram extention', '', 'Sector 10 jankipuram extention CDRI lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226031, 35, 2, '', 'DR. <NAME>', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (94, 83, 'allhabad', '', 'Thorn hill road, civil line allhabad', '', 'ALLAHABAD', 'Uttar Pradesh', 211001, 37, 2, '', 'DR. ANUPAMA', '', '9415020350', '', '2017-05-31', '2017-05-31', 1, ''), (95, 84, 'GORAKHPUR', '', '<NAME>', '', 'GORAKHPUR', 'Uttar Pradesh', 273013, 38, 2, '', 'DR. SHILPA', '', '7388700641', '', '2017-05-31', '2017-05-31', 1, ''), (96, 85, 'ALLHABAD', '', '55B LOWTHER ROAD GEORGE TOWN ALLHABAD', '', 'ALLAHABAD', 'Uttar Pradesh', 211002, 33, 2, '', 'DR. PRACHI', '', '9838917698', '', '2017-05-31', '2017-05-31', 1, ''), (97, 86, ' ghaila ', '', 'IIM ROAD ghaila LUCKNOW 226020', '', 'LUCKNOW', 'Uttar Pradesh', 226020, 29, 2, '', 'DR. <NAME>', '', '7275100015', '', '2017-05-31', '2017-05-31', 1, ''), (98, 87, 'BAREILLY', '', 'ROHILKHAND MEDICAL COOLEGE BAREILLY', '', 'BAREILLY', 'Uttar Pradesh', 243006, 40, 2, '', 'DR. <NAME>', '', '9412291009', '', '2017-05-31', '2017-05-31', 1, ''), (99, 88, 'MEERUT', '', 'jai bhim nagar MEDICAL COLLEGE MEERUT', '', 'MEERUT', 'Uttar Pradesh', 250004, 25, 2, '', 'DR. ', '', '9719408040', '', '2017-05-31', '2017-05-31', 1, ''), (100, 89, 'Jankipuram ', '', 'CP 2 Sector F Jankipuram lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226021, 34, 2, '', 'DR. MOHIT ', '', '8601047333', '', '2017-05-31', '2017-05-31', 1, ''), (101, 90, 'gomti nagar', '', 'B1/12 vipul khand gomti nagar lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226010, 26, 2, '', 'DR. <NAME>', '', '9795328522', '', '2017-05-31', '2017-05-31', 1, ''), (102, 91, 'Chowk', '', 'new opd lab kgmc chowk lucknow', '', 'HALDWANI', 'Uttar Pradesh', 226003, 28, 2, '', 'DR. <NAME>', '', '9208052893', '', '2017-05-31', '2017-05-31', 1, ''), (103, 92, '<NAME>', '', 'vrindaban colony lucknow', '', 'ALLAHABAD', 'Uttar Pradesh', 226029, 43, 2, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (104, 93, 'chowk ', '', 'satabdi bulding kgmc chowk lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 28, 2, '', 'DR. A K TRIPATHI', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (105, 94, ' noida ', '', 'Gautam Budh nagar sector 30 noida ', '', 'noida', 'Uttar Pradesh', 201303, 45, 2, '', 'DR. USHA BINDAL', '', '8376061302', '', '2017-05-31', '2017-05-31', 1, ''), (106, 95, 'gomti nagar ', '', 'vijay khand gomti nagar lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226010, 26, 2, '', 'DR. MOHIT', '', '7310100705', '', '2017-05-31', '2017-05-31', 1, ''), (107, 96, 'kanpur', '', '<NAME>', '', 'kanpur', 'Uttar Pradesh', 208002, 47, 2, '', 'MR. MANISH', '', '9794994937', '', '2017-05-31', '2017-05-31', 1, ''), (108, 97, 'jhansi', '', 'kanpur road bundelkhand university jhansi', '', 'Jhanshi', 'Uttar Pradesh', 284001, 48, 2, '', 'MR. <NAME>', '', '7388700670', '', '2017-05-31', '2017-05-31', 1, ''), (109, 98, 'LUCKNOW', '', 'k 994 Aashiyana lucknow ', '', 'LUCKNOW', 'Uttar Pradesh', 226012, 49, 2, '', 'mr. <NAME>', '', '9919660578', '', '2017-05-31', '2017-05-31', 1, ''), (110, 80, 'LUCKNOW', '', 'NIEL LINE CANT LUCKNOW', '', 'LUCKNOW', 'Uttar Pradesh', 226002, 0, 2, '', '<NAME>', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (111, 99, 'LUCKNOW', '', 'Gautam Budh nagar sector 30 noida ', '', 'noida', 'Uttar Pradesh', 201303, 45, 2, '', 'Mr. Rajeev', '', '8376061302', '', '2017-05-31', '2017-05-31', 1, ''), (112, 100, 'Kanpur', '', '7/199 Swwaroop nagar kanur', '', 'kanpur', 'Uttar Pradesh', 208002, 47, 2, '', 'mr. <NAME>', '', '9935053720', '', '2017-05-31', '2017-05-31', 1, ''), (113, 101, 'LUCKNOW', '', 'trauma center kamc chowk lucknow', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 28, 2, '', 'Dr. <NAME>', '', '9198518227', '', '2017-05-31', '2017-05-31', 1, ''), (114, 102, 'Dehradun', '', '7b astely hall dehradun', '', 'dehradun', 'Uttar Pradesh', 248001, 52, 2, '', 'dr. alok ahuja', '', '9627370258', '', '2017-05-31', '2017-05-31', 1, ''), (115, 103, 'Etawa', '', 'State Highway saifai ', '', 'etawa', 'Uttar Pradesh', 206130, 53, 2, '', 'Dr. prachi', '', '9410058658', '', '2017-05-31', '2017-05-31', 1, ''), (116, 104, 'BHOPAL', '0755 667 9101', 'Bhainsakhedi, Near Bairagarh, Bhopal-Indore Highway, Bhopal, Madhya Pradesh 462030', '', 'BHOPAL', 'Madhya Pradesh', 462030, 54, 3, '', 'DEEPAK SHRIVASTAVA', 'Quality manager', '9926369364', '', '2017-05-31', '2017-05-31', 1, ''), (117, 105, 'BHOPAL', '', 'S 204 GM TOWERS 10 NO MARKET, Arera Colony, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462016, 55, 3, '', 'Dr. <NAME>', 'Director', '9425006315', '', '2017-05-31', '2017-05-31', 1, ''), (118, 106, 'BHOPAL', '', 'Kasturba Market, BHEL, Opposite Habibganj Station, Habib Ganj, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462024, 56, 3, '', 'Mrs. Sushma', 'Head Technician', '9165799791', '', '2017-05-31', '2017-05-31', 1, ''), (119, 107, 'BHOPAL', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462003, 57, 3, '', 'Dr. <NAME>', '', '9826089221', '', '2017-05-31', '2017-05-31', 1, ''), (120, 108, 'RAIPUR', '0731 400 4368', ' New Bust Stand, Pandri, Raipur, Chhattisgarh ', '', 'RAIPUR', 'Madhya Pradesh', 492001, 58, 3, '', 'Mr. Pushpraj', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (121, 109, 'RAIPUR', '0731 249 3911', 'Gudhiyari Road, Behind Hotel Piccadily,Raipur (Chhattisgarh)', '', 'RAIPUR', 'Madhya Pradesh', 492001, 58, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (122, 110, 'BHILAI', '0788 285 5011', 'Jawaharlal Nehru Hospital & Research Centre sector 9 Bhilai CG ', '', 'BHILAI', 'Madhya Pradesh', 490001, 59, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (123, 111, 'JABALPUR', '076126 00568', '<NAME>, Pachpedi, Jabalpur, Madhya Pradesh', '', 'JABALPUR', 'Madhya Pradesh', 482001, 60, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (124, 142, 'INDORE', '(073) 16622222', 'A.B. Road, Near L.I.G Square, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452008, 70, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (125, 112, 'UJJAIN', ' 0734 253 4000', 'Hari Phatak Bye-Pass Road, Nana Kheda, Ujjain, Madhya Pradesh', '', 'UJJAIN', 'Madhya Pradesh', 456010, 61, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (126, 113, 'INDORE', ' 0731 236 2491', '14, Manik Bagh Road, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452014, 62, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (127, 114, 'INDORE', '0731 252 7383', 'A.B.Road, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452001, 63, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (128, 115, 'INDORE', '0731 663 3333', '11/2, Old Palasia, Near Palasia Thana, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452018, 64, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (129, 116, 'INDORE', '0731 423 1000', 'Ujjain State Highway, Near MR 10 Crossing, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 453555, 65, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (130, 117, 'INDORE', '0731 4412121', '34/2, Near Om Shanti Bhavan Circle, New Palasia, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452001, 63, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (131, 118, 'INDORE', '0731 455 0400', 'Vijay Nagar, Scheme No 74, Indore, Madhya Pradesh ', '', 'INDORE', 'Madhya Pradesh', 452010, 66, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (132, 119, 'INDORE', '0731 6633111', '22, 23 24 First floor Yashwant Plaza, Opposite Indore Railway Station ( Pf 1 side), Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452001, 63, 3, '', '', '', '7869999937', '', '2017-05-31', '2017-05-31', 1, ''), (133, 120, 'CHITRAKOOT', '076702 65320', 'Sadguru Eye Hospital, District Satna, Chitrakoot, Madhya Pradesh', '', 'CHITRAKOOT', 'Madhya Pradesh', 210204, 67, 3, '', 'Mr. Kamal', 'Head Technician', '8349235204', '', '2017-05-31', '2017-05-31', 1, ''), (134, 121, 'BHOPAL', '0755-4086000', 'Near Shahpura Lake, Shahpura, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462016, 55, 3, '', 'Mr. Vijay', '', '7987053765', '', '2017-05-31', '2017-05-31', 1, ''), (135, 122, 'INDORE', '0731 402 9133', 'Morya Centre, 16/1 Race Course Rd, Opp. Basket Ball Complex, Palasia, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452001, 63, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (136, 123, 'BHOPAL', '0755-2737405', '6, Malipura, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462001, 68, 3, '', 'Mr. Anil ', '', '9893264320', '', '2017-05-31', '2017-05-31', 1, ''), (137, 124, 'BHOPAL', '0755-2556707', 'MP State Branch Red Cross Bhawan Shivaji Nagar,, Bhopal, Madhya Pradesh ', '', 'BHOPAL', 'Madhya Pradesh', 462016, 55, 3, '', 'Mr. Irshad', '', '8871979174', '', '2017-05-31', '2017-05-31', 1, ''), (138, 109, 'INDORE', '0731 249 3911', '5/1, A B Road, Opposite MGM Medical College, Indore, Madhya Pradesh ', '', 'INDORE', 'Madhya Pradesh', 452001, 63, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (139, 126, 'JABALPUR', '8720847047', 'Russel Crossing, Napier Town, Jabalpur, Madhya Pradesh', '', 'JABALPUR', 'Madhya Pradesh', 482002, 69, 3, '', 'Dr. Lokwani', '', '9425939131', '', '2017-05-31', '2017-05-31', 1, ''), (140, 127, 'JABALPUR', '', 'Plot B, Scheme No 5, Ahinsa Chowk, Kanchnar City Road, Vijay Nagar Colony, Jabalpur, Madhya Pradesh', '', 'JABALPUR', 'Madhya Pradesh', 482002, 69, 3, '', 'Dr. <NAME>', '', '9575801110', '', '2017-05-31', '2017-05-31', 1, ''), (141, 128, 'INDORE', '0731 679 9999', '5/1, Bhawarkuan Main Road, Transport Nagar, Indore, Madhya Pradesh ', '', 'INDORE', 'Madhya Pradesh', 452008, 70, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (142, 127, 'INDORE', '0731 667 7777', 'Part 5 & 6, Race Course Road, R S bhandari Marg, Janjeerwala Square, Indore, Madhya Pradesh ', '', 'INDORE', 'Madhya Pradesh', 452003, 71, 3, '', 'Mr. Ashu', '', '7049918754', '', '2017-05-31', '2017-05-31', 1, ''), (143, 130, 'INDORE', '0731 427 1600', ' Old Palasia, Ravindra Nagar, Manorama Ganj, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452018, 64, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (144, 131, 'SATNA', '076722 57412', ' J.R. Birla Road, Birla Vikas, Satna, Madhya Pradesh', '', 'SATNA', 'Madhya Pradesh', 485005, 72, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (145, 132, 'GWALIOR', '', 'S K V Rd, Basant Vihar Colony, Lashkar, Gwalior, Madhya Pradesh', '', 'GWALIOR', 'Madhya Pradesh', 474002, 73, 3, '', '', '', '9554587808', '', '2017-05-31', '2017-05-31', 1, ''), (146, 133, 'RAIPUR', '', ' Krishna Complex, Opposite Civil Court, Raipur', '', 'RAIPUR', 'Madhya Pradesh', 492001, 58, 3, '', 'Mr. Tilak', '', '9302321425', '', '2017-05-31', '2017-05-31', 1, ''), (147, 134, 'INDORE', '', '14 Manik Bagh Road, Indore, Madhya Pradesh', '', 'INDORE', 'Madhya Pradesh', 452014, 62, 3, '', 'Mr.Sheel', '', '7314206705', '', '2017-05-31', '2017-05-31', 1, ''), (148, 135, 'JABALPUR', '', ',Tilwara Road, Jabalpur, Madhya Pradesh ', '', 'JABALPUR', 'Madhya Pradesh', 482003, 74, 3, '', 'Mr. <NAME>', '', '9826132618', '', '2017-05-31', '2017-05-31', 1, ''), (149, 136, 'BHOPAL', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', 'BHOPAL', 'Madhya Pradesh', 462016, 55, 3, '', 'Dr. <NAME>', '', '9425302826', '', '2017-05-31', '2017-05-31', 1, ''), (150, 137, 'UMARIYA', '', 'Dist. Hospital Umariya', '', 'UMARIYA', 'Madhya Pradesh', 484661, 75, 3, '', 'Mr. Virendra ', '', '7987068397', '', '2017-05-31', '2017-05-31', 1, ''), (151, 138, 'SHAHDOL', '', '<NAME>, Shahdol, Madhya Pradesh', '', 'SHAHDOL', 'Madhya Pradesh', 484001, 76, 3, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (152, 139, 'ANUPPUR', '', ',<NAME>, Anuppur, Madhya Pradesh', '', 'ANUPPUR', 'Madhya Pradesh', 484224, 77, 3, '', 'Mr. Narendra', '', '7879301484', '', '2017-05-31', '2017-05-31', 1, ''), (153, 140, 'BHOPAL', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', 'BHOPAL', 'Madhya Pradesh', 462003, 57, 3, '', 'Dr. <NAME>', '', '9826089221', '', '2017-05-31', '2017-05-31', 1, ''), (154, 141, 'BHOPAL', '', 'Sultania Rd, Royal Market, Near Hamidia Hospital, Bhopal, Madhya Pradesh ', '', 'BHOPAL', 'Madhya Pradesh', 462001, 68, 3, '', 'Mr. Verma', '', '7898003228', '', '2017-05-31', '2017-05-31', 1, ''), (155, 143, 'Goregaon', '', 'Plot No 1, Prime Square building,Next to Patel Petrol Pump,S.V. Road,Goregaon West', '', 'Mumbai', 'Maharashtra', 400062, 1, 1, '', 'Mrs. Manisha ', 'Section Head', '9833031032', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (156, 144, 'Vidyavihar', '022-30840771', '4rth floor, kohinoor commercial building', '', 'Mumbai', 'Maharashtra', 400070, 2, 1, '', 'Ms.Jinal', 'Senior Technician', '9869314808', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (157, 145, 'Parel', '', '6th floor,Global Hospital', '', 'Mumbai', 'Maharashtra', 400012, 3, 1, '', 'Mr. <NAME>', 'Lab Manager', '9892982681', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (158, 146, '<NAME>', '022 23533333', 'Dr. deshmukh road', '', 'Mumbai', 'Maharashtra', 400026, 4, 1, '', 'Mr. <NAME>', 'Senior Technician', '9765268965', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (159, 147, 'Charni road', '022 67570111', 'Charni road ', '', 'Mumbai', 'Maharashtra', 400004, 5, 1, '', 'Mr. <NAME>', 'Senior Technician', '8691077402', '', '2017-05-31', '2017-05-31', 1, ''), (160, 148, 'Andheri East', '022-30999999', 'Varsova', '', 'Mumbai', 'Maharashtra', 400053, 6, 1, '', 'Mrs. Bhavini', 'Senior Technician', '9820468893', '', '2017-05-31', '2017-05-31', 1, ''), (161, 17, 'Belapur', '022-33503350', 'Belapur CBD', '', 'Mumbai', 'Telangana', 400614, 0, 13, '', 'Dr. Vishal', 'Doctor', '7738058952', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (162, 149, 'Chembur', '022-25598253', '<NAME>', '', 'Mumbai', 'Maharashtra', 400094, 7, 1, '', 'Dr. Jamuna', 'Doctor', '9833645854', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (163, 150, 'Thane', '', 'Wagle Industrial Estate, Ambika Nagar No 3', '', 'Mumbai', 'Maharashtra', 400604, 8, 1, '', 'Mrs. Gargi', 'Senior Technician', '9870889775', '', '2017-05-31', '2017-05-31', 1, ''), (164, 151, 'Bhulabhai nagar', '022-23667788', '60 A, Bhulabhai desai road', '', 'Mumbai', 'Maharashtra', 400026, 4, 1, '', 'Mr. Shankar', 'Biomedical Enginner', '9819750173', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (165, 152, 'Andheri west', '', 'Juhu', '', 'Mumbai', 'Maharashtra', 400049, 10, 1, '', 'Mr. Trunal', 'Senior Technician', '9819281495', '', '2017-05-31', '2017-05-31', 1, ''), (166, 153, 'Dahisar', '', 'near Trimurti film city', '', 'Mumbai', 'Maharashtra', 400068, 11, 1, '', 'Mrs. Parinda', 'Senior Technician', '9892259766', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (167, 154, 'Ghatkopar', '', 'Near Ghatkopar Railway station', '', 'Mumbai', 'Maharashtra', 400086, 12, 1, '', 'Mr. Sarfaraz', 'Senior Technician', '9769909209', '', '2017-05-31', '2017-05-31', 1, ''), (168, 155, 'Parel', '022-24138518', '13 floor,New building, KEM Hospital', '', 'Mumbai', 'Maharashtra', 400012, 3, 1, '', 'Dr.<NAME>', 'Doctor', '', '', '2017-05-31', '2017-05-31', 1, ''), (169, 156, '<NAME>', '022-66173333', '383 Bhaveshwar Vihar, Sardar V P Road', '', 'Mumbai', 'Maharashtra', 400004, 5, 1, '', 'Mrs. <NAME>', 'Lab Manager', '9323483252', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (170, 157, '<NAME>', '022-28262741', '1st floor, A wing, Ambika apmt.', '', 'Mumbai', 'Maharashtra', 400069, 13, 1, '', 'Mr. <NAME>', 'Senior Technician', '8767210472', '', '2017-05-31', '2017-05-31', 1, ''), (171, 158, 'Ghatkopar', '022-25111313', 'Sarvodya Hospital, LBS road', '', 'Mumbai', 'Maharashtra', 400086, 12, 1, '', 'Dr. <NAME>', 'Doctor', '9594032520', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (172, 159, 'Dadar', '', 'Dadar', '', 'Mumbai', 'Maharashtra', 400014, 14, 1, '', 'Dr. Sushant', 'Doctor', '9833454470', '', '2017-05-31', '2017-05-31', 1, ''), (173, 160, 'Kharghar', '', 'Bhumi tawer, Kharghar, sector-4', '', 'Mumbai', 'Maharashtra', 410210, 139, 13, '', 'Dr. <NAME>', 'Doctor', '9004402557', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (174, 161, 'Vashi', '', 'Forites hospital sector 10, Vashi', '', 'Mumbai', 'Maharashtra', 400703, 140, 13, '', 'Mr. Aparna', 'Senior Technician', '9757209333', '', '2017-05-31', '2017-05-31', 1, ''), (175, 162, 'Parel', '022-65231212', 'Opp. KEM Hospital', '', 'Mumbai', 'Maharashtra', 400012, 3, 1, '', 'Mr. Devendra', 'Senior Technician', '9619952626', '', '2017-05-31', '2017-05-31', 1, ''), (176, 163, 'Kalyan', '', 'Fortis Hospital, Bail bazar', '', 'Mumbai', 'Maharashtra', 421301, 15, 1, '', 'Mr. <NAME>', 'Senior Technician', '8108888464', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (177, 164, 'Gamdevi', '', 'Near Gamdevi polis station', '', 'Mumbai', 'Maharashtra', 400007, 16, 1, '', 'Mrs. Ashwini ', 'Senior Technician', '9820444855', '', '2017-05-31', '2017-05-31', 1, ''), (178, 165, 'Bandra', '', 'S-341, Near Collector Office, Gandhi Nagar', '', 'Mumbai', 'Maharashtra', 400, 17, 1, '', 'Mr. Sujan', 'Senior Technician', '9869774812', '', '2017-05-31', '2017-05-31', 1, ''), (179, 166, 'Sanpada', '', 'Sector 24, Sanpada', '', 'Mumbai', 'Maharashtra', 400705, 18, 1, '', 'Mr. Rajan', 'Lab in-charge', '9773315523', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (180, 80, 'Pune', '', 'Command Pathology Lab Camp Pune', '', 'Pune', 'Maharashtra', 411040, 186, 15, '', 'Mr. Navin', 'Technician', '7769800108', '', '2017-05-31', '2017-05-31', 1, ''), (181, 167, 'Pune', '', 'MH, Range Hill, Kirki, Pune', '', 'Pune', 'Maharashtra', 411003, 177, 15, '', '<NAME>', 'Senior Technician', '9657357524', '', '2017-05-31', '2017-05-31', 1, ''), (182, 168, 'Pune', '', 'Gokhale nagar, Pune', '', 'Pune', 'Maharashtra', 411016, 178, 15, '', 'Dr. <NAME>', 'HOD', '8605123100', '', '2017-05-31', '2017-05-31', 1, ''), (183, 169, 'Pune', '', 'Balgandharve Road, Pune', '', 'Pune', 'Maharashtra', 411001, 179, 15, '', 'Mr. Shirish', 'Lab Manager', '9890125380', '', '2017-05-31', '2017-05-31', 1, ''), (184, 170, 'Pune', '', 'Chinchwad, Pune', '', 'Pune', 'Maharashtra', 411019, 180, 15, '', 'Mr.Santosh', 'Biomedical Enginner', '8888804546', '', '2017-05-31', '2017-05-31', 1, ''), (185, 171, 'Pune', '', 'Deccan, Pune', '', 'Pune', 'Maharashtra', 411004, 181, 15, '', 'Mrs. Rupali', 'Biomedical Enginner', '9689911129', '', '2017-05-31', '2017-05-31', 1, ''), (186, 172, 'Pune', '2066548700', '375,Urawade, Tal- Muishi, Pune', '', 'Pune', 'Maharashtra', 412115, 182, 15, '', 'Dr. <NAME>', 'Doctor', '2331122546666', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (187, 180, 'Pune', '2024449527', 'Swargate, Pune', '', 'Pune', 'Maharashtra', 411042, 0, 15, '', 'Mrs. Amruta', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (188, 173, 'Pune', '', 'Kharadi Bypass Road, Hadapsar, Pune', '', 'Pune', 'Maharashtra', 411014, 183, 15, '', 'Mr. Paskal', 'Senior Technician', '8411000515', '', '2017-05-31', '2017-05-31', 1, ''), (189, 174, 'Pune', '2066749457', '46/47A Nannde Mulshi, Pune', '', 'Pune', 'Maharashtra', 412108, 184, 15, '', 'Ms. <NAME>', 'Senior Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (190, 175, 'Pune', '', 'Pawana Nagar Housing CHS chinchwad, Pune', '', 'Pune', 'Maharashtra', 411033, 185, 15, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (191, 176, 'Pune', '2026022599', 'MH ctc, Golibar Maidan Pune', '', 'Pune', 'Maharashtra', 411040, 186, 15, '', '', 'Senior Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (192, 177, 'Barshi', '2172726858', 'barshi', '', 'Barshi', 'Maharashtra', 413001, 187, 15, '', 'Mr. Patil', 'Purchase Manager', '', '', '2017-05-31', '2017-05-31', 1, ''), (193, 178, 'Solapur', '', 'Old Employment chowk, Solapur', '', 'Solapur', 'Maharashtra', 413002, 188, 15, '', '', 'Senior Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (194, 179, 'Nashik', '', 'Dr.Athavale chamber, Tilak Rd, Nashik', '', 'Nashik', 'Maharashtra', 422001, 189, 15, '', 'Mr. Sandip', 'Senior Technician', '9881907660', '', '2017-05-31', '2017-05-31', 1, ''), (195, 180, 'Pune', '', 'Gangapur Road, Sh<NAME>ar, Nashik', '', 'Pune', 'Maharashtra', 422013, 190, 15, '', 'Mr. Prasad', 'Senior Technician', '8625996927', '', '2017-05-31', '2017-05-31', 1, ''), (196, 181, 'Nanded', '', 'vazirabad, Nanded', '', 'Nanded', 'Maharashtra', 431601, 191, 15, '', 'Dr. Mrs. Deshpande', 'Doctor', '9421448576', '', '2017-05-31', '2017-05-31', 1, ''), (197, 182, 'Aurangabad', '', '<NAME>, Beed Bypass Rd. Aurangabad', '', 'Aurangabad', 'Maharashtra', 431005, 192, 15, '', 'Dr. Mrs. Ekbote', 'Doctor', '9822329832', '', '2017-05-31', '2017-05-31', 1, ''), (198, 183, 'Pune', '', '<NAME>', '', 'Pune', 'Maharashtra', 413736, 193, 15, '', 'Mr. Bhalerao', 'Biomedical Enginner', '9970532827', '', '2017-05-31', '2017-05-31', 1, ''), (199, 180, 'Pune', '', 'Malegaon Road, Patangan, Ahmednagar', '', 'Pune', 'Maharashtra', 414001, 196, 15, '', '', 'Doctor', '', '', '2017-05-31', '2017-05-31', 1, ''), (200, 184, 'Aurangabad', '', 'D-4, MIDC, Chikalthana Aurangabad', '', 'Aurangabad', 'Maharashtra', 431210, 194, 15, '', 'Mr. <NAME>', 'Technician', '9175470933', '<EMAIL>', '2017-05-31', '2017-05-31', 1, ''), (201, 185, 'Aurangabad', '', '<NAME> mandir rd. garkheda, Aurangabad', '', 'Aurangabad', 'Maharashtra', 431005, 192, 15, '', 'Dr. Patwadkar', 'Doctor', '9822435510', '', '2017-05-31', '2017-05-31', 1, ''), (202, 186, 'Sangali', '2332331354', 'Ashirwad Bldg, Sangli', '', 'Sangali', 'Maharashtra', 416416, 195, 15, '', 'Dr. Gujar', 'Doctor', '', '', '2017-05-31', '2017-05-31', 1, ''), (203, 187, 'Sangali', '', '<NAME>', '', 'Sangali', 'Maharashtra', 416416, 195, 15, '', 'Dr. Mrs. <NAME>', 'Doctor', '9422662066', '', '2017-05-31', '2017-05-31', 1, ''), (204, 188, 'Ahamednagar', '', '<NAME>, AHMADNAGAR', '', 'Ahamednagar', 'Maharashtra', 414001, 196, 15, '', 'Mrs. Ashwini', 'Biomedical Engineer', '9850184250', '', '2017-05-31', '2017-05-31', 1, ''), (205, 189, 'Kolhapur', '', '<NAME>', '', 'Kolhapur', 'Maharashtra', 416001, 197, 15, '', 'Mr. Sagar', 'Senior Technician', '9373827739', '', '2017-05-31', '2017-05-31', 1, ''), (206, 190, 'Kolhapur', '', 'Communit Hall, Karveer, Kolhapur', '', 'Kolhapur', 'Maharashtra', 416003, 198, 15, '', 'Mr. <NAME>', 'Purchase Manager', '9370503021', '', '2017-05-31', '2017-05-31', 1, ''), (207, 191, 'Kolhapur', '', '1719, Panchsheel, rajaram puri, Kolhapur', '', 'Kolhapur', 'Maharashtra', 416008, 199, 15, '', 'Mr. Appa', 'Lab in-charge', '8485058315', '', '2017-05-31', '2017-05-31', 1, ''), (208, 192, 'Latur', '2382245903', 'Vida nagar, Singal camp, Latur', '', 'Latur', 'Maharashtra', 413512, 200, 15, '', '', 'Biomedical Engineer', '', '', '2017-05-31', '2017-05-31', 1, ''), (209, 193, 'Latur', '', 'Gandhi Market, sawewadi, Latur', '', 'Latur', 'Maharashtra', 413531, 201, 15, '', '', '', '9422072610', '', '2017-05-31', '2017-05-31', 1, ''), (210, 194, 'Barshi', '', 'Jawahar Hospital Compound, Somwarpeth, barshi', '', 'Barshi', 'Maharashtra', 413401, 202, 15, '', 'Mr. Buduk', 'Technician', '9011095659', '', '2017-05-31', '2017-05-31', 1, ''), (211, 178, 'Akola', '', '<NAME>, <NAME>, Akola', '', 'Akola', 'Maharashtra', 444010, 0, 15, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (212, 195, 'Goa', '', 'Dr.E Borges Rd. <NAME>', '', 'Goa', 'Maharashtra', 403004, 203, 15, '', 'Mr. <NAME>', 'Senior Technician', '9422639883', '', '2017-05-31', '2017-05-31', 1, ''), (213, 196, 'karad', '', 'Malakapur, karad.', '', 'Karad', 'Maharashtra', 415539, 204, 15, '', 'Mr. Kanase', 'Senior Technician', '8796323157', '', '2017-05-31', '2017-05-31', 1, ''), (214, 197, 'Sangali', '', '<NAME>', '', 'Sangali', 'Maharashtra', 416410, 205, 15, '', 'Dr. Quraishi', 'Doctor', '9604542311', '', '2017-05-31', '2017-05-31', 1, ''), (215, 198, 'Pune', '', 'NCL, Pashan RD. Pune', '', 'Pune', 'Maharashtra', 411008, 206, 15, '', 'Mrs. Manisha', 'Technician', '9420172329', '', '2017-05-31', '2017-05-31', 1, ''), (216, 199, 'Nashik', '', 'United legend building, parijat Nagar , Nashik', '', 'Nashik', 'Maharashtra', 422005, 207, 15, '', 'Mr. <NAME>', 'Purchase Manager', '8237077830', '', '2017-05-31', '2017-05-31', 1, ''), (217, 200, 'Pune', '', 'Dhole Palit Rd. Pune', '', 'Pune', 'Maharashtra', 411001, 179, 15, '', 'Mr. Bhosale', 'Biomedical Engineer', '9890300502', '', '2017-05-31', '2017-05-31', 1, ''), (218, 201, 'Pune', '', 'AFMC Special Lab Camp Pune', '', 'Pune', 'Maharashtra', 411040, 186, 15, '', 'Mr. <NAME>', ' Technician', '8168421620', '', '2017-05-31', '2017-05-31', 1, ''), (219, 202, 'Pune', '', 'Hinjewadi Phase 2', '', 'Pune', 'Maharashtra', 41102, 208, 15, '', 'Mr. mahendra', ' Technician', '9922568759', '', '2017-05-31', '2017-05-31', 1, ''), (220, 203, 'Pune', '', 'Narhe, Pune', '', 'Pune', 'Maharashtra', 411041, 209, 15, '', 'Dr. Mrs. Gogate', 'Doctor', '9822862623', '', '2017-05-31', '2017-05-31', 1, ''), (221, 204, 'Nagpur', '', 'Nagpur', '', 'Nagpur', 'Maharashtra', 440003, 210, 15, '', 'Dr. Poornima', 'Doctor', '8975812067', '', '2017-05-31', '2017-05-31', 1, ''), (222, 205, 'Nanded', '', 'vazirabad, Nanded', '', 'Nanded', 'Maharashtra', 431601, 191, 15, '', ' Dr. Amita', ' Doctor', '7719999118', '', '2017-05-31', '2017-05-31', 1, ''), (223, 206, 'Nashik', '', '<NAME>', '', 'Nashik', 'Maharashtra', 422001, 189, 15, '', 'Dr. Shimpi', 'Doctor', '9890304750', '', '2017-05-31', '2017-05-31', 1, ''), (224, 207, 'Amaravati', '', 'Amrawati', '', 'Amaravati', 'Maharashtra', 444601, 211, 15, '', 'Dr. <NAME>', 'Biomedical Engineer', '9822470078', '', '2017-05-31', '2017-05-31', 1, ''), (225, 208, 'Pune', '', 'Bhandarkar Road, Deccan, Pune', '', 'Pune', 'Maharashtra', 411004, 181, 15, '', 'Mrs. Nupoor', 'Technician', '9657722055', '', '2017-05-31', '2017-05-31', 1, ''), (226, 209, 'head office', '', '<NAME>,patna', '', 'patna', 'Bihar', 801505, 86, 6, '', '<NAME>', 'Head Technician', '9572288749', '', '2017-05-31', '2017-05-31', 1, ''), (227, 210, 'head office', '', 'kamendra market,chhatauni Road,opposite Dr. kamta prasad singh,', '', 'motihari', 'Bihar', 800014, 87, 6, '', 'aurangjeb', 'Head Technician', '9504116518', '', '2017-05-31', '2017-05-31', 1, ''), (228, 211, 'head office', '', 'Allalpatti,near donar chowk', '', 'Darbhanga', 'Bihar', 846003, 88, 6, '', '<NAME>', 'Head Technician', '8271786771', '', '2017-05-31', '2017-05-31', 1, ''), (229, 212, 'head office', '', 'Laheria srai bangali tola', '', 'Darbhanga', 'Bihar', 846003, 88, 6, '', 'Ramkrishna', 'Head Technician', '9608995602', '', '2017-05-31', '2017-05-31', 1, ''), (230, 213, 'head office', '', 'Sachivalya colony,kankarbagh', '', 'patna', 'Bihar', 800020, 89, 6, '', 'Zunaid', 'Head Technician', '7781006893', '', '2017-05-31', '2017-05-31', 1, ''), (231, 214, 'head office', '', 'Heaart Hospital,kankarbagh,', '', 'patna', 'Bihar', 800026, 90, 6, '', '<NAME>', 'Head Technician', '7783856038', '', '2017-05-31', '2017-05-31', 1, ''), (232, 175, 'head office', '', 'C/O MEDICA SUPER SPECIALTY HOSPITAL,', '', 'Ranchi', 'Bihar', 834009, 91, 6, '', '<NAME>', 'Quality manager', '9903778425', '', '2017-05-31', '2017-05-31', 1, ''), (233, 216, 'head office', '', 'Raja bazar,shiekpura', '', 'patna', 'Bihar', 800014, 87, 6, '', 'Dr. bipin', 'HOD Pathology', '8804254155', '', '2017-05-31', '2017-05-31', 1, ''), (234, 217, 'head office', '', 'Line bazar chowk', '', 'purnea', 'Bihar', 854301, 93, 6, '', 'sadique', 'Head Technician', '7480820534', '', '2017-05-31', '2017-05-31', 1, ''), (235, 218, 'head office', '', 'BAILY ROAD , <NAME>', '', 'patna', 'Bihar', 800014, 87, 6, '', '<NAME>', 'Quality manager', '8877887712', '', '2017-05-31', '2017-05-31', 1, ''), (236, 219, 'head office', '', 'vivek nand marg,,booring road', '', 'patna', 'Bihar', 800013, 94, 6, '', 'Dr. <NAME>', 'Director', '9334119090', '', '2017-05-31', '2017-05-31', 1, ''), (237, 220, 'head office', '', 'JAWAHAR LAL NEHRU MEDICAL COLLEGE', '', 'AJMER', 'Rajasthan', 305001, 141, 14, '', 'Rajesh', 'Technician', '094148 34332', '', '2017-05-31', '2017-05-31', 1, ''), (238, 221, 'head office', '', 'CENTRAL LAB JLN HOSPITAL', '', 'AJMER', 'Rajasthan', 305001, 141, 14, '', 'Rajesh', 'Technician', '094148 34333', '', '2017-05-31', '2017-05-31', 1, ''), (239, 222, 'head office', '0144-6450005', 'GOVT. HOSPITAL', '', 'ALWAR', 'Rajasthan', 301001, 142, 14, '', 'Deepak', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (240, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'BALOTARA', 'Rajasthan', 344022, 143, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (241, 222, 'head office', '07453-231435', 'GOVT. HOSPITAL', '', 'BARAN', 'Rajasthan', 325205, 144, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (242, 225, 'head office', '', 'LADDHA HOSPITAL', '', 'BANSWARA', 'Rajasthan', 327001, 145, 14, '', '<NAME>', 'Incharge', '9414725116', '', '2017-05-31', '2017-05-31', 1, ''), (243, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'BEAWAR', 'Rajasthan', 305901, 146, 14, '', 'Dr. Manish', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (244, 222, 'head office', '05644-224555', 'GOVT. HOSPITAL', '', 'BHARATPUR', 'Rajasthan', 321001, 147, 14, '', '', '', '9413787556', '', '2017-05-31', '2017-05-31', 1, ''), (245, 228, 'head office', '1482253101', 'ARIHANT HOSPITAL & RESEARCH CENTER', '', 'BHILWARA', 'Rajasthan', 311001, 148, 14, '', '<NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (246, 222, 'head office', '01482-239643', 'GOVT. HOSPITAL', '', 'BHILWARA', 'Rajasthan', 311001, 148, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''); INSERT INTO `customer_service_location` (`id`, `customer_id`, `branch_name`, `landline`, `address`, `address1`, `city`, `state`, `pincode`, `area`, `service_zone_loc`, `zone_coverage`, `contact_name`, `designation`, `mobile`, `email_id`, `created_on`, `updated_on`, `user_id`, `flag`) VALUES (247, 230, 'head office', '', 'WELL CURE PATH LAB AND DIAGNOSTICS CENTRE', '', 'BHILWARA', 'Rajasthan', 311001, 148, 14, '', 'Anil', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (248, 222, 'head office', '0151-2204557', 'GOVT. HOSPITAL', '', 'BIKANER', 'Rajasthan', 334001, 149, 14, '', '', '', '9414139854', '', '2017-05-31', '2017-05-31', 1, ''), (249, 232, 'head office', '0151-2204557', 'GOVT. P.B. HOSPITAL , BIKANER', '', 'BIKANER', 'Rajasthan', 334001, 149, 14, '', 'Dr. Arya', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (250, 233, 'head office', '', 'BINNANI X RAY CLINIC & DIAGNOSTICS CENTER', '', 'BIKANER', 'Rajasthan', 334001, 149, 14, '', 'Dr. Binani', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (251, 222, 'head office', '0747-2444169', 'GOVT. HOSPITAL', '', 'BUNDI', 'Rajasthan', 323001, 150, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (252, 222, 'head office', '01562-222092', 'GOVT. HOSPITAL', '', 'CHURU', 'Rajasthan', 331001, 151, 14, '', 'Ravi', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (253, 236, 'head office', '', 'SHIVAM AURTHO & GENERAL HOSPITAL', '', 'CHURU', 'Rajasthan', 331001, 151, 14, '', 'Vikash', 'Technician', '9610140113', '', '2017-05-31', '2017-05-31', 1, ''), (254, 222, 'head office', '01427-230088', 'GOVT. HOSPITAL', '', 'DAUSA', 'Rajasthan', 303303, 152, 14, '', 'Dr. Rajkumari', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (255, 238, 'head office', '01427-230088', 'GOVT. TROMA CENTER', '', 'DAUSA', 'Rajasthan', 303303, 152, 14, '', 'Dr. Rajkumari', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (256, 222, 'head office', '05642-220765', 'GOVT. HOSPITAL', '', 'DHAULPUR', 'Rajasthan', 328001, 153, 14, '', 'Murari', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (257, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'DIDWANA', 'Rajasthan', 341303, 154, 14, '', 'Mustak', 'Technician', '9460918951', '', '2017-05-31', '2017-05-31', 1, ''), (258, 222, 'head office', '02964-232423', 'GOVT. HOSPITAL', '', 'DUNGARPUR', 'Rajasthan', 314001, 155, 14, '', 'Mahesh', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (259, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'GANGAPUR CITY', 'Rajasthan', 322201, 156, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (260, 222, 'head office', '01552-265692', 'GOVT. HOSPITAL', '', 'HANUMANGARH', 'Rajasthan', 335512, 157, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (261, 244, 'head office', '1414101202', 'APEX HOSPITAL, MALVIYA NAGAR, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Navnand', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (262, 245, 'head office', '1412754677', 'B LAL CLINICAL LAB, VIDYADHAR NAGAR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Amit', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (263, 246, 'head office', '', 'BANI PARK DHARMARTH SANSTHAN, BANI PARK', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Neeta', 'Technician', '9414446280', '', '2017-05-31', '2017-05-31', 1, ''), (264, 247, 'head office', '', 'BHAGWAN MAHAVIR CANCER HOSPITAL & RESEARCH CENTER', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Ranu', 'Technician', '8696666310', '', '2017-05-31', '2017-05-31', 1, ''), (265, 248, 'head office', '', 'CENTRAL PATHOLOGY LAB, SMS HOSPITAL , JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '<NAME>', 'Store Incharge', '9928204161', '', '2017-05-31', '2017-05-31', 1, ''), (266, 249, 'head office', '', 'Dr. GOYAL''S PATH LAB, SODALA', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Anil', 'Incharge', '8387065299', '', '2017-05-31', '2017-05-31', 1, ''), (267, 250, 'head office', '', 'GANGAOURI HOSPITAL, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Manish', 'Technician', '9782143671', '', '2017-05-31', '2017-05-31', 1, ''), (268, 251, 'head office', '1412563743', 'GETWELL DIAGNOSTICS CENTER, JLN MARG, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Devendr', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (269, 252, 'head office', '', 'HLA LAB & ADVANCED HEAMATOLOGY LAB, SMS MEDICAL COLLEGE , JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Sandhya', 'Incharge', '9829010184', '', '2017-05-31', '2017-05-31', 1, ''), (270, 253, 'head office', '', 'J.K. LOAN HOSPITAL , JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '8890365219', '', '2017-05-31', '2017-05-31', 1, ''), (271, 254, 'head office', '', 'JEEVAN REKHA CRITICAL CARE AND TRAUMA HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Ram', 'Incharge', '9694094521', '', '2017-05-31', '2017-05-31', 1, ''), (272, 255, 'head office', '', 'GOVT. JAIPURIYA HOSPITA', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Ramesh', 'Technician', '9414887695', '', '2017-05-31', '2017-05-31', 1, ''), (273, 256, 'head office', '', 'GOVT. KANWATIYA HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dinesh', 'Technician', '9829053073', '', '2017-05-31', '2017-05-31', 1, ''), (274, 257, 'head office', '', 'GOVT. DENTAL HOSPITAL, <NAME>', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Satish', 'Store ', '9413453143', '', '2017-05-31', '2017-05-31', 1, ''), (275, 258, 'head office', '', 'GOVT. SETHI COLONI HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (276, 259, 'head office', '', 'JAIPUR HOSPITAL, TONK ROAD', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Omna', 'Technician', '9460557229', '', '2017-05-31', '2017-05-31', 1, ''), (277, 260, 'head office', '', 'M.G. HOSPITAL & MEDICAL COLLEGE, TONK ROAD', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Puspendr', 'Incharge', '9799999691', '', '2017-05-31', '2017-05-31', 1, ''), (278, 261, 'head office', '', 'MAHILA CHIKITSHALAY HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Yogesh', 'Incharge', '9413253748', '', '2017-05-31', '2017-05-31', 1, ''), (279, 262, 'head office', '', 'MANU HOSPITAL& RESEARCH CENTRE, JAIPUR.', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '9929239089', '', '2017-05-31', '2017-05-31', 1, ''), (280, 263, 'head office', '', 'MENTAL HOSPITAL JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '9829206370', '', '2017-05-31', '2017-05-31', 1, ''), (281, 264, 'head office', '', 'NUROCARE HOSPITAL,VIDHYADHAR NAGAR , JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (282, 265, 'head office', '', 'PRECISION PATH LAB', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. samir', 'Incharge', '9983117003', '', '2017-05-31', '2017-05-31', 1, ''), (283, 266, 'head office', '', 'RELIABLLE DIAGNOSTICS CENTER, NEAR J.K. LOAN HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. <NAME>', 'Incharge', '1412744929', '', '2017-05-31', '2017-05-31', 1, ''), (284, 267, 'head office', '', 'RAILWAYS CENTRAL HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Ramesh', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (285, 268, 'head office', '', 'S.K. SONI HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Surendra', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (286, 269, 'head office', '', 'SANTOKABA DURLABH JI MEMORIAL HOSPITAL, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Rakesh', 'Incharge', '7611933299', '', '2017-05-31', '2017-05-31', 1, ''), (287, 270, 'head office', '', 'SHALBY HOSPITAL, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Parul', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (288, 271, 'head office', '1412560291', 'SMS HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '<NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (289, 272, 'head office', '', 'SMS HOSPITAL,TROMA UNIT, JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Ashish', 'Incharge', '9460115310', '', '2017-05-31', '2017-05-31', 1, ''), (290, 273, 'head office', '1412560291', 'SMS HOSPITAL, LIVER TRANSPLANT', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Dr. Mukesh', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (291, 274, 'head office', '', 'T.B. HOSPITAL, <NAME>', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '9414851935', '', '2017-05-31', '2017-05-31', 1, ''), (292, 275, 'head office', '1412370271', 'TONGYA HEART & GENERAL HOSPITAL', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Valsamma', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (293, 276, 'head office', '', 'UNIPATH SPECIALITY LABORATORY', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (294, 277, 'head office', '', 'ZANANA HOSPITAL , JAIPUR', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, '', 'Ramesh', 'Technician', '7340293776', '', '2017-05-31', '2017-05-31', 1, ''), (295, 222, 'head office', '07432-230906', 'GOVT. HOSPITAL', '', 'JHALAWAR', 'Rajasthan', 326001, 159, 14, '', 'Dr <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (296, 222, 'head office', '01592-230953', 'GOVT. HOSPITAL', '', 'JHUNJHUNU', 'Rajasthan', 333001, 160, 14, '', 'A. Goyal', 'Technician', '9897023414', '', '2017-05-31', '2017-05-31', 1, ''), (297, 280, 'head office', '0291 274 0741', 'AIIMS , JODHPUR', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Dr. <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (298, 281, 'head office', '', 'GOVT. HOSPITAL , MANDOR', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (299, 282, 'head office', '', 'M.G. HOSPITAL ', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', '<NAME>', 'Technician', '7737360845', '', '2017-05-31', '2017-05-31', 1, ''), (300, 283, 'head office', '', 'MATHURA DAS MATHUR HOSPITAL(MDM) JODHPUR', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Dr. arpita', 'Incharge', '9828067203', '', '2017-05-31', '2017-05-31', 1, ''), (301, 284, 'head office', '1415102613', 'OK DIAGNOSTICS CENTER,JODHPUR', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (302, 285, 'head office', '1412744929', 'RELIABLE DIAGNOSTICS CENTRE JODHPUR', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Dr. manish', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (303, 286, 'head office', '', 'RO<NAME> , JALORI GATE', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Dr. Mukesh', 'Incharge', '8829802738', '', '2017-05-31', '2017-05-31', 1, ''), (304, 287, 'head office', '', 'S.N. MEDICAL COLLEGE', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Dr. Upadhyay', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (305, 288, 'head office', '', 'UMMAID HOSPITAL ', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', 'Ramesh', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (306, 289, 'head office', '', 'VASUNDHARA LABORATORY, SARDARPURA', '', 'JODHPUR', 'Rajasthan', 342005, 161, 14, '', '', '', '9828243908', '', '2017-05-31', '2017-05-31', 1, ''), (307, 222, 'head office', '07464-220996', 'GOVT. HOSPITAL', '', 'KARAULI', 'Rajasthan', 322230, 162, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (308, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'KEKARI', 'Rajasthan', 305404, 163, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (309, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'KISHANGARH', 'Rajasthan', 305801, 164, 14, '', 'Dr. Anil', 'Incharge', '9214556402', '', '2017-05-31', '2017-05-31', 1, ''), (310, 293, 'head office', '', 'ANSHU DIAGNOSTICS CENTER KOTA', '', 'KOTA', 'Rajasthan', 324005, 165, 14, '', 'Dr. Anshu', 'Incharge', '9414186141', '', '2017-05-31', '2017-05-31', 1, ''), (311, 294, 'head office', '', 'GOVERNMENT MEDICAL COLLEGE, KOTA', '', 'KOTA', 'Rajasthan', 324005, 165, 14, '', '', '', '9829038938', '', '2017-05-31', '2017-05-31', 1, ''), (312, 295, 'head office', '', 'M.B.S. HOSPITAL ', '', 'KOTA', 'Rajasthan', 324005, 165, 14, '', '<NAME>', 'Incharge', '9829038938', '', '2017-05-31', '2017-05-31', 1, ''), (313, 296, 'head office', '', 'KOTA HEART & GENERAL HOSPITAL', '', 'KOTA', 'Rajasthan', 324005, 165, 14, '', 'Dr. yogesh', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (314, 297, 'head office', '', 'SUDHA HOSPITAL & MEDICAL RESEARCH CENTRE PVT. LTD.', '', 'KOTA', 'Rajasthan', 324005, 165, 14, '', 'Dr. yogesh', 'Incharge', '9929418654', '', '2017-05-31', '2017-05-31', 1, ''), (315, 222, 'head office', '1421226386', 'GOVT. HOSPITAL', '', 'KOTPUTLI', 'Rajasthan', 303108, 166, 14, '', 'Chetram', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (316, 222, 'head office', '01582-245680', 'GOVT. HOSPITAL', '', 'NAGAUR', 'Rajasthan', 341023, 167, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (317, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'NASIRABAD', 'Rajasthan', 305601, 168, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (318, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'NATHDWARA', 'Rajasthan', 313301, 169, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (319, 222, 'head office', '0295-2221268', 'GOVT. HOSPITAL', '', 'RAJSAMAND', 'Rajasthan', 313324, 170, 14, '', 'Manohar', 'Technician', '9414249964', '', '2017-05-31', '2017-05-31', 1, ''), (320, 303, 'head office', '', 'WELIOR HEATH CARE ', '', 'SHAHPURA', 'Rajasthan', 303103, 171, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (321, 222, 'head office', '01572-248339', 'GOVT. HOSPITAL', '', 'SIKAR', 'Rajasthan', 332001, 172, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (322, 305, 'head office', '', 'RELIABLE DIAGNOSTIS CENTER', '', 'SIKAR', 'Rajasthan', 332001, 172, 14, '', 'Dr. Vibha', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (323, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'SIROHI', 'Rajasthan', 307001, 173, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (324, 222, 'head office', '', 'GOVT. HOSPITAL', '', 'SUJANGARH', 'Rajasthan', 311507, 174, 14, '', '', '', '9887120414', '', '2017-05-31', '2017-05-31', 1, ''), (325, 222, 'head office', '01432-246194', 'GOVT. HOSPITAL', '', 'TONK', 'Rajasthan', 304001, 175, 14, '', 'Pooran', 'Technician', '9214015200', '', '2017-05-31', '2017-05-31', 1, ''), (326, 309, 'head office', '2945100917', 'AMOLAK DIAGNOSTICS PVT. LTD. / Dr. LAL Lab', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (327, 310, 'head office', '', 'ARAWALI HOSPITAL , UDAIPUR', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', '', '', '', '', '2017-05-31', '2017-05-31', 1, ''), (328, 311, 'head office', '2945102252', 'ARTH DIAGNOSTICS CENTER', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Mahendra', 'Technician', '', '', '2017-05-31', '2017-05-31', 1, ''), (329, 312, 'head office', '', 'CENTRAL PATHOLOGY LAB, R.N.T. MEDICAL COLLEGE', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Vijay Rajat', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (330, 313, 'head office', '', 'GEETANJALI HOSPITAL & MEDICAL COLLEGE', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', '<NAME>', 'Technician', '9352030843', '', '2017-05-31', '2017-05-31', 1, ''), (331, 314, 'head office', '', 'GOVT. HOSPITAL , HIRAN MAGRI', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', '', '', '9460727698', '', '2017-05-31', '2017-05-31', 1, ''), (332, 315, 'head office', '2942429210', 'G.B.H. AMERICAN HOSPITAL', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Dr. <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (333, 316, 'head office', '', 'GOYAL CLINIC & DIAGNOSTICS CENTER', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Vinod', 'Technician', '9649936655', '', '2017-05-31', '2017-05-31', 1, ''), (334, 317, 'head office', '9828412258', 'HIRAN X-RAY Clinic', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Dr. Hiran', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (335, 318, 'head office', '2942523191', 'KALPANA NURSING HOME PVT. LTD.', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Dr. <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (336, 319, 'head office', '2942523191', 'KALPANA PATH LAB / Govt. Hospital', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Dr. <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (337, 320, 'head office', '2942429210', 'MEDICENTER SONOGRAPHY & CLINICAL LAB', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Dr. <NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (338, 321, 'head office', '', 'PACIFIC MEDICAL COLLEGE & HOSPITAL', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Anil', 'Biomedical', '9413776010', '', '2017-05-31', '2017-05-31', 1, ''), (339, 322, 'head office', '', 'PACIFIC INSTITUTE OF MEDICAL SCIENCE,UMARADA ,UDAIPUR', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Anil', 'Biomedical', '9413776010', '', '2017-05-31', '2017-05-31', 1, ''), (340, 323, 'head office', '', 'R.N.T.. MEDICAL COLLEGE BLOOD BANK', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', '<NAME>', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (341, 324, 'head office', '', 'SRL FORTIS HOSPITAL', '', 'UDAIPUR', 'Rajasthan', 313001, 176, 14, '', 'Amit', 'Incharge', '', '', '2017-05-31', '2017-05-31', 1, ''), (342, 325, 'Head Office', '', '154/9, bannerghata road, opp. IIM - B', '', 'Bangalore', 'Karnataka', 560076, 80, 5, 'outstation', 'Dr Manjula', '', '9880224502', '', '', '', 0, ''), (343, 326, 'Head Office', '', '', '', '', '', 600010, 0, 8, 'outstation', 'Hitech', '', '9176869133', '', '', '', 0, ''), (344, 327, 'Head Office', '', 'no. 2 test nagar', '', 'Chennai', 'Tamil Nadu', 600010, 100, 8, 'outstation', 'Test Contact', '', '9962135225', '<EMAIL>', '', '', 0, ''), (345, 328, 'Head Office', '', 'No.96,Industrial Suburb, II Stage, Industrial Area, Yeshwantpur ', '', '', '', 560022, 0, 5, 'outstation', 'Jubilant biosys', '', '8066628736', '', '', '', 0, ''), (346, 329, 'Head Office', '', 'Chandra nagar colony,varanas', '', 'VARANASI', 'Uttar Pradesh', 221010, 213, 2, 'outstation', 'Aish Asghar', '', '09811138416', '', '', '', 0, ''), (347, 330, 'Head Office', '', 'new avadi rd chennai', '', '', '', 600010, 0, 8, 'outstation', 'SRL Lab New avadi', '', '9840645605', '', '', '', 0, ''), (348, 331, 'Head Office', '', 'Gorakhpur, Uttar Pradesh ', '', 'GORAKHPUR', 'Uttar Pradesh', 273013, 38, 2, 'outstation', 'AAAA', '', '0551 250 1736', '', '', '', 0, ''), (349, 332, 'Head Office', '', 'B-55 & C-42, Mandir Marg, Mahanagar Extention, Lucknow, Uttar Pradesh', '', 'LUCKNOW', 'Uttar Pradesh', 226006, 214, 0, '', 'bbbbbbbb', '', 'MIDLAND HEALTH CARE AND RESEARCH CENTRE', '', '', '', 0, ''), (350, 333, 'Head Office', '', 'Nehru Road, Bhilwara', '', 'BHILWARA', 'Rajasthan', 311001, 148, 14, 'outstation', 'cccccccc', '', '01482 - 238642', '', '', '', 0, ''), (351, 334, 'Head Office', '', '', '', '', '', 0, 0, 8, 'outstation', '', '', '', '', '', '', 0, ''), (352, 335, 'Head Office', '', 'C/O DR.HEDGEWAR RUGNALAYA, ASHOK NAGAR, GARKHEDA-431005', '', 'AURANGABAD', 'Maharashtra', 431005, 215, 1, 'outstation', 'Mr.<NAME>', 'Lab Incharge', '9822435509', '<EMAIL>', '', '', 0, ''), (353, 336, 'Head Office', '', 'VEER SAVERKAR NAGAR, NEAR NIMBALKAR HOSPITAL, DAUND', '', 'PUNE', 'Maharashtra', 413801, 217, 15, 'outstation', 'Dr <NAME>', 'HOD', '9637223520', '<EMAIL>', '', '', 0, ''), (354, 337, 'Head Office', '', 'Shivaji Ward, Tili Road, Sagar, Madhya Pradesh ', '', 'SAGAR', 'Madhya Pradesh', 470001, 218, 3, 'outstation', 'Dr <NAME>', 'HOD', '9165804580', '', '', '', 0, ''), (355, 338, 'Head Office', '', '', '', 'MEERUT', 'Uttar Pradesh', 250002, 220, 2, 'outstation', 'Dr Rashi', 'HOD', '7442150266', '', '', '', 0, ''), (356, 339, 'Head Office', '', 'Aga Hall Nesbit Road, Mazagaon Mumbai-400 010', '', '', '', 400010, 0, 1, 'outstation', 'Prince Aly Khan Hospital', '', '2223777800', '', '', '', 0, ''), (357, 340, 'Head Office', '', 'J.K. Town, Sarvadharam C-Sector, Kolar Road, Bhopal, Madhya Pradesh', 'J.K. Town, Sarvadharam C-Sector, Kolar Road, Bhopal, Madhya Pradesh', 'BHOPAL', 'Madhya Pradesh', 462042, 219, 3, 'outstation', 'SOMIL JAIN ', 'BIOMEDICAL ENGINEER', '9770836446', '', '', '', 0, ''), (358, 341, 'Head Office', '', 'Dr. Ahujas'' Pathology and Imaging Centre 7-B, Astley Hall, Ugrasain Road,, Ashtley Hall, Irigation Colony, Karanpur, Dehradun, Uttarakhand ', '', '', '', 248001, 0, 2, 'outstation', 'Dr Abuja''s pathology &imaging center', '', '8574654388', '', '', '', 0, ''), (359, 342, 'Head Office', '', 'Lanka near bhu Varanasi', '', 'VARANASI', '', 221005, 27, 2, 'outstation', 'Dr S.P,SINGH', 'HOD', '9452566502', '', '', '', 0, ''), (360, 9, 'SRL LTD C/O FORTIS HEALTHCARE VADAPALANI BRANCH', '', '2nd floor,kochar pss tower,arcot rd,Chennai-26', '', 'CHENNAI', 'TAMILNADU', 600026, 98, 8, '', 'MURUGAVEL', 'SSE', '9840645605', '', '', '', 0, ''), (361, 343, 'Head Office', '', 'Gorakhpur, Uttar Pradesh 273013', '', 'GORAKHPUR', 'Uttar Pradesh', 273013, 38, 2, 'outstation', 'Dr Shilpa', '', '9415313049', '', '', '', 0, ''), (362, 344, 'Head Office', '', 'SAHAHRANPUR U.P', '', 'SAHARANPUR', 'Uttar Pradesh', 247001, 221, 2, 'outstation', 'MR JITENDRA SINGH', '', '9897300715', '', '', '', 0, ''), (363, 345, 'Head Office', '', 'SULTANPUR,UP', '', 'SULTANPUR', 'Uttar Pradesh', 228001, 222, 2, 'on_site', 'Ramkumar', '', '11111111112', '', '', '', 0, ''), (364, 346, 'Head Office', '', 'BAREILLY,UP', '', 'BAREILLY', 'Uttar Pradesh', 243001, 223, 0, '', 'UV SINGH', '', '111111111111', '', '', '', 0, ''), (365, 347, 'Head Office', '', 'ALLAHABAD,UP', '', 'ALLAHABAD', 'Uttar Pradesh', 211002, 224, 0, '', '<NAME>', '', '11111111111111', '', '', '', 0, ''), (366, 348, 'Head Office', '', 'ALLAHABAD UP', '', 'ALLAHABAD', 'Uttar Pradesh', 211003, 225, 2, 'on_site', 'DR <NAME>', '', '111111111111111', '', '', '', 0, ''), (367, 349, 'Head Office', '', 'JAUNPUR ,UP', '', 'JAUNPUR', 'Uttar Pradesh', 222001, 226, 2, 'on_site', 'Dr S DAS', '', '00000000000', '', '', '', 0, ''), (368, 350, 'Head Office', '', 'ALIGARH,UP', '', 'ALIGARH', 'Uttar Pradesh', 202001, 227, 2, 'on_site', 'DR <NAME>', '', '9358203015', '', '', '', 0, ''), (369, 351, 'Head Office', '', 'GORAKHPUR,UP', '', 'GORAKHPUR', 'Uttar Pradesh', 273001, 228, 2, 'on_site', 'DR K M SINGH', '', '000000000000', '', '', '', 0, ''), (370, 352, 'Head Office', '', 'Kailly basti,up', '', 'KAILLY BASTI', 'Tamil Nadu', 272001, 229, 2, 'on_site', 'DR VK PRASAD', '', '00000000000000', '', '', '', 0, ''), (371, 353, 'Head Office', '', 'GHAZIABAD UP', '', 'GHAZIABAD', 'Uttar Pradesh', 201009, 230, 2, 'on_site', 'DR AK DUA', '', '000000000000000', '', '', '', 0, ''), (372, 354, 'Head Office', '', 'HAPUR,UP', '', 'HAPUR', 'Uttar Pradesh', 245101, 231, 2, 'on_site', 'DR MAN<NAME>', '', '', '', '', '', 0, ''), (373, 355, 'Head Office', '', '<NAME>', '', 'Kanpur', 'Uttar Pradesh', 209101, 232, 2, 'on_site', '<NAME>', '', '1478523691', '', '', '', 0, ''), (374, 356, 'Head Office', '', 'kanpur nagar u.p', '', 'Kanpur', 'Uttar Pradesh', 208001, 233, 2, 'on_site', 'DR SC VERMA', 'HOD', '9415068049', '', '', '', 0, ''), (375, 357, 'Head Office', '', 'AGRA,UP', '', 'AGRA', 'Uttar Pradesh', 282001, 234, 2, 'on_site', 'DR NM SHARMA', '', '00012333345556', '', '', '', 0, ''), (376, 358, 'Head Office', '', 'sant ravidas nagar u.p', '', 'bhadohi', 'Uttar Pradesh', 221304, 235, 2, 'on_site', 'PRAMOD KUMAR TIWARI', '', '9415845407', '', '', '', 0, ''), (377, 359, 'Head Office', '', 'MAU,UP', '', 'MAU', 'Uttar Pradesh', 275101, 236, 2, 'on_site', 'XXX', '', '123589764213', '', '', '', 0, ''), (378, 360, 'Head Office', '', 'LUCKNOW,UP', '', 'LUCKNOW', 'Uttar Pradesh', 226001, 237, 2, 'on_site', '<NAME>', '', '', '', '', '', 0, ''), (379, 361, 'Head Office', '', '', '', 'GONDA', 'Uttar Pradesh', 271001, 238, 2, 'on_site', '<NAME>', 'HOD', '9839900229', '', '', '', 0, ''), (380, 362, 'Head Office', '', 'FIROZABAD,UP', '', 'FIROZABAD', 'Uttar Pradesh', 283203, 239, 2, 'on_site', '<NAME>', '', '333333333333333', '', '', '', 0, ''), (381, 363, 'Head Office', '', 'MATHURA,UP', '', 'MATHURA', 'Uttar Pradesh', 281001, 240, 2, 'on_site', '<NAME>', '', '4444444444', '', '', '', 0, ''), (382, 364, 'Head Office', '', 'FARRUKHABAD,UP', '', 'FARRUKHABAD', 'Uttar Pradesh', 209605, 241, 2, 'on_site', '<NAME>', '', '44444444444', '', '', '', 0, ''), (383, 365, 'Head Office', '', 'KAUSHAMBI,UP', '', 'KAUSHAMBI', 'Uttar Pradesh', 212207, 242, 2, 'on_site', 'MR <NAME>AR', '', '9839462910', '', '', '', 0, ''), (384, 366, 'Head Office', '', 'FATEHPUR,UP', '', 'FATEHPUR', 'Uttar Pradesh', 212601, 243, 2, 'on_site', 'MR KC UMRAO', '', '444444444444', '', '', '', 0, ''), (385, 366, '', '', '', '', '', '', 0, 216, 1, '', '', '', '', '', '', '', 0, ''), (386, 367, 'Head Office', '', 'PRATAPGARH,UP', '', 'PRATAPGARH', 'Uttar Pradesh', 230001, 244, 2, 'on_site', 'MR K D PANDEY', '', '44444444411', '', '', '', 0, ''), (387, 368, 'Head Office', '', 'BANDA,UP', '', 'BANDA', 'Uttar Pradesh', 210001, 245, 2, 'on_site', 'DR SK BAJPAYEE', '', '777777777777777', '', '', '', 0, ''), (388, 369, 'Head Office', '', 'BALLIA,UP', '', 'BALLIA', 'Uttar Pradesh', 277001, 246, 2, 'on_site', 'DR R N SIDHARTH', '', '9832200297', '', '', '', 0, ''), (389, 370, 'Head Office', '', '', '', 'AZAMGARH', 'Uttar Pradesh', 276001, 247, 2, 'on_site', '<NAME>', '', '8888888888888', '', '', '', 0, ''), (390, 371, 'Head Office', '', 'SONBHADRA,UP', '', '', 'Uttar Pradesh', 231216, 248, 2, 'on_site', '<NAME>', '', '321465478941', '', '', '', 0, ''), (391, 372, 'Head Office', '', 'VARANASI,UP', '', 'VARANASI', 'Uttar Pradesh', 221002, 249, 2, 'on_site', '<NAME>', '', '9451638802', '', '', '', 0, ''), (392, 373, 'Head Office', '', 'DEORIA,UP', '', 'DEORIA', 'Uttar Pradesh', 274001, 250, 2, 'on_site', '<NAME>', '', '9450482902', '', '', '', 0, ''), (393, 374, 'Head Office', '', 'MEERUT,UP', '', 'MEERUT', 'Uttar Pradesh', 250004, 251, 2, 'on_site', '', '', '89099930001', '', '', '', 0, ''), (394, 375, 'Head Office', '', 'ALIGARH,UP', '', 'ALIGARH', 'Uttar Pradesh', 202001, 227, 2, 'on_site', '<NAME>', '', '3333333333333', '', '', '', 0, ''), (395, 376, 'Head Office', '', 'BULANDSHAHAR,UP', '', 'BULANDSHAHAR', 'Uttar Pradesh', 203001, 252, 2, 'on_site', 'MR UTTAM SHARMA', '', '88888888888888', '', '', '', 0, ''), (396, 377, 'Head Office', '', 'KANPUR,AP', '', 'Kanpur', '', 208002, 253, 2, 'on_site', 'DR LUBA KHAN', '', '8400033110', '', '', '', 0, ''), (397, 378, 'Head Office', '', 'ETAWA,UP', '', 'Etawa', 'Uttar Pradesh', 206001, 254, 2, 'on_site', 'DR SS BHADAURIYA', '', '8279573396', '', '', '', 0, ''), (398, 379, 'Head Office', '', 'BAHRAICH,UP', '', 'BAHRAICH', 'Uttar Pradesh', 271801, 255, 2, 'on_site', 'MR R PTRIPATHI', '', '', '', '', '', 0, ''), (399, 380, 'Head Office', '', 'SAIFAI ,ETAWAH', '', 'Etawa', 'Uttar Pradesh', 206130, 256, 2, 'on_site', 'DR SHWETA', '', '44444444455', '', '', '', 0, ''), (400, 381, 'Head Office', '', 'VARANASI,UP', '', 'VARANASI', 'Uttar Pradesh', 221001, 257, 2, 'on_site', 'SANJAY SINGH', '', '555555555555', '', '', '', 0, ''), (401, 382, 'Head Office', '', 'MEERUT,UP', '', 'MEERUT', 'Uttar Pradesh', 250002, 220, 2, 'on_site', 'DR KAUSHALENDRA SINGH', '', '9999774370', '', '', '', 0, ''), (402, 383, 'Head Office', '', '', '', '<NAME>', 'Uttar Pradesh', 262701, 258, 2, 'on_site', 'MR INDRJEET SINGH', '', '', '', '', '', 0, ''), (403, 384, 'Head Office', '', 'AMROHA,UP', '', 'AMROHA', 'Uttar Pradesh', 244221, 259, 2, 'on_site', 'MR VIVEK SHARMA', '', '', '', '', '', 0, ''), (404, 385, 'Head Office', '', 'RAMPUR UP', '', 'RAMPUR', 'Uttar Pradesh', 244901, 260, 2, 'on_site', 'MR <NAME>', '', '963484870', '', '', '', 0, ''), (405, 386, 'Head Office', '', 'LUCKNOW,UP', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 51, 2, 'on_site', 'MR <NAME>', '', '77777777777', '', '', '', 0, ''), (406, 387, 'Head Office', '', 'JHANSI,UP', '', 'Jhanshi', 'Uttar Pradesh', 284002, 261, 2, 'on_site', 'DR R K SAXENA', '', '999999999999', '', '', '', 0, ''), (407, 388, 'Head Office', '', 'KUSHINAGAR,UP', '', 'KUSHINAGAR', 'Uttar Pradesh', 276507, 262, 2, 'on_site', '<NAME>', '', '9450886921', '', '', '', 0, ''), (408, 389, 'Head Office', '', '<NAME>, Grant Road West, Tardeo, Mumbai, Maharashtra 400007', '', 'MUMBAI', 'Maharashtra', 400007, 216, 1, 'outstation', 'DR', '', '111111233332222', '', '', '', 0, ''), (409, 384, 'DISTRICT COMBINE HOSPITAL SAMBHAL', '', 'SHAMBAL,UP', '', 'SHAMBAL', 'UTTAR PRADESH', 244302, 0, 2, '', ' Mr. <NAME>', '', '9794189851', '', '', '', 0, ''), (410, 390, 'Head Office', '', '8/3 river bank colony Lucknow 226018', '', 'LUCKNOW', 'Uttar Pradesh', 226018, 264, 2, 'on_site', 'DR M KAR', '', '9452925064', '', '', '', 0, ''), (411, 391, 'Head Office', '', 'HAMIRPUR,UP', '', 'HAMIRPUR', 'Uttar Pradesh', 210301, 266, 2, 'on_site', 'SANTOSH', '', '2222222222', '', '', '', 0, ''), (412, 392, 'Head Office', '', 'MORADABAD,UP', '', 'MORADABAD', 'Uttar Pradesh', 244001, 267, 2, 'on_site', 'Dr <NAME>', '', '333333333333', '', '', '', 0, ''), (413, 71, 'SGPGI BLOOD BANK TRANSFUTION MEDICINE', '', 'Graund Floor, blood bank SGPGI Lucknow', '', 'LUCKNOW', 'UTTAR PRADESH', 226014, 0, 2, '', '<NAME>', 'HOD', '9334730220', '', '', '', 0, ''), (414, 393, 'Head Office', '', 'RAIBARLI,UP', '', 'RAIBARLI', 'Uttar Pradesh', 229001, 268, 2, 'on_site', '<NAME>', '', '9335623018', '', '', '', 0, ''), (415, 394, 'Head Office', '', 'BIJNOR,UP', '', 'BIJNOR', 'Uttar Pradesh', 250001, 269, 2, 'on_site', 'DR <NAME>', '', '', '', '', '', 0, ''), (416, 395, 'Head Office', '', 'LALITPUR,UP', '', 'LALITPUR', 'Uttar Pradesh', 284403, 270, 2, 'on_site', 'Dr <NAME>', '', '44444444444444', '', '', '', 0, ''), (417, 396, 'Head Office', '', 'SAMLI,UP', '', 'SAMLI', 'Uttar Pradesh', 247776, 271, 2, 'on_site', 'Dr <NAME>', '', '6555555555556', '', '', '', 0, ''), (418, 397, 'Head Office', '', 'No.7, Millers Tank Bed Area, Opposite Guru Nanak Bhavan, Jasma Bhavan Road, Vasanth Nagar, Bengaluru, ', '', 'Bangalore', 'Karnataka', 560052, 272, 5, 'outstation', 'Dr <NAME>', '', '9538869421', '', '', '', 0, ''), (419, 398, 'Head Office', '', 'Near Love garden chauraya,RC Vyas clony,Bhilwara', '', 'BHILWARA', 'Rajasthan', 311001, 273, 14, 'outstation', 'Dr <NAME>', '', '01482233006', '', '', '', 0, ''), (420, 399, 'Head Office', '', 'BANDRA EAST,MUMBAI 51', '', 'MUMBAI', 'Maharashtra', 400051, 274, 1, 'outstation', 'MRS BHAKTI MORE', '', '5555555555555', '', '', '', 0, ''), (421, 400, 'Head Office', '', 'Sanjeev Bld , ground floor, Ganesh gavade road, next to vijaya bank, mulund W, Mumbai 400080', '', 'MUMBAI', 'Maharashtra', 400080, 276, 1, 'outstation', 'Dr Nilesh', 'HOD', '02225655354', '', '', '', 0, ''), (422, 401, 'Head Office', '', '195/109 jagat narain road chowk, Lucknow 226003', '', 'LUCKNOW', 'Uttar Pradesh', 226003, 51, 2, 'on_site', 'Dr <NAME>', '', '9889124814', '', '', '', 0, ''), (423, 402, 'Head Office', '', 'R.S.No.628, B Ward, Near Shastri Nagar, Kolhapur-416012', '', 'KOLHAPUR', 'Maharashtra', 416012, 277, 1, 'outstation', 'Dr <NAME>', 'hod', '9225068410', '<EMAIL>', '', '', 0, ''), (424, 403, 'Head Office', '', 'SANGLI MIRAJ ROAD,VIJAYA NAGAR', '', 'SANGLI', 'Maharashtra', 416414, 278, 1, 'outstation', 'MR KIRAN', '', '02332601593', '', '', '', 0, ''), (425, 404, 'Head Office', '', 'NEAR CIVIL HOSPITAL', '', 'SANGLI', 'Maharashtra', 416416, 279, 15, 'outstation', 'DR BHUMI AGARWAL', '', '9585290232', '', '', '', 0, ''), (426, 405, 'Head Office', '', 'Bommasandra Industrial Area, Phase 4, Jigani link road, Biocon Park,, Bengaluru, Karnataka 560099', '', 'Bangalore', 'Karnataka', 560099, 282, 5, 'outstation', 'LOGESH', '', '9962594660', '', '', '', 0, ''), (427, 406, 'Head Office', '', '141,kamaraj rd,palladam main rd,tiruppur 641604', '', 'TIRUPPUR', 'Tamil Nadu', 641606, 283, 0, 'outstation', 'JAGATHEESWARAN', '', '9809727724', '', '', '', 0, ''), (428, 407, 'Head Office', '', 'BOLLARAM RD,MIYAPUR', '', 'HYDERABAD', 'Telangana', 500049, 134, 11, 'outstation', 'YUVARAJU', 'ENGINEERING MAINTENANCE', '7330834340', '', '', '', 0, ''), (429, 408, 'Head Office', '', '1719, Panchsheel, 7th Lane, Rajarampuri, Kolhapur-416230', '', 'KOLHAPUR', 'Maharashtra', 416230, 280, 1, 'outstation', 'APPA', '', '8485058315', '<EMAIL>', '', '', 0, ''), (430, 409, 'Head Office', '', 'A J Hospital Research Centre, Kuntikana, Mangalore - 575004', '', 'MANGALORE', 'Karnataka', 575004, 284, 5, 'outstation', 'SHANTI', 'HEAD HEMATOLOGY', '8246610800', '', '', '', 0, ''), (431, 410, 'Head Office', '', 'CPL HAEMATOLOGY DEPT. KATORA TAL ROAD, LASHKAR,GWALIOR 10City State name- gwalior M.P.', '', 'GWALIOR', 'Madhya Pradesh', 474009, 285, 3, 'outstation', 'Dr Bharat Jain', '', '9425116399', '', '', '', 0, ''), (432, 411, 'Head Office', '', 'FLAT NO 204 METRO PLAZA NEAR AJMERI PULIA ', '', 'JAIPUR', 'Rajasthan', 302001, 158, 14, 'outstation', '<NAME>', 'chief technician', '8004695112', '', '', '', 0, ''), (433, 412, 'Head Office', '', '<NAME>', '', 'LUCKNOW', 'Uttar Pradesh', 226010, 46, 2, 'on_site', 'Dr <NAME>', 'LAB Incharge', '9839261348', '', '', '', 0, ''), (434, 413, 'Head Office', '', 'II A TALWANDI KOTA', '', 'KOTA', 'Rajasthan', 324005, 165, 14, 'outstation', 'DR YOGESH GUPTA', '', '7442790059', '', '', '', 0, ''), (435, 414, 'Head Office', '', 'Near Dhebewadi Raod, Pune-Banglore Nh-4, Malkapur', '', 'KARAD', 'Maharashtra', 415110, 286, 15, 'outstation', ' Mrs Swati', 'Lab Incharge', '9623628646', '', '', '', 0, ''), (436, 415, 'Head Office', '', '111,nanjappa nagar,trichy road,coimbatore-641005', '', 'Coimbatore', 'Tamil Nadu', 641005, 287, 17, 'outstation', ' DR Neminathan', '', '9842811198', '', '', '', 0, ''), (437, 416, 'Head Office', '', 'chikkasandra,bengaluru', '', 'Bangalore', 'Karnataka', 560090, 288, 5, 'outstation', 'DR C VIJAYA', '', '9535282323', '', '', '', 0, ''), (438, 417, 'Head Office', '', '276,2ND FLOOR,HIRANA,UDAIPUR', '', 'UDAIPUR', 'Rajasthan', 313001, 289, 14, 'outstation', 'DR ANKIT SHARMA', '', '02942483077', '', '', '', 0, ''), (439, 417, 'molecular scientific jodhpur', '', '3-B-5 NIJKARMA HIGH COURT COLONY', '', 'jodhpur', 'Rajasthan', 0, 0, 14, '', 'Mr. <NAME>', '', '09984092480', '', '', '', 0, ''), (440, 418, 'Head Office', '', 'BARANA ROAD BORKHERA OPPOSITE SANJEEVNI HOSPITAL', '', 'KOTA', 'Rajasthan', 324001, 291, 14, 'outstation', 'SANDEEP', '', '08840668600', '', '', '', 0, ''), (441, 419, 'Head Office', '', 'BELAPUR CBD', '', 'BELAPUR', 'Maharashtra', 400614, 292, 13, 'outstation', 'DR VISHAL', '', '7738058952', '', '', '', 0, ''), (442, 420, 'Head Office', '', 'No.12 test road ', 'test nagar', 'Chennai', 'Tamil Nadu', 600017, 106, 8, 'outstation', 'Test customer Contact', '', '9962135224', '<EMAIL>', '', '', 0, ''), (443, 421, 'Head Office', '08754510262', 'first main road', 'thillai ganga nagar', '', '', 0, 0, 0, 'outstation', '', '', '', '', '', '', 0, ''), (444, 422, 'Head Office', '', 'orathur orthur', 'orathur', 'Chennai', 'Tamil Nadu', 614717, 296, 19, 'on_site', 'spvengat', '', '9874566258598', '<EMAIL>', '', '', 0, ''), (445, 423, 'Head Office', '', 'orathur', 'orathur', '', 'Tamil Nadu', 614717, 296, 19, 'on_site', 'afsdaasa', '', '9843609636', '<EMAIL>', '', '', 0, ''), (446, 424, 'Head Office', '', 'otathur', 'orathur', 'Pondichery', 'Tamil Nadu', 614717, 296, 19, 'on_site', 'spvinayage', '', '9874656314855', '<EMAIL>', '', '', 0, ''), (447, 425, 'Head Office', '', 'safsaf', 'afsafas', '', '', 614717, 0, 19, 'on_site', 'svik', '', '7654321345566', '<EMAIL>', '', '', 0, ''), (448, 426, 'Head Office', '', 'dsafas', 'afasfas', '', '', 614717, 296, 19, 'on_site', 'cvcvfdf', '', '45654345677', '<EMAIL>', '', '', 0, ''), (449, 427, 'Head Office', '', 'chennai', '', 'CHITRAKOOT', 'Lakshadweep', 614717, 296, 19, 'on_site', 'susren', '', '342543252523523', '<EMAIL>', '', '', 0, ''), (450, 428, 'Head Office', '', 'mannai', '', 'MATHURA', 'Tamil Nadu', 614717, 296, 19, 'on_site', 'vivek', '', '874596525885', '<EMAIL>', '', '', 0, ''), (451, 429, 'Head Office', '', 'jaipur', '', 'PATNA', 'Tamil Nadu', 614717, 296, 19, 'on_site', 'chandru', '', '8965412365878', '', '', '', 0, ''), (452, 430, 'Head Office', '', 'chetpet', 'nowroji road', '', '', 600010, 100, 8, 'outstation', 'sunrise', '', '9750098438', '<EMAIL>', '', '', 0, ''), (453, 431, 'Head Office', '', '', '', '', '', 600010, 100, 8, 'outstation', 'vijay', '', '9874563654', '<EMAIL>', '', '', 0, ''), (454, 432, 'Head Office', '', 'chennai', 'chennnai', '', '', 614717, 296, 19, 'on_site', 'lizy', '', '98456321458', '<EMAIL>', '', '', 0, ''), (455, 433, 'Head Office', '', 'kilpauk', 'kilpauk', '', '', 600010, 100, 8, 'outstation', 'jaya', '', '9874563698', '<EMAIL>', '', '', 0, ''), (456, 434, 'Head Office', '', '', '', '', '', 614717, 296, 19, 'on_site', 'arul', '', '96325874125', '', '', '', 0, ''), (457, 435, 'Head Office', '', '', '', '', '', 614717, 296, 19, 'on_site', 'gfd', '', '89652314755', '', '', '', 0, ''), (458, 436, 'Head Office', '', '', '', '', '', 614717, 296, 19, 'on_site', 'national', '', '9486043054', '', '', '', 0, ''), (459, 437, 'Head Office', '', 'chennai', 'chennai', '', '', 600010, 100, 8, 'outstation', 'vens', '', '9856321474', '<EMAIL>', '', '', 0, ''), (460, 438, 'Head Office', '', 'chennai', 'chennai', '', '', 614717, 296, 19, 'on_site', 'vishnu', '', '7845963214', '<EMAIL>', '', '', 0, ''), (461, 439, 'Head Office', '', 'chennai', 'chennai', '', '', 600010, 100, 8, 'outstation', 'sivaraj', '', '9874589654', '<EMAIL>', '', '', 0, ''), (462, 440, 'Head Office', '', 'chennai', '', '', '', 614717, 296, 19, 'on_site', 'negal', '', '957845213698', '<EMAIL>', '', '', 0, ''), (463, 441, 'Head Office', '', '', '', '', '', 614717, 296, 19, 'on_site', 'kavis', '', '258698745857', '', '', '', 0, 'Deleted'), (464, 442, 'Head Office', '', 'chennai', 'chennai', '', '', 614717, 296, 19, 'on_site', 'testings', '', '98745862145', '<EMAIL>', '', '', 0, ''); -- -------------------------------------------------------- -- -- Table structure for table `customer_type` -- CREATE TABLE IF NOT EXISTS `customer_type` ( `id` int(2) unsigned zerofill NOT NULL AUTO_INCREMENT, `type` varchar(100) NOT NULL, `Status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ; -- -- Dumping data for table `customer_type` -- INSERT INTO `customer_type` (`id`, `type`, `Status`) VALUES (01, 'Multispecialty Hospital', 0), (02, 'Lab', 0), (03, 'Medical college&Hospital', 0), (04, 'district Govt Hospital', 0), (05, 'Central Govt Hospital', 0), (06, 'Clinic', 0), (07, 'Trust Hospital', 0), (08, 'Hospital lab', 0), (09, 'DIAGNOSTICS LAB', 0), (10, 'Pharma', 0), (11, 'College', 0), (12, 'BLOOD BANK', 0), (13, 'Laboratory', 0), (14, 'Govt Hospital', 0), (15, 'Mission Hospital', 0), (16, 'medical center', 0), (17, 'medical university', 0), (18, 'Hospital', 0), (19, 'research center', 0), (20, 'cardiac center', 0), (21, 'cancer care', 0), (22, 'dental hospital', 0), (23, 'HEART INSTITUTE', 0); -- -------------------------------------------------------- -- -- Table structure for table `employee` -- CREATE TABLE IF NOT EXISTS `employee` ( `id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT, `emp_id` varchar(10) NOT NULL, `emp_name` varchar(100) NOT NULL, `emp_designation` varchar(100) NOT NULL, `emp_mobile` varchar(50) NOT NULL, `emp_email` varchar(100) NOT NULL, `emp_edu` varchar(100) NOT NULL, `emp_exp` varchar(250) NOT NULL, `doj` varchar(100) NOT NULL, `emp_addr` varchar(250) NOT NULL, `emp_addr1` varchar(250) NOT NULL, `emp_city` varchar(100) NOT NULL, `emp_state` varchar(100) NOT NULL, `emp_pincode` int(100) NOT NULL, `service_zone` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ; -- -- Dumping data for table `employee` -- INSERT INTO `employee` (`id`, `emp_id`, `emp_name`, `emp_designation`, `emp_mobile`, `emp_email`, `emp_edu`, `emp_exp`, `doj`, `emp_addr`, `emp_addr1`, `emp_city`, `emp_state`, `emp_pincode`, `service_zone`) VALUES (00001, 'ENG00001', '<NAME>', 'Service Manager', '9302253658', '<EMAIL>', 'B', '', '', '', '', 'Bhopal', '20', 0, '3,17'), (00002, 'ENG00002', '<NAME>', '', '9827029218', '<EMAIL>', '', '', '', '', '', 'Bhopal', '', 0, '0'), (00003, 'ENG00003', '<NAME>', 'Sr. Manager', '9462941594', '<EMAIL>', '', '10 years', '11/1/2014', '', '', 'jaipur', 'Rajasthan', 302020, '0'), (00004, 'ENG00004', '<NAME>', '', '9838251300', '<EMAIL>', '', '', '', '', '', 'Lucknow', '', 0, '0'), (00005, 'ENG00005', '<NAME>', '', '8574654388', '<EMAIL>', 'BE', '', '', '', '', 'Lucknow', '', 0, '2'), (00006, 'ENG00006', '<NAME> ', '', '9451194463', '<EMAIL>', 'BE', '', '', '', '', '', '', 0, '2'), (00007, 'ENG00007', '<NAME>', '', '9860305866', '<EMAIL>', 'be', '', '', '', '', 'Mumbai', '', 0, '1'), (00008, 'ENG00008', '<NAME>', '', '9769306298', '<EMAIL>', 'BE', '', '', '', '', '', '', 0, '1'), (00009, 'ENG00009', '<NAME>', '', '8669094180', '<EMAIL>', 'BE', '', '', '', '', '', '', 0, '15'), (00010, 'ENG00010', '<NAME>', '', '9561717349', '<EMAIL>', 'be', '', '', '', '', '', '', 0, '15'), (00011, 'ENG00011', '<NAME>', '', '9304589851', '<EMAIL>', 'B.E.', '', '', '', '', 'Patna', '5', 0, '1,3,6,8,9'), (00012, 'ENG00012', 'Bhaskar s.', 'Service&application engineer', '9164923679', '<EMAIL>', 'BE', '', '', '', '', 'Bangalore', '', 0, '5'), (00013, 'ENG00013', 'srividhya.P', 'Service&application engineer', '9176869133', '<EMAIL>', 'BE', '4.5yrs', '1/1/2015', '', '', 'Chennai', '31', 600007, '8'), (00014, 'ENG00014', '<NAME>', 'Service engineer', '9440488415', '<EMAIL>', 'BE ', '', '', '', '', 'Hyderabad', '', 0, '11'), (00015, 'ENG00015', '<NAME>', 'Service engineer', '9581284444', '<EMAIL>', 'BE', '', '', '', '', 'Hyderabad', '', 0, '5'), (00016, 'ENG00016', 'J.Suresh', 'Application specialist', '7093301265', '<EMAIL>', '', '', '', '', '', 'Hyderabad', 'Telangana', 0, '0'), (00017, 'ENG00017', 'Test Engineer', 'Service Engineer', '9962135225', '<EMAIL>', '', '', '', '', '', '', '', 0, '0'), (00018, 'ENG00018', 'TestEmployee', 'Engineer', '7845124578', '<EMAIL>', 'BE', '4', '2017-01-04', 'Chennai', 'Chennai', 'Chennai', '31', 600013, '2,8'), (00019, 'ENG00019', 'tesing', 'afsasa', '23654178855', '<EMAIL>', 'mca', 'mca', '2017-12-20', 'safsa', 'safs', 'MUMBAI', '31', 614717, '1'), (00020, 'ENG00020', 'testing ', 'asdfsallsa', '23145687455858', '<EMAIL>', 'mca', '', '', '', '', 'MUMBAI', '15', 614717, '3'), (00021, 'ENG00021', 'ghhd', 'fdhfd', '21456987555', '<EMAIL>', 'dsafsaf', '', '', 'kochi', 'kochi', 'tambaram', '15', 614717, '5'), (00022, 'ENG00022', 'dgdsgds', 'fdsgfsdgds', '56231475852585', '<EMAIL>', 'aslflas', '', '', '', '', 'PUNE', '16', 614717, '4'), (00023, 'ENG00023', 'cvcvcvcvvdv', '', '23456788967543', '<EMAIL>', 'mca', '', '', '', '', 'CHITRAKOOT', '17', 614717, '2,6,8'), (00024, 'ENG00024', 'dsgsdgsdg', '', '3454345454545', '<EMAIL>', 'vukasklf', '', '', '', '', 'Chennai', '18', 614717, '2,7'), (00025, 'ENG00025', 'aaaa', 'aaaasss', '231312312323', '<EMAIL>', 'MCA', '4yrs', '2017-12-20', 'sda dsadas dasd asd', '3weqweqw e qwe', 'Chennai', '31', 600032, '17'), (00026, 'ENG00026', 'spudhaya', 'supervisorf', '23658974155', '<EMAIL>', 'mca', '5', '2018-02-08', 'mannai', 'mannai', 'KOLHAPUR', '31', 614717, '19'), (00027, 'ENG00027', 'spram', 'engineerq', '3', '<EMAIL>', 'mca', '2', '2018-02-14', 'mannai', 'mannai', 'MUMBAI', '31', 614717, '19'), (00028, 'ENG00028', 'd', 'd', '332345345353454', '<EMAIL>', 'fgdg', '', '', '', '', '', '', 0, '5'); -- -------------------------------------------------------- -- -- Table structure for table `employee_service_skill` -- CREATE TABLE IF NOT EXISTS `employee_service_skill` ( `id` int(10) NOT NULL AUTO_INCREMENT, `empid` varchar(50) NOT NULL, `p_category` varchar(100) NOT NULL, `sub_category` varchar(100) NOT NULL, `brand` varchar(100) NOT NULL, `p_model` varchar(100) NOT NULL, `service_category` varchar(250) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=388 ; -- -- Dumping data for table `employee_service_skill` -- INSERT INTO `employee_service_skill` (`id`, `empid`, `p_category`, `sub_category`, `brand`, `p_model`, `service_category`) VALUES (28, '00008', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (29, '00008', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (30, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (31, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (32, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (33, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (34, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (35, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (36, '00008', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (46, '00005', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (47, '00005', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (48, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (49, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (50, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (51, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (52, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (53, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (54, '00005', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (64, '00010', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (65, '00010', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (66, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (67, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (68, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'PM&CAL'), (69, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (70, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (71, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (72, '00010', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (82, '00007', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'PM&CAL'), (83, '00007', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (84, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (85, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (86, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (87, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (88, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (89, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (90, '00007', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (100, '00006', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (101, '00006', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (102, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN'), (103, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (104, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (105, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (106, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (107, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (108, '00006', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (109, '00009', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'PM&CAL'), (110, '00009', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (111, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (112, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (113, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (114, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (115, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (116, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (117, '00009', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (172, '00014', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN,troubleshooting'), (173, '00014', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN'), (174, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN'), (175, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (176, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'BREAKDOWN'), (177, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'BREAKDOWN'), (178, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (179, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (180, '00014', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (190, '00012', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (191, '00012', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (192, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN'), (193, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (194, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (195, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (196, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (197, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (198, '00012', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (199, '00013', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (200, '00013', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (201, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (202, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN,troubleshooting'), (203, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (204, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'troubleshooting'), (205, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (206, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (207, '00013', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (217, '00015', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (218, '00015', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (219, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN'), (220, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN,troubleshooting'), (221, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (222, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (223, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (224, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (225, '00015', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (226, '00019', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN,troubleshooting,General Visit'), (227, '00019', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'Weekly maintenance'), (228, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN,Monthly maintenance'), (229, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'PM&CAL,Calibration,troubleshooting'), (230, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'Monthly maintenance,Software Upgradation'), (231, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'BREAKDOWN'), (232, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', 'Software Upgradation'), (233, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', 'Weekly maintenance'), (234, '00019', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', 'Software Upgradation'), (235, '00020', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (236, '00020', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN'), (237, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'Weekly maintenance'), (238, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'Weekly maintenance'), (239, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (240, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'Monthly maintenance'), (241, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', 'PM&CAL'), (242, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (243, '00020', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', 'Monthly maintenance'), (244, '00021', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (245, '00021', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'Weekly maintenance'), (246, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (247, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (248, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'Weekly maintenance'), (249, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'Weekly maintenance'), (250, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (251, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (252, '00021', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (253, '00022', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (254, '00022', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (255, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'Monthly maintenance'), (256, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'Monthly maintenance'), (257, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'Monthly maintenance'), (258, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (259, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (260, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (261, '00022', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (280, '00024', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (281, '00024', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN'), (282, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (283, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (284, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (285, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (286, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (287, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (288, '00024', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (289, '00011', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (290, '00011', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (291, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN'), (292, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (293, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (294, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (295, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (296, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (297, '00011', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (307, '00023', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'Weekly maintenance'), (308, '00023', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (309, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'Monthly maintenance'), (310, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (311, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (312, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (313, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (314, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (315, '00023', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (316, '00018', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (317, '00018', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN'), (318, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (319, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (320, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (321, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'BREAKDOWN'), (322, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (323, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (324, '00018', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (325, '00001', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (326, '00001', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (327, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (328, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (329, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (330, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (331, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (332, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (333, '00001', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', 'BREAKDOWN,Weekly maintenance,Monthly maintenance,PM&CAL,Calibration,troubleshooting'), (334, '00025', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (335, '00025', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (336, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (337, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (338, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (339, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (340, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (341, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (342, '00025', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', 'BREAKDOWN'), (343, '00026', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN'), (344, '00026', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'Weekly maintenance'), (345, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', 'Weekly maintenance'), (346, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', 'BREAKDOWN'), (347, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (348, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (349, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (350, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (351, '00026', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (370, '00027', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', 'BREAKDOWN,Calibration'), (371, '00027', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', 'Weekly maintenance'), (372, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (373, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (374, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', 'Calibration'), (375, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (376, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (377, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (378, '00027', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''), (379, '00028', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start 4', ''), (380, '00028', 'Semi Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'Start Max', ''), (381, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Satellite', ''), (382, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact', ''), (383, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max', ''), (384, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA Compact Max2', ''), (385, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R ', ''), (386, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R EVOLUTION', ''), (387, '00028', 'Fully Automated Coagulation Analyzer', 'COAGULATION', 'STAGO', 'STA-R MAX', ''); -- -------------------------------------------------------- -- -- Table structure for table `eng_notess` -- CREATE TABLE IF NOT EXISTS `eng_notess` ( `id` int(255) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `eng_notess` varchar(500) NOT NULL, `engg_id` int(10) NOT NULL, `created_on` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=95 ; -- -- Dumping data for table `eng_notess` -- INSERT INTO `eng_notess` (`id`, `req_id`, `eng_notess`, `engg_id`, `created_on`) VALUES (4, 25, 'test notes', 43, '2017-07-12 11:57:01'), (5, 36, 'first notes', 18, '2017-07-12 16:49:52'), (6, 37, ' eeeeeee', 18, '2017-07-12 16:59:32'), (7, 39, 'second notes ma', 18, '2017-07-12 17:22:23'), (8, 40, 'notest kjklsjdfkljskldjflkjs lkfjldsjf', 18, '2017-07-12 17:37:06'), (9, 32, 'Liquid filter was cleaned, fluidic circuit connections was checked. Instrument is working.', 12, '2017-07-12 19:07:32'), (10, 32, ' Liquid filter was cleaned, fluidic circuit connections was checked. Instrument is working.', 12, '2017-07-12 19:08:29'), (11, 41, 'I visited instrument, customer complaint that its show"error 49.03.04,\r\nmeasure timeout,waiting for ACK".check instrument \r\n''pc rack assembly''\r\nboard and re-connected cable and board .Again start instrument ,its working properly.\r\n', 6, '2017-07-13 22:22:58'), (12, 47, 'Checked instrument ,this problem is due to distrub of test parameter ,so correct the setting .', 6, '2017-07-15 17:18:38'), (13, 50, ' ', 1, '2017-07-17 17:06:33'), (14, 49, ' ', 12, '2017-07-22 12:54:56'), (15, 59, 'Weekly maintenance', 13, '2017-07-24 18:49:34'), (16, 59, ' Weekly maintenance', 13, '2017-07-26 13:02:17'), (17, 63, ' ', 13, '2017-07-27 11:43:46'), (18, 65, 'Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. ', 6, '2017-07-28 10:08:51'), (19, 65, 'Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. ', 6, '2017-07-28 10:12:07'), (20, 65, 'Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. ', 6, '2017-07-28 10:12:26'), (21, 65, ' Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. ', 6, '2017-07-28 10:13:00'), (22, 59, ' Weekly maintenance', 13, '2017-07-29 15:45:10'), (23, 59, ' Weekly maintenance', 13, '2017-07-29 15:49:37'), (24, 2, ' ', 7, '2017-07-30 19:31:23'), (25, 94, 'Printer head is faulty. Replaced with new one.', 1, '2017-08-10 16:31:52'), (26, 89, 'Instrument in working condition, because x1axis belt is damage some corner, and in future problem is come due to this reason. ', 6, '2017-08-11 10:51:23'), (27, 65, ' Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. ', 6, '2017-08-11 10:52:11'), (28, 102, 'Instrument calibration done', 0, '2017-08-18 12:13:36'), (29, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:13:06'), (30, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:46'), (31, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:47'), (32, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:48'), (33, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:49'), (34, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:50'), (35, 107, 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly', 0, '2017-08-19 11:32:51'), (36, 106, 'Instrument working satisfactory.', 0, '2017-08-19 15:17:57'), (37, 81, ' ', 0, '2017-08-28 22:59:11'), (38, 120, 'Checked instrument, problem is temperature sense cable is not working. Changed cable. It working properly. I''m ', 0, '2017-08-29 18:59:16'), (39, 121, 'Dust in Home sensor,clean the same .Instrument is working.', 0, '2017-08-30 15:50:52'), (40, 126, 'adjust printer ,need to replace printer thermic in future.', 0, '2017-09-01 13:00:22'), (41, 126, 'adjust printer ,need to replace printer thermic in future.', 0, '2017-09-01 13:10:49'), (42, 127, 'clean and re do the mapping of product carousol,clean the cuvette loading area.', 0, '2017-09-01 13:12:43'), (43, 129, 'Replaced with new keyboard, Now instrument is working fine', 0, '2017-09-02 13:37:28'), (44, 120, ' Checked instrument, problem is temperature sense cable is not working. Changed cable. It working properly. I''m ', 6, '2017-09-04 18:30:26'), (45, 120, ' Checked instrument, problem is temperature sense cable is not working. Changed cable. It working properly. I''m ', 6, '2017-09-04 18:32:48'), (46, 125, ' ', 13, '2017-09-08 12:54:45'), (47, 137, 'Needle is blocked, clean needle. After check program\r\nLoad new regent, its working properly. ', 0, '2017-09-10 01:38:41'), (48, 140, 'Do the mapping and change the suction tip', 0, '2017-09-18 13:17:17'), (49, 151, 'Make program for drvv s, drvv c, PC, PS, ATiii, and run drvv program for the test ', 0, '2017-09-23 19:19:01'), (50, 164, 'APTT results and controles are in higher side', 0, '2017-09-26 16:50:40'), (51, 174, 'This instrument is 5 year warranty ', 0, '2017-09-26 22:26:19'), (52, 193, 'Sample Needle is bended and temperature is out of range', 0, '2017-10-05 22:13:51'), (53, 197, 'Instrument working satisfactory.', 0, '2017-10-12 12:45:53'), (54, 201, 'Replaced kit peltier. now instrument is working fine ', 0, '2017-10-16 16:31:27'), (55, 219, 'Cuvette stuck in rail', 0, '2017-10-25 15:52:52'), (56, 220, 'Reagents are not loaded properly by new technician. ', 1, '2017-10-26 14:58:17'), (57, 199, 'PM and Calibration of start4', 9, '2017-10-28 14:19:04'), (58, 230, 'Product carousel temp. Out of range ', 1, '2017-10-31 14:41:59'), (59, 236, 'Shuttle is not moving properly, leakage in pneumatic jack tubing.', 14, '2017-10-31 18:53:19'), (60, 234, 'Visited to produce the training certificates', 15, '2017-10-31 20:47:28'), (61, 233, 'Lld issue with cephascrenn ', 15, '2017-10-31 20:48:33'), (62, 232, 'Visited for lis purpose', 15, '2017-10-31 20:49:17'), (63, 231, 'Visited to give demo of the instrument', 15, '2017-10-31 20:50:19'), (64, 224, 'Steel ball struked in the first position of the washing well removed and done mapping for niddel ', 15, '2017-10-31 20:54:13'), (65, 224, 'Steel ball strucked in the washing well first position', 15, '2017-10-31 20:55:05'), (66, 237, 'Needle was pipetting sample from the wall of the sample tube some time it touch the wall and give the error . May be needle was hit. ', 8, '2017-11-01 12:24:50'), (67, 241, 'Needle 3 broken', 15, '2017-11-06 15:11:55'), (68, 238, 'Bio logical validation', 15, '2017-11-06 15:12:44'), (69, 246, 'routine maintenance', 13, '2017-11-07 13:51:53'), (70, 118, 'Instrument working fine.', 11, '2017-11-08 22:49:39'), (71, 84, 'Instrument working fine', 0, '2017-11-08 22:50:59'), (72, 248, 'Frequently cuvette missing', 9, '2017-11-09 13:20:50'), (73, 211, 'In global Verification the arm No 2 is not checking suction pressure, then its giving a suction is not operating correctly. ', 14, '2017-11-10 18:16:55'), (74, 253, 'Photometric board faulty.', 1, '2017-11-11 12:39:49'), (75, 257, 'Preventive maintanence and training for new technicians', 15, '2017-11-20 12:07:50'), (76, 261, 'Shuttle jam', 9, '2017-11-30 23:45:20'), (77, 260, 'Shuttle missing', 9, '2017-11-30 23:47:56'), (78, 265, 'software issue. ', 14, '2017-12-11 21:20:27'), (79, 274, 'Visited in instrument and its show error "incubation temperature is out of range ".and pipetting is blocked ', 6, '2017-12-15 19:35:11'), (80, 263, 'May time it''s products drawer not close properly and give drawer closing issue ', 5, '2017-12-16 11:39:39'), (81, 290, 'hiiii', 0, '2018-02-08 16:33:09'), (82, 290, 'sgdfsgsdgdsgsdgsdg', 26, '2018-02-08 16:41:12'), (83, 289, 'tryreytttr', 0, '2018-02-08 17:03:31'), (84, 289, 'tytttttttter', 0, '2018-02-08 17:04:44'), (85, 289, 'rtyrtyyyyyy', 0, '2018-02-08 17:11:28'), (86, 291, 'rsdgrrdcrtgerd', 0, '2018-02-08 17:15:46'), (87, 291, 'rtdtrhygftrhycfghgd', 26, '2018-02-08 17:17:20'), (88, 289, 'ygiytitfityu', 18, '2018-02-08 18:24:27'), (89, 294, 'asffasfsafsaf', 26, '2018-02-13 18:24:41'), (90, 295, 'aaaaaaaa', 27, '2018-02-14 11:28:53'), (91, 297, 'sdafasfasfasf', 27, '2018-02-14 15:19:28'), (92, 296, 'hgdfhdfhdfhdf', 0, '2018-02-14 16:13:03'), (93, 298, 'sdgsdgsdgds', 26, '2018-02-14 16:33:04'), (94, 298, 'sgfsgfsdgsdgds', 26, '2018-02-14 16:34:19'); -- -------------------------------------------------------- -- -- Table structure for table `history_cust_remark` -- CREATE TABLE IF NOT EXISTS `history_cust_remark` ( `id` int(255) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `cust_remark` varchar(500) NOT NULL, `engg_id` int(10) NOT NULL, `given_by` varchar(10) NOT NULL, `created_on` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=136 ; -- -- Dumping data for table `history_cust_remark` -- INSERT INTO `history_cust_remark` (`id`, `req_id`, `cust_remark`, `engg_id`, `given_by`, `created_on`) VALUES (9, 25, 'new remarks', 1, '1', '2017-07-12 11:24:42'), (10, 25, ' new remarks', 1, '1', '2017-07-12 11:54:20'), (11, 33, ' new test remark', 1, '1', '2017-07-12 12:05:46'), (12, 36, ' first remark', 18, '1', '2017-07-12 16:45:45'), (13, 37, ' secodndndndndnd', 18, '1', '2017-07-12 16:54:54'), (14, 37, 'ewewrwerwer', 18, '1', '2017-07-12 17:00:00'), (17, 39, 'second remarks', 18, '1', '2017-07-12 17:23:29'), (18, 40, ' cust jbjdkfhsjdkdgsdg sdfdfsdf', 18, '1', '2017-07-12 17:40:13'), (19, 40, ' cust jbjdkfhsjdkdgsdg sdfdfsdf', 18, '1', '2017-07-12 17:41:03'), (20, 1, ' ', 9, '1', '2017-07-17 13:40:40'), (21, 48, ' Clean PDR.', 1, '1', '2017-07-17 14:27:30'), (22, 47, ' ', 6, '1', '2017-07-17 14:28:26'), (23, 46, ' replaced the LLD cable', 8, '1', '2017-07-17 14:29:06'), (24, 44, ' ', 5, '1', '2017-07-17 14:32:09'), (25, 51, ' ', 13, '1', '2017-07-20 20:58:39'), (26, 55, ' ', 1, '1', '2017-07-22 12:22:23'), (27, 57, ' ', 13, '1', '2017-07-24 14:26:37'), (28, 56, ' ', 13, '1', '2017-07-24 14:26:54'), (29, 60, ' ', 13, '1', '2017-07-25 17:05:00'), (30, 61, ' ', 13, '1', '2017-07-26 13:04:05'), (31, 33, ' new test remark', 18, '1', '2017-07-26 13:04:28'), (32, 25, ' new remarks', 18, '1', '2017-07-26 13:05:28'), (33, 3, ' ', 13, '1', '2017-07-26 13:05:52'), (34, 63, ' Product Drawer Temperature was high.Checked and filled coolant also lubricated coolant pump.Room temperature was high around 26-27.informed customer to maintain below 23deg.', 13, '1', '2017-07-27 11:46:24'), (35, 36, ' first remark', 18, '1', '2017-07-29 15:46:31'), (36, 64, ' ', 13, '1', '2017-07-31 13:16:09'), (37, 62, ' Mapping in eppendof cup was not proper.After mapping correctly issue solved.', 5, '1', '2017-07-31 13:41:32'), (38, 59, ' ', 13, '1', '2017-08-01 17:44:59'), (39, 69, ' asasasa', 18, '1', '2017-08-03 10:24:19'), (40, 77, ' After lubricating coolant pump problem solved.', 13, '1', '2017-08-03 14:26:39'), (41, 76, ' ', 13, '1', '2017-08-03 14:26:53'), (42, 75, ' ', 13, '1', '2017-08-03 14:27:08'), (43, 67, ' After installing OS and software problem solved', 14, '1', '2017-08-04 12:33:13'), (44, 82, ' ', 9, '1', '2017-08-05 15:44:44'), (45, 86, ' ', 13, '1', '2017-08-08 12:47:44'), (46, 87, ' ', 8, '1', '2017-08-08 13:31:34'), (47, 78, ' ', 13, '1', '2017-08-09 17:54:43'), (48, 94, ' ', 1, '1', '2017-08-10 16:34:37'), (49, 50, ' ', 1, '1', '2017-08-10 16:35:27'), (50, 2, ' ', 7, '1', '2017-08-10 16:36:36'), (51, 54, ' ', 9, '1', '2017-08-10 16:37:54'), (52, 95, ' ', 18, '1', '2017-08-10 17:47:07'), (53, 95, ' ', 18, '1', '2017-08-10 17:47:16'), (54, 84, ' ', 11, '1', '2017-08-11 15:07:50'), (55, 106, ' ', 10, '1', '2017-08-24 15:38:16'), (56, 113, ' ', 0, '1', '2017-08-28 17:38:46'), (57, 121, ' Dust in home sensor,clean the same instrument is working now', 1, '1', '2017-08-30 16:05:46'), (58, 127, ' ', 1, '1', '2017-09-08 16:15:43'), (59, 126, ' ', 1, '1', '2017-09-08 16:16:50'), (60, 143, ' ', 13, '1', '2017-09-18 18:46:31'), (61, 145, ' ', 13, '1', '2017-09-18 18:47:33'), (62, 141, ' ', 13, '1', '2017-09-18 18:48:36'), (63, 119, ' ', 13, '1', '2017-09-18 18:49:50'), (64, 147, ' ', 13, '1', '2017-09-19 14:30:50'), (65, 142, ' ', 13, '1', '2017-09-19 14:31:06'), (66, 135, ' ', 13, '1', '2017-09-19 14:31:22'), (67, 134, ' ', 13, '1', '2017-09-19 14:31:45'), (68, 148, ' ', 13, '1', '2017-09-20 16:43:48'), (69, 150, ' ', 13, '1', '2017-09-21 13:11:06'), (70, 146, ' ', 9, '1', '2017-09-21 13:11:47'), (71, 140, ' ', 9, '1', '2017-09-21 13:12:02'), (72, 128, ' ', 13, '1', '2017-09-21 13:12:23'), (73, 152, ' ', 13, '1', '2017-09-22 13:50:19'), (74, 139, ' ', 7, '1', '2017-09-22 13:50:34'), (75, 153, ' ', 13, '1', '2017-09-22 17:53:14'), (76, 137, ' ', 6, '1', '2017-09-22 17:55:07'), (77, 154, ' ', 13, '1', '2017-09-25 13:11:08'), (78, 154, ' ', 13, '1', '2017-09-25 13:13:06'), (79, 158, ' ', 13, '1', '2017-09-26 19:49:23'), (80, 124, ' ', 13, '1', '2017-09-29 13:39:20'), (81, 188, ' ', 13, '1', '2017-10-03 20:26:36'), (82, 184, ' ', 13, '1', '2017-10-03 20:26:50'), (83, 195, ' ', 13, '1', '2017-10-06 12:18:43'), (84, 194, ' ', 13, '1', '2017-10-06 12:22:43'), (85, 193, ' ', 6, '1', '2017-10-06 12:23:12'), (86, 192, ' ', 5, '1', '2017-10-06 12:23:24'), (87, 198, ' ', 13, '1', '2017-10-12 17:54:41'), (88, 201, ' ', 14, '1', '2017-10-16 17:59:59'), (89, 197, ' ', 10, '1', '2017-10-16 18:00:14'), (90, 197, ' ', 10, '1', '2017-10-16 18:02:14'), (91, 196, ' ', 5, '1', '2017-10-16 18:05:29'), (92, 191, ' ', 13, '1', '2017-10-16 18:06:28'), (93, 190, ' ', 6, '1', '2017-10-16 18:06:42'), (94, 189, ' ', 5, '1', '2017-10-16 18:06:56'), (95, 189, ' ', 5, '1', '2017-10-16 18:07:13'), (96, 183, ' ', 0, '1', '2017-10-16 18:07:32'), (97, 182, ' ', 13, '1', '2017-10-16 18:07:43'), (98, 203, ' ', 13, '1', '2017-10-16 18:31:15'), (99, 177, ' ', 6, '1', '2017-10-16 18:31:32'), (100, 176, ' ', 6, '1', '2017-10-16 18:31:47'), (101, 175, ' ', 6, '1', '2017-10-16 18:32:03'), (102, 174, ' ', 5, '1', '2017-10-16 18:32:24'), (103, 173, ' ', 6, '1', '2017-10-16 18:32:38'), (104, 169, ' ', 6, '1', '2017-10-16 18:33:04'), (105, 168, ' ', 6, '1', '2017-10-16 18:33:25'), (106, 207, ' ', 13, '1', '2017-10-17 18:44:48'), (107, 167, ' ', 6, '1', '2017-10-17 18:45:01'), (108, 166, ' ', 13, '1', '2017-10-17 18:45:15'), (109, 165, ' ', 0, '1', '2017-10-17 18:45:31'), (110, 164, ' ', 1, '1', '2017-10-17 18:45:45'), (111, 160, ' ', 5, '1', '2017-10-17 18:46:00'), (112, 151, ' ', 5, '1', '2017-10-17 18:46:47'), (113, 212, ' ', 8, '1', '2017-10-25 15:37:27'), (114, 210, ' ', 13, '1', '2017-10-25 15:37:41'), (115, 209, ' ', 13, '1', '2017-10-25 15:38:38'), (116, 206, ' ', 1, '1', '2017-10-25 15:39:29'), (117, 136, ' ', 1, '1', '2017-10-25 15:39:49'), (118, 133, ' ', 6, '1', '2017-10-25 15:40:08'), (119, 132, ' ', 5, '1', '2017-10-25 15:40:23'), (120, 131, ' ', 6, '1', '2017-10-25 15:40:37'), (121, 129, ' ', 14, '1', '2017-10-25 15:43:33'), (122, 229, ' ', 13, '1', '2017-10-31 15:32:24'), (123, 95, 'xcxcvx', 18, '1', '2017-12-29 19:04:07'), (124, 289, ' ', 18, '1', '2017-12-30 12:18:55'), (125, 285, ' ', 15, '1', '2017-12-30 14:30:01'), (126, 290, ' ', 26, '1', '2018-02-08 13:32:22'), (127, 290, 'sadfsafsadfdasfsafasdfasfsdaf', 26, '1', '2018-02-08 16:45:49'), (128, 289, 'dfgdsfgsdgdsgsdgsd', 18, '1', '2018-02-08 17:01:22'), (129, 291, ' trhyrdtxfthytjhnygtuj', 26, '1', '2018-02-08 17:14:29'), (130, 289, 'gdhfgggggg', 18, '1', '2018-02-08 17:23:08'), (131, 289, 'gsdgsdgsdgsdgsdgdsgds', 18, '1', '2018-02-08 18:31:19'), (132, 292, ' a new customer remarks', 26, '1', '2018-02-13 16:41:33'), (133, 296, ' ', 26, '1', '2018-02-14 14:13:05'), (134, 297, 'dsgsdgdsfgdsgsdgfdsgsdgsdgsdgfsd', 27, '1', '2018-02-14 15:28:25'), (135, 298, 'sdgfdsgdsgsdgs', 26, '1', '2018-06-29 14:58:56'); -- -------------------------------------------------------- -- -- Table structure for table `history_cust_solution` -- CREATE TABLE IF NOT EXISTS `history_cust_solution` ( `id` int(255) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `cust_solution` varchar(500) NOT NULL, `engg_id` int(10) NOT NULL, `given_by` varchar(10) NOT NULL, `created_on` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=97 ; -- -- Dumping data for table `history_cust_solution` -- INSERT INTO `history_cust_solution` (`id`, `req_id`, `cust_solution`, `engg_id`, `given_by`, `created_on`) VALUES (6, 25, 'test solution', 43, '7', '2017-07-12 11:56:24'), (7, 36, 'first solution', 18, '7', '2017-07-12 16:26:26'), (8, 37, 'soluttitititittiti', 18, '7', '2017-07-12 16:55:23'), (9, 38, 'ssssssssssss', 18, '7', '2017-07-12 17:03:57'), (10, 39, 'second solution', 18, '7', '2017-07-12 17:21:32'), (11, 40, 'fghdfgdfgfdgfdg fdg fdg', 18, '7', '2017-07-12 17:37:40'), (12, 40, ' fghdfgdfgfdgfdg fdg fdg', 18, '7', '2017-07-12 17:38:45'), (13, 40, ' fghdfgdfgfdgfdg fdg fdg', 18, '7', '2017-07-12 17:39:31'), (14, 53, 'Problem is due to product carasuel positioning sensor ,open instrument and clean sensor .And mapping instrument .it work properly', 6, '7', '2017-07-21 11:57:13'), (15, 55, 'replaced printer head.', 1, '7', '2017-07-22 12:20:20'), (16, 50, 'rEPLACED pHOTOMETRIC BOARD WITH FIBER DONE MAPPING,PHOTOMETRIC CALIBRATION RUN CONTROL,RUN 5 SAMPLES.', 1, '7', '2017-07-27 21:41:25'), (17, 54, 'I have replace the needle No3 and run the endorance now machine is working fine.', 9, '7', '2017-07-31 12:58:11'), (18, 67, 'Upgraded OS 107.03 to 108.08.02, Now instrument is working fine.', 14, '7', '2017-08-02 10:26:35'), (19, 77, 'Due to too much dust and rust after lubrication problem solved', 13, '7', '2017-08-03 13:57:35'), (20, 78, 'Lubricated the pump.need to change new pump', 13, '7', '2017-08-04 15:25:55'), (21, 82, 'Factor 7 callibration select the neoplastin lot number in callibration menu.', 9, '7', '2017-08-05 15:29:27'), (22, 87, 'After removing paper cleaned the printer area.Problem solved', 8, '7', '2017-08-08 13:30:52'), (23, 78, ' Lubricated the pump.need to change new pump', 13, '7', '2017-08-09 17:50:33'), (24, 92, 'Measurement and callibration of temperature done', 9, '7', '2017-08-10 16:40:11'), (25, 91, 'Clean glass windows of rail and clean camera then done mapping ', 5, '7', '2017-08-11 10:04:16'), (26, 98, 'Change cacl2 and tip for electronic pipettes and then run and control sample and find good results ', 0, '7', '2017-08-12 12:53:06'), (27, 100, 'troubleshooted for time being.But need to replace cap', 0, '7', '2017-08-14 14:52:51'), (28, 101, 'Tubeing in between vacuum reservoir and electrovalve are damage so change tube and solve problem', 0, '7', '2017-08-16 16:23:20'), (29, 96, 'Routed x axis belt 180 degree and solve problem instrument in running condition but in future need to replace belt \r\nBecause some teeth of belt is damage \r\nWhen we routed belt 180 degree then damage teeth is not in use and belt working fine \r\n ', 0, '7', '2017-08-16 16:29:18'), (30, 109, 'done instrument calibration and replaced cap waste container', 0, '7', '2017-08-19 12:23:48'), (31, 117, 'Clean the printer and remove dust particles from printer.', 0, '7', '2017-08-28 22:58:22'), (32, 121, 'Dust in home sensor clean the same. Instrument is working now.', 1, '7', '2017-08-30 15:53:46'), (33, 123, 'We have make 1/15 dilution in between 1/7 & 1/40 dilutions for Immunodef Factor VIII test set up.\r\n\r\nFor PT comparison, we used same vial of PT Reagent on both Compact Max and Satellite Instrument.', 0, '7', '2017-09-01 13:41:39'), (34, 123, ' We have make 1/15 dilution in between 1/7 & 1/40 dilutions for Immunodef Factor VIII test set up.\r\n\r\nFor PT comparison, we used same vial of PT Reagent on both Compact Max and Satellite Instrument.', 10, '7', '2017-09-01 13:43:50'), (35, 131, 'Instrument is not start checked instrument it problem due to fuse F3(1A)\r\nChanged fuse. ', 0, '7', '2017-09-04 18:42:11'), (36, 132, 'Problem due to dust in between barcode reader and product carousel glass ', 0, '7', '2017-09-05 13:27:49'), (37, 112, 'I changed optical sensor, instrument working properly', 6, '7', '2017-09-06 16:45:07'), (38, 141, 'Reset PID RAM in drawer product solved', 0, '7', '2017-09-15 11:35:43'), (39, 145, 'Checked auto mode settings and did bidirectional interface.it worked', 0, '7', '2017-09-18 13:10:58'), (40, 146, 'PM and Callibration of the Start4', 0, '7', '2017-09-18 22:42:53'), (41, 147, 'Routine maintenance', 0, '7', '2017-09-19 14:30:12'), (42, 152, 'Performed Recalibration.Qc is in range.It is under observation', 0, '7', '2017-09-22 13:49:48'), (43, 153, 'Sample tube was empty so needle went to bottom of the tube.after checking prob solved', 0, '7', '2017-09-22 17:30:53'), (44, 160, 'Make program for TT and run calibration and test ', 0, '7', '2017-09-23 21:10:36'), (45, 164, 'decontaminate instrument done user maintenance run control .controls are in range.', 0, '7', '2017-09-26 16:50:40'), (46, 165, 'decontaminate instrument run control.all are in range', 0, '7', '2017-09-26 16:52:01'), (47, 174, 'Check instrument and find 20 pluses volume issue so set V pump and slove problem \r\nThen run PC PS ATIII and APCR test ', 0, '7', '2017-09-26 22:26:19'), (48, 177, 'Buffer vial can not create vaccume beacuse tube connection is break, reconnected tube connector. Its working properly. ', 0, '7', '2017-09-27 19:45:18'), (49, 180, 'PM and Calibration', 0, '7', '2017-09-28 21:34:59'), (50, 189, 'Change needle and done mapping solve problems', 0, '7', '2017-10-03 20:28:38'), (51, 190, 'Done Instrument mapping. ', 0, '7', '2017-10-05 07:13:25'), (52, 192, 'Run PC FIb and drvv c calibration and control also run test ', 0, '7', '2017-10-05 18:05:39'), (53, 193, 'Done needle straight, reconnected in sample needle position. Checked volume of dispence, it is ok. And temprature problem due to glycol pump is not work and heating so open and clean pump it is working properly. ', 0, '7', '2017-10-05 22:13:51'), (54, 196, 'Solve problems', 0, '7', '2017-10-07 21:37:20'), (55, 197, 'Syringe Tip replaced.', 0, '7', '2017-10-12 12:45:53'), (56, 198, 'replaced from spare box.they need new one for future', 0, '7', '2017-10-12 17:41:07'), (57, 206, 'Arm Z movement is not proper,Clean arm and lubricate Z Pully,run tests.working OK', 0, '7', '2017-10-17 23:54:45'), (58, 219, 'open and clean rail module,clean the theta motor pully and lubricate the same , check the mapping, run the test .', 0, '7', '2017-10-25 15:52:52'), (59, 221, 'Checked instrument, no problem found ininstrument, problem is in 50micro liter plama dispensing by Pipette. Changed pipette. Solve problem. ', 0, '7', '2017-10-25 17:44:40'), (60, 220, 'Reload all reagents and guide about Loading unloading and to run control. ', 1, '7', '2017-10-26 14:58:17'), (61, 230, 'Check the temperature it is showing 17 ''C in instrument and in temperature probe found that the filters are block from dust, replaced the filter clean the fan. Product temp. Is now 13''C.', 1, '7', '2017-10-31 14:41:59'), (62, 236, 'Refitted the pneumatic jack tubing tightly, and cleaned the shuttle rail, now Instrument is working fine.', 14, '7', '2017-10-31 18:53:19'), (63, 233, 'Mapping done now the instrument is working fine', 15, '7', '2017-10-31 20:48:33'), (64, 224, 'Removed and done mapping', 15, '7', '2017-10-31 20:55:05'), (65, 237, 'Mapping for the sample pipetting and product pipetting was done. ', 8, '7', '2017-11-01 12:24:50'), (66, 240, 'Neddle puresing volume is low cleaning needle and set volcur pump. Problem is solve. ', 6, '7', '2017-11-04 08:07:31'), (67, 241, 'Replaced with new one and done mapping', 15, '7', '2017-11-06 15:11:55'), (68, 245, 'completed the Calibration and run the quality control both PT & APTT are passed.\r\nPT 13.2 / 22.3 , APTT 32.5 / 52.0', 14, '7', '2017-11-07 16:32:04'), (69, 118, 'Multifunction board replaced.', 11, '7', '2017-11-08 22:49:39'), (70, 84, 'Replaced PC Board.', 0, '7', '2017-11-08 22:50:59'), (71, 248, 'Done the mapping arm 2 and clean the suction tip', 9, '7', '2017-11-09 13:20:50'), (72, 249, 'Visit in lab and found problem APTT regent. APTT regent contaminate and also not proper trained technician so give training to all technician and solve issue ', 5, '7', '2017-11-09 15:04:33'), (73, 211, 'after replacing the I/O power board instrument is working fine.', 14, '7', '2017-11-10 18:16:55'), (74, 253, 'Clean fibers and measurement area, but problem remain same, then press Q and start chronometric test only. Need to replace photometricboard. ', 1, '7', '2017-11-11 12:39:49'), (75, 250, 'Make program for fviii and fix also make program for fviii low curve and run calibration and control ', 5, '7', '2017-11-13 09:12:04'), (76, 261, 'Remove the steel ball from shuttle rack after that machine is working fine.', 9, '7', '2017-11-30 23:45:20'), (77, 260, 'Remove the steel ball from shuttle rack. Now machine is working fine.', 9, '7', '2017-11-30 23:47:56'), (78, 265, 'Reloaded the software, and done all the mapping, and done calibration & QC. Now instrument is working fine. ', 14, '7', '2017-12-11 21:20:27'), (79, 264, 'Solve error of instrument & Run control for pt & Appt ', 5, '7', '2017-12-11 22:55:19'), (80, 274, 'Checked glycol pump is not liquid flow cooling reservoir to meeting block pump is not work .open and clean pump and rectifying the problem .after cleaning and holing its work properly. I', 6, '7', '2017-12-15 19:35:11'), (81, 269, 'Find some broken cuvette in cuter which blocked the cuter movement so remove it and solve issue', 5, '7', '2017-12-16 11:36:20'), (82, 273, 'Check pipetting tip, measurement chamber and product drawer teprature and calibration was done for temp.\r\n', 7, '7', '2017-12-16 14:16:51'), (83, 290, 'how r u', 0, '7', '2018-02-08 16:33:09'), (84, 290, 'fdsgdfsgsdgsdgd', 26, '7', '2018-02-08 16:41:12'), (85, 289, 'yttryyyyyyyyy', 0, '7', '2018-02-08 17:03:31'), (86, 289, 'yteyeetteyer', 0, '7', '2018-02-08 17:04:44'), (87, 289, 'yyyyyyttttttttttttttttttttttttttttttttr', 0, '7', '2018-02-08 17:11:28'), (88, 291, 'gtresdgtzsdgtdrshgyrtsyr', 0, '7', '2018-02-08 17:15:47'), (89, 291, 'hjutfujgtfujgtjitgui', 26, '7', '2018-02-08 17:17:21'), (90, 289, 'trjururt', 18, '7', '2018-02-08 18:24:27'), (91, 294, 'safsafasfasfsafsafsafsafsfsafs', 26, '7', '2018-02-13 18:24:41'), (92, 295, 'bbbbbbbbbbb', 27, '7', '2018-02-14 11:28:54'), (93, 297, 'fsafdsafsdafsafsafdsafsdafasfafasfasfa', 27, '7', '2018-02-14 15:19:28'), (94, 296, 'dhdfhdfhd', 0, '7', '2018-02-14 16:13:03'), (95, 298, 'gdsgdsgsdgsdgsdgsdgsdgs', 26, '7', '2018-02-14 16:33:04'), (96, 298, 'gsfdgdsfgsdgfsdgsdgsdgdsgdsgsdgds', 26, '7', '2018-02-14 16:34:19'); -- -------------------------------------------------------- -- -- Table structure for table `history_review` -- CREATE TABLE IF NOT EXISTS `history_review` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` varchar(255) NOT NULL, `eng_notes` varchar(1000) NOT NULL, `engg_id` varchar(255) NOT NULL, `created_on` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `history_review` -- INSERT INTO `history_review` (`id`, `req_id`, `eng_notes`, `engg_id`, `created_on`) VALUES (1, '00002', 'dsd', '', '2017-06-08 13:10:00'); -- -------------------------------------------------------- -- -- Table structure for table `lab_tech` -- CREATE TABLE IF NOT EXISTS `lab_tech` ( `id` int(10) NOT NULL AUTO_INCREMENT, `lab_name` varchar(255) NOT NULL, `status` int(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `log_onhold` -- CREATE TABLE IF NOT EXISTS `log_onhold` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` varchar(50) NOT NULL, `emp_id` varchar(50) NOT NULL, `on_hold` varchar(50) NOT NULL, `onhold_reason` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ; -- -- Dumping data for table `log_onhold` -- INSERT INTO `log_onhold` (`id`, `req_id`, `emp_id`, `on_hold`, `onhold_reason`) VALUES (1, '00017', '00012', '2017-06-08 15:53:35', 'TROUBLE SHOOTING STILL CONTINIOUE'), (2, '00049', '00012', '2017-07-17 13:03:22', ''), (3, '00050', '00001', '2017-07-17 17:00:06', 'need to replace Photometery board waiting for approval.'), (4, '00050', '00001', '2017-07-17 17:06:03', ''), (5, '00049', '00012', '2017-07-22 12:52:56', ''), (6, '00078', '00013', '2017-08-04 15:23:46', 'Need to get spare approval'), (7, '00081', '00009', '2017-08-05 15:29:48', 'Because there is printing issue in control values and patient result is printing clear.as per discuss with an sir. I am going to write the mail to Anil sir and boss'), (8, '00096', '00005', '2017-08-11 10:04:39', 'Need to replace x arm belt\r\n\r\n'), (9, '00112', '00006', '2017-08-20 05:54:18', 'Biddlestone home senser is not available in stock. '), (10, '00116', '00009', '2017-08-24 17:53:44', 'Due to AMC and part are not available.'), (11, '00125', '00013', '2017-08-31 16:26:36', ''), (12, '00143', '00013', '2017-09-15 13:19:18', 'PM due is on 28th'), (13, '00211', '00014', '2017-11-07 09:57:07', ''), (14, '00250', '00005', '2017-11-13 09:10:38', ''), (15, '00263', '00005', '2017-12-16 11:36:32', ''), (16, '00290', '0', '2018-02-08 16:32:33', 'fdsafddsafsafs'), (17, '00289', '0', '2018-02-08 17:03:18', ''), (18, '00291', '00026', '2018-02-08 17:13:54', 'hytutrutryujhtrhtynjty'), (19, '00289', '00018', '2018-02-08 18:24:09', ''), (20, '00289', '00018', '2018-02-08 18:30:16', 'dsgsgdsfgdsgdsgds'), (21, '00289', '00018', '2018-02-08 18:32:58', ''), (22, '00291', '00026', '2018-02-13 12:56:46', ''), (23, '00291', '00026', '2018-02-13 12:58:18', ''), (24, '00291', '00026', '2018-02-13 14:16:16', ''), (25, '00291', '00026', '2018-02-13 14:16:33', ''), (26, '00291', '00026', '2018-02-13 14:17:37', ''), (27, '00291', '00026', '2018-02-13 14:18:12', ''), (28, '00291', '00026', '2018-02-13 14:47:11', 'sadfsafasfasfafafaf'), (29, '00292', '00026', '2018-02-13 16:40:20', 'sfsafasfsafasfsaf'), (30, '00296', '0', '2018-02-14 16:11:59', 'dfhdfhdfhdfhdhdhh'), (31, '00298', '00026', '2018-02-14 16:32:20', 'fsdgsgsgsdgsgsdgsdgdsgsdgsdgdsgsd'); -- -------------------------------------------------------- -- -- Table structure for table `log_onhold_stamping` -- CREATE TABLE IF NOT EXISTS `log_onhold_stamping` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `stamping_id` int(10) NOT NULL, `emp_id` varchar(10) NOT NULL, `on_hold_date` varchar(50) NOT NULL, `on_hold_reason` varchar(250) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `log_reassign_engg` -- CREATE TABLE IF NOT EXISTS `log_reassign_engg` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` int(50) NOT NULL, `engg_id` varchar(100) NOT NULL, `updated_on` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=167 ; -- -- Dumping data for table `log_reassign_engg` -- INSERT INTO `log_reassign_engg` (`id`, `req_id`, `engg_id`, `updated_on`) VALUES (1, 127, '00001', '2017-09-01 12:47:26'), (2, 128, '00013', '2017-09-02 12:30:42'), (3, 129, '00014', '2017-09-02 12:33:31'), (4, 130, '00012,00015', '2017-09-02 16:58:31'), (5, 131, '00006', '2017-09-04 16:16:04'), (6, 132, '00005', '2017-09-04 16:17:56'), (7, 133, '00006', '2017-09-05 14:56:43'), (8, 134, '00013', '2017-09-07 12:20:51'), (9, 135, '00013', '2017-09-07 12:21:44'), (10, 136, '00001', '2017-09-08 16:06:02'), (11, 137, '00006', '2017-09-09 14:52:04'), (12, 139, '00007', '2017-09-13 20:49:10'), (13, 140, '00009', '2017-09-13 20:50:32'), (14, 141, '00013', '2017-09-15 11:34:33'), (15, 142, '00013', '2017-09-15 12:13:35'), (16, 143, '00013', '2017-09-15 13:18:54'), (17, 1, '00009', '2017-09-15 15:18:44'), (18, 85, '00007', '2017-09-15 15:29:12'), (19, 145, '00013', '2017-09-18 13:09:51'), (20, 146, '00009', '2017-09-18 13:18:04'), (21, 147, '00013', '2017-09-18 17:10:28'), (22, 148, '00013', '2017-09-19 15:06:06'), (23, 150, '00013', '2017-09-21 13:08:17'), (24, 151, '00005', '2017-09-22 13:42:25'), (25, 152, '00013', '2017-09-22 13:48:41'), (26, 153, '00013', '2017-09-22 17:29:33'), (27, 154, '00013', '2017-09-22 18:05:10'), (28, 159, '00009', '2017-09-23 20:02:48'), (29, 160, '00005', '2017-09-23 20:04:32'), (30, 161, '00007', '2017-09-23 20:09:35'), (31, 158, '00013', '2017-09-25 13:20:06'), (32, 163, '00012,00015', '2017-09-26 12:21:41'), (33, 164, '00001', '2017-09-26 13:22:11'), (34, 165, '00001', '2017-09-26 13:36:26'), (35, 166, '00013', '2017-09-26 13:39:00'), (36, 167, '00006', '2017-09-26 14:44:35'), (37, 168, '00006', '2017-09-26 14:45:39'), (38, 169, '00006', '2017-09-26 14:46:17'), (39, 173, '00006', '2017-09-26 14:50:34'), (40, 174, '00005', '2017-09-26 19:20:25'), (41, 175, '00006', '2017-09-26 19:46:46'), (42, 176, '00006', '2017-09-26 20:57:59'), (43, 177, '00006', '2017-09-27 15:24:44'), (44, 179, '00007', '2017-09-27 15:42:01'), (45, 178, '00007', '2017-09-27 15:42:21'), (46, 179, '00007,00006', '2017-09-27 15:51:37'), (47, 178, '00007,00006', '2017-09-27 15:51:53'), (48, 179, '00007,00008', '2017-09-27 15:52:26'), (49, 178, '00007,00008', '2017-09-27 15:52:42'), (50, 180, '00009', '2017-09-28 15:56:28'), (51, 182, '00013', '2017-09-29 13:36:34'), (52, 183, '00007,00008', '2017-09-29 15:58:19'), (53, 184, '00013', '2017-09-29 17:32:39'), (54, 188, '00013', '2017-10-03 13:22:04'), (55, 189, '00005', '2017-10-03 20:25:46'), (56, 190, '00006', '2017-10-04 14:34:43'), (57, 191, '00013', '2017-10-04 16:52:50'), (58, 192, '00005', '2017-10-04 17:27:42'), (59, 193, '00006', '2017-10-05 17:48:50'), (60, 194, '00013', '2017-10-05 18:41:30'), (61, 195, '00013', '2017-10-06 12:17:23'), (62, 196, '00005', '2017-10-07 21:32:38'), (63, 197, '00010', '2017-10-12 09:06:32'), (64, 198, '00013', '2017-10-12 17:34:50'), (65, 199, '00009', '2017-10-12 17:51:12'), (66, 201, '00014', '2017-10-16 13:51:21'), (67, 203, '00013', '2017-10-16 15:26:03'), (68, 204, '00005', '2017-10-16 17:43:19'), (69, 205, '00007', '2017-10-16 21:05:57'), (70, 206, '00001', '2017-10-17 12:32:46'), (71, 207, '00013', '2017-10-17 12:37:16'), (72, 208, '00006', '2017-10-17 16:22:55'), (73, 209, '00013', '2017-10-20 13:37:59'), (74, 210, '00013', '2017-10-23 12:10:46'), (75, 211, '00014', '2017-10-23 12:33:17'), (76, 212, '00008', '2017-10-23 16:33:24'), (77, 215, '00015', '2017-10-25 14:03:43'), (78, 216, '00015', '2017-10-25 15:17:05'), (79, 217, '00008', '2017-10-25 15:35:24'), (80, 218, '00013', '2017-10-25 15:36:48'), (81, 219, '00001', '2017-10-25 15:45:24'), (82, 220, '00001', '2017-10-25 16:18:50'), (83, 221, '00006', '2017-10-25 16:46:24'), (84, 222, '00008', '2017-10-27 12:15:18'), (85, 223, '00013', '2017-10-27 12:16:32'), (86, 224, '00015', '2017-10-27 13:10:10'), (87, 225, '00015', '2017-10-27 13:12:56'), (88, 226, '00009', '2017-10-27 13:19:00'), (89, 18, '00012', '2017-10-27 15:04:01'), (90, 228, '00005', '2017-10-28 12:25:20'), (91, 229, '00013', '2017-10-28 15:14:29'), (92, 230, '00001', '2017-10-31 12:51:59'), (93, 231, '00015', '2017-10-31 13:22:13'), (94, 232, '00015', '2017-10-31 13:23:04'), (95, 233, '00015', '2017-10-31 13:23:59'), (96, 234, '00015', '2017-10-31 13:25:04'), (97, 235, '00013', '2017-10-31 16:17:45'), (98, 236, '00014', '2017-10-31 18:15:45'), (99, 237, '00008', '2017-10-31 20:24:33'), (100, 238, '00015', '2017-11-01 14:39:08'), (101, 239, '00013', '2017-11-01 14:43:13'), (102, 240, '00006', '2017-11-03 15:26:02'), (103, 241, '00015', '2017-11-03 15:31:44'), (104, 242, '00013', '2017-11-04 12:16:05'), (105, 243, '00013', '2017-11-06 12:35:03'), (106, 244, '00014', '2017-11-06 18:13:15'), (107, 245, '00014', '2017-11-07 13:40:24'), (108, 246, '00013', '2017-11-07 13:41:27'), (109, 247, '00013', '2017-11-08 15:09:00'), (110, 248, '00009', '2017-11-08 16:53:07'), (111, 249, '00005', '2017-11-09 13:24:25'), (112, 250, '00005', '2017-11-09 15:02:13'), (113, 251, '00013', '2017-11-10 12:56:55'), (114, 252, '00013', '2017-11-10 12:57:35'), (115, 253, '00001', '2017-11-10 13:12:40'), (116, 254, '00013', '2017-11-15 14:25:06'), (117, 255, '00013', '2017-11-15 14:25:53'), (118, 257, '00015', '2017-11-16 13:49:51'), (119, 259, '00007', '2017-11-20 01:33:48'), (120, 260, '00009', '2017-11-21 11:45:09'), (121, 261, '00009', '2017-11-29 17:10:03'), (122, 262, '00009', '2017-11-30 15:49:54'), (123, 263, '00005', '2017-12-05 13:29:56'), (124, 264, '00005', '2017-12-11 14:04:31'), (125, 265, '00014', '2017-12-11 17:38:29'), (126, 266, '00009', '2017-12-13 13:42:48'), (127, 268, '00009', '2017-12-13 13:45:03'), (128, 267, '00014', '2017-12-13 13:48:27'), (129, 269, '00005', '2017-12-14 13:56:20'), (130, 270, '00013', '2017-12-14 14:06:04'), (131, 271, '00013', '2017-12-14 17:27:25'), (132, 272, '00013', '2017-12-15 12:23:56'), (133, 273, '00007,00008', '2017-12-15 12:57:25'), (134, 274, '00006', '2017-12-15 14:01:45'), (135, 275, '00013', '2017-12-15 17:28:52'), (136, 276, '00013', '2017-12-16 12:43:47'), (137, 278, '00013', '2017-12-16 14:32:23'), (138, 280, '00013', '2017-12-18 13:37:13'), (139, 281, '00013', '2017-12-19 12:53:16'), (140, 282, '00015', '2017-12-19 13:12:54'), (141, 283, '00015', '2017-12-19 13:13:34'), (142, 284, '00015', '2017-12-19 13:23:10'), (143, 285, '00015', '2017-12-19 13:24:09'), (144, 284, '00012,00015', '2017-12-20 13:05:38'), (145, 287, '00001,00025', '2017-12-20 14:52:38'), (146, 289, '00018', '2017-12-30 10:48:29'), (147, 290, '00026', '2018-02-08 13:31:53'), (148, 291, '00026', '2018-02-08 17:13:41'), (149, 292, '00026', '2018-02-13 16:40:13'), (150, 293, '00026', '2018-02-13 18:18:34'), (151, 294, '00026', '2018-02-13 18:23:59'), (152, 295, '00027', '2018-02-14 10:25:30'), (153, 296, '00026', '2018-02-14 14:11:43'), (154, 297, '00027', '2018-02-14 15:18:18'), (155, 298, '00026', '2018-02-14 16:29:59'), (156, 299, '00011', '2018-07-02 11:18:33'), (157, 300, '00027', '2018-07-02 11:41:26'), (158, 301, '00027', '2018-07-02 11:45:06'), (159, 302, '00011', '2018-07-02 11:53:02'), (160, 303, '00013', '2018-07-02 12:01:26'), (161, 304, '00026', '2018-07-02 12:08:40'), (162, 305, '00026', '2018-07-02 12:17:48'), (163, 306, '00027', '2018-07-02 12:18:25'), (164, 307, '00026', '2018-07-03 14:43:28'), (165, 313, '00018', '2018-10-10 11:07:05'), (166, 314, '00018', '2018-10-10 11:29:04'); -- -------------------------------------------------------- -- -- Table structure for table `log_service_payment_details` -- CREATE TABLE IF NOT EXISTS `log_service_payment_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` int(11) NOT NULL, `cmr_paid` int(11) NOT NULL, `payment_mode` varchar(100) NOT NULL, `pending_amt` int(10) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `log_service_payment_details` -- INSERT INTO `log_service_payment_details` (`id`, `req_id`, `cmr_paid`, `payment_mode`, `pending_amt`, `updated_on`, `user_id`) VALUES (1, 290, 111, '', 787, '2018-02-08 16:47:51', 1); -- -------------------------------------------------------- -- -- Table structure for table `log_stamping` -- CREATE TABLE IF NOT EXISTS `log_stamping` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `stamping_id` int(10) NOT NULL, `cmr_paid` int(10) NOT NULL, `payment_mode` varchar(50) NOT NULL, `pending_amt` int(10) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE IF NOT EXISTS `orders` ( `id` int(10) NOT NULL AUTO_INCREMENT, `order_id` int(6) unsigned zerofill NOT NULL, `customer_id` int(10) NOT NULL, `mobile` varchar(50) NOT NULL, `email_id` varchar(50) NOT NULL, `address` varchar(250) NOT NULL, `city` varchar(100) NOT NULL, `state` varchar(100) NOT NULL, `pincode` int(10) NOT NULL, `status` varchar(50) NOT NULL, `purchase_date` varchar(50) NOT NULL, `sub_total` double NOT NULL, `disc` int(11) NOT NULL, `grand_total` double NOT NULL, `amt_paid` int(11) NOT NULL, `amt_pending` int(11) NOT NULL, `created_on` varchar(50) NOT NULL, `updated_on` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; -- -- Dumping data for table `orders` -- INSERT INTO `orders` (`id`, `order_id`, `customer_id`, `mobile`, `email_id`, `address`, `city`, `state`, `pincode`, `status`, `purchase_date`, `sub_total`, `disc`, `grand_total`, `amt_paid`, `amt_pending`, `created_on`, `updated_on`) VALUES (1, 000001, 2, '9840289188', '', 'No.21 Palavanthangal', 'Coimbatore', 'Tamil Nadu', 600054, '', '2018-10-15 15:05', 212, 20, 192, 130, 50, '2018-10-16 11:37:11', '2018-10-16 11:37:11'), (2, 000002, 5, '9988776333', '', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-10-17 15:54', 240, 10, 216, 216, 0, '2018-10-17 15:58:49', '2018-10-17 15:58:49'), (3, 000003, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-10-17 16:53', 2882, 10, 2594, 0, 2594, '2018-10-17 16:56:31', '2018-10-17 16:56:31'), (4, 000004, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-10-17 17:06', 270, 0, 270, 0, 270, '2018-10-17 17:07:11', '2018-10-17 17:07:11'), (5, 000005, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:52', 21, 0, 21, 0, 21, '2018-12-22 22:52:20', '2018-12-22 22:52:20'), (6, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 22:54:52', '2018-12-22 22:54:52'), (7, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 22:58:35', '2018-12-22 22:58:35'), (8, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 22:59:11', '2018-12-22 22:59:11'), (9, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 23:01:34', '2018-12-22 23:01:34'), (10, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 23:02:30', '2018-12-22 23:02:30'), (11, 000006, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 22:54', 903, 0, 903, 0, 903, '2018-12-22 23:03:58', '2018-12-22 23:03:58'), (12, 000007, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 23:04', 4000, 0, 4000, 0, 4000, '2018-12-22 23:04:37', '2018-12-22 23:04:37'), (13, 000008, 5, '9988776333', '<EMAIL>', 'No.12 Test Address', 'Chennai', 'Tamil Nadu', 500012, '', '2018-12-22 23:31', 66, 0, 66, 0, 66, '2018-12-22 23:32:13', '2018-12-22 23:32:13'); -- -------------------------------------------------------- -- -- Table structure for table `order_details` -- CREATE TABLE IF NOT EXISTS `order_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `order_id` varchar(50) NOT NULL, `p_name` int(50) NOT NULL, `qty` int(11) NOT NULL, `price` double NOT NULL, `sub_total` double NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ; -- -- Dumping data for table `order_details` -- INSERT INTO `order_details` (`id`, `order_id`, `p_name`, `qty`, `price`, `sub_total`) VALUES (1, '1', 0, 2, 100, 200), (2, '1', 0, 1, 12, 12), (3, '2', 0, 2, 120, 240), (4, '3', 0, 22, 20, 440), (5, '3', 0, 11, 222, 2442), (6, '4', 0, 2, 12, 24), (7, '4', 0, 2, 123, 246), (8, '5', 15, 1, 21, 21), (9, '6', 15, 43, 21, 903), (10, '7', 15, 43, 21, 903), (11, '8', 15, 43, 21, 903), (12, '9', 15, 43, 21, 903), (13, '10', 15, 43, 21, 903), (14, '11', 15, 43, 21, 903), (15, '12', 15, 20, 200, 4000), (16, '13', 15, 2, 21, 42), (17, '13', 14, 2, 12, 24); -- -------------------------------------------------------- -- -- Table structure for table `petty_log` -- CREATE TABLE IF NOT EXISTS `petty_log` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_id` int(30) NOT NULL, `qty_plus` int(30) NOT NULL, `employee` int(30) NOT NULL, `status` int(30) NOT NULL, `todaydate` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ; -- -- Dumping data for table `petty_log` -- INSERT INTO `petty_log` (`id`, `spare_id`, `qty_plus`, `employee`, `status`, `todaydate`) VALUES (1, 1, 0, 0, 2, '18-09-2017 13:57:20'), (2, 1, 0, 0, 2, '18-09-2017 13:57:26'), (3, 156, 0, 0, 2, '18-09-2017 13:57:35'), (4, 277, 0, 15, 2, '31-10-2017 15:34:42'), (5, 277, 0, 15, 2, '31-10-2017 15:34:55'), (6, 1, 50, 18, 1, '29-12-2017 17:14:59'), (7, 82, 0, 18, 2, '29-12-2017 17:16:40'), (8, 82, 30, 18, 1, '29-12-2017 17:16:49'), (9, 305, 20, 18, 1, '29-12-2017 17:28:17'), (10, 60, 20, 18, 1, '29-12-2017 17:28:51'), (11, 82, 20, 18, 1, '29-12-2017 17:29:28'), (12, 74, 5, 18, 1, '30-12-2017 10:51:09'), (13, 0, 0, 0, 2, '08-02-2018 11:49:18'), (14, 0, 0, 0, 2, '08-02-2018 11:55:30'), (15, 0, 0, 0, 2, '08-02-2018 11:55:56'), (16, 0, 0, 0, 2, '08-02-2018 12:14:27'), (17, 0, 0, 0, 2, '08-02-2018 12:15:21'), (18, 0, 0, 0, 2, '08-02-2018 16:38:24'), (19, 0, 0, 0, 2, '08-02-2018 16:38:35'), (20, 0, 0, 0, 2, '08-02-2018 18:22:30'), (21, 0, 0, 0, 2, '08-02-2018 18:22:54'), (22, 0, 0, 0, 2, '08-02-2018 18:25:17'), (23, 0, 0, 0, 2, '08-02-2018 18:25:20'), (24, 0, 0, 0, 2, '08-02-2018 18:25:51'), (25, 0, 0, 0, 2, '08-02-2018 18:27:34'), (26, 0, 0, 0, 2, '08-02-2018 18:27:46'), (27, 0, 0, 0, 2, '08-02-2018 18:28:30'), (28, 307, 1, 26, 1, '09-02-2018 10:39:48'), (29, 6, 0, 4, 2, '09-02-2018 10:43:14'), (30, 6, 1, 4, 1, '09-02-2018 10:43:34'), (31, 308, 7, 27, 1, '14-02-2018 10:22:18'), (32, 308, 2, 27, 1, '14-02-2018 11:55:28'), (33, 309, 2, 27, 1, '14-02-2018 15:11:02'), (34, 310, 2, 26, 1, '14-02-2018 16:22:57'); -- -------------------------------------------------------- -- -- Table structure for table `petty_spare` -- CREATE TABLE IF NOT EXISTS `petty_spare` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_id` int(255) NOT NULL, `qty_plus` int(255) NOT NULL, `employee` int(255) NOT NULL, `todaydate` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Dumping data for table `petty_spare` -- INSERT INTO `petty_spare` (`id`, `spare_id`, `qty_plus`, `employee`, `todaydate`) VALUES (1, 1, 0, 0, '18-09-2017 13:57:20'), (2, 156, 0, 0, '18-09-2017 13:57:35'), (3, 277, 0, 15, '31-10-2017 15:34:42'), (4, 262, 1, 1, '2017-11-16'), (5, 1, 50, 18, '29-12-2017 17:14:59'), (6, 82, 54, 18, '29-12-2017 17:16:40'), (7, 305, 24, 18, '29-12-2017 17:28:17'), (8, 60, 23, 18, '29-12-2017 17:28:51'), (9, 74, 11, 18, '30-12-2017 10:51:09'), (10, 0, 0, 0, '08-02-2018 11:49:18'), (11, 307, 3, 26, '09-02-2018 10:39:48'), (12, 6, 1, 4, '09-02-2018 10:43:14'), (13, 308, 11, 27, '14-02-2018 10:22:18'), (14, 309, 2, 27, '14-02-2018 15:11:02'), (15, 310, 4, 26, '14-02-2018 16:22:57'); -- -------------------------------------------------------- -- -- Table structure for table `preventive_log` -- CREATE TABLE IF NOT EXISTS `preventive_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `prev_main_alert` varchar(100) NOT NULL, `orderid` varchar(50) NOT NULL, `date_updated` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `preventive_log` -- INSERT INTO `preventive_log` (`id`, `prev_main_alert`, `orderid`, `date_updated`) VALUES (1, '2017-08-05', '3481', '2017-08-05'), (2, '2017-08-05', '3481', '2017-08-05'); -- -------------------------------------------------------- -- -- Table structure for table `preventive_maintenance_alerts` -- CREATE TABLE IF NOT EXISTS `preventive_maintenance_alerts` ( `id` int(10) NOT NULL AUTO_INCREMENT, `order_id` int(10) NOT NULL, `schedule_date` varchar(50) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=101 ; -- -- Dumping data for table `preventive_maintenance_alerts` -- INSERT INTO `preventive_maintenance_alerts` (`id`, `order_id`, `schedule_date`, `status`) VALUES (1, 4, '2017-12-22', 1), (2, 174, '2017-07-29', 0), (3, 207, '2017-09-23', 1), (4, 173, '2017-09-23', 1), (5, 172, '2017-09-21', 0), (6, 200, '2017-07-15', 0), (7, 190, '2017-08-04', 0), (8, 189, '2017-08-19', 0), (9, 209, '2017-08-18', 0), (10, 251, '2017-08-19', 0), (11, 18, '2017-07-12', 0), (12, 22, '2017-07-19', 0), (13, 97, '2017-08-10', 0), (14, 110, '2017-08-28', 0), (15, 73, '2017-08-10', 0), (16, 87, '2017-07-03', 0), (17, 78, '2017-07-31', 0), (18, 88, '2017-07-18', 0), (19, 7, '2017-08-22', 0), (20, 462, '2018-03-18', 0), (21, 65, '2017-09-26', 1), (22, 194, '2017-09-26', 0), (23, 196, '2017-09-27', 1), (24, 195, '2017-09-27', 1), (25, 221, '2017-09-28', 1), (26, 463, '2017-08-08', 0), (27, 464, '', 0), (28, 465, '', 0), (29, 466, '2017-08-01', 0), (30, 467, '', 0), (31, 468, '2018-10-15', 0), (32, 185, '2017-10-16', 1), (33, 77, '2017-10-17', 1), (34, 469, '2018-09-24', 0), (35, 470, '2018-10-16', 0), (36, 43, '2017-10-24', 0), (37, 471, '2018-10-22', 0), (38, 472, '2017-10-24', 0), (39, 473, '', 0), (40, 474, '', 0), (41, 475, '2018-10-23', 0), (42, 476, '2018-10-23', 0), (43, 477, '', 0), (44, 478, '', 0), (45, 479, '2017-12-19', 1), (46, 480, '', 0), (47, 245, '', 0), (48, 150, '', 0), (49, 75, '', 0), (50, 171, '2017-10-14', 0), (51, 481, '', 0), (52, 482, '', 0), (53, 483, '', 0), (54, 484, '', 0), (55, 485, '', 0), (56, 486, '', 0), (57, 487, '', 0), (58, 175, '2017-10-31', 0), (59, 488, '', 0), (60, 489, '', 0), (61, 490, '', 0), (62, 491, '', 0), (63, 492, '', 0), (64, 179, '2017-11-09', 0), (65, 191, '', 0), (66, 184, '', 0), (67, 493, '', 0), (68, 494, '', 0), (69, 210, '2017-05-22', 0), (70, 210, '', 0), (71, 495, '2017-11-16', 1), (72, 5, '2017-11-17', 0), (73, 496, '', 0), (74, 177, '2017-11-20', 1), (75, 497, '', 0), (76, 498, '', 0), (77, 176, '2017-11-18', 0), (78, 178, '2017-11-22', 0), (79, 246, '2017-11-30', 1), (80, 499, '', 0), (81, 500, '2018-05-27', 0), (82, 229, '2017-12-13', 1), (83, 228, '2017-12-13', 1), (84, 501, '', 0), (85, 502, '', 0), (86, 503, '', 0), (87, 6, '2017-12-23', 1), (88, 504, '', 0), (89, 505, '', 0), (90, 506, '', 0), (91, 507, '2017-12-16', 0), (92, 508, '', 0), (93, 4, '2017-12-31', 1), (94, 4, '2017-12-30', 0), (95, 509, '2017-12-30', 0), (96, 510, '2018-02-08', 0), (97, 529, '2018-02-14', 0), (98, 530, '2018-02-14', 0), (99, 531, '2018-02-14', 0), (100, 532, '', 0); -- -------------------------------------------------------- -- -- Table structure for table `problem_category` -- CREATE TABLE IF NOT EXISTS `problem_category` ( `id` int(10) NOT NULL AUTO_INCREMENT, `prob_category` varchar(100) NOT NULL, `model` varchar(100) NOT NULL, `prob_code` varchar(50) NOT NULL, `prob_description` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=196 ; -- -- Dumping data for table `problem_category` -- INSERT INTO `problem_category` (`id`, `prob_category`, `model`, `prob_code`, `prob_description`) VALUES (7, 'multifunction board required', '3', '', ''), (8, 'PREVENTIVE ', '5', '', ''), (9, 'PHOTO METRIC CALIBRATION NOT DONE', '5', '', ''), (10, '03.05.03 initialization waiting for carousel initialization time out', '3', '', ''), (16, 'shuttle missing', '4', '', ''), (17, '50102 Cleaner Solution Empty Unable to fill buffer vial. Fluidic circuit busy during 30 sec. ', '3', '', ''), (19, 'SHUTTLE ERROR', '4', '', ''), (22, 'showing error BREAKOFF VERSION 1.0', '4', '', ''), (23, 'CTRL BREAK DESACTIVE', '4', '', ''), (24, 'Printer problem', '1', '', ''), (25, 'RINSING TIME OUT ', '3', '', ''), (37, 'not identified', '4', '', ''), (38, 'All results out of range', '4', '', ''), (39, 'Reagent volume ', '3', '', ''), (40, 'NRF error', '4', '', ''), (41, 'not recived aknowledgement', '4', '', ''), (43, 'DESORB U MISSING BY NEEDLE 3', '4', '', ''), (44, 'Test category one', '4', '00001', 'test category description'), (45, 'test category two', '5', '00002', 'test category two'), (46, 'test category three', '8', '00003', 'test category three'), (47, 'test category four', '3', '00004', 'test category four'), (48, 'test category five', '3', '00005', 'test category five'), (49, 'test category six', '4', '00006', 'test category six'), (50, 'test category seven', '3', '00007', 'test category seven'), (55, 'dddddddd', '5', 'dddddddddd', 'ddddddddddddd'), (56, 'bbbbbbbbbb', '3', 'bbbbbbbbb', 'bbbbbbbbbbbbb'), (57, 'sssssssss', '6', 'ssssss', 'sssss'), (58, 'wwwwwwww', '5', 'wwwwww', 'wwwwwwwwwwwwww'), (59, 'xxxxxxxxxx', '6', 'xxxxxx', 'xxxxxxx'), (60, '', '4', '', ''), (61, 'Reagent volume missing', '3', '', ''), (62, '', '5', '', ''), (63, 'results issue', '1', '', ''), (64, '', '1', '', ''), (65, 'ERROR 02.02.04 RINSING FAILURE TO CHECK PDR HOME POSITION', '3', '', ''), (66, '', '3', '', ''), (67, 'ERROR 12.01.10 CHECKING PHOTOMETRIC MODULE PHOTOMETRIC STATUS WRONG PS 402222 ', '3', '', ''), (68, '', '6', '', ''), (69, '03.05.03 INITIALIZATION WAITING TIME OUT', '3', '', ''), (70, 'printer', '1', '', ''), (71, 'Preventive Maintenance Visit', '9', '', ''), (72, 'Calibration over due', '1', '', ''), (73, 'Product Drawer Temperature is around 23deg.Instrument shown alarm', '4', '', ''), (74, 'ERROR 01.06.00 VACUUM RESIERVOIR INSUFFICIENT VACUUM', '4', '', ''), (75, '', '7', '', ''), (76, 'Error-"rinsing unable to depressurize the rinsing system timeout.', '3', '', ''), (77, 'Reagent Drawer Temperature out of limit', '4', '', ''), (78, 'PRINTING PROBLEM', '4', '', ''), (79, 'FACTOR VII CAL PROBLEM', '5', '', ''), (80, 'ERROR 02.02.19 RINSING UNABLE TO DEPRESSURIZE THE RINSING SYSTEM TIME OUT', '3', '', ''), (81, 'DISPLAY REMAIN BLACK', '3', '', ''), (82, '', '8', '', ''), (83, 'Printing issue paper got stuck', '3', '', ''), (84, 'Operating system loading screen stuck', '6', '', ''), (85, 'n1', '4', '', ''), (86, 'n2 bended during sample run', '4', '', ''), (87, 'QNS error&ball movement is too low', '3', '', ''), (88, 'while running samples during measurement it couldnt dispense starter reagent', '3', '', ''), (89, 'AMBIENT TEMPERATURE OUT OF RANGE', '4', '', ''), (90, 'x axis belt tooth damaged', '4', '', ''), (91, 'dispensing samples problem', '4', '', ''), (92, 'APTT results are going in Higher Side', '1', '', ''), (93, 'Position F1 not detected drawer Jam error frequently', '4', '', ''), (94, 'Sample draw home sensor', '4', '', ''), (95, 'Used liquid container maximum error', '4', '', ''), (96, 'Vacuum reservoir insufficient vacuum', '4', '', ''), (97, 'APTT results problem', '4', '', ''), (98, 'Product drawer temperature is high', '4', '', ''), (99, 'DRVV product loading issues &pt aptt control out', '3', '', ''), (100, 'error 11.08.05 chromogenic optical motor is too low', '4', '', ''), (101, 'error 02.02.02 rinsing moving zaxis into well time out', '3', '', ''), (102, 'sample drawer jammed', '4', '', ''), (103, 'PM&CAL', '1', '', ''), (104, 'status nRx error', '4', '', ''), (105, 'Error 07.01.12 Uncompleted axis Y Movement', '4', '', ''), (106, 'PRINTER NOT WORKING', '1', '', ''), (107, 'ERROR 03.05.03 INITIALIZATION FOR CAROUSEL.INITIALIZATION TIME OUT', '3', '', ''), (108, 'issue with FVIII cal and also PT sample comparison is not ok with backup instrument', '5', '', ''), (109, 'product carousel missing', '3', '', ''), (110, 'error 10.09.03 cuvette management', '3', '', ''), (111, 'keypad issue', '1', '', ''), (112, 'error 10.05.01', '3', '', ''), (113, 'Instrument not started properly', '4', '', ''), (114, 'product carousel initialization failure', '3', '', ''), (115, 'factor viii qc is in lower side', '4', '', ''), (116, 'QC out of range', '3', '', ''), (117, 'ball movement too low', '3', '', ''), (118, 'cuvette missing', '5', '', ''), (119, 'NO 9 position in product drawer is blinking always.', '4', '', ''), (120, 'PROBLEM WITH BIDIRECTIONAL INTERFACE', '6', '', ''), (121, 'need modification in drvv program', '3', '', ''), (122, 'Fib Qc is in higher side', '6', '', ''), (123, 'Needle no 1 must be bended', '6', '', ''), (124, 'for adding TT progam', '4', '', ''), (125, 'aptt results and controls are in higher side', '3', '', ''), (126, 'aptt results/controls are in high side', '3', '', ''), (127, 'to prepare fvii program', '4', '', ''), (128, 'to make fvii program', '4', '', ''), (129, 'problem with thrombotic panel', '4', '', ''), (130, 'LIS problem', '2', '', ''), (131, 'error 03.01.06', '3', '', ''), (132, 'error 05.17.01', '3', '', ''), (133, 'unable to fill buffer', '3', '', ''), (134, 'NEEDLE BENDED', '4', '', ''), (135, 'needle hitting in reagent vial corner', '3', '', ''), (136, 'pc ps test and calibration', '3', '', ''), (137, 'temperature out of range', '4', '', ''), (138, 'ddi control out of range', '4', '', ''), (139, 'fib control lower side within range', '4', '', ''), (140, 'syringe maintenance over due', '5', '', ''), (141, 'N3 BEND', '4', '', ''), (142, 'ambient tempertaure out of range', '5', '', ''), (143, 'PS and ATIII calibration and test', '3', '', ''), (144, 'error 02.02.01 rinsing', '3', '', ''), (145, 'movinf z axis into well time out', '3', '', ''), (146, 'Routine maintenance', '4', '', ''), (147, 'MAINTENANCE', '4', '', ''), (148, 'suction not operating correctly', '6', '', ''), (149, 'cooling liquid pump stuck', '4', '', ''), (150, 'decontamination and cleaning', '3', '', ''), (151, 'error 10.04.02 cuvette adjustment', '3', '', ''), (152, 'error 02.00.08 arm initialization', '3', '', ''), (153, 'instrument is in sleeping mode', '3', '', ''), (154, 'QC results are in higher side', '1', '', ''), (155, 'technical error in sample tube due to LLD issue', '4', '', ''), (156, 'contamination issue with PT LOT .They want other lot replacementt', '4', '', ''), (157, 'NEEDLE STUCK IN WELL', '4', '', ''), (158, 'REAGENT NOT TAKING', '6', '', ''), (159, 'printer paper stuck', '1', '', ''), (160, 'for running FVIII ', '2', '', ''), (161, 'FIB', '2', '', ''), (162, 'temperature out of range ', '3', '', ''), (163, 'LIS CONNECTION CHECK', '3', '', ''), (164, 'LLD issue with Cephascreen vial', '3', '', ''), (165, '02.12.00 SHUTTLE MISSING', '5', '', ''), (166, 'error 02.03.29 sample suction', '3', '', ''), (167, 'liquid suction at the bottom of tube.', '3', '', ''), (168, 'PS&PC result in higher side', '4', '', ''), (169, 'needle n3 broken', '6', '', ''), (170, 'CALIBRATION', '5', '', ''), (171, 'CALIBRATION', '4', '', ''), (172, 'ROUTINE MONTLY MAINTENANCE', '6', '', ''), (173, 'error cuvette missing', '5', '', ''), (174, 'while running in measurement chamner got error ', '2', '', ''), (175, 'low curve program for fviii and normal program fviii & ix', '4', '', ''), (176, 'to run equas', '6', '', ''), (177, 'TO RUN PC PS TEST', '6', '', ''), (178, 'product drawer jam...', '4', '', ''), (179, 'error during test run', '2', '', ''), (180, 'system error', '6', '', ''), (181, 'New site verification', '4', '', ''), (182, 'after sample loading the status screen is not appearing', '4', '', ''), (183, 'temp at pipetting tip out of limit', '4', '', ''), (184, 'product and incubation temperature is out of range', '4', '', ''), (185, 'routine maintenance', '6', '', ''), (186, 'routine maintenance and also to run LIQ FIB cal', '4', '', ''), (187, 'vacuum reservoir empty error', '4', '', ''), (188, '', '2', '', ''), (189, 'shuttle missing', '6', '', ''), (190, 'calibration issue', '2', '', ''), (191, 'sfsa', '4', 'dssfs', 'fdsafsaf'), (192, 'multifunction board required', '6', '', ''), (193, 'test category three', '12', '', ''), (194, '', '12', '', ''), (195, '', 'multiple', '', ''); -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE IF NOT EXISTS `products` ( `id` int(10) NOT NULL AUTO_INCREMENT, `category` int(10) NOT NULL, `subcategory` int(10) NOT NULL, `model` varchar(100) NOT NULL, `stock_qty` int(50) NOT NULL, `used_qty` int(50) NOT NULL, `description` varchar(250) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `category`, `subcategory`, `model`, `stock_qty`, `used_qty`, `description`, `status`) VALUES (1, 2, 2, 'Start 4', 0, 0, '', 0), (2, 2, 2, 'Start Max', 0, 0, '', 0), (3, 1, 1, 'STA Satellite', 0, 0, '', 0), (4, 1, 1, 'STA Compact', 0, 0, '', 1), (5, 1, 1, 'STA Compact Max', 0, 0, '', 1), (6, 1, 1, 'STA Compact Max2', 0, 0, '', 0), (7, 1, 1, 'STA-R ', 0, 0, '', 0), (8, 1, 1, 'STA-R EVOLUTION', 0, 0, '', 0), (9, 1, 1, 'STA-R MAX', 0, 0, '', 0), (10, 1, 1, 'prince1', 0, 0, 'afdasfdsafdasfsaf', 0), (11, 1, 1, 'sudar', 0, 0, 'afdafdasfas', 0), (12, 1, 1, 'generals', 0, 0, 'asfasfsafsa', 0), (13, 1, 1, 'havels', 0, 0, 'havesl', 0), (14, 1, 1, 'c123', 10, 2, 'aasfas', 0), (15, 1, 1, 'Product sample11', 508, 22, 'dfsdf fdsf dsfdfgdsf df dsf tttttbnbvnbv', 0), (16, 4, 3, 'dfdsfdsfdsfds', 22, 0, 'dsfdsf', 0); -- -------------------------------------------------------- -- -- Table structure for table `prod_category` -- CREATE TABLE IF NOT EXISTS `prod_category` ( `id` int(10) NOT NULL AUTO_INCREMENT, `product_category` varchar(100) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `prod_category` -- INSERT INTO `prod_category` (`id`, `product_category`, `status`) VALUES (1, 'Fully Automated Coagulation Analyzer', 0), (2, 'Semi Automated Coagulation Analyzer', 0), (3, 'test', 0), (4, 'ffff', 0); -- -------------------------------------------------------- -- -- Table structure for table `prod_subcategory` -- CREATE TABLE IF NOT EXISTS `prod_subcategory` ( `id` int(10) NOT NULL AUTO_INCREMENT, `prod_category_id` int(10) NOT NULL, `subcat_name` varchar(100) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `prod_subcategory` -- INSERT INTO `prod_subcategory` (`id`, `prod_category_id`, `subcat_name`, `status`) VALUES (1, 1, 'COAGULATION', 0), (2, 2, 'COAGULATION', 0), (3, 4, 'ddd', 0); -- -------------------------------------------------------- -- -- Table structure for table `purchase_orders` -- CREATE TABLE IF NOT EXISTS `purchase_orders` ( `id` int(10) NOT NULL AUTO_INCREMENT, `to_name` varchar(100) NOT NULL, `to_addr` varchar(500) NOT NULL, `to_cont_name` varchar(100) NOT NULL, `to_cont_no` varchar(100) NOT NULL, `to_cont_mail` varchar(100) NOT NULL, `todaydate` varchar(100) NOT NULL, `refno` varchar(100) NOT NULL, `cst_no` varchar(100) NOT NULL, `basicamount` int(50) NOT NULL, `cst` varchar(100) NOT NULL, `tax_id` int(10) NOT NULL, `freight` int(50) NOT NULL, `totalamount` int(50) NOT NULL, `spec_addr` varchar(500) NOT NULL, `spec_ins` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `purchase_orders` -- INSERT INTO `purchase_orders` (`id`, `to_name`, `to_addr`, `to_cont_name`, `to_cont_no`, `to_cont_mail`, `todaydate`, `refno`, `cst_no`, `basicamount`, `cst`, `tax_id`, `freight`, `totalamount`, `spec_addr`, `spec_ins`) VALUES (1, '', '', '', '', '', '24-08-2017 12:19:16', '', '', 0, '', 1, 0, 0, '', ''); -- -------------------------------------------------------- -- -- Table structure for table `purchase_order_details` -- CREATE TABLE IF NOT EXISTS `purchase_order_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `purchase_order_id` int(10) NOT NULL, `sr_no` varchar(100) NOT NULL, `spare_name` int(10) NOT NULL, `spare_qty` int(10) NOT NULL, `rate` int(20) NOT NULL, `spare_tot` int(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `purchase_order_details` -- INSERT INTO `purchase_order_details` (`id`, `purchase_order_id`, `sr_no`, `spare_name`, `spare_qty`, `rate`, `spare_tot`) VALUES (1, 1, '', 0, 0, 0, 0), (2, 1, '', 9, 0, 0, 0), (3, 1, '', 0, 0, 0, 0), (4, 1, '', 0, 0, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `qc_masters` -- CREATE TABLE IF NOT EXISTS `qc_masters` ( `id` int(10) NOT NULL AUTO_INCREMENT, `model` int(10) NOT NULL, `qc_param` varchar(100) NOT NULL, `qc_value` varchar(100) NOT NULL, `created_on` varchar(50) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `qc_masters` -- INSERT INTO `qc_masters` (`id`, `model`, `qc_param`, `qc_value`, `created_on`, `updated_on`, `user_id`) VALUES (1, 3, 'PT', '12.7', '2017-06-08 15:53:10', '2017-06-08 15:53:10', 1), (2, 5, 'PT', '', '2017-07-22 13:28:59', '2017-07-22 13:28:59', 1), (3, 5, 'APTT', '', '2017-07-22 13:28:59', '2017-07-22 13:28:59', 1), (4, 5, 'FIB', '', '2017-07-22 13:28:59', '2017-07-22 13:28:59', 1), (5, 5, 'D-DI', '', '2017-07-22 13:28:59', '2017-07-22 13:28:59', 1); -- -------------------------------------------------------- -- -- Table structure for table `qc_parameters_details` -- CREATE TABLE IF NOT EXISTS `qc_parameters_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `request_id` int(50) NOT NULL, `qc_master_id` int(10) NOT NULL, `result_qc_value` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=274 ; -- -- Dumping data for table `qc_parameters_details` -- INSERT INTO `qc_parameters_details` (`id`, `request_id`, `qc_master_id`, `result_qc_value`) VALUES (1, 17, 1, '13.0'), (3, 32, 1, ''), (6, 48, 1, ''), (7, 44, 1, ''), (10, 52, 1, '13.4'), (11, 53, 1, '13.4'), (12, 49, 1, ''), (13, 33, 2, ''), (14, 33, 3, ''), (15, 33, 4, ''), (16, 33, 5, ''), (17, 25, 2, ''), (18, 25, 3, ''), (19, 25, 4, ''), (20, 25, 5, ''), (26, 36, 2, '14.1'), (27, 36, 3, ''), (28, 36, 4, ''), (29, 36, 5, ''), (38, 82, 2, ''), (39, 82, 3, ''), (40, 82, 4, ''), (41, 82, 5, ''), (43, 87, 1, ''), (44, 50, 1, ''), (45, 54, 2, ''), (46, 54, 3, ''), (47, 54, 4, ''), (48, 54, 5, ''), (49, 91, 1, ''), (55, 108, 1, ''), (57, 106, 2, '15.8'), (58, 106, 3, '33.8'), (59, 106, 4, '226'), (60, 106, 5, ''), (63, 121, 1, ''), (76, 127, 1, ''), (84, 140, 2, ''), (85, 140, 3, ''), (86, 140, 4, ''), (87, 140, 5, ''), (88, 139, 1, ''), (89, 137, 1, ''), (104, 192, 1, ''), (113, 201, 2, ''), (114, 201, 3, ''), (115, 201, 4, ''), (116, 201, 5, ''), (121, 197, 2, ''), (122, 197, 3, ''), (123, 197, 4, ''), (124, 197, 5, ''), (125, 190, 1, ''), (126, 177, 1, '13.8'), (127, 176, 1, ''), (128, 165, 1, ''), (129, 164, 1, ''), (130, 151, 1, ''), (132, 206, 1, ''), (133, 136, 1, ''), (134, 132, 1, ''), (140, 161, 2, ''), (141, 161, 3, ''), (142, 161, 4, ''), (143, 161, 5, ''), (144, 220, 1, '13.7'), (145, 219, 1, ''), (146, 215, 1, ''), (147, 130, 1, ''), (148, 123, 2, ''), (149, 123, 3, ''), (150, 123, 4, ''), (151, 123, 5, ''), (152, 112, 1, ''), (153, 83, 1, ''), (154, 74, 1, ''), (156, 204, 1, ''), (165, 237, 1, ''), (166, 236, 2, ''), (167, 236, 3, ''), (168, 236, 4, ''), (169, 236, 5, ''), (170, 233, 1, ''), (171, 232, 1, ''), (172, 230, 1, ''), (174, 238, 1, ''), (179, 244, 2, '13.7/22.8'), (180, 244, 3, '31.6/51.0'), (181, 244, 4, ''), (182, 244, 5, ''), (185, 118, 1, ''), (186, 84, 1, ''), (191, 248, 2, ''), (192, 248, 3, ''), (193, 248, 4, ''), (194, 248, 5, ''), (196, 253, 1, ''), (205, 261, 2, ''), (206, 261, 3, ''), (207, 261, 4, ''), (208, 261, 5, ''), (209, 260, 2, ''), (210, 260, 3, ''), (211, 260, 4, ''), (212, 260, 5, ''), (214, 269, 1, ''), (267, 291, 2, ''), (268, 291, 3, ''), (269, 291, 4, ''), (270, 291, 5, ''), (273, 298, 1, ''); -- -------------------------------------------------------- -- -- Table structure for table `quote_review` -- CREATE TABLE IF NOT EXISTS `quote_review` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` int(10) NOT NULL, `model_id` int(10) NOT NULL, `spare_tax` float NOT NULL, `spare_tot` int(10) NOT NULL, `labourcharge` int(10) NOT NULL, `concharge` int(10) NOT NULL, `total_charge` int(10) NOT NULL, `total_amt` int(10) NOT NULL, `disc_amt` int(10) NOT NULL, `plus_amt` int(10) NOT NULL, `pending_amt` int(50) NOT NULL, `cmr_paid` int(50) NOT NULL, `payment_mode` varchar(100) NOT NULL, `delivery_date` varchar(100) NOT NULL, `comments` varchar(250) NOT NULL, `assign_to` int(10) NOT NULL, `notes` varchar(500) NOT NULL, `eng_notes` varchar(500) NOT NULL, `cust_remark` varchar(500) NOT NULL, `rating` int(10) NOT NULL, `cust_feed` varchar(500) NOT NULL, `emp_pts` double NOT NULL, `eng_ack` varchar(100) NOT NULL, `created_on` varchar(50) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, `onhold_date` varchar(50) NOT NULL, `onhold_reason` varchar(500) NOT NULL, `warranty_mode` varchar(50) NOT NULL, `code_no` varchar(50) NOT NULL, `code_date` varchar(50) NOT NULL, `status` varchar(100) NOT NULL, `cust_solution` varchar(500) NOT NULL, `notes_all` varchar(30) NOT NULL, `eng_notes_sol` varchar(500) NOT NULL, `eng_notess` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=251 ; -- -- Dumping data for table `quote_review` -- INSERT INTO `quote_review` (`id`, `req_id`, `model_id`, `spare_tax`, `spare_tot`, `labourcharge`, `concharge`, `total_charge`, `total_amt`, `disc_amt`, `plus_amt`, `pending_amt`, `cmr_paid`, `payment_mode`, `delivery_date`, `comments`, `assign_to`, `notes`, `eng_notes`, `cust_remark`, `rating`, `cust_feed`, `emp_pts`, `eng_ack`, `created_on`, `updated_on`, `user_id`, `onhold_date`, `onhold_reason`, `warranty_mode`, `code_no`, `code_date`, `status`, `cust_solution`, `notes_all`, `eng_notes_sol`, `eng_notess`) VALUES (1, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-06-07 18:25:44', '', 0, 'Machine sifted to apollo specialty.replaced EPROM latest.Need to get payment', '', ' ', 0, '', 0, '', '2017-06-07 18:25:48', '2017-07-26 13:05:52', 1, '', '', '', '', '', '', '', '', '', ''), (2, 2, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-06-08 13:09:28', 'Delivered', 0, 'BUBBLE FORMS IN NEEDLE NO. 1 TUBING', 'dsd', ' ', 0, '', 0, '', '2017-06-08 13:10:00', '2017-08-10 16:36:36', 1, '', '', '', '', '', '', '', '', '', ' '), (3, 17, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-06-08 15:53:35', '', 0, 'PT QC RESULTS ARE NOT OK', '', '', 0, '', 0, '', '2017-06-08 15:56:45', '2017-06-08 15:56:45', 0, '2017-06-08 15:53:35', 'TROUBLE SHOOTING STILL CONTINIOUE', '', '', '', '', '', '', '', ''), (4, 22, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-01 15:38:38', '', 0, '', '', ' ', 0, '', 0, '', '2017-07-01 15:38:48', '2017-07-01 16:04:36', 43, '', '', '', '', '', '', 'have to do', '', '', ''), (5, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-03 13:20:30', '', 0, '', '', ' ', 1, '', 0, '', '2017-07-03 13:20:49', '2017-07-03 13:20:49', 0, '', '', '', '', '', '', '', '', '', ''), (6, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-03 14:20:03', 'Delivered', 9, 'PHOTOMETRIC CALIBRATION ISSUE', '', ' ', 0, '', 0, '', '2017-07-03 14:23:24', '2017-07-17 13:41:45', 1, '', '', '', '', '', '', '', '', '', ''), (7, 30, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 11:05:22', '', 0, 'test', '', 'tested', 0, '', 0, '', '2017-07-12 11:05:35', '2017-07-12 11:05:35', 0, '', '', '', '', '', '', '', '', '', ''), (8, 25, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 11:14:46', '', 0, 'sssssssssssss', '', ' new remarks', 0, '', 0, '', '2017-07-12 11:14:59', '2017-07-26 13:05:28', 1, '', '', '', '', '', '', '', '', '', 'test notes'), (9, 33, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 12:05:31', 'Delivered', 0, 'test notes new', '', ' new test remark', 0, '', 0, '', '2017-07-12 12:05:46', '2017-07-26 13:04:28', 1, '', '', '', '', '', '', '', '', '', ''), (10, 36, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 16:19:18', 'Delivered', 0, 'first notes', '', ' first remark', 0, '', 0, '', '2017-07-12 16:26:26', '2017-07-29 15:46:31', 1, '', '', '', '', '', '', '', '', '', 'first notes'), (11, 37, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 16:54:42', '', 0, 'eeeeeeeeeeeeeeee', '', 'ewewrwerwer', 0, '', 0, '', '2017-07-12 16:54:54', '2017-07-12 17:00:00', 1, '', '', '', '', '', '', '', '', '', ' eeeeeee'), (12, 37, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 16:54:36', '', 0, 'eeeeeeeeeeeeeeee', '', 'ewewrwerwer', 0, '', 0, '', '2017-07-12 16:55:23', '2017-07-12 17:00:00', 1, '', '', '', '', '', '', '', '', '', ' eeeeeee'), (13, 38, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 17:03:51', '', 0, '', '', '', 0, '', 0, '', '2017-07-12 17:03:57', '2017-07-12 17:03:57', 0, '', '', '', '', '', '', 'ssssssssssss', '', '', ''), (14, 38, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 17:03:43', '', 0, 'wwwwwwwwwwwwww', '', ' eeeeeeeeeeeeee', 0, '', 0, '', '2017-07-12 17:04:12', '2017-07-12 17:04:12', 0, '', '', '', '', '', '', '', '', '', ''), (15, 39, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 17:21:21', '', 18, 'second notes', '', 'second remarks', 0, '', 0, '', '2017-07-12 17:21:32', '2017-07-22 12:27:36', 1, '', '', '', '', '', '', '', '', '', 'second notes ma'), (16, 40, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 17:36:54', 'Delivered', 18, 'test notess test notessss', '', ' cust jbjdkfhsjdkdgsdg sdfdfsdf', 0, '', 0, '', '2017-07-12 17:37:06', '2017-07-12 17:41:26', 1, '', '', '', '', '', '', ' fghdfgdfgfdgfdg fdg fdg', '', '', ''), (17, 32, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-12 19:04:10', '', 0, '', '', '', 2, '', 0, 'accept', '2017-07-12 19:07:32', '2017-07-12 19:08:29', 34, '', '', '', '', '', '', '', '', '', ' Liquid filter was cleaned, fluidic circuit connections was checked. Instrument is working.'), (18, 41, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-13 15:00', '', 0, '', '', '', 0, '', 0, 'accept', '2017-07-13 22:22:58', '2017-07-13 22:22:58', 0, '', '', '', '', '', '', '', '', '', 'I visited instrument, customer complaint that its show"error 49.03.04,\r\nmeasure timeout,waiting for ACK".check instrument \r\n''pc rack assembly''\r\nboard and re-connected cable and board .Again start instrument ,its working properly.\r\n'), (19, 43, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-14 18:48:37', '', 0, '', '', '', 0, '', 0, 'accept', '2017-07-14 18:50:15', '2017-07-14 18:50:15', 0, '', '', '', '', '', '', '', '', '', ''), (20, 48, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-15 13:05:53', 'Delivered', 0, 'CLEAN PDR HOME SENSOR ', '', ' Clean PDR.', 1, '', 0, '', '2017-07-15 13:06:36', '2017-07-17 14:27:30', 1, '', '', '', '', '', '', '', '', '', ''), (21, 47, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-15 17:12:37', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-07-15 17:18:38', '2017-07-17 14:28:26', 1, '', '', '', '', '', '', '', '', '', 'Checked instrument ,this problem is due to distrub of test parameter ,so correct the setting .'), (22, 49, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-17 13:03:22', '', 0, '', '', '', 0, '', 0, '', '2017-07-17 13:09:24', '2017-07-22 12:54:56', 34, '2017-07-22 12:52:56', '', '', '', '', '', '', '', '', ' '), (23, 46, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-17 14:28:38', '', 0, 'LLD cable issue replaced the same', '', ' replaced the LLD cable', 0, '', 0, '', '2017-07-17 14:29:06', '2017-07-17 14:29:06', 0, '', '', '', '', '', '', '', '', '', ''), (24, 44, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-17 14:31:49', '', 0, 'Mapping issue ,done mapping ', '', ' ', 0, '', 0, '', '2017-07-17 14:32:09', '2017-07-17 14:32:09', 0, '', '', '', '', '', '', '', '', '', ''), (25, 50, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-17 17:00:06', 'Delivered', 0, '', '', ' ', 3, '', 0, '', '2017-07-17 17:01:27', '2017-08-10 16:35:27', 1, '2017-07-17 17:06:03', '', '', '', '', '', 'rEPLACED pHOTOMETRIC BOARD WITH FIBER DONE MAPPING,PHOTOMETRIC CALIBRATION RUN CONTROL,RUN 5 SAMPLES.', '', '', ''), (26, 52, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-19 13:55:22', '', 0, '', '', '', 0, '', 0, '', '2017-07-19 13:56:07', '2017-07-19 13:56:07', 0, '', '', '', '', '', '', '', '', '', ''), (27, 51, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-20 20:58:15', '', 13, 'Routine maintenance', '', ' ', 0, '', 0, '', '2017-07-20 20:58:39', '2017-07-22 12:27:17', 1, '', '', '', '', '', '', '', '', '', ''), (28, 53, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-21 11:51:22', '', 0, '', '', '', 0, '', 0, 'accept', '2017-07-21 11:57:13', '2017-07-21 11:57:13', 0, '', '', '', '', '', '', 'Problem is due to product carasuel positioning sensor ,open instrument and clean sensor .And mapping instrument .it work properly', '', '', ''), (29, 55, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-22 12:19:12', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-07-22 12:20:20', '2017-07-22 12:22:23', 1, '', '', '', '', '', '', 'replaced printer head.', '', '', ''), (30, 57, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-24 14:24:16', 'Delivered', 0, 'Routine maintenance', '', ' ', 2, '', 0, '', '2017-07-24 14:24:38', '2017-07-24 14:26:37', 1, '', '', '', '', '', '', '', '', '', ''), (31, 57, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-24 14:24:16', 'Delivered', 0, 'Routine maintenance', '', ' ', 2, '', 0, '', '2017-07-24 14:25:41', '2017-07-24 14:26:37', 1, '', '', '', '', '', '', '', '', '', ''), (32, 56, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-24 14:26:44', '', 0, 'Routine Maintenance', '', ' ', 0, '', 0, '', '2017-07-24 14:26:54', '2017-07-24 14:26:54', 0, '', '', '', '', '', '', '', '', '', ''), (33, 59, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-24 18:48:41', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-07-24 18:49:34', '2017-08-01 17:44:59', 1, '', '', '', '', '', '', '', '', '', ' Weekly maintenance'), (34, 60, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-25 17:03:58', 'Delivered', 0, '', '', ' ', 2, '', 0, '', '2017-07-25 17:04:21', '2017-07-25 17:05:00', 1, '', '', '', '', '', '', '', '', '', ''), (35, 61, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-26 13:01:35', 'Delivered', 0, 'Routine Maintenance', '', ' ', 2, '', 0, '', '2017-07-26 13:01:52', '2017-07-26 13:04:05', 1, '', '', '', '', '', '', '', '', '', ''), (36, 63, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-26 13:02:25', 'Delivered', 0, '', '', ' Product Drawer Temperature was high.Checked and filled coolant also lubricated coolant pump.Room temperature was high around 26-27.informed customer to maintain below 23deg.', 1, '', 0, '', '2017-07-26 13:03:03', '2017-07-27 11:46:24', 1, '', '', '', '', '', '', '', '', '', ' '), (37, 62, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-26 15:44:50', 'Delivered', 0, 'Problem with FVIII calibration they found error in 3rd and 4th dilution', '', ' Mapping in eppendof cup was not proper.After mapping correctly issue solved.', 0, '', 0, '', '2017-07-26 15:45:31', '2017-07-31 13:41:32', 1, '', '', '', '', '', '', '', '', '', ''), (38, 65, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-28 10:01:36', '', 0, '', '', '', 0, '', 0, '', '2017-07-28 10:08:51', '2017-08-11 10:52:11', 40, '', '', '', '', '', '', '', '', '', ' Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. '), (39, 65, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-28 10:01:36', '', 0, '', '', '', 0, '', 0, '', '2017-07-28 10:12:07', '2017-08-11 10:52:11', 40, '', '', '', '', '', '', '', '', '', ' Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. '), (40, 65, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-28 10:01:36', '', 0, '', '', '', 0, '', 0, '', '2017-07-28 10:12:26', '2017-08-11 10:52:11', 40, '', '', '', '', '', '', '', '', '', ' Visited in instrument, checked vacuum in pump and connection of tubing. Found problem in connection of filter and tube. Solved problem. Its working properly. '), (41, 54, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-28 17:56:01', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-07-28 17:56:35', '2017-08-10 16:37:54', 1, '', '', '', '', '', '', 'I have replace the needle No3 and run the endorance now machine is working fine.', '', '', ''), (42, 64, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-07-31 13:14:55', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-07-31 13:15:07', '2017-07-31 13:16:09', 1, '', '', '', '', '', '', '', '', '', ''), (43, 67, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-01 15:00', 'Delivered', 0, 'System stuck', '', ' After installing OS and software problem solved', 3, '', 0, '', '2017-08-02 10:26:35', '2017-08-04 12:33:13', 1, '', '', '', '', '', '', 'Upgraded OS 107.03 to 108.08.02, Now instrument is working fine.', '', '', ''), (44, 69, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-03 10:24:14', '', 0, 'sdfsdfds', '', ' asasasa', 0, '', 0, '', '2017-08-03 10:24:19', '2017-08-03 10:24:19', 0, '', '', '', '', '', '', '', '', '', ''), (45, 77, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-03 13:46:15', 'Delivered', 0, '', '', ' After lubricating coolant pump problem solved.', 0, '', 0, '', '2017-08-03 13:57:35', '2017-08-03 14:26:39', 1, '', '', '', '', '', '', 'Due to too much dust and rust after lubrication problem solved', '', '', ''), (46, 76, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-03 13:57:41', 'Delivered', 0, 'routine maintenance', '', ' ', 0, '', 0, '', '2017-08-03 13:57:51', '2017-08-03 14:26:53', 1, '', '', '', '', '', '', '', '', '', ''), (47, 75, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-03 13:57:57', 'Delivered', 0, 'Routine Maintenance', '', ' ', 0, '', 0, '', '2017-08-03 13:58:08', '2017-08-03 14:27:08', 1, '', '', '', '', '', '', '', '', '', ''), (48, 78, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-04 15:23:46', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-08-04 15:25:55', '2017-08-09 17:54:43', 1, '2017-08-04 15:23:46', 'Need to get spare approval', '', '', '', '', ' Lubricated the pump.need to change new pump', '', '', ''), (49, 82, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-05 15:24:55', 'Delivered', 0, '', '', ' ', 4, '', 0, '', '2017-08-05 15:29:27', '2017-08-05 15:44:44', 1, '', '', '', '', '', '', 'Factor 7 callibration select the neoplastin lot number in callibration menu.', '', '', ''), (50, 81, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-05 15:29:48', '', 0, '', '', '', 0, '', 0, 'accept', '2017-08-05 15:34:54', '2017-10-27 15:26:29', 1, '2017-08-05 15:29:48', 'Because there is printing issue in control values and patient result is printing clear.as per discuss with an sir. I am going to write the mail to Anil sir and boss', '', '', '', '', '', '', '', ' '), (51, 86, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-08 12:46:55', 'Delivered', 0, 'Routine maintenance', '', ' ', 0, '', 0, '', '2017-08-08 12:47:09', '2017-08-08 12:47:44', 1, '', '', '', '', '', '', '', '', '', ''), (52, 87, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-08 13:30:12', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-08-08 13:30:52', '2017-08-08 13:31:34', 1, '', '', '', '', '', '', 'After removing paper cleaned the printer area.Problem solved', '', '', ''), (53, 94, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-10 16:25:16', 'Delivered', 0, '', '', ' ', 2, '', 0, '', '2017-08-10 16:31:52', '2017-08-10 16:34:37', 1, '', '', '', '', '', '', '', '', '', 'Printer head is faulty. Replaced with new one.'), (54, 92, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-10 16:38:20', '', 0, '', '', '', 4, '', 0, 'accept', '2017-08-10 16:40:11', '2017-08-10 16:40:11', 0, '', '', '', '', '', '', 'Measurement and callibration of temperature done', '', '', ''), (55, 95, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-10 17:47:03', '', 0, 'test notes entry', '', 'xcxcvx', 1, '', 0, '', '2017-08-10 17:47:07', '2018-02-13 14:51:02', 1, '', '', '', '', '', '', '', '', '', ''), (56, 91, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-11 09:59:54', '', 0, '', '', '', 1, '', 0, 'accept', '2017-08-11 10:04:16', '2017-08-11 10:04:16', 0, '', '', '', '', '', '', 'Clean glass windows of rail and clean camera then done mapping ', '', '', ''), (57, 96, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-11 10:04:39', '', 0, '', '', '', 0, '', 0, 'accept', '2017-08-11 10:10:54', '2017-08-16 16:29:18', 39, '2017-08-11 10:04:39', 'Need to replace x arm belt\r\n\r\n', '', '', '', '', 'Routed x axis belt 180 degree and solve problem instrument in running condition but in future need to replace belt \r\nBecause some teeth of belt is damage \r\nWhen we routed belt 180 degree then damage teeth is not in use and belt working fine \r\n ', '', '', ''), (58, 89, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-11 10:20:29', '', 0, '', '', '', 0, '', 0, 'accept', '2017-08-11 10:51:23', '2017-08-11 10:51:23', 0, '', '', '', '', '', '', '', '', '', 'Instrument in working condition, because x1axis belt is damage some corner, and in future problem is come due to this reason. '), (59, 84, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-11 15:06:50', '', 0, '', '', ' ', 0, '', 0, '', '2017-08-11 15:07:50', '2017-11-09 13:11:36', 1, '', '', '', '', '', '', 'Replaced PC Board.', '', '', 'Instrument working fine'), (60, 97, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-11 19:20:42', '', 0, '', '', '', 0, '', 0, '', '2017-08-11 19:20:54', '2017-08-11 19:20:54', 0, '', '', '', '', '', '', '', '', '', ''), (61, 98, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-12 12:51:03', '', 0, '', '', '', 0, '', 0, '', '2017-08-12 12:53:06', '2017-08-12 12:53:06', 0, '', '', '', '', '', '', 'Change cacl2 and tip for electronic pipettes and then run and control sample and find good results ', '', '', ''), (62, 93, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-14 14:51:49', '', 0, '', '', '', 0, '', 0, '', '2017-08-14 14:51:57', '2017-08-14 14:51:57', 0, '', '', '', '', '', '', '', '', '', ''), (63, 100, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-14 14:52:04', '', 0, '', '', '', 0, '', 0, '', '2017-08-14 14:52:51', '2017-08-14 14:52:51', 0, '', '', '', '', '', '', 'troubleshooted for time being.But need to replace cap', '', '', ''), (64, 101, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-16 16:19:06', '', 0, '', '', '', 0, '', 0, '', '2017-08-16 16:23:20', '2017-08-16 16:23:20', 0, '', '', '', '', '', '', 'Tubeing in between vacuum reservoir and electrovalve are damage so change tube and solve problem', '', '', ''), (65, 102, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-18 12:13:13', '', 0, '', '', '', 0, '', 0, '', '2017-08-18 12:13:36', '2017-08-18 12:13:36', 0, '', '', '', '', '', '', '', '', '', 'Instrument calibration done'), (66, 103, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-18 12:13:42', '', 0, '', '', '', 0, '', 0, '', '2017-08-18 12:13:50', '2017-08-18 12:13:50', 0, '', '', '', '', '', '', '', '', '', ''), (67, 104, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-18 12:16:36', '', 0, '', '', '', 0, '', 0, '', '2017-08-18 12:16:51', '2017-08-18 12:16:51', 0, '', '', '', '', '', '', '', '', '', ''), (68, 105, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-18 17:03:44', '', 0, '', '', '', 4, '', 0, '', '2017-08-18 17:04:22', '2017-08-18 17:04:22', 0, '', '', '', '', '', '', '', '', '', ''), (69, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:13:06', '2017-08-19 11:13:06', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (70, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:46', '2017-08-19 11:32:46', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (71, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:47', '2017-08-19 11:32:47', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (72, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:48', '2017-08-19 11:32:48', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (73, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:49', '2017-08-19 11:32:49', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (74, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:50', '2017-08-19 11:32:50', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (75, 107, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 11:03:35', '', 0, '', '', '', 2, '', 0, '', '2017-08-19 11:32:51', '2017-08-19 11:32:51', 0, '', '', '', '', '', '', '', '', '', 'Temperature Problem is come due to temp senser not sensInstrument temperature because heat sink comp are not working solved problem \r\nInstrument working properly'), (76, 109, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 12:22:26', '', 0, '', '', '', 1, '', 0, '', '2017-08-19 12:23:48', '2017-08-19 12:23:48', 0, '', '', '', '', '', '', 'done instrument calibration and replaced cap waste container', '', '', ''), (77, 106, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 15:12:35', 'Delivered', 0, 'PM&CAL', '', ' ', 4, '', 0, '', '2017-08-19 15:17:57', '2017-08-24 15:38:16', 1, '', '', '', '', '', '', '', '', '', 'Instrument working satisfactory.'), (78, 108, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-19 19:49:57', '', 0, '', '', '', 0, '', 0, '', '2017-08-19 19:50:56', '2017-08-19 19:50:56', 0, '', '', '', '', '', '', '', '', '', ''), (79, 112, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-20 05:54:18', '', 0, '', '', '', 0, '', 0, '', '2017-08-20 05:56:26', '2017-10-27 15:19:17', 1, '2017-08-20 05:54:18', 'Biddlestone home senser is not available in stock. ', '', '', '', '', 'I changed optical sensor, instrument working properly', '', '', ''), (80, 115, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-24 17:53:07', '', 0, '', '', '', 4, '', 0, '', '2017-08-24 17:53:29', '2017-10-27 15:18:24', 1, '', '', '', '', '', '', '', '', '', ''), (81, 116, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-24 17:53:44', '', 0, '', '', '', 4, '', 0, '', '2017-08-24 17:55:16', '2017-08-24 17:55:16', 0, '2017-08-24 17:53:44', 'Due to AMC and part are not available.', '', '', '', '', '', '', '', ''), (82, 113, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-28 17:38:13', '', 0, '', '', ' ', 0, '', 0, '', '2017-08-28 17:38:46', '2017-10-27 15:19:02', 1, '', '', '', '', '', '', '', '', '', ''), (83, 119, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-28 18:42:25', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-08-28 18:42:33', '2017-09-18 18:49:50', 1, '', '', '', '', '', '', '', '', '', ''), (84, 117, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-28 22:57:18', '', 0, '', '', '', 4, '', 0, '', '2017-08-28 22:58:22', '2017-10-27 15:18:00', 1, '', '', '', '', '', '', 'Clean the printer and remove dust particles from printer.', '', '', ''), (85, 120, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-29 18:52:28', '', 0, '', '', '', 0, '', 0, '', '2017-08-29 18:59:16', '2017-10-27 15:17:46', 1, '', '', '', '', '', '', '', '', '', ' Checked instrument, problem is temperature sense cable is not working. Changed cable. It working properly. I''m '), (86, 121, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-30 15:49:23', '', 0, '', '', ' Dust in home sensor,clean the same instrument is working now', 0, '', 0, '', '2017-08-30 15:50:52', '2017-08-30 16:05:46', 1, '', '', '', '', '', '', 'Dust in home sensor clean the same. Instrument is working now.', '', '', ''), (87, 122, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-30 17:29:16', '', 0, '', '', '', 0, '', 0, '', '2017-08-30 17:29:27', '2017-10-27 15:17:32', 1, '', '', '', '', '', '', '', '', '', ''), (88, 124, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-31 11:47:58', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-08-31 11:48:07', '2017-09-29 13:39:20', 1, '', '', '', '', '', '', '', '', '', ''), (89, 125, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-08-31 16:26:36', '', 0, '', '', '', 0, '', 0, '', '2017-08-31 16:27:15', '2017-10-27 15:16:43', 1, '2017-08-31 16:26:36', '', '', '', '', '', '', '', '', ' '), (90, 126, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-01 12:55:53', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-01 13:00:22', '2017-09-08 16:16:50', 1, '', '', '', '', '', '', '', '', '', 'adjust printer ,need to replace printer thermic in future.'), (91, 126, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-01 12:55:53', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-01 13:10:49', '2017-09-08 16:16:50', 1, '', '', '', '', '', '', '', '', '', 'adjust printer ,need to replace printer thermic in future.'), (92, 127, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-01 13:11:16', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-01 13:12:43', '2017-09-08 16:15:43', 1, '', '', '', '', '', '', '', '', '', 'clean and re do the mapping of product carousol,clean the cuvette loading area.'), (93, 123, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-01 13:37:27', '', 0, '', '', '', 4, '', 0, '', '2017-09-01 13:41:39', '2017-10-27 15:16:57', 1, '', '', '', '', '', '', ' We have make 1/15 dilution in between 1/7 & 1/40 dilutions for Immunodef Factor VIII test set up.\r\n\r\nFor PT comparison, we used same vial of PT Reagent on both Compact Max and Satellite Instrument.', '', '', ''), (94, 129, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-01 13:34', 'Delivered', 0, '', '', ' ', 2, '', 0, '', '2017-09-02 13:37:28', '2017-10-25 15:43:33', 1, '', '', '', '', '', '', '', '', '', 'Replaced with new keyboard, Now instrument is working fine'), (95, 131, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-04 18:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-04 18:42:11', '2017-10-25 15:40:37', 1, '', '', '', '', '', '', 'Instrument is not start checked instrument it problem due to fuse F3(1A)\r\nChanged fuse. ', '', '', ''), (96, 128, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-05 12:51:43', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-05 12:51:55', '2017-09-21 13:12:23', 1, '', '', '', '', '', '', '', '', '', ''), (97, 132, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-05 13:25:30', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-05 13:27:49', '2017-10-25 15:40:23', 1, '', '', '', '', '', '', 'Problem due to dust in between barcode reader and product carousel glass ', '', '', ''), (98, 133, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-06 09:19:23', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-06 09:19:49', '2017-10-25 15:40:08', 1, '', '', '', '', '', '', '', '', '', ''), (99, 135, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-07 12:22:03', 'Delivered', 0, 'maintenance', '', ' ', 0, '', 0, '', '2017-09-07 12:22:09', '2017-09-19 14:31:22', 1, '', '', '', '', '', '', '', '', '', ''), (100, 134, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-07 12:22:25', 'Delivered', 0, 'maintenance routine', '', ' ', 0, '', 0, '', '2017-09-07 12:22:34', '2017-09-19 14:31:45', 1, '', '', '', '', '', '', '', '', '', ''), (101, 136, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-08 16:06:26', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-08 16:06:46', '2017-10-25 15:39:49', 1, '', '', '', '', '', '', '', '', '', ''), (102, 137, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-09 18:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-10 01:38:41', '2017-09-22 17:55:07', 1, '', '', '', '', '', '', '', '', '', 'Needle is blocked, clean needle. After check program\r\nLoad new regent, its working properly. '), (103, 141, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-15 11:35:06', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-15 11:35:43', '2017-09-18 18:48:36', 1, '', '', '', '', '', '', 'Reset PID RAM in drawer product solved', '', '', ''), (104, 142, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-15 12:14:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-15 12:16:05', '2017-09-19 14:31:06', 1, '', '', '', '', '', '', '', '', '', ''), (105, 143, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-15 13:19:18', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-15 13:21:46', '2017-09-18 18:46:31', 1, '2017-09-15 13:19:18', 'PM due is on 28th', '', '', '', '', '', '', '', ''), (106, 139, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-15 15:21:12', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-15 15:21:25', '2017-09-22 13:50:34', 1, '', '', '', '', '', '', '', '', '', ''), (107, 145, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-18 13:10:18', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-18 13:10:58', '2017-09-18 18:47:33', 1, '', '', '', '', '', '', 'Checked auto mode settings and did bidirectional interface.it worked', '', '', ''), (108, 140, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-18 13:16:23', 'Delivered', 0, '', '', ' ', 1, '', 0, '', '2017-09-18 13:17:17', '2017-09-21 13:12:02', 1, '', '', '', '', '', '', '', '', '', 'Do the mapping and change the suction tip'), (109, 146, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-18 22:42:20', 'Delivered', 0, 'PM&CAL', '', ' ', 0, '', 0, '', '2017-09-18 22:42:53', '2017-09-21 13:11:47', 1, '', '', '', '', '', '', 'PM and Callibration of the Start4', '', '', ''), (110, 147, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-19 14:29:45', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-19 14:30:12', '2017-09-19 14:30:50', 1, '', '', '', '', '', '', 'Routine maintenance', '', '', ''), (111, 148, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-20 16:42:59', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-20 16:43:09', '2017-09-20 16:43:48', 1, '', '', '', '', '', '', '', '', '', ''), (112, 150, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-21 13:09:04', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-21 13:09:13', '2017-09-21 13:11:06', 1, '', '', '', '', '', '', '', '', '', ''), (113, 152, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-22 13:49:05', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-22 13:49:48', '2017-09-22 13:50:19', 1, '', '', '', '', '', '', 'Performed Recalibration.Qc is in range.It is under observation', '', '', ''), (114, 153, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-22 17:30:14', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-22 17:30:53', '2017-09-22 17:53:14', 1, '', '', '', '', '', '', 'Sample tube was empty so needle went to bottom of the tube.after checking prob solved', '', '', ''), (115, 151, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-23 19:17:19', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-23 19:19:01', '2017-10-17 18:46:47', 1, '', '', '', '', '', '', '', '', '', 'Make program for drvv s, drvv c, PC, PS, ATiii, and run drvv program for the test '), (116, 160, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-23 18:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-23 21:10:36', '2017-10-17 18:46:00', 1, '', '', '', '', '', '', 'Make program for TT and run calibration and test ', '', '', ''), (117, 154, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-25 13:08:52', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-25 13:09:12', '2017-09-25 13:13:06', 1, '', '', '', '', '', '', '', '', '', ''), (118, 154, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-25 13:08:52', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-25 13:10:10', '2017-09-25 13:13:06', 1, '', '', '', '', '', '', '', '', '', ''), (119, 164, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 16:48:31', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 16:50:40', '2017-10-17 18:45:45', 1, '', '', '', '', '', '', 'decontaminate instrument done user maintenance run control .controls are in range.', '', '', 'APTT results and controles are in higher side'), (120, 165, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 16:51:02', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 16:52:01', '2017-10-17 18:45:31', 1, '', '', '', '', '', '', 'decontaminate instrument run control.all are in range', '', '', ''), (121, 167, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 16:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 18:59:48', '2017-10-17 18:45:01', 1, '', '', '', '', '', '', '', '', '', ''), (122, 168, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 14:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:03:16', '2017-10-16 18:33:25', 1, '', '', '', '', '', '', '', '', '', ''), (123, 168, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 14:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:04:00', '2017-10-16 18:33:25', 1, '', '', '', '', '', '', '', '', '', ''), (124, 158, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 19:48:05', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:48:17', '2017-09-26 19:49:23', 1, '', '', '', '', '', '', '', '', '', ''), (125, 169, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 19:53:45', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:54:03', '2017-10-16 18:33:04', 1, '', '', '', '', '', '', '', '', '', ''), (126, 173, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 19:54:13', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:54:30', '2017-10-16 18:32:38', 1, '', '', '', '', '', '', '', '', '', ''), (127, 175, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-25 18:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 19:57:09', '2017-10-16 18:32:03', 1, '', '', '', '', '', '', '', '', '', ''), (128, 176, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 21:48:32', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 21:49:15', '2017-10-16 18:31:47', 1, '', '', '', '', '', '', '', '', '', ''), (129, 174, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 22:23:42', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-26 22:26:19', '2017-10-16 18:32:24', 1, '', '', '', '', '', '', 'Check instrument and find 20 pluses volume issue so set V pump and slove problem \r\nThen run PC PS ATIII and APCR test ', '', '', 'This instrument is 5 year warranty '), (130, 161, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:02:22', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:28:20', '2017-10-27 15:14:46', 1, '', '', '', '', '', '', '', '', '', ''), (131, 85, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:28:45', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:29:04', '2017-10-27 15:25:34', 1, '', '', '', '', '', '', '', '', '', ''), (132, 110, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:29:16', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:29:42', '2017-10-27 15:23:49', 1, '', '', '', '', '', '', '', '', '', ''), (133, 111, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:32:12', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:32:33', '2017-10-27 15:22:53', 1, '', '', '', '', '', '', '', '', '', ''), (134, 114, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:32:40', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:32:57', '2017-10-27 15:18:36', 1, '', '', '', '', '', '', '', '', '', ''), (135, 83, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:33:06', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:33:32', '2017-10-27 15:26:03', 1, '', '', '', '', '', '', '', '', '', ''), (136, 58, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-26 23:33:40', '', 0, '', '', '', 4, '', 0, '', '2017-09-26 23:33:54', '2017-10-27 15:23:12', 1, '', '', '', '', '', '', '', '', '', ''), (137, 177, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-27 16:11:26', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-27 19:45:18', '2017-10-16 18:31:32', 1, '', '', '', '', '', '', 'Buffer vial can not create vaccume beacuse tube connection is break, reconnected tube connector. Its working properly. ', '', '', ''), (138, 74, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 10:38:02', '', 0, '', '', '', 0, '', 0, '', '2017-09-28 10:38:23', '2017-10-27 15:26:43', 1, '', '', '', '', '', '', '', '', '', ''), (139, 179, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 10:39:40', '', 0, '', '', '', 0, '', 0, '', '2017-09-28 10:40:18', '2017-10-27 15:14:08', 1, '', '', '', '', '', '', '', '', '', ''), (140, 178, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 10:40:29', '', 0, '', '', '', 0, '', 0, '', '2017-09-28 10:40:40', '2017-10-27 15:14:20', 1, '', '', '', '', '', '', '', '', '', ''), (141, 99, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 10:40:58', '', 0, '', '', '', 0, '', 0, '', '2017-09-28 10:41:55', '2017-10-27 15:24:14', 1, '', '', '', '', '', '', '', '', '', ''), (142, 90, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 10:42:03', '', 0, '', '', '', 0, '', 0, '', '2017-09-28 10:42:27', '2017-10-27 15:25:01', 1, '', '', '', '', '', '', '', '', '', ''), (143, 159, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 21:33:28', '', 0, '', '', '', 4, '', 0, '', '2017-09-28 21:34:01', '2017-10-27 15:15:00', 1, '', '', '', '', '', '', '', '', '', ''), (144, 180, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-28 21:34:27', '', 0, '', '', '', 4, '', 0, '', '2017-09-28 21:34:59', '2017-10-27 15:13:53', 1, '', '', '', '', '', '', 'PM and Calibration', '', '', ''), (145, 182, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-29 13:37:03', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-29 13:37:11', '2017-10-16 18:07:43', 1, '', '', '', '', '', '', '', '', '', ''), (146, 166, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-29 13:37:21', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-29 13:37:27', '2017-10-17 18:45:15', 1, '', '', '', '', '', '', '', '', '', ''), (147, 184, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-29 17:33:05', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-29 17:33:14', '2017-10-03 20:26:50', 1, '', '', '', '', '', '', '', '', '', ''), (148, 183, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-09-30 22:11:32', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-09-30 22:11:53', '2017-10-16 18:07:32', 1, '', '', '', '', '', '', '', '', '', ''), (149, 188, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-03 13:22:30', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-03 13:22:44', '2017-10-03 20:26:36', 1, '', '', '', '', '', '', '', '', '', ''), (150, 189, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-03 20:27:29', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-03 20:28:38', '2017-10-16 18:07:13', 1, '', '', '', '', '', '', 'Change needle and done mapping solve problems', '', '', ''), (151, 191, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-04 16:53:22', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-04 16:53:34', '2017-10-16 18:06:28', 1, '', '', '', '', '', '', '', '', '', ''), (152, 190, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-04 16:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-05 07:13:25', '2017-10-16 18:06:42', 1, '', '', '', '', '', '', 'Done Instrument mapping. ', '', '', ''), (153, 192, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-05 18:04:18', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-05 18:05:39', '2017-10-06 12:23:24', 1, '', '', '', '', '', '', 'Run PC FIb and drvv c calibration and control also run test ', '', '', ''), (154, 194, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-05 18:41:56', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-05 18:42:03', '2017-10-06 12:22:43', 1, '', '', '', '', '', '', '', '', '', ''), (155, 193, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-05 19:00', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-05 22:13:51', '2017-10-06 12:23:12', 1, '', '', '', '', '', '', 'Done needle straight, reconnected in sample needle position. Checked volume of dispence, it is ok. And temprature problem due to glycol pump is not work and heating so open and clean pump it is working properly. ', '', '', 'Sample Needle is bended and temperature is out of range'), (156, 195, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-06 12:17:54', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-06 12:18:09', '2017-10-06 12:18:43', 1, '', '', '', '', '', '', '', '', '', ''), (157, 196, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-07 21:36:50', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-07 21:37:20', '2017-10-16 18:05:29', 1, '', '', '', '', '', '', 'Solve problems', '', '', ''), (158, 197, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-12 12:44:30', 'Delivered', 0, '', '', ' ', 4, '', 0, '', '2017-10-12 12:45:53', '2017-10-16 18:02:14', 1, '', '', '', '', '', '', 'Syringe Tip replaced.', '', '', 'Instrument working satisfactory.'), (159, 198, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-12 17:40:18', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-12 17:41:07', '2017-10-12 17:54:41', 1, '', '', '', '', '', '', 'replaced from spare box.they need new one for future', '', '', ''), (160, 201, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-16 15:52:32', 'Delivered', 0, '', '', ' ', 2, '', 0, '', '2017-10-16 16:31:27', '2017-10-16 17:59:59', 1, '', '', '', '', '', '', '', '', '', 'Replaced kit peltier. now instrument is working fine '), (161, 203, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-16 18:21:31', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-16 18:21:41', '2017-10-16 18:31:15', 1, '', '', '', '', '', '', '', '', '', ''), (162, 207, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 12:43:44', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-17 12:43:51', '2017-10-17 18:44:48', 1, '', '', '', '', '', '', '', '', '', ''), (163, 206, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 23:52:48', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-17 23:54:45', '2017-10-25 15:39:29', 1, '', '', '', '', '', '', 'Arm Z movement is not proper,Clean arm and lubricate Z Pully,run tests.working OK', '', '', ''), (164, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:29:50', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (165, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:13', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (166, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:14', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (167, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:16', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (168, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:17', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (169, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:18', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (170, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:31:19', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (171, 208, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-17 18:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-18 06:32:12', '2017-10-27 15:13:40', 1, '', '', '', '', '', '', '', '', '', ''), (172, 209, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-20 13:38:26', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-20 13:38:35', '2017-10-25 15:38:38', 1, '', '', '', '', '', '', '', '', '', ''), (173, 210, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-23 12:11:10', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-23 12:11:19', '2017-10-25 15:37:41', 1, '', '', '', '', '', '', '', '', '', ''), (174, 212, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-24 10:16:14', 'Delivered', 0, '', '', ' ', 0, '', 0, '', '2017-10-24 10:16:38', '2017-10-25 15:37:27', 1, '', '', '', '', '', '', '', '', '', ''), (175, 219, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 15:48:01', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 15:52:52', '2017-10-27 15:15:28', 1, '', '', '', '', '', '', 'open and clean rail module,clean the theta motor pully and lubricate the same , check the mapping, run the test .', '', '', 'Cuvette stuck in rail'), (176, 220, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 16:19:24', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 16:20:22', '2017-10-27 15:15:12', 1, '', '', '', '', '', '', 'Reload all reagents and guide about Loading unloading and to run control. ', '', '', 'Reagents are not loaded properly by new technician. '), (177, 163, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 17:13:14', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 17:13:43', '2017-10-27 15:14:32', 1, '', '', '', '', '', '', '', '', '', ''), (178, 130, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 17:14:23', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 17:14:48', '2017-10-27 15:16:27', 1, '', '', '', '', '', '', '', '', '', ''), (179, 216, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 17:15:33', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 17:15:52', '2017-10-27 15:16:01', 1, '', '', '', '', '', '', '', '', '', ''), (180, 215, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 17:16:09', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 17:16:18', '2017-10-27 15:16:13', 1, '', '', '', '', '', '', '', '', '', ''), (181, 221, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-25 17:39:13', '', 0, '', '', '', 0, '', 0, '', '2017-10-25 17:44:40', '2017-10-27 15:07:59', 1, '', '', '', '', '', '', 'Checked instrument, no problem found ininstrument, problem is in 50micro liter plama dispensing by Pipette. Changed pipette. Solve problem. ', '', '', ''), (182, 218, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 12:32:13', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 12:32:22', '2017-10-27 15:15:50', 1, '', '', '', '', '', '', '', '', '', ''), (183, 218, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 12:32:13', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 12:36:18', '2017-10-27 15:15:50', 1, '', '', '', '', '', '', '', '', '', ''), (184, 218, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 12:32:13', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 12:37:13', '2017-10-27 15:15:50', 1, '', '', '', '', '', '', '', '', '', ''), (185, 223, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 15:27:59', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 15:28:11', '2017-10-27 15:35:28', 1, '', '', '', '', '', '', '', '', '', ''), (186, 222, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 22:59:23', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 22:59:45', '2017-10-28 09:34:22', 1, '', '', '', '', '', '', '', '', '', ''), (187, 217, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-27 22:59:59', '', 0, '', '', '', 0, '', 0, '', '2017-10-27 23:10:46', '2017-10-28 09:36:41', 1, '', '', '', '', '', '', '', '', '', ''), (188, 204, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-28 14:16:41', '', 0, '', '', '', 0, '', 0, '', '2017-10-28 14:17:01', '2017-10-31 12:58:15', 1, '', '', '', '', '', '', '', '', '', ''), (189, 226, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-28 14:17:39', '', 0, '', '', '', 0, '', 0, '', '2017-10-28 14:18:05', '2017-10-31 12:58:04', 1, '', '', '', '', '', '', '', '', '', ''), (190, 228, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-28 14:17:08', '', 0, '', '', '', 0, '', 0, '', '2017-10-28 14:18:59', '2017-10-31 12:57:48', 1, '', '', '', '', '', '', '', '', '', ''), (191, 199, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-28 14:18:19', '', 0, '', '', '', 0, '', 0, '', '2017-10-28 14:19:04', '2017-10-31 12:58:33', 1, '', '', '', '', '', '', '', '', '', 'PM and Calibration of start4'), (192, 230, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 14:38:16', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 14:41:59', '2017-11-02 15:03:19', 1, '', '', '', '', '', '', 'Check the temperature it is showing 17 ''C in instrument and in temperature probe found that the filters are block from dust, replaced the filter clean the fan. Product temp. Is now 13''C.', '', '', 'Product carousel temp. Out of range '), (193, 229, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 15:32:14', '', 0, '', '', ' ', 0, '', 0, '', '2017-10-31 15:32:24', '2017-10-31 15:32:24', 0, '', '', '', '', '', '', '', '', '', ''), (194, 235, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 17:37:00', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 17:37:08', '2017-11-02 15:02:19', 1, '', '', '', '', '', '', '', '', '', ''), (195, 236, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 18:44:22', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 18:53:19', '2017-11-02 15:01:51', 1, '', '', '', '', '', '', 'Refitted the pneumatic jack tubing tightly, and cleaned the shuttle rail, now Instrument is working fine.', '', '', 'Shuttle is not moving properly, leakage in pneumatic jack tubing.'), (196, 234, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:46:39', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:47:28', '2017-11-02 15:02:30', 1, '', '', '', '', '', '', '', '', '', 'Visited to produce the training certificates'), (197, 233, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:47:36', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:48:33', '2017-11-02 15:02:42', 1, '', '', '', '', '', '', 'Mapping done now the instrument is working fine', '', '', 'Lld issue with cephascrenn '), (198, 232, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:48:42', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:49:17', '2017-11-02 15:02:57', 1, '', '', '', '', '', '', '', '', '', 'Visited for lis purpose'), (199, 231, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:49:23', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:50:19', '2017-11-02 15:03:08', 1, '', '', '', '', '', '', '', '', '', 'Visited to give demo of the instrument'), (200, 225, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:50:31', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:51:24', '2017-11-02 15:03:41', 1, '', '', '', '', '', '', '', '', '', ''), (201, 224, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-10-31 20:51:33', '', 0, '', '', '', 0, '', 0, '', '2017-10-31 20:54:13', '2017-11-02 15:04:00', 1, '', '', '', '', '', '', 'Removed and done mapping', '', '', 'Steel ball strucked in the washing well first position'), (202, 237, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-01 12:19:28', '', 0, '', '', '', 0, '', 0, '', '2017-11-01 12:24:50', '2017-11-02 15:01:35', 1, '', '', '', '', '', '', 'Mapping for the sample pipetting and product pipetting was done. ', '', '', 'Needle was pipetting sample from the wall of the sample tube some time it touch the wall and give the error . May be needle was hit. '), (203, 240, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-04 08:05:03', '', 0, '', '', '', 0, '', 0, '', '2017-11-04 08:07:31', '2017-11-04 13:56:53', 1, '', '', '', '', '', '', 'Neddle puresing volume is low cleaning needle and set volcur pump. Problem is solve. ', '', '', ''), (204, 242, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-04 12:16:56', '', 0, '', '', '', 0, '', 0, '', '2017-11-04 12:17:07', '2017-11-04 13:56:37', 1, '', '', '', '', '', '', '', '', '', ''); INSERT INTO `quote_review` (`id`, `req_id`, `model_id`, `spare_tax`, `spare_tot`, `labourcharge`, `concharge`, `total_charge`, `total_amt`, `disc_amt`, `plus_amt`, `pending_amt`, `cmr_paid`, `payment_mode`, `delivery_date`, `comments`, `assign_to`, `notes`, `eng_notes`, `cust_remark`, `rating`, `cust_feed`, `emp_pts`, `eng_ack`, `created_on`, `updated_on`, `user_id`, `onhold_date`, `onhold_reason`, `warranty_mode`, `code_no`, `code_date`, `status`, `cust_solution`, `notes_all`, `eng_notes_sol`, `eng_notess`) VALUES (205, 239, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-04 12:17:13', '', 0, '', '', '', 0, '', 0, '', '2017-11-04 12:17:23', '2017-11-04 13:57:07', 1, '', '', '', '', '', '', '', '', '', ''), (206, 243, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-06 12:47:07', '', 0, '', '', '', 0, '', 0, '', '2017-11-06 12:47:17', '2017-11-06 13:32:02', 1, '', '', '', '', '', '', '', '', '', ''), (207, 241, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-06 15:11:13', '', 0, '', '', '', 0, '', 0, '', '2017-11-06 15:11:55', '2017-11-06 18:13:35', 1, '', '', '', '', '', '', 'Replaced with new one and done mapping', '', '', 'Needle 3 broken'), (208, 238, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-06 15:12:04', '', 0, '', '', '', 0, '', 0, '', '2017-11-06 15:12:44', '2017-11-06 18:13:52', 1, '', '', '', '', '', '', '', '', '', 'Bio logical validation'), (209, 244, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-07 09:53:45', '', 0, '', '', '', 0, '', 0, '', '2017-11-07 09:56:54', '2017-11-07 16:35:26', 1, '', '', '', '', '', '', '', '', '', ''), (210, 211, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-07 09:57:07', '', 0, '', '', '', 0, '', 0, '', '2017-11-07 09:57:34', '2017-11-13 15:22:36', 1, '2017-11-07 09:57:07', '', '', '', '', '', 'after replacing the I/O power board instrument is working fine.', '', '', 'In global Verification the arm No 2 is not checking suction pressure, then its giving a suction is not operating correctly. '), (211, 246, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-07 13:51:29', '', 0, '', '', '', 0, '', 0, '', '2017-11-07 13:51:53', '2017-11-07 16:35:52', 1, '', '', '', '', '', '', '', '', '', 'routine maintenance'), (212, 245, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-07 16:23:08', '', 0, '', '', '', 0, '', 0, '', '2017-11-07 16:32:04', '2017-11-07 16:35:39', 1, '', '', '', '', '', '', 'completed the Calibration and run the quality control both PT & APTT are passed.\r\nPT 13.2 / 22.3 , APTT 32.5 / 52.0', '', '', ''), (213, 247, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-08 15:10:17', '', 0, '', '', '', 0, '', 0, '', '2017-11-08 15:10:26', '2017-11-08 15:10:51', 1, '', '', '', '', '', '', '', '', '', ''), (214, 118, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-08 22:47:51', '', 0, '', '', '', 0, '', 0, '', '2017-11-08 22:49:39', '2017-11-09 13:11:07', 1, '', '', '', '', '', '', 'Multifunction board replaced.', '', '', 'Instrument working fine.'), (215, 248, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-09 13:18:41', '', 0, '', '', '', 0, '', 0, '', '2017-11-09 13:20:50', '2017-11-10 13:15:58', 1, '', '', '', '', '', '', 'Done the mapping arm 2 and clean the suction tip', '', '', 'Frequently cuvette missing'), (216, 249, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-09 15:01:27', '', 0, '', '', '', 0, '', 0, '', '2017-11-09 15:04:33', '2017-11-10 13:13:06', 1, '', '', '', '', '', '', 'Visit in lab and found problem APTT regent. APTT regent contaminate and also not proper trained technician so give training to all technician and solve issue ', '', '', ''), (217, 252, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-10 16:26:58', '', 0, '', '', '', 0, '', 0, '', '2017-11-10 16:27:11', '2017-11-10 16:29:26', 1, '', '', '', '', '', '', '', '', '', ''), (218, 251, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-10 16:27:22', '', 0, '', '', '', 0, '', 0, '', '2017-11-10 16:27:31', '2017-11-10 16:29:41', 1, '', '', '', '', '', '', '', '', '', ''), (219, 253, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-11 12:35:09', '', 0, '', '', '', 0, '', 0, '', '2017-11-11 12:39:49', '2017-11-13 15:21:44', 1, '', '', '', '', '', '', 'Clean fibers and measurement area, but problem remain same, then press Q and start chronometric test only. Need to replace photometricboard. ', '', '', 'Photometric board faulty.'), (220, 250, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-13 09:10:38', '', 0, '', '', '', 0, '', 0, '', '2017-11-13 09:12:04', '2017-11-13 15:22:24', 1, '2017-11-13 09:10:38', '', '', '', '', '', 'Make program for fviii and fix also make program for fviii low curve and run calibration and control ', '', '', ''), (221, 255, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-15 14:36:55', '', 0, '', '', '', 0, '', 0, '', '2017-11-15 14:37:58', '2017-11-15 15:51:18', 1, '', '', '', '', '', '', '', '', '', ''), (222, 254, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-15 14:38:26', '', 0, '', '', '', 0, '', 0, '', '2017-11-15 14:38:48', '2017-11-15 15:51:32', 1, '', '', '', '', '', '', '', '', '', ''), (223, 257, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-20 12:07:13', '', 0, '', '', '', 0, '', 0, '', '2017-11-20 12:07:50', '2017-12-14 15:06:10', 1, '', '', '', '', '', '', '', '', '', 'Preventive maintanence and training for new technicians'), (224, 262, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-30 23:43:00', '', 0, '', '', '', 0, '', 0, '', '2017-11-30 23:43:22', '2017-12-14 15:05:37', 1, '', '', '', '', '', '', '', '', '', ''), (225, 261, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-30 23:43:37', '', 0, '', '', '', 0, '', 0, '', '2017-11-30 23:45:20', '2017-12-14 15:07:37', 1, '', '', '', '', '', '', 'Remove the steel ball from shuttle rack after that machine is working fine.', '', '', 'Shuttle jam'), (226, 260, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-11-30 23:45:40', '', 0, '', '', '', 0, '', 0, '', '2017-11-30 23:47:56', '2017-12-14 15:07:51', 1, '', '', '', '', '', '', 'Remove the steel ball from shuttle rack. Now machine is working fine.', '', '', 'Shuttle missing'), (227, 265, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-11 21:17:41', '', 0, '', '', '', 0, '', 0, '', '2017-12-11 21:20:27', '2017-12-14 15:07:00', 1, '', '', '', '', '', '', 'Reloaded the software, and done all the mapping, and done calibration & QC. Now instrument is working fine. ', '', '', 'software issue. '), (228, 264, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-11 22:53:16', '', 0, '', '', '', 0, '', 0, '', '2017-12-11 22:55:19', '2017-12-14 15:07:22', 1, '', '', 'credit', '44', '12-02-2018', 'credit note received', 'Solve error of instrument & Run control for pt & Appt ', '', '', ''), (229, 270, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-14 14:06:43', '', 0, '', '', '', 0, '', 0, '', '2017-12-14 14:06:51', '2017-12-14 15:06:34', 1, '', '', '', '', '', '', '', '', '', ''), (230, 271, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-15 12:22:33', '', 0, '', '', '', 0, '', 0, '', '2017-12-15 12:22:44', '2017-12-15 17:04:53', 1, '', '', '', '', '', '', '', '', '', ''), (231, 272, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-15 17:05:43', '', 0, '', '', '', 0, '', 0, '', '2017-12-15 17:06:00', '2017-12-15 17:06:54', 1, '', '', '', '', '', '', '', '', '', ''), (232, 274, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-15 19:12:19', '', 0, '', '', '', 0, '', 0, '', '2017-12-15 19:35:11', '2017-12-18 14:03:46', 1, '', '', '', '', '', '', 'Checked glycol pump is not liquid flow cooling reservoir to meeting block pump is not work .open and clean pump and rectifying the problem .after cleaning and holing its work properly. I', '', '', 'Visited in instrument and its show error "incubation temperature is out of range ".and pipetting is blocked '), (233, 269, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-16 11:34:30', '', 0, '', '', '', 0, '', 0, '', '2017-12-16 11:36:20', '2017-12-18 14:04:20', 1, '', '', '', '', '', '', 'Find some broken cuvette in cuter which blocked the cuter movement so remove it and solve issue', '', '', ''), (234, 263, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-16 11:36:32', '', 0, '', '', '', 0, '', 0, '', '2017-12-16 11:39:39', '2017-12-16 11:39:39', 0, '2017-12-16 11:36:32', '', '', '', '', '', '', '', '', 'May time it''s products drawer not close properly and give drawer closing issue '), (235, 276, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-16 13:01:28', '', 0, '', '', '', 0, '', 0, '', '2017-12-16 13:01:36', '2017-12-18 14:03:29', 1, '', '', '', '', '', '', '', '', '', ''), (236, 273, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-16 14:14:08', '', 0, '', '', '', 0, '', 0, '', '2017-12-16 14:16:51', '2017-12-18 14:03:59', 1, '', '', '', '', '', '', 'Check pipetting tip, measurement chamber and product drawer teprature and calibration was done for temp.\r\n', '', '', ''), (237, 280, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-18 16:21:57', '', 0, '', '', '', 0, '', 0, '', '2017-12-18 16:22:07', '2017-12-18 16:24:47', 1, '', '', '', '', '', '', '', '', '', ''), (238, 278, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-18 16:22:13', '', 0, '', '', '', 0, '', 0, '', '2017-12-18 16:22:28', '2017-12-18 16:25:02', 1, '', '', '', '', '', '', '', '', '', ''), (239, 281, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-19 12:54:14', '', 0, '', '', '', 0, '', 0, '', '2017-12-19 12:54:26', '2017-12-19 12:57:45', 1, '', '', '', '', '', '', '', '', '', ''), (240, 289, 7, 0, 900, 0, 0, 0, 900, 0, 0, 900, 0, '', '2017-12-30 12:18:24', '', 0, 'this is test data. please ignore itgfdhgfhfd', '', 'gsdgsdgsdgsdgsdgdsgds', 0, '', 0, '', '2017-12-30 12:18:55', '2018-02-08 18:35:10', 1, '2018-02-08 18:32:58', '', '', '', '', '', 'trjururt', '', '', 'ygiytitfityu'), (241, 285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2017-12-30 14:29:56', '', 0, '', '', ' ', 0, '', 0, '', '2017-12-30 14:30:01', '2017-12-30 14:30:01', 0, '', '', '', '', '', '', '', '', '', ''), (242, 276, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '', '', 0, '', '', '', 0, '', 0, '', '', '', 0, '', '', '', '', '', '', '', '', '', ''), (243, 290, 4, 0, 0, 0, 897, 0, 898, 0, 1, 787, 111, '', '2018-02-08 13:32:09', 'Cdsafafas', 0, 'asfasdfasfasf', '', 'sadfsafsadfdasfsafasdfasfsdaf', 0, '', 0, '', '2018-02-08 13:32:22', '2018-02-08 16:47:51', 1, '2018-02-08 16:32:33', 'fdsafddsafsafs', '', '', '', '', 'fdsgdfsgsdgsdgd', '', '', 'sgdfsgsdgdsgsdgsdg'), (244, 291, 5, 0, 0, 0, 897, 0, 897, 0, 0, 897, 0, '', '2018-02-08 17:13:54', '', 0, 'asfasfdsafasfasfasfasfsafsafsafasfsafsa', '', ' trhyrdtxfthytjhnygtuj', 0, '', 0, '', '2018-02-08 17:14:29', '2018-02-13 14:47:35', 1, '2018-02-13 14:47:11', 'sadfsafasfasfafafaf', '', '', '', '', 'hjutfujgtfujgtjitgui', '', '', 'rtdtrhygftrhycfghgd'), (245, 292, 4, 0, 234, 111111, 897, 0, 112242, 0, 0, 0, 0, '', '2018-02-13 16:40:20', '', 0, 'ssssssssssssss', '', ' a new customer remarks', 1, '', 0, '', '2018-02-13 16:41:33', '2018-02-13 16:41:33', 0, '2018-02-13 16:40:20', 'sfsafasfsafasfsaf', '', '', '', '', '', '', '', ''), (246, 294, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2018-02-13 18:24:10', '', 0, '', '', '', 0, '', 0, '', '2018-02-13 18:24:41', '2018-02-13 18:24:41', 0, '', '', '', '', '', '', 'safsafasfasfsafsafsafsafsfsafs', '', '', 'asffasfsafsaf'), (247, 295, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2018-02-14 11:28:14', '', 0, '', '', '', 0, '', 0, '', '2018-02-14 11:28:53', '2018-02-14 11:28:53', 0, '', '', '', '', '', '', 'bbbbbbbbbbb', '', '', 'aaaaaaaa'), (248, 296, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '', '2018-02-14 14:11:52', '', 0, 'sasdssdadsssas', '', ' ', 0, '', 0, '', '2018-02-14 14:13:05', '2018-02-14 16:13:03', 44, '2018-02-14 16:11:59', 'dfhdfhdfhdfhdhdhh', '', '', '', '', 'dhdfhdfhd', '', '', 'hgdfhdfhdfhdf'), (249, 297, 8, 0, 1752, 0, 897, 0, 2649, 0, 0, 2649, 0, '', '2018-02-14 15:18:55', 'dsfgsdgsdgsd', 0, '', '', 'dsgsdgdsfgdsgsdgfdsgsdgsdgsdgfsd', 1, '', 0, '', '2018-02-14 15:19:28', '2018-02-14 15:28:25', 1, '', '', '', '', '', '', 'fsafdsafsdafsafsafdsafsdafasfafasfasfa', '', '', 'sdafasfasfasf'), (250, 298, 3, 0, 86508706, 0, 897, 0, 86509603, 0, 0, 86509603, 0, '', '2018-02-14 16:32:20', 'Delivered', 0, '', '', 'sdgfdsgdsgsdgs', 0, '', 0, '', '2018-02-14 16:33:04', '2018-06-29 14:58:56', 1, '2018-02-14 16:32:20', 'fsdgsgsgsdgsgsdgsdgdsgsdgsdgdsgsd', '', '', '', '', 'gsfdgdsfgsdgfsdgsdgsdgdsgdsgsdgds', '', '', 'sgfsgfsdgsdgds'); -- -------------------------------------------------------- -- -- Table structure for table `quote_review_spare_details` -- CREATE TABLE IF NOT EXISTS `quote_review_spare_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `request_id` int(50) NOT NULL, `spare_id` int(10) NOT NULL, `spare_qty` int(10) NOT NULL, `amt` int(10) NOT NULL, `spare_engg_id` int(50) NOT NULL, `approval_status` varchar(50) NOT NULL, `warranty_claim_status` varchar(100) NOT NULL, `desc_failure` varchar(500) NOT NULL, `why_failure` varchar(500) NOT NULL, `correct_action` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ; -- -- Dumping data for table `quote_review_spare_details` -- INSERT INTO `quote_review_spare_details` (`id`, `request_id`, `spare_id`, `spare_qty`, `amt`, `spare_engg_id`, `approval_status`, `warranty_claim_status`, `desc_failure`, `why_failure`, `correct_action`) VALUES (1, 17, 0, 0, 0, 0, '', 'to_claim', '', '', ''), (4, 1, 63, 1, 0, 1, 'approved', '', '', '', ''), (7, 55, 0, 0, 0, 0, '', '', '', '', ''), (8, 49, 114, 1, 0, 1, 'approved', '', '', '', ''), (9, 49, 189, 1, 0, 1, 'approved', '', '', '', ''), (15, 78, 236, 1, 0, 0, '', '', '', '', ''), (16, 50, 262, 1, 0, 0, '', 'to_claim', 'ERROR 12.01.10', 'DURING TEST RUN', 'REPLACED PHOTOMETRIC BOARD '), (17, 54, 40, 0, 0, 0, '', '', '', '', ''), (18, 84, 274, 1, 0, 0, '', 'to_claim', '', '', ''), (19, 100, 111, 1, 0, 0, '', '', '', '', ''), (20, 126, 71, 1, 0, 0, '', '', '', '', ''), (21, 126, 71, 1, 0, 0, '', '', '', '', ''), (22, 253, 262, 1, 0, 1, 'approved', 'to_claim', '', '', ''), (23, 95, 60, 1, 100, 0, '', '', '', '', ''), (24, 95, 82, 2, 400, 0, '', '', '', '', ''), (25, 95, 305, 3, 150, 0, '', '', '', '', ''), (26, 289, 74, 2, 100, 1, 'rejected', 'to_claim', 'fghdfhf', 'hgdf', 'hhfgfgfdhfghfgh'), (27, 289, 305, 2, 100, 1, 'rejected', '', '', '', ''), (28, 289, 82, 2, 400, 1, 'rejected', '', '', '', ''), (29, 289, 60, 3, 300, 1, 'rejected', '', '', '', ''), (30, 292, 307, 1, 234, 0, '', '', '', '', ''), (31, 294, 307, 1, 234, 1, 'approved', '', '', '', ''), (32, 295, 308, 2, 282828, 1, 'approved', '', '', '', ''), (33, 297, 309, 2, 1752, 1, 'approved', '', '', '', ''), (34, 298, 310, 2, 86508706, 1, 'approved', '', '', '', ''); -- -------------------------------------------------------- -- -- Table structure for table `service_category` -- CREATE TABLE IF NOT EXISTS `service_category` ( `id` int(10) NOT NULL AUTO_INCREMENT, `service_category` varchar(100) NOT NULL, `created_on` varchar(100) NOT NULL, `updated_on` varchar(100) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ; -- -- Dumping data for table `service_category` -- INSERT INTO `service_category` (`id`, `service_category`, `created_on`, `updated_on`, `user_id`) VALUES (1, 'BREAKDOWN', '2017-06-08 14:54:12', '2017-07-14 13:19:10', 1), (2, 'Weekly maintenance', '2017-07-24 16:06:17', '2017-07-24 16:06:17', 1), (3, 'Monthly maintenance', '2017-07-24 16:06:31', '2017-07-24 16:06:31', 1), (4, 'PM&CAL', '2017-07-24 16:06:59', '2017-07-24 16:06:59', 1), (5, 'Calibration', '2017-07-24 16:07:13', '2017-07-24 16:07:13', 1), (6, 'troubleshooting', '2017-07-24 16:07:24', '2017-07-24 16:07:24', 1), (7, 'General Visit', '2017-07-24 16:07:41', '2017-07-24 16:07:41', 1), (8, 'Software Upgradation', '2017-07-24 16:08:15', '2017-07-24 16:08:15', 1), (9, 'application call', '2017-10-31 15:36:23', '2018-02-14 14:35:19', 1); -- -------------------------------------------------------- -- -- Table structure for table `service_charge` -- CREATE TABLE IF NOT EXISTS `service_charge` ( `id` int(10) NOT NULL AUTO_INCREMENT, `service_cat_id` int(10) NOT NULL, `model` int(10) NOT NULL, `service_charge` int(50) NOT NULL, `created_on` varchar(100) NOT NULL, `updated_on` varchar(100) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `service_charge` -- INSERT INTO `service_charge` (`id`, `service_cat_id`, `model`, `service_charge`, `created_on`, `updated_on`, `user_id`) VALUES (1, 1, 4, 111111, '2018-02-09 16:24:49', '2018-02-09 16:24:49', 1); -- -------------------------------------------------------- -- -- Table structure for table `service_location` -- CREATE TABLE IF NOT EXISTS `service_location` ( `id` int(10) NOT NULL AUTO_INCREMENT, `serv_loc_code` varchar(100) NOT NULL, `service_loc` varchar(100) NOT NULL, `concharge` int(10) NOT NULL, `zone_coverage` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; -- -- Dumping data for table `service_location` -- INSERT INTO `service_location` (`id`, `serv_loc_code`, `service_loc`, `concharge`, `zone_coverage`) VALUES (1, '1', 'MUMBAI', 0, 'outstation'), (2, '2', 'UP', 0, 'on_site'), (3, '3', 'BHOPAL', 0, 'outstation'), (4, '4', 'JAIPUR', 0, 'outstation'), (5, '5', 'BANGALORE', 0, 'outstation'), (6, '6', 'PATNA', 0, 'outstation'), (7, '7', 'HYDERABAD', 0, 'outstation'), (8, '8', 'CHENNAI', 0, 'outstation'), (9, '9', 'Vellore', 0, 'outstation'), (10, '10', 'Chitoor', 0, 'outstation'), (11, '11', 'Telangana', 0, 'outstation'), (12, '12', '<NAME>', 0, 'outstation'), (13, '13', 'Navi-Mumbai', 0, 'outstation'), (14, '14', 'Rajasthan', 0, 'outstation'), (15, '15', 'PUNE', 0, 'outstation'), (16, '16', 'INDORE', 0, 'outstation'), (17, '17', 'TAMILNADU', 0, 'outstation'), (18, '11', 'choolai', 3333, 'on_site'), (19, '61', 'Mannargudi', 897, 'on_site'); -- -------------------------------------------------------- -- -- Table structure for table `service_request` -- CREATE TABLE IF NOT EXISTS `service_request` ( `id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT, `request_id` varchar(50) NOT NULL, `cust_name` varchar(100) NOT NULL, `br_name` int(10) NOT NULL, `mobile` varchar(50) NOT NULL, `email_id` varchar(250) NOT NULL, `address` varchar(100) NOT NULL, `address1` varchar(100) NOT NULL, `request_date` varchar(100) NOT NULL, `status` int(10) NOT NULL DEFAULT '0', `created_on` varchar(50) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, `active_req` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=315 ; -- -- Dumping data for table `service_request` -- INSERT INTO `service_request` (`id`, `request_id`, `cust_name`, `br_name`, `mobile`, `email_id`, `address`, `address1`, `request_date`, `status`, `created_on`, `updated_on`, `user_id`, `active_req`) VALUES (00001, '00001', '00201', 218, '8168421620', '', 'AFMC Special Lab Camp Pune', '', '2017-06-02 15:06', 3, '2017-06-02 15:10:37', '2017-09-15 15:18:52', 1, 0), (00002, '00002', '00202', 219, '9922568759', '', 'Hinjewadi Phase 2', '', '2017-06-02 15:12', 3, '2017-06-02 15:14:10', '2017-08-10 16:36:36', 1, 0), (00003, '00003', '00002', 2, '9884057732', '<EMAIL>', 'Greams Rd,Chennai', '', '2017-06-02 17:02', 5, '2017-06-02 17:06:01', '2017-07-26 13:05:52', 1, 1), (00017, '00004', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-06-06 14:52', 3, '2017-06-08 15:12:49', '2017-07-13 17:06:47', 1, 0), (00018, '00005', '00328', 345, '8066628736', '', 'No.96,Industrial Suburb, II Stage, Industrial Area, Yeshwantpur ', '', '2017-06-20 12:38', 1, '2017-06-20 12:44:48', '2017-10-27 15:04:01', 1, 0), (00019, '00006', '00002', 2, '9884057732', '<EMAIL>', 'Greams Rd,Chennai', '', '2017-06-20 12:49', 3, '2017-06-20 12:51:37', '2017-06-20 12:51:37', 1, 0), (00020, '00007', '00069', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-05-25 19:27', 1, '2017-06-29 19:31:00', '2017-07-03 12:53:11', 1, 0), (00021, 'P-00001', '00155', 168, '', '', '', '', '2017-07-01 00:00:00', 3, '', '2017-07-03 13:20:49', 1, 0), (00023, '00008', '00017', 161, '7738058952', '<EMAIL>', 'Belapur CBD', '', '2017-07-29 13:33', 3, '2017-07-03 13:45:08', '2017-07-03 13:45:08', 1, 0), (00024, '00009', '00134', 147, '7314206705', '', '14 Manik Bagh Road, Indore, Madhya Pradesh', '', '2017-06-24 16:37', 3, '2017-07-03 16:48:08', '2017-07-06 14:18:49', 1, 0), (00025, '00010', '00002', 2, '9884057732', '<EMAIL>', 'Greams Rd,Chennai', '', '2017-07-03 18:36', 10, '2017-07-03 18:38:03', '2017-07-26 13:05:28', 1, 1), (00026, '00011', '00059', 69, '9918883214', '', '1 st Floor, C block Pathology Lab SGPGI Lucknow', '', '2017-07-05 14:14', 3, '2017-07-05 14:15:46', '2017-07-05 14:15:46', 1, 0), (00027, '00012', '00140', 153, '9826089221', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', '2017-07-06 11:00', 3, '2017-07-06 14:16:37', '2017-07-06 14:21:19', 1, 0), (00028, '00013', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-07-07 15:31', 3, '2017-07-07 15:33:18', '2017-07-07 15:33:18', 1, 0), (00029, '00014', '00203', 220, '9822862623', '', 'Narhe, Pune', '', '2017-07-11 14:26', 3, '2017-07-11 14:27:38', '2017-07-11 14:32:36', 1, 0), (00030, '00015', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-07-11 18:22', 3, '2017-07-11 18:37:33', '2017-07-12 14:40:12', 1, 0), (00031, '00016', '00173', 188, '8411000515', '', 'Kharadi Bypass Road, Hadapsar, Pune', '', '2017-07-12 10:00', 3, '2017-07-12 11:13:56', '2017-07-12 14:37:04', 1, 0), (00032, '00017', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-07-12 11:14', 3, '2017-07-12 11:16:55', '2017-07-12 19:08:29', 34, 0), (00033, '00018', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 12:00', 3, '2017-07-12 12:01:19', '2017-07-26 13:04:28', 1, 1), (00034, '00019', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 12:04', 3, '2017-07-12 12:04:47', '2017-07-12 12:04:47', 1, 0), (00035, '00020', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-07-12 13:34', 3, '2017-07-12 13:35:37', '2017-07-12 13:35:37', 1, 0), (00036, '00021', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 15:58', 3, '2017-07-12 16:08:01', '2017-07-29 15:46:31', 1, 0), (00037, '00022', '1', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 16:53', 3, '2017-07-12 16:53:45', '2017-07-12 17:00:00', 1, 0), (00038, '00023', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 17:02', 1, '2017-07-12 17:03:07', '2017-07-12 17:04:12', 1, 0), (00039, '00024', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-12 17:20', 4, '2017-07-12 17:20:58', '2017-07-22 12:27:36', 1, 0), (00040, '00025', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-07-12 17:35', 4, '2017-07-12 17:36:35', '2017-07-12 17:41:26', 1, 0), (00041, '00026', '00066', 78, '9452177802', '', '7th floor RMLIMS Vibhuti khand Gomti Nagr LUCKNOW', '', '2017-07-13 17:08', 3, '2017-07-13 17:10:46', '2017-07-14 11:15:27', 1, 0), (00042, '00027', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-07-13 18:43', 3, '2017-07-13 18:43:53', '2017-07-13 18:43:53', 1, 0), (00043, '00028', '61', 73, '9412901682', '', 'doiawalla jolly grand dehradun', '', '2017-07-13 18:00', 3, '2017-07-14 11:08:58', '2017-07-14 18:50:15', 39, 0), (00044, '00029', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-07-14 11:10', 3, '2017-07-14 11:11:50', '2017-07-17 14:32:09', 1, 0), (00045, '00030', '00330', 347, '9840645605', '', 'new avadi rd chennai', '', '2017-07-14 13:56', 3, '2017-07-14 14:03:07', '2017-07-14 17:55:09', 1, 0), (00046, '00031', '00150', 163, '9870889775', '', 'Wagle Industrial Estate, Ambika Nagar No 3', '', '2017-07-14 17:38', 3, '2017-07-14 17:44:13', '2017-07-17 14:29:06', 1, 0), (00047, '00032', '00076', 88, '7579174424', '', ' rampur road haldwani', '', '2017-07-15 12:43', 3, '2017-07-15 12:44:23', '2017-07-17 14:28:26', 1, 0), (00048, '00033', '00140', 153, '9826089221', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', '2017-07-15 13:01', 3, '2017-07-15 13:03:29', '2017-07-17 14:27:30', 1, 0), (00049, '00034', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-07-17 12:59', 9, '2017-07-17 13:00:20', '2017-07-22 12:54:56', 34, 0), (00050, '00035', '00136', 149, '9425302826', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', '2017-07-17 16:44', 3, '2017-07-17 16:49:44', '2017-08-10 16:35:27', 1, 0), (00051, '00036', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-18 13:29', 3, '2017-07-18 13:30:31', '2017-07-22 12:27:17', 1, 0), (00052, '00037', '00069', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-07-18 15:11', 3, '2017-07-18 15:13:12', '2017-07-19 13:56:07', 39, 0), (00053, '00038', '69', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-07-20 20:48', 3, '2017-07-20 20:51:00', '2017-07-21 11:57:13', 40, 0), (00054, '00039', '00201', 218, '8168421620', '', 'AFMC Special Lab Camp Pune', '', '2017-07-20 20:52', 3, '2017-07-20 20:53:19', '2017-08-10 16:37:54', 1, 0), (00055, '00040', '00123', 136, '9893264320', '', '6, Malipura, Bhopal, Madhya Pradesh', '', '2017-07-21 18:36', 3, '2017-07-21 18:38:51', '2017-08-28 17:45:44', 1, 0), (00056, '00041', '00006', 6, '9962474499', '', '<NAME>,Chennai', '', '2017-07-22 12:09', 3, '2017-07-22 12:10:29', '2017-07-24 14:26:54', 1, 0), (00057, '00042', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-07-22 12:12', 3, '2017-07-22 12:14:12', '2017-07-24 14:26:37', 1, 0), (00058, '00043', '00202', 219, '9922568759', '', 'Hinjewadi Phase 2', '', '2017-07-24 15:22', 3, '2017-07-24 15:23:19', '2017-10-27 15:23:12', 1, 0), (00059, '00044', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-24 18:35', 3, '2017-07-24 18:36:58', '2017-08-01 17:44:59', 1, 0), (00060, '00045', '00013', 13, '9444200883', '', 'Perambur,Chennai', '', '2017-07-25 17:01', 3, '2017-07-25 17:02:55', '2017-07-25 17:05:00', 1, 0), (00061, '00046', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-07-25 17:55', 3, '2017-07-25 17:56:40', '2017-07-26 13:04:05', 1, 0), (00062, '00047', '00066', 78, '9452177802', '', '7th floor RMLIMS Vibhuti khand Gomti Nagr LUCKNOW', '', '2017-07-26 12:48', 3, '2017-07-26 12:53:26', '2017-07-31 13:41:32', 1, 0), (00063, '00048', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-07-26 12:57', 3, '2017-07-26 13:00:34', '2017-07-27 11:46:24', 1, 0), (00064, '00049', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-07-27 15:52', 3, '2017-07-27 15:54:33', '2017-07-31 13:16:09', 1, 0), (00065, '00050', '61', 73, '9412901682', '', 'doiawalla jolly grand dehradun', '', '2017-07-27 12:00', 3, '2017-07-27 21:38:19', '2017-08-11 10:52:11', 40, 0), (00066, '00051', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-07-29 10:48', 1, '2017-07-29 10:49:53', '2017-07-29 10:49:53', 1, 1), (00067, '00052', '00026', 28, '04023480421', '', '230/235, Gemome Valley Road, Shamirper, ', '', '2017-08-01 17:40', 3, '2017-08-01 17:41:22', '2017-08-04 12:33:13', 1, 0), (00068, '00053', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-03 10:22', 1, '2017-08-03 10:22:37', '2017-08-03 10:22:37', 1, 1), (00069, '00054', '3', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-08-03 10:23', 1, '2017-08-03 10:23:37', '2017-08-03 10:24:19', 1, 1), (00070, '00055', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-03 10:24', 1, '2017-08-03 10:24:52', '2017-08-03 10:24:52', 1, 1), (00071, '00056', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-03 10:26', 1, '2017-08-03 10:26:41', '2017-08-03 10:26:41', 1, 1), (00072, '00057', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-03 10:30', 1, '2017-08-03 10:30:36', '2017-08-03 10:30:36', 1, 1), (00073, '00058', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-08-03 11:08', 1, '2017-08-03 11:09:06', '2017-08-03 11:09:06', 1, 0), (00074, '00059', '00152', 165, '9819281495', '', 'Juhu', '', '2017-08-03 13:01', 3, '2017-08-03 13:03:25', '2017-10-27 15:26:43', 1, 0), (00075, '00060', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-08-03 13:42', 3, '2017-08-03 13:43:18', '2017-08-03 14:27:08', 1, 0), (00076, '00061', '00006', 6, '9962474499', '', '<NAME>,Chennai', '', '2017-08-03 13:43', 3, '2017-08-03 13:44:33', '2017-08-03 14:26:53', 1, 0), (00077, '00062', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-08-03 13:45', 3, '2017-08-03 13:45:52', '2017-08-03 14:26:39', 1, 0), (00078, '00063', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-08-04 15:22', 3, '2017-08-04 15:23:17', '2017-08-09 17:54:43', 1, 0), (00079, '00064', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-08-04 15:44', 1, '2017-08-04 15:45:21', '2017-08-04 15:45:21', 1, 1), (00080, 'P-00002', '00329', 346, '09811138416', '', '', '', '2017-08-05 00:00:00', 3, '', '', 0, 0), (00081, '00065', '00203', 220, '9822862623', '', 'Narhe, Pune', '', '2017-08-05 15:19', 3, '2017-08-05 15:20:25', '2017-10-27 15:26:29', 1, 0), (00082, '00066', '00201', 218, '8168421620', '', 'AFMC Special Lab Camp Pune', '', '2017-08-05 15:20', 3, '2017-08-05 15:22:01', '2017-08-05 15:44:44', 1, 0), (00083, '00067', '00153', 166, '9892259766', '<EMAIL>', 'near Trimurti film city', '', '2017-08-07 13:00', 3, '2017-08-07 15:45:07', '2017-10-27 15:26:03', 1, 0), (00084, '00068', '00218', 235, '8877887712', '', '<NAME> , <NAME>', '', '2017-08-06 11:00', 3, '2017-08-07 15:47:53', '2017-11-09 13:11:36', 1, 0), (00085, '00069', '00144', 156, '9869314808', '<EMAIL>', '4rth floor, kohinoor commercial building', '', '2017-07-29 10:00', 3, '2017-08-07 17:24:54', '2017-10-27 15:25:34', 1, 0), (00086, '00070', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-08-08 12:45', 3, '2017-08-08 12:46:34', '2017-08-08 12:47:44', 1, 0), (00087, '00071', '00339', 356, '2223777800', '', 'Aga Hall Nesbit Road, Mazagaon Mumbai-400 010', '', '2017-08-08 13:21', 3, '2017-08-08 13:27:19', '2017-08-08 13:31:34', 1, 0), (00088, '00072', '00056', 66, '9972089942', '', 'M S Ramaiah Narayana Heart Centre, Basement, M. S. Ramaiah Memorial Hospital, MSR College Road, MSRI', '', '2017-08-08 16:28', 1, '2017-08-08 16:29:38', '2017-08-08 16:29:38', 1, 0), (00089, '00073', '00061', 73, '9412901682', '', 'doiawalla jolly grand dehradun', '', '2017-08-09 16:39', 3, '2017-08-09 17:08:34', '2017-08-11 10:51:23', 40, 0), (00090, '00074', '00017', 161, '7738058952', '<EMAIL>', 'Belapur CBD', '', '2017-08-09 17:08', 3, '2017-08-09 17:13:39', '2017-10-27 15:25:01', 1, 0), (00091, '00075', '00069', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-08-10 13:01', 3, '2017-08-10 13:06:47', '2017-08-11 10:04:16', 39, 0), (00092, '00076', '00203', 220, '9822862623', '', 'Narhe, Pune', '', '2017-08-10 14:43', 3, '2017-08-10 14:44:53', '2017-08-10 16:40:11', 33, 0), (00093, '00077', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-10 14:56', 3, '2017-08-10 14:57:20', '2017-08-14 14:51:57', 32, 0), (00094, '00078', '00340', 357, '9770836446', '', 'J.K. Town, Sarvadharam C-Sector, Kolar Road, Bhopal, Madhya Pradesh', 'J.K. Town, Sarvadharam C-Sector, Kolar Road, Bhopal, Madhya Pradesh', '2017-08-10 12:00', 3, '2017-08-10 16:24:50', '2017-08-10 16:34:37', 1, 0), (00095, '00079', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-08-10 17:45', 1, '2017-08-10 17:46:42', '2018-02-13 14:51:02', 1, 0), (00096, '00080', '00061', 73, '9412901682', '', 'doiawalla jolly grand dehradun', '', '2017-08-11 09:54', 3, '2017-08-11 09:56:58', '2017-08-16 16:29:18', 39, 0), (00097, '00081', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-08-11 19:14', 1, '2017-08-11 19:14:56', '2017-08-11 19:20:54', 43, 1), (00098, '00082', '00093', 104, '', '', 'satabdi bulding kgmc chowk lucknow', '', '2017-08-12 12:07', 3, '2017-08-12 12:08:11', '2017-08-12 12:53:06', 39, 0), (00099, '00083', '00145', 157, '9892982681', '<EMAIL>', '6th floor,Global Hospital', '', '2017-08-12 12:10', 3, '2017-08-12 12:17:58', '2017-10-27 15:24:14', 1, 0), (00100, '00084', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-08-14 14:49', 3, '2017-08-14 14:51:15', '2017-08-14 14:52:51', 32, 0), (00101, '00085', '00063', 75, '8439233948', '', '7 manjila bullding pathology lab moti katra agra', '', '2017-08-16 15:53', 3, '2017-08-16 15:54:18', '2017-08-16 16:23:20', 39, 0), (00102, '00086', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-16 15:54', 3, '2017-08-16 15:56:38', '2017-08-18 12:13:36', 32, 0), (00103, '00087', '00007', 7, '9841429606', '', '<NAME>', '', '2017-08-18 12:10', 3, '2017-08-18 12:12:13', '2017-08-18 12:13:50', 32, 0), (00104, '00088', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-08-18 12:14', 3, '2017-08-18 12:15:51', '2017-08-18 12:16:51', 32, 0), (00105, '00089', '00171', 185, '9689911129', '', 'Deccan, Pune', '', '2017-08-18 15:27', 3, '2017-08-18 15:28:48', '2017-08-18 17:04:22', 33, 0), (00106, '00090', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-08-18 16:02', 3, '2017-08-18 16:02:45', '2017-08-24 15:38:16', 1, 0), (00107, '00091', '00147', 159, '8691077402', '', 'Charni road ', '', '2017-08-18 17:48', 3, '2017-08-18 17:49:06', '2017-08-19 11:32:51', 40, 0), (00108, '00092', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-08-19 12:14', 3, '2017-08-19 12:14:59', '2017-08-19 19:50:56', 39, 0), (00109, '00093', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-08-19 12:21', 3, '2017-08-19 12:21:54', '2017-08-19 12:23:48', 32, 0), (00110, '00094', '00156', 169, '9323483252', '<EMAIL>', '383 Bhaveshwar Vihar, Sardar V P Road', '', '2017-08-19 16:42', 3, '2017-08-19 16:43:35', '2017-10-27 15:23:49', 1, 0), (00111, '00095', '00147', 159, '8691077402', '', 'Charni road ', '', '2017-08-19 16:45', 3, '2017-08-19 16:46:11', '2017-10-27 15:22:53', 1, 0), (00112, '00096', '00059', 71, '9335903344', '', '1 st Floor, 24 hr Lab SGPGI Lucknow', '', '2017-08-19 16:55', 3, '2017-08-19 16:57:49', '2017-10-27 15:19:17', 1, 0), (00113, '00097', '00145', 157, '9892982681', '<EMAIL>', '6th floor,Global Hospital', '', '2017-08-21 19:36', 3, '2017-08-21 19:37:36', '2017-10-27 15:19:02', 1, 0), (00114, '00098', '00147', 159, '8691077402', '', 'Charni road ', '', '2017-08-22 15:07', 3, '2017-08-22 15:07:55', '2017-10-27 15:18:36', 1, 0), (00115, '00099', '00180', 187, '', '', 'Swargate, Pune', '', '2017-08-23 17:38', 3, '2017-08-23 17:40:18', '2017-10-27 15:18:24', 1, 0), (00116, '00100', '00206', 223, '9890304750', '', '<NAME>', '', '2017-08-24 13:22', 9, '2017-08-24 13:26:15', '2017-08-24 17:55:16', 33, 0), (00117, '00101', '00172', 186, '', '<EMAIL>', '375,Urawade, Tal- Muishi, Pune', '', '2017-08-28 13:22', 3, '2017-08-28 13:23:08', '2017-10-27 15:18:00', 1, 0), (00118, '00102', '00218', 235, '8877887712', '', 'BAILY ROAD , RAJA BAJAR', '', '2017-08-28 14:09', 3, '2017-08-28 14:10:41', '2017-11-09 13:11:07', 1, 0), (00119, '00103', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-08-28 18:41', 3, '2017-08-28 18:42:01', '2017-09-18 18:49:50', 1, 0), (00120, '00104', '00103', 115, '9410058658', '', 'State Highway saifai ', '', '2017-08-29 14:30', 3, '2017-08-29 14:31:56', '2017-10-27 15:17:46', 1, 0), (00121, '00105', '00141', 154, '7898003228', '', 'Sultania Rd, Royal Market, Near Hamidia Hospital, Bhopal, Madhya Pradesh ', '', '2017-08-30 15:45', 3, '2017-08-30 15:48:47', '2017-08-30 16:05:46', 1, 0), (00122, '00106', '00004', 4, '9884050521', 'drdeepakala.<EMAIL>', 'vadapalani,Chennai', '', '2017-08-30 17:28', 3, '2017-08-30 17:28:54', '2017-10-27 15:17:32', 1, 0), (00123, '00107', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-08-31 07:41', 3, '2017-08-31 07:43:39', '2017-10-27 15:16:57', 1, 0), (00124, '00108', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-08-31 11:46', 3, '2017-08-31 11:47:15', '2017-09-29 13:39:20', 1, 0), (00125, '00109', '00009', 9, '9941623477', '', 'adyar,chennai', '', '2017-08-31 13:39', 3, '2017-08-31 13:40:20', '2017-10-27 15:16:43', 1, 0), (00126, '00110', '00124', 137, '8871979174', '', 'MP State Branch Red Cross Bhawan <NAME>,, Bhopal, Madhya Pradesh ', '', '2017-08-31 15:32', 3, '2017-08-31 15:33:06', '2017-09-08 16:16:50', 1, 0), (00127, '00111', '00136', 149, '9425302826', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', '2017-09-01 12:46', 3, '2017-09-01 12:47:18', '2017-09-08 16:15:43', 1, 0), (00128, '00112', '00007', 7, '9841429606', '', '<NAME>', '', '2017-09-02 12:29', 3, '2017-09-02 12:30:24', '2017-09-21 13:12:23', 1, 0), (00129, '00113', '00031', 44, '9100974616', '', 'D.No: 48-10-12/2A, Opp. NTR University of Health Sciences, Vijayawada, Andhra Pradesh?', '', '2017-09-02 12:32', 3, '2017-09-02 12:33:10', '2017-10-25 15:43:33', 1, 0), (00130, '00114', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-09-02 16:57', 3, '2017-09-02 16:58:08', '2017-10-27 15:16:27', 1, 0), (00131, '00115', '00103', 115, '9410058658', '', 'State Highway saifai ', '', '2017-09-04 16:12', 3, '2017-09-04 16:15:46', '2017-10-25 15:40:37', 1, 0), (00132, '00116', '00068', 80, '8423740390', '', 'LANKA VARANASI', '', '2017-09-04 16:16', 3, '2017-09-04 16:17:45', '2017-10-25 15:40:23', 1, 0), (00133, '00117', '00059', 71, '9335903344', '', '1 st Floor, 24 hr Lab SGPGI Lucknow', '', '2017-09-05 14:54', 3, '2017-09-05 14:56:41', '2017-10-25 15:40:08', 1, 0), (00134, '00118', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-09-07 12:20', 3, '2017-09-07 12:20:48', '2017-09-19 14:31:45', 1, 0), (00135, '00119', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-09-07 12:20', 3, '2017-09-07 12:21:38', '2017-09-19 14:31:22', 1, 0), (00136, '00120', '00140', 153, '9826089221', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', '2017-09-08 16:04', 3, '2017-09-08 16:05:40', '2017-10-25 15:39:49', 1, 0), (00137, '00121', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-09-09 14:50', 3, '2017-09-09 14:51:43', '2017-09-22 17:55:07', 1, 0), (00138, '00122', '', 0, '', '', '', '', '', 0, '2017-09-09 14:51:43', '2017-09-09 14:51:43', 0, 0), (00139, '00123', '00152', 165, '9819281495', '', 'Juhu', '', '2017-09-13 20:48', 3, '2017-09-13 20:49:09', '2017-09-22 13:50:34', 1, 0), (00140, '00124', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-09-13 20:49', 3, '2017-09-13 20:50:30', '2017-09-21 13:12:02', 1, 0), (00141, '00125', '00007', 7, '9841429606', '', '<NAME>', '', '2017-09-15 11:33', 3, '2017-09-15 11:34:24', '2017-09-18 18:48:36', 1, 0), (00142, '00126', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-09-15 12:12', 3, '2017-09-15 12:13:32', '2017-09-19 14:31:06', 1, 0), (00143, '00127', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-09-28 13:18', 3, '2017-09-15 13:18:52', '2017-09-18 18:46:31', 1, 0), (00144, '00128', '00097', 108, '7388700670', '', '', '', '2017-09-18 00:00:00', 0, '', '', 0, 0), (00145, '00129', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-09-18 13:08', 3, '2017-09-18 13:09:49', '2017-09-18 18:47:33', 1, 0), (00146, '00130', '00200', 217, '9890300502', '', 'Dhole Palit Rd. Pune', '', '2017-09-18 13:17', 3, '2017-09-18 13:17:40', '2017-09-21 13:11:47', 1, 0), (00147, '00131', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-09-18 17:09', 3, '2017-09-18 17:10:26', '2017-09-19 14:30:50', 1, 0), (00148, '00132', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-09-19 15:05', 3, '2017-09-19 15:06:04', '2017-09-20 16:43:48', 1, 0), (00149, '00133', '00009', 360, '9941623477', '', '', '', '2017-09-21 00:00:00', 0, '', '', 0, 0), (00150, '00134', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-09-21 13:07', 3, '2017-09-21 13:08:04', '2017-09-21 13:11:06', 1, 0), (00151, '00135', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-09-22 13:41', 3, '2017-09-22 13:42:22', '2017-10-17 18:46:47', 1, 0), (00152, '00136', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-09-22 13:47', 3, '2017-09-22 13:48:33', '2017-09-22 13:50:19', 1, 0), (00153, '00137', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-09-22 17:28', 3, '2017-09-22 17:29:26', '2017-09-22 17:53:14', 1, 0), (00154, '00138', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-09-22 18:04', 3, '2017-09-22 18:05:06', '2017-09-25 13:13:06', 1, 0), (00155, '00139', '00143', 155, '9833031032', '<EMAIL>', 'Plot No 1, Prime Square building,Next to Patel Petrol Pump,S.V. Road,Goregaon West', '', '2017-09-23 13:35', 1, '2017-09-23 13:38:18', '2017-09-23 13:38:18', 1, 0), (00156, '00140', '00143', 155, '9833031032', '<EMAIL>', 'Plot No 1, Prime Square building,Next to Patel Petrol Pump,S.V. Road,Goregaon West', '', '2017-09-23 13:38', 1, '2017-09-23 13:38:56', '2017-09-23 13:38:56', 1, 0), (00157, '00141', '00143', 155, '9833031032', '<EMAIL>', 'Plot No 1, Prime Square building,Next to Patel Petrol Pump,S.V. Road,Goregaon West', '', '2017-09-23 13:48', 1, '2017-09-23 13:48:44', '2017-09-23 13:48:44', 1, 0), (00158, 'P-00003', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-09-23', 3, '', '2017-09-26 19:49:23', 1, 0), (00159, 'P-00004', '00169', 183, '9890125380', '', 'Balgandharve Road, Pune', '', '2017-09-23', 3, '', '2017-10-27 15:15:00', 1, 0), (00160, '00142', '00061', 73, '9412901682', '', '<NAME>', '', '2017-09-23 20:03', 3, '2017-09-23 20:04:30', '2017-10-17 18:46:00', 1, 0), (00161, 'P-00005', '00143', 155, '9833031032', '<EMAIL>', 'Plot No 1, Prime Square building,Next to Patel Petrol Pump,S.V. Road,Goregaon West', '', '2017-09-23', 3, '', '2017-10-27 15:14:46', 1, 0), (00162, '00143', '00396', 417, '6555555555556', '', '', '', '2017-09-25 00:00:00', 0, '', '', 0, 0), (00163, 'P-00006', '00051', 61, '9663827717', '', 'HCG Towers No 8, Kalinga Rao Road, HMT Estate, Sampangiram Nagar, Bengaluru,', '', '2017-09-26', 3, '', '2017-10-27 15:14:32', 1, 0), (00164, '00144', '00136', 149, '9425302826', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', '2017-09-26 13:21', 3, '2017-09-26 13:22:10', '2017-10-17 18:45:45', 1, 0), (00165, '00145', '00136', 149, '9425302826', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', '2017-09-26 13:35', 3, '2017-09-26 13:36:25', '2017-10-17 18:45:31', 1, 0), (00166, '00146', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-09-26 13:38', 3, '2017-09-26 13:38:59', '2017-10-17 18:45:15', 1, 0), (00167, '00147', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-09-26 14:42', 3, '2017-09-26 14:43:38', '2017-10-17 18:45:01', 1, 0), (00168, '00148', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-09-26 14:42', 3, '2017-09-26 14:44:35', '2017-10-16 18:33:25', 1, 0), (00169, '00149', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-09-26 14:42', 3, '2017-09-26 14:45:40', '2017-10-16 18:33:04', 1, 0), (00170, '00150', '', 0, '', '', '', '', '', 0, '2017-09-26 14:47:31', '2017-09-26 14:47:31', 1, 0), (00171, '00151', '', 0, '', '', '', '', '', 0, '2017-09-26 14:47:34', '2017-09-26 14:47:34', 1, 0), (00172, '00152', '', 0, '', '', '', '', '', 0, '2017-09-26 14:47:35', '2017-09-26 14:47:35', 1, 0), (00173, '00153', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-09-26 14:49', 3, '2017-09-26 14:50:23', '2017-10-16 18:32:38', 1, 0), (00174, '00154', '00066', 78, '9452177802', '', '7th floor RMLIMS Vibhuti khand Gomti Nagr LUCKNOW', '', '2017-09-26 19:17', 3, '2017-09-26 19:20:24', '2017-10-16 18:32:24', 1, 0), (00175, '00155', '00386', 405, '77777777777', '', 'LUCKNOW,UP', '', '2017-09-26 19:45', 3, '2017-09-26 19:46:44', '2017-10-16 18:32:03', 1, 0), (00176, '00156', '00069', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-09-26 20:56', 3, '2017-09-26 20:57:58', '2017-10-16 18:31:47', 1, 0), (00177, '00157', '00070', 82, '9208052893', '', 'CVTS LAB KGMC chowk lucknow', '', '2017-09-27 15:19', 3, '2017-09-27 15:24:43', '2017-10-16 18:31:32', 1, 0), (00178, 'P-00007', '00161', 174, '9757209333', '', 'Forites hospital sector 10, Vashi', '', '2017-09-27', 3, '', '2017-10-27 15:14:20', 1, 0), (00179, 'P-00008', '00162', 175, '9619952626', '', 'Opp. KEM Hospital', '', '2017-09-27', 3, '', '2017-10-27 15:14:08', 1, 0), (00180, 'P-00009', '00182', 197, '9822329832', '', '<NAME>, B<NAME> Rd. Aurangabad', '', '2017-09-28', 3, '', '2017-10-27 15:13:53', 1, 0), (00181, '00158', '00397', 418, '9538869421', '', '', '', '2017-09-29 00:00:00', 0, '', '', 0, 0), (00182, '00159', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-09-29 13:36', 3, '2017-09-29 13:36:29', '2017-10-16 18:07:43', 1, 0), (00183, '00160', '00149', 162, '9833645854', '<EMAIL>', '<NAME>', '', '2017-09-29 15:57', 3, '2017-09-29 15:58:17', '2017-10-16 18:07:32', 1, 0), (00184, '00161', '00007', 7, '9841429606', '', '<NAME>', '', '2017-09-29 17:32', 3, '2017-09-29 17:32:37', '2017-10-03 20:26:50', 1, 0), (00185, '00162', '00001', 1, '9841313358', '<EMAIL>', '', '', '2017-10-03 00:00:00', 0, '', '', 0, 0), (00186, '00163', '00002', 2, '9884057732', '<EMAIL>', '', '', '2017-10-03 00:00:00', 0, '', '', 0, 0), (00187, '00164', '00001', 1, '9841313358', '<EMAIL>', '', '', '2017-10-03 00:00:00', 0, '', '', 0, 0), (00188, '00165', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-10-03 13:21', 3, '2017-10-03 13:22:01', '2017-10-03 20:26:36', 1, 0), (00189, '00166', '00066', 78, '9452177802', '', '7th floor RMLIMS Vibhuti khand Gomti Nagr LUCKNOW', '', '2017-10-03 20:24', 3, '2017-10-03 20:25:45', '2017-10-16 18:07:13', 1, 0), (00190, '00167', '00101', 113, '9198518227', '', 'trauma center kamc chowk lucknow', '', '2017-10-04 14:33', 3, '2017-10-04 14:34:42', '2017-10-16 18:06:42', 1, 0), (00191, '00168', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-10-04 16:52', 3, '2017-10-04 16:52:49', '2017-10-16 18:06:28', 1, 0), (00192, '00169', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-10-04 17:26', 3, '2017-10-04 17:27:37', '2017-10-06 12:23:24', 1, 0), (00193, '00170', '00060', 72, '7060771155', '', 'nirala nagar lucknow', '', '2017-10-05 17:47', 3, '2017-10-05 17:48:48', '2017-10-06 12:23:12', 1, 0), (00194, '00171', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-10-05 18:40', 3, '2017-10-05 18:41:29', '2017-10-06 12:22:43', 1, 0), (00195, '00172', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-10-06 12:16', 3, '2017-10-06 12:17:21', '2017-10-06 12:18:43', 1, 0), (00196, '00173', '00059', 71, '9335903344', '', '1 st Floor, 24 hr Lab SGPGI Lucknow', '', '2017-10-07 21:30', 3, '2017-10-07 21:32:37', '2017-10-16 18:05:29', 1, 0), (00197, '00174', '00201', 218, '8168421620', '', 'AFMC Special Lab Camp Pune', '', '2017-10-12 09:04', 3, '2017-10-12 09:05:53', '2017-10-16 18:02:14', 1, 0), (00198, '00175', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-10-12 17:34', 3, '2017-10-12 17:34:47', '2017-10-12 17:54:41', 1, 0), (00199, '00176', '00172', 186, '2331122546666', '<EMAIL>', '375,Urawade, Tal- Muishi, Pune', '', '2017-10-12 17:50', 3, '2017-10-12 17:51:11', '2017-10-31 12:58:33', 1, 0), (00200, '00177', '00008', 8, '9994780672', '<EMAIL>', '', '', '2017-10-13 00:00:00', 0, '', '', 0, 0), (00201, '00178', '00019', 19, '11111114444444', '', 'Road No. 1, Banjara Hills, Hyderabad', '', '2017-10-16 13:50', 3, '2017-10-16 13:51:18', '2017-10-16 17:59:59', 1, 0), (00202, '00179', '', 0, '', '', '', '', '', 0, '2017-10-16 13:51:18', '2017-10-16 13:51:18', 0, 0), (00203, '00180', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-10-16 15:25', 3, '2017-10-16 15:26:01', '2017-10-16 18:31:15', 1, 0), (00204, '00181', '00102', 114, '9627370258', '', '7b astely hall dehradun', '', '2017-10-16 17:42', 3, '2017-10-16 17:43:18', '2017-10-31 12:58:15', 1, 0), (00205, 'P-00010', '00153', 166, '9892259766', '<EMAIL>', 'near Trimurti film city', '', '2017-10-16', 0, '', '2017-11-14 14:09:30', 1, 0), (00206, '00182', '00140', 153, '9826089221', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', '2017-10-17 12:30', 3, '2017-10-17 12:32:45', '2017-10-25 15:39:29', 1, 0), (00207, '00183', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-10-17 12:35', 3, '2017-10-17 12:37:14', '2017-10-17 18:44:48', 1, 0), (00208, 'P-00011', '00059', 71, '9335903344', '', '1 st Floor, 24 hr Lab SGPGI Lucknow', '', '2017-10-17', 3, '', '2017-10-27 15:13:40', 1, 0), (00209, '00184', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-10-20 13:37', 3, '2017-10-20 13:37:57', '2017-10-25 15:38:38', 1, 0), (00210, '00185', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-10-23 12:10', 3, '2017-10-23 12:10:45', '2017-10-25 15:37:41', 1, 0), (00211, '00186', '00018', 18, '1111111111111', '', 'Virinchi Circle,, Hyderabad,', '', '2017-10-23 12:29', 3, '2017-10-23 12:29:42', '2017-11-13 15:22:36', 1, 0), (00212, '00187', '00389', 408, '111111233332222', '', 'T<NAME>, Grant Road West, Tardeo, Mumbai, Maharashtra 400007', '', '2017-10-23 16:28', 3, '2017-10-23 16:29:24', '2017-10-25 15:37:27', 1, 0), (00213, '00188', '00396', 417, '6555555555556', '', '', '', '2017-10-25 00:00:00', 0, '', '', 0, 0), (00214, '00189', '00401', 422, '9889124814', '', '', '', '2017-10-25', 0, '', '', 0, 0), (00215, '00190', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-10-25 13:59', 3, '2017-10-25 14:00:36', '2017-10-27 15:16:13', 1, 0), (00216, '00191', '00058', 68, '9900566592', '', 'Hosur Road, Lakkasandra, Wilson Garden', '', '2017-10-25 15:16', 3, '2017-10-25 15:17:02', '2017-10-27 15:16:01', 1, 0), (00217, '00192', '00151', 164, '9819750173', '<EMAIL>', '60 A, Bhulabhai desai road', '', '2017-10-25 15:31', 3, '2017-10-25 15:32:14', '2017-10-28 09:36:41', 1, 0), (00218, '00193', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-10-25 15:36', 3, '2017-10-25 15:36:42', '2017-10-27 15:15:50', 1, 0), (00219, '00194', '00136', 149, '9425302826', '', '120-121,Near Personal Branch SBI, Link Rd Number 3, E-3, Arera Colony, Bhopal, Madhya Pradesh ', '', '2017-10-24 14:00', 3, '2017-10-25 15:45:18', '2017-10-27 15:15:28', 1, 0), (00220, '00195', '00141', 154, '7898003228', '', 'Sultania Rd, Royal Market, Near Hamidia Hospital, Bhopal, Madhya Pradesh ', '', '2017-10-25 16:17', 3, '2017-10-25 16:18:42', '2017-10-27 15:15:12', 1, 0), (00221, '00196', '00069', 81, '9208052893', '', 'kgmc Trauma center chowk lucknow', '', '2017-10-25 16:45', 3, '2017-10-25 16:46:19', '2017-10-27 15:07:59', 1, 0), (00222, '00197', '00150', 163, '9870889775', '', 'Wagle Industrial Estate, Ambika Nagar No 3', '', '2017-10-27 12:14', 3, '2017-10-27 12:15:17', '2017-10-28 09:34:22', 1, 0), (00223, '00198', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-10-27 12:15', 3, '2017-10-27 12:16:31', '2017-10-27 15:35:28', 1, 0), (00224, '00199', '00405', 426, '9962594660', '', 'Bommasandra Industrial Area, Phase 4, Jigani link road, Biocon Park,, Bengaluru, Karnataka 560099', '', '2017-10-27 13:09', 3, '2017-10-27 13:10:09', '2017-11-02 15:04:00', 1, 0), (00225, '00200', '00325', 342, '9880224502', '', '154/9, bannerghata road, opp. IIM - B', '', '2017-10-27 13:11', 3, '2017-10-27 13:12:53', '2017-11-02 15:03:41', 1, 0), (00226, '00201', '00404', 425, '9585290232', '', 'NEAR CIVIL HOSPITAL', '', '2017-10-27 13:15', 3, '2017-10-27 13:18:59', '2017-10-31 12:58:04', 1, 0), (00227, '00202', '00171', 185, '9689911129', '', '', '', '2017-10-28', 0, '', '', 0, 0), (00228, '00203', '00099', 111, '8376061302', '', 'Gautam Budh nagar sector 30 noida ', '', '2017-10-28 12:23', 3, '2017-10-28 12:25:10', '2017-10-31 12:57:48', 1, 0), (00229, '00204', '00007', 7, '9841429606', '', '<NAME>', '', '2017-10-28 15:13', 3, '2017-10-28 15:14:28', '2017-10-31 15:32:24', 1, 0), (00230, '00205', '00134', 147, '7314206705', '', '14 Manik Bagh Road, Indore, Madhya Pradesh', '', '2017-10-31 12:51', 3, '2017-10-31 12:51:54', '2017-11-02 15:03:19', 1, 0), (00231, '00206', '00056', 66, '9972089942', '', 'M S Ramaiah Narayana Heart Centre, Basement, M. S. Ramaiah Memorial Hospital, MSR College Road, MSRI', '', '2017-10-31 13:21', 3, '2017-10-31 13:22:11', '2017-11-02 15:03:08', 1, 0), (00232, '00207', '00397', 418, '9538869421', '', 'No.7, Millers Tank Bed Area, Opposite Guru Nanak Bhavan, Jasma Bhavan Road, Vasanth Nagar, Bengaluru', '', '2017-10-31 13:22', 3, '2017-10-31 13:23:02', '2017-11-02 15:02:57', 1, 0), (00233, '00208', '00057', 67, '7829889829', '', '?No.31, Behind Big Marker, G Block, Bellary Road, Sahakara Nagar,?', '', '2017-10-31 13:23', 3, '2017-10-31 13:23:58', '2017-11-02 15:02:42', 1, 0), (00234, '00209', '00325', 342, '9880224502', '', '154/9, bannerghata road, opp. IIM - B', '', '2017-10-31 13:24', 3, '2017-10-31 13:25:03', '2017-11-02 15:02:30', 1, 0), (00235, '00210', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-10-31 16:16', 3, '2017-10-31 16:17:44', '2017-11-02 15:02:19', 1, 0), (00236, '00211', '00019', 19, '11111114444444', '', 'Road No. 1, Banjara Hills, Hyderabad', '', '2017-10-31 18:14', 3, '2017-10-31 18:15:44', '2017-11-02 15:01:51', 1, 0), (00237, '00212', '00152', 165, '9819281495', '', 'Juhu', '', '2017-10-31 20:23', 3, '2017-10-31 20:24:31', '2017-11-02 15:01:35', 1, 0), (00238, '00213', '00397', 418, '9538869421', '', 'No.7, Millers Tank Bed Area, Opposite Guru Nanak Bhavan, Jasma Bhavan Road, Vasanth Nagar, Bengaluru', '', '2017-11-01 14:38', 3, '2017-11-01 14:39:06', '2017-11-06 18:13:52', 1, 0), (00239, '00214', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-11-01 14:41', 3, '2017-11-01 14:43:12', '2017-11-04 13:57:07', 1, 0), (00240, '00215', '00059', 70, '9452243957', '', ' 1st Floor, C block Hemtology Lab SGPGI Lucknow', '', '2017-11-03 14:07', 3, '2017-11-03 15:26:01', '2017-11-04 13:56:53', 1, 0), (00241, '00216', '00017', 60, '9900654134', '', '154/11, Bannerghatta Road, Opposite IIM, Bengaluru,?', '', '2017-11-03 15:30', 3, '2017-11-03 15:31:40', '2017-11-06 18:13:35', 1, 0), (00242, '00217', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-11-04 12:15', 3, '2017-11-04 12:16:04', '2017-11-04 13:56:37', 1, 0), (00243, '00218', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-11-06 12:34', 3, '2017-11-06 12:35:02', '2017-11-06 13:32:02', 1, 0), (00244, '00219', '00020', 20, '123334566300', '', '3-6-16 & 17, Street No. 19, Himayatnagar,', '', '2017-11-06 18:12', 3, '2017-11-06 18:13:12', '2017-11-07 16:35:26', 1, 0), (00245, '00220', '00021', 22, '040-67776754111', '', '<NAME> Rd, <NAME>, Somajiguda, Hyderabad,', '', '2017-11-07 13:39', 3, '2017-11-07 13:40:20', '2017-11-07 16:35:39', 1, 0), (00246, '00221', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-11-07 13:40', 3, '2017-11-07 13:41:25', '2017-11-07 16:35:52', 1, 0), (00247, '00222', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-11-08 15:05', 3, '2017-11-08 15:08:57', '2017-11-08 15:10:51', 1, 0), (00248, '00223', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-11-08 16:52', 3, '2017-11-08 16:53:04', '2017-11-10 13:15:58', 1, 0), (00249, '00224', '00344', 362, '9897300715', '', 'SAHAHRANPUR U.P', '', '2017-11-09 13:23', 3, '2017-11-09 13:24:21', '2017-11-10 13:13:06', 1, 0), (00250, '00225', '00061', 73, '9412901682', '', 'doiawalla j<NAME>', '', '2017-11-09 15:00', 3, '2017-11-09 15:02:11', '2017-11-13 15:22:24', 1, 0), (00251, '00226', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-11-10 12:56', 3, '2017-11-10 12:56:53', '2017-11-10 16:29:41', 1, 0), (00252, '00227', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-11-10 12:57', 3, '2017-11-10 12:57:34', '2017-11-10 16:29:26', 1, 0), (00253, '00228', '00140', 153, '9826089221', '', '52-117, Bhadbhada Road, North TT Nagar, TT Nagar, Bhopal, Madhya Pradesh', '', '2017-11-10 13:11', 3, '2017-11-10 13:12:34', '2017-11-13 15:21:44', 1, 0), (00254, '00229', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-11-15 14:24', 3, '2017-11-15 14:25:04', '2017-11-15 15:51:32', 1, 0), (00255, '00230', '00004', 4, '9884050521', '<EMAIL>', 'vadapalani,Chennai', '', '2017-11-15 14:25', 3, '2017-11-15 14:25:52', '2017-11-15 15:51:18', 1, 0), (00256, 'P-00012', '00409', 430, '8246610800', '', '', '', '2017-11-16', 0, '', '', 0, 0), (00257, 'P-00013', '00409', 430, '8246610800', '', 'A J Hospital Research Centre, Kuntikana, Mangalore - 575004', '', '2017-11-16', 3, '', '2017-12-14 15:06:10', 1, 0), (00258, '00231', '00033', 36, '8283060421', '', '', '', '2017-11-16', 0, '', '', 0, 0), (00259, 'P-00014', '00146', 158, '9765268965', '<EMAIL>', 'Dr. deshmukh road', '', '2017-11-19', 0, '', '2017-11-20 01:33:48', 1, 0), (00260, '00232', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-11-21 11:43', 3, '2017-11-21 11:45:08', '2017-12-14 15:07:51', 1, 0), (00261, '00233', '00208', 225, '9657722055', '', 'Bhandarkar Road, Deccan, Pune', '', '2017-11-29 17:08', 3, '2017-11-29 17:10:02', '2017-12-14 15:07:37', 1, 0), (00262, 'P-00015', '00203', 220, '9822862623', '', '<NAME>', '', '2017-11-30', 3, '', '2017-12-14 15:05:37', 1, 0), (00263, '00234', '00059', 69, '9918883214', '', '1 st Floor, C block Pathology Lab SGPGI Lucknow', '', '2017-12-05 13:25', 9, '2017-12-05 13:29:55', '2017-12-16 11:39:39', 39, 0), (00264, '00235', '00353', 371, '000000000000000', '', 'GHAZIABAD UP', '', '2017-12-11 14:02', 3, '2017-12-11 14:04:30', '2017-12-14 15:07:22', 1, 0), (00265, '00236', '00017', 17, '8106298889', '', ' Road No 72, Opp. Bharatiya Vidya Bhavan School, Film Nagar, Jubilee Hills', '', '2017-12-11 17:37', 3, '2017-12-11 17:38:28', '2017-12-14 15:07:00', 1, 0), (00266, 'P-00016', '00188', 204, '9850184250', '', '<NAME>, AHMADNAGAR', '', '2017-12-13', 0, '', '2017-12-13 13:42:48', 1, 0), (00267, 'P-00017', '00046', 55, '9573313499', '', '3-6-282, Opp. Old MLA Quarters, Hyderguda, Hyderabad', '', '2017-12-13', 0, '', '2017-12-13 13:48:27', 1, 0), (00268, 'P-00018', '00188', 204, '9850184250', '', '<NAME>, AHMADNAGAR', '', '2017-12-13', 0, '', '2017-12-13 13:45:03', 1, 0), (00269, '00237', '00073', 85, '9452569502', '', 'LANKA VARANASI', '', '2017-12-14 13:54', 3, '2017-12-14 13:56:19', '2017-12-18 14:04:20', 1, 0), (00270, '00238', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-12-14 14:03', 3, '2017-12-14 14:06:02', '2017-12-14 15:06:34', 1, 0), (00271, '00239', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-12-14 17:26', 3, '2017-12-14 17:27:19', '2017-12-15 17:04:53', 1, 0), (00272, '00240', '00003', 3, '9566275789', '<EMAIL>', 'Nungambkkam,Chennai', '', '2017-12-15 12:22', 3, '2017-12-15 12:23:54', '2017-12-15 17:06:54', 1, 0), (00273, '00241', '00145', 157, '9892982681', '<EMAIL>', '6th floor,Global Hospital', '', '2017-12-15 12:55', 3, '2017-12-15 12:57:22', '2017-12-18 14:03:59', 1, 0), (00274, '00242', '00060', 72, '7060771155', '', 'nirala nagar lucknow', '', '2017-12-15 14:00', 3, '2017-12-15 14:01:36', '2017-12-18 14:03:46', 1, 0), (00275, 'P-00019', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-12-15', 0, '', '2017-12-15 17:28:52', 1, 0), (00276, '00243', '00001', 1, '9841313358', '<EMAIL>', 'Cenatoph Road,Teyanampet,Chennai', '', '2017-12-16 12:42', 3, '2017-12-16 12:43:46', '2017-12-18 14:03:29', 1, 0), (00277, '00244', '00033', 36, '8283060421', '', '', '', '2017-12-16', 0, '', '', 0, 0), (00278, '00245', '00007', 7, '9841429606', '', '<NAME>,Chennai', '', '2017-12-16 14:31', 3, '2017-12-16 14:32:22', '2017-12-18 16:25:02', 1, 0), (00279, '00246', '00411', 432, '8004695112', '', '', '', '2017-12-18 00:00:00', 0, '', '', 0, 0), (00280, '00247', '00006', 6, '9962474499', '', 'PH rd,Chennai', '', '2017-12-18 13:36', 3, '2017-12-18 13:37:12', '2017-12-18 16:24:47', 1, 0), (00281, '00248', '00005', 5, '9840605384', '', 'Chetepet,Chennai', '', '2017-12-19 12:52', 3, '2017-12-19 12:53:15', '2017-12-19 12:57:45', 1, 0), (00282, '00249', '00052', 62, '9900564277', '', 'Bannerghatta Main Road, Jayanagara 9th Block, Bengaluru, Karnataka', '', '2017-12-19 13:11', 1, '2017-12-19 13:12:53', '2017-12-19 13:12:53', 1, 0), (00283, '00250', '00416', 437, '9535282323', '', 'chikkasandra,bengaluru', '', '2017-12-19 13:13', 1, '2017-12-19 13:13:33', '2017-12-19 13:13:33', 1, 0), (00284, '00251', '00017', 60, '9900654134', '', '154/11, Bannerghatta Road, Opposite IIM, Bengaluru,?', '', '2017-12-19 13:22', 1, '2017-12-19 13:23:08', '2017-12-20 13:05:38', 1, 0), (00285, '00252', '00328', 345, '8066628736', '', 'No.96,Industrial Suburb, II Stage, Industrial Area, Yeshwantpur ', '', '2017-12-19 13:23', 1, '2017-12-19 13:24:08', '2017-12-30 14:30:01', 1, 0), (00286, '00253', '00415', 436, '9842811198', '', '', '', '2017-12-20', 0, '', '', 0, 0), (00287, '00254', '00415', 436, '9842811198', '', '111,nanjappa nagar,trichy road,coimbatore-641005', '', '2017-12-20 14:51', 1, '2017-12-20 14:52:31', '2017-12-20 14:52:31', 1, 0), (00288, 'P-00020', '00004', 4, '9884050521', '<EMAIL>', '', '', '2017-12-20', 0, '', '', 0, 0), (00289, '00255', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2017-12-30 10:47', 9, '2017-12-30 10:48:25', '2018-02-08 18:35:10', 1, 0), (00290, '00256', '00422', 444, '9874566258598', '<EMAIL>', 'or<NAME>', 'orathur', '2018-02-08 13:30', 3, '2018-02-08 13:31:46', '2018-02-08 16:45:49', 1, 0), (00291, '00257', '00422', 444, '9874566258598', '<EMAIL>', 'or<NAME>', 'orathur', '2018-02-08 17:12', 1, '2018-02-08 17:13:37', '2018-02-13 14:47:35', 1, 0), (00292, '00258', '00422', 444, '9874566258598', '<EMAIL>', 'or<NAME>', 'orathur', '2018-02-13 16:39', 9, '2018-02-13 16:40:08', '2018-02-13 16:41:33', 1, 0), (00293, '00259', '00422', 444, '9874566258598', '<EMAIL>', '<NAME>', 'orathur', '2018-02-13 18:17', 1, '2018-02-13 18:18:30', '2018-02-13 18:18:30', 1, 0), (00294, '00260', '00422', 444, '9874566258598', '<EMAIL>', '<NAME>', 'orathur', '2018-02-13 18:23', 16, '2018-02-13 18:23:55', '2018-02-13 18:24:41', 44, 0), (00295, '00261', '00423', 445, '7373204044', '<EMAIL>', 'orathur', 'orathur', '2018-02-14 10:22', 16, '2018-02-14 10:25:21', '2018-02-14 11:28:53', 45, 0), (00296, '00262', '00423', 445, '7373204044', '<EMAIL>', 'orathur', 'orathur', '2018-02-14 14:10', 9, '2018-02-14 14:11:38', '2018-02-14 16:13:03', 44, 0), (00297, '00263', '00423', 445, '7373204044', '<EMAIL>', 'orathur', 'orathur', '2018-02-14 15:17', 3, '2018-02-14 15:18:12', '2018-02-14 15:28:25', 1, 0), (00298, '00264', '00423', 445, '7373204044', '<EMAIL>', 'orathur', 'orathur', '2018-02-14 16:25', 3, '2018-02-14 16:29:55', '2018-06-29 14:58:56', 1, 0), (00299, '00265', '00213', 230, '7781006893', '', 'Sachivalya colony,kankarbagh', '', '2018-07-02 11:17', 1, '2018-07-02 11:18:28', '2018-07-02 11:18:28', 1, 0), (00300, '00266', '00429', 451, '8965412365878', '', 'jaipur', '', '2018-07-02 11:37', 1, '2018-07-02 11:41:20', '2018-07-02 11:41:20', 1, 0), (00302, 'P-00021', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2018-07-02 11:51', 1, '2018-07-02 11:53:00', '2018-07-02 11:53:00', 1, 0), (00305, '00267', '00429', 451, '8965412365878', '', 'jaipur', '', '2018-07-02 12:17', 1, '2018-07-02 12:17:46', '2018-07-02 12:17:46', 1, 0), (00306, 'P-00022', '00429', 451, '8965412365878', '', 'jaipur', '', '2018-07-02 12:18', 1, '2018-07-02 12:18:22', '2018-07-02 12:18:22', 1, 0), (00307, '00268', '00423', 445, '9843609636', '<EMAIL>', 'orathur', 'orathur', '2018-07-03 14:41', 1, '2018-07-03 14:43:22', '2018-07-03 14:43:22', 1, 0), (00308, '00269', '00429', 451, '8965412365878', '', 'jaipur', '', '2018-07-03 14:45', 1, '2018-07-03 14:46:27', '2018-07-03 14:46:27', 1, 0), (00309, 'P-00023', '00429', 451, '8965412365878', '', 'jaipur', '', '2018-07-03 14:47', 1, '2018-07-03 14:47:56', '2018-07-03 14:47:56', 1, 0), (00310, '00270', '00423', 445, '9843609636', '<EMAIL>', 'orathur', 'orathur', '2018-07-06 11:55', 1, '2018-07-06 11:56:11', '2018-07-06 11:56:11', 1, 0), (00311, 'P-00024', '00429', 451, '8965412365878', '', '', '', '2018-07-27 00:00:00', 0, '', '', 0, 0), (00312, 'P-00025', '00442', 464, '98745862145', '<EMAIL>', '', '', '2018-07-27 00:00:00', 0, '', '', 0, 0), (00313, '00271', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2018-10-10 11:06', 1, '2018-10-10 11:06:56', '2018-10-10 11:06:56', 1, 0), (00314, '00272', '00327', 344, '9962135225', '<EMAIL>', 'no. 2 test nagar', '', '2018-10-10 11:15', 1, '2018-10-10 11:28:58', '2018-10-10 11:31:48', 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `service_request_details` -- CREATE TABLE IF NOT EXISTS `service_request_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `request_id` varchar(100) NOT NULL, `serial_no` varchar(100) NOT NULL, `batch_no` varchar(100) NOT NULL, `cat_id` int(10) NOT NULL, `subcat_id` int(10) NOT NULL, `brand_id` int(10) NOT NULL, `model_id` int(10) NOT NULL, `warranty_date` varchar(100) NOT NULL, `amc_end_date` varchar(50) NOT NULL, `machine_status` varchar(100) NOT NULL, `service_type` varchar(100) NOT NULL, `service_cat` varchar(100) NOT NULL, `zone` varchar(100) NOT NULL, `service_loc_coverage` varchar(100) NOT NULL, `problem` varchar(100) NOT NULL, `assign_to` varchar(100) NOT NULL, `app_time` varchar(100) NOT NULL, `addl_engg_name` int(10) NOT NULL, `service_priority` varchar(100) NOT NULL, `blank_app` int(10) NOT NULL, `received` varchar(250) NOT NULL, `notes` varchar(500) NOT NULL, `eng_ack` varchar(100) NOT NULL, `accepted_engg_id` int(10) NOT NULL, `active_req` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=297 ; -- -- Dumping data for table `service_request_details` -- INSERT INTO `service_request_details` (`id`, `request_id`, `serial_no`, `batch_no`, `cat_id`, `subcat_id`, `brand_id`, `model_id`, `warranty_date`, `amc_end_date`, `machine_status`, `service_type`, `service_cat`, `zone`, `service_loc_coverage`, `problem`, `assign_to`, `app_time`, `addl_engg_name`, `service_priority`, `blank_app`, `received`, `notes`, `eng_ack`, `accepted_engg_id`, `active_req`) VALUES (1, '00001', 'CF75051429', '', 1, 1, 1, 5, '', '', 'Preventive', 'Breakdown', '', '15', 'outstation', '9,62,62', '00009', '', 0, 'Critical', 0, '', 'PHOTOMETRIC CALIBRATION ISSUE,replace the optical fiber harness', '', 0, 0), (2, '00002', 'CJ06020456', '', 1, 1, 1, 9, '', '', 'Preventive', 'Breakdown', '', '15', 'outstation', '', '00007', '', 0, 'High', 0, '', 'BUBBLE FORMS IN NEEDLE NO. 1 TUBING', '', 0, 0), (3, '00003', 'AA31042569', '', 1, 1, 1, 4, '', '', 'Preventive', 'Out Of Warranty', '', '8', 'outstation', '', '00013', '', 0, 'Low', 0, '', 'Machine sifted to apollo specialty.replaced EPROM latest.Need to get payment', '', 0, 0), (10, '00017', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Preventive', 'Breakdown', '', '5', 'outstation', '18', '00012', '', 0, '', 0, '', 'PT QC RESULTS ARE NOT OK', '', 0, 0), (11, '00018', 'DUM0000001', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Breakdown', '', '5', '', '64', '00012', '', 0, 'High', 0, '', 'problem in measurement block,CHECKED AND FOUND PCB MOTHER IS FAULTY', '', 0, 0), (12, '00019', 'AA31042569', '', 1, 1, 1, 4, '2011-08-16', '', 'Preventive', 'Reverification', '', '8', 'outstation', '', '00013', '', 0, 'Low', 0, '', 'need to get payment for eprom', '', 0, 0), (13, '00020', 'BG84112343', '', 1, 1, 1, 3, '2017-07-11', '', 'Preventive', 'Breakdown', '1', '2', 'outstation', '7', '00005', '', 0, 'High', 0, '', '', '', 0, 0), (14, '00021', '1156566000002', '', 2, 2, 1, 2, '', '', 'Preventive', 'Preventive', '', '1', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (16, '00023', 'CF76052625', '', 1, 1, 1, 5, '2017-12-11', '', 'Preventive', 'Preventive', '', '13', 'outstation', '8', '00008', '', 0, 'Low', 0, '', '', '', 0, 0), (17, '00024', 'BJ04062089', '', 1, 1, 1, 3, '', '', 'Preventive', 'Breakdown', '', '3', 'outstation', '10,18', '00001', '', 0, 'High', 0, '', 'some particle in optical sensor,clean optical sensor run test.', '', 0, 0), (18, '00025', 'EEER45', 'EEER45', 1, 1, 1, 5, '', '', 'Warranty', 'Demo', '', '8', 'outstation', '9,12', '00018', '', 0, 'Low', 0, '', 'sssssssssssss', '', 0, 0), (19, '00026', 'CC30018168', '', 1, 1, 1, 4, '2011-06-08', '', 'Preventive', 'Breakdown', '', '2', 'outstation', '16', '00006', '', 0, 'High', 0, '', '', '', 0, 0), (20, '00027', 'BG85052603', '', 1, 1, 1, 3, '2018-02-03', '', 'Preventive', 'Breakdown', '', '3', 'outstation', '17,18', '00001', '', 0, 'Critical', 0, '', 'cleaner solution tubing is loose so cleaner solution not supplied, re fix the tubing run test', '', 0, 0), (21, '00028', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Preventive', 'Breakdown', '', '8', 'outstation', '19', '00013', '', 0, 'High', 0, '', '', '', 0, 0), (22, '00029', 'BR62029703', '', 1, 1, 1, 4, '', '', 'Warranty', 'Breakdown', '', '15', 'outstation', '20,20', '00009', '', 0, 'High', 0, '', 'control values are out of range, they are running system control instead of coag control', '', 0, 0), (23, '00030', 'BT3203A640', '', 1, 1, 1, 4, '2016-02-02', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '22,23,20', '00005', '', 0, 'High', 0, '', 'Fuse and key board is faulty,after replacement instrument working properly ', '', 0, 0), (24, '00031', 'BR3007C385', '', 2, 2, 1, 1, '', '', 'AMC', 'Breakdown', '', '15', 'outstation', '24,27', '00009', '', 0, 'Low', 0, '', 'solved after cleaning of printer thermic', '', 0, 0), (25, '00032', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Warranty', 'Breakdown', '', '5', 'outstation', '25', '00012', '', 0, 'Low', 0, '', '', '', 0, 0), (26, '00033', 'DDS44', 'DDS44', 1, 1, 1, 5, '', '', 'Warranty', 'AMC', '', '8', 'outstation', '26', '00018', '', 0, '', 0, '', 'test notes new', '', 0, 0), (27, '00034', 'DDS44', '', 1, 1, 1, 5, '', '', 'Warranty', 'Out Of Warranty', '', '8', 'outstation', '26', '00018', '', 0, 'Critical', 0, '', 'new test notes', '', 0, 0), (28, '00035', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Warranty', 'Preventive', '', '8', 'outstation', '20', '00013', '', 0, 'Low', 0, '', '', '', 0, 0), (29, '00036', 'DDS44', 'DDS44', 1, 1, 1, 5, '', '', 'Warranty', 'Out Of Warranty', '', '8', 'outstation', '26', '00018', '', 0, '', 0, '', 'first notes', '', 0, 0), (32, '00039', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Breakdown', '', '8', 'outstation', '28', '00018', '', 0, 'High', 0, '', 'second notes', '', 0, 0), (33, '00040', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Warranty', 'Breakdown', '', '8', 'outstation', '32', '00018', '', 0, 'Low', 0, '', 'test notess test notessss', '', 0, 0), (34, '00041', 'CC3212A195', '', 1, 1, 1, 4, '2018-06-07', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '40,41', '00006', '', 0, 'High', 0, '', 're insert 4 port serial board , (Problem in 4 port serial port positioning)', '', 0, 0), (35, '00042', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '20', '00013', '', 0, 'Low', 0, '', 'Weekly maintenance', '', 0, 0), (36, '00043', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '38', '00005', '', 0, 'High', 0, '', '', '', 0, 0), (37, '00044', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '61', '00005', '', 0, 'Critical', 0, '', 'Mapping issue ,done mapping ', '', 0, 0), (38, '00045', 'DUM0000002', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Demo', '', '8', 'outstation', '42,42', '00013', '', 0, 'High', 0, '', 'Instrument was brought from bangalore. amc should be signed.', '', 0, 0), (39, '00046', 'BR69121947', '', 1, 1, 1, 4, '2018-01-03', '', 'Warranty', 'Breakdown', '', '1', 'outstation', '43,60', '00008', '', 0, 'High', 0, '', 'LLD cable issue replaced the same', '', 0, 0), (40, '00047', 'BT31019267', '', 2, 2, 1, 1, '2012-08-01', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '63,64', '00006', '', 0, 'High', 0, '', '', '', 0, 0), (41, '00048', 'BG85052603', '', 1, 1, 1, 3, '2018-02-03', '', 'Warranty', 'Breakdown', '', '3', 'outstation', '65', '00001', '', 0, 'High', 0, '', 'CLEAN PDR HOME SENSOR ', '', 0, 0), (42, '00049', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Warranty', 'Breakdown', '', '5', 'outstation', '25,66', '00012', '', 0, 'High', 0, '', '', '', 0, 0), (43, '00050', 'BG84082177', '', 1, 1, 1, 3, '2017-11-08', '', 'Warranty', 'Breakdown', '', '3', 'outstation', '67,66', '00001', '', 0, 'High', 0, '', '', '', 0, 0), (44, '00051', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', 'Routine maintenance', '', 0, 0), (45, '00052', 'BG85022476', '', 1, 1, 1, 3, '2017-09-25', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '66', '00005', '', 0, 'Low', 0, '', '', '', 0, 0), (46, '00053', 'BG85022476', '', 1, 1, 1, 3, '2017-09-25', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '69', '00006', '', 0, 'High', 0, '', '', '', 0, 0), (47, '00054', 'CF75051429', '', 1, 1, 1, 5, '2016-09-13', '', 'Warranty', 'Breakdown', '', '15', 'outstation', '62', '00009', '', 0, 'High', 0, '', '', '', 0, 0), (48, '00055', 'BT3202A182', '', 2, 2, 1, 1, '', '', 'AMC', 'Breakdown', '1', '3', 'outstation', '106', '00001', '', 0, 'Low', 0, '', '', '', 0, 0), (49, '00056', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Warranty', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', 'Routine Maintenance', '', 0, 0), (50, '00057', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'Routine maintenance', '', 0, 0), (51, '00058', 'CJ06020456', '', 1, 1, 1, 9, '2017-07-19', '', 'Warranty', 'Preventive', '', '15', 'outstation', '71', '00007', '', 0, 'Low', 0, '', '', '', 0, 0), (52, '00059', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68,68', '00013', '', 0, '', 0, '', '', '', 0, 0), (53, '00060', 'BR30078980', '', 2, 2, 1, 1, '2011-10-12', '', 'Warranty', 'Preventive', '', '8', 'outstation', '72', '00013', '', 0, 'High', 0, '', '', '', 0, 0), (54, '00061', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Warranty', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'Routine Maintenance', '', 0, 0), (55, '00062', 'CC3212A195', '', 1, 1, 1, 4, '2018-06-07', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '60', '00005', '', 0, 'High', 0, '', 'Problem with FVIII calibration they found error in 3rd and 4th dilution', '', 0, 0), (56, '00063', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Breakdown', '', '8', 'outstation', '73', '00013', '', 0, 'High', 0, '', '', '', 0, 0), (57, '00064', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Warranty', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', '', '', 0, 0), (58, '00065', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '74', '00006', '', 0, 'High', 0, '', '', '', 0, 0), (59, '00066', 'DDS44', '', 1, 1, 1, 5, '', '', 'Warranty', 'AMC', '', '8', 'outstation', '45,62', '00018', '', 0, 'Critical', 0, '', 'ssssssssssss', '', 0, 0), (60, '00067', 'AA40032084', '', 1, 1, 1, 4, '', '', 'AMC', 'Breakdown', '', '11', 'outstation', '60', '00014', '', 0, 'High', 0, '', 'System stuck', '', 0, 0), (61, '00068', 'DDS44', '', 1, 1, 1, 5, '', '', 'Warranty', 'AMC', '', '8', 'outstation', '9,62', '00017', '', 0, 'High', 0, '', 'asdasdasd', '', 0, 0), (62, '00069', '7127199', '', 2, 2, 1, 1, '2009-07-18', '', 'Warranty', 'Out Of Warranty', '', '8', 'outstation', '64', '00018', '', 0, 'High', 0, '', 'sdfsdfds', '', 0, 0), (63, '00070', 'DDS44', '', 1, 1, 1, 5, '', '', 'Warranty', 'Out Of Warranty', '', '8', 'outstation', '62', '00017', '', 0, '', 0, '', 'as', '', 0, 0), (64, '00071', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Out Of Warranty', '', '8', 'outstation', '68', '00018', '', 0, 'Critical', 0, '', 'sss', '', 0, 0), (65, '00072', 'DDS44', '', 1, 1, 1, 5, '', '', 'Warranty', 'AMC', '', '8', 'outstation', '62', '00018', '', 0, 'Critical', 0, '', 'ggggg', '', 0, 0), (66, '00073', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Warranty', 'Breakdown', '', '8', 'outstation', '75', '00018', '', 0, 'Low', 0, '', '', '', 0, 0), (67, '00074', 'BJ05042548', '', 1, 1, 1, 3, '2017-04-27', '', 'Warranty', 'Breakdown', '', '1', 'outstation', '76', '00008', '', 0, 'High', 0, '', '', '', 0, 0), (68, '00075', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Warranty', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'Routine Maintenance', '', 0, 0), (69, '00076', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Warranty', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', 'routine maintenance', '', 0, 0), (70, '00077', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Breakdown', '', '8', 'outstation', '77', '00013', '', 0, 'High', 0, '', '', '', 0, 0), (71, '00078', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Breakdown', '', '8', 'outstation', '77,60', '00013', '', 0, 'High', 0, '', '', '', 0, 0), (72, '00079', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Warranty', 'Breakdown', '', '8', 'outstation', '75', '00018', '', 0, 'Low', 0, '', 'test entry', '', 0, 0), (73, '00080', ' BR3604C883', '', 2, 2, 1, 1, '2018-07-05', '', 'Warranty', 'Warranty', '', '2', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (74, '00081', 'BR62029703', '', 1, 1, 1, 4, '', '', 'Warranty', 'Breakdown', '', '15', 'outstation', '78', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (75, '00082', 'CF75051429', '', 1, 1, 1, 5, '2016-09-13', '', 'Warranty', 'Breakdown', '', '15', 'outstation', '79', '00009', '', 0, '', 0, '', '', '', 0, 0), (76, '00083', 'BJ84112342', '', 1, 1, 1, 3, '2016-09-08', '', 'Warranty', 'Breakdown', '', '1', 'outstation', '80', '00007', '', 0, 'High', 0, '', '', 'accept', 7, 0), (77, '00084', 'BG-85042547', '', 1, 1, 1, 3, '2017-09-22', '', 'Warranty', 'Breakdown', '', '6', 'outstation', '81', '00011', '', 0, 'High', 0, '', '', 'accept', 11, 0), (78, '00085', 'BS43035046', '', 1, 1, 1, 8, '2017-08-02', '', 'Warranty', 'Preventive', '', '1', 'outstation', '82,82', '00007', '', 0, 'Low', 0, '', '', '', 0, 0), (79, '00086', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'Routine maintenance', '', 0, 0), (80, '00087', 'BT3604C888', '', 1, 1, 1, 3, '2018-08-07 00:00:00', '', 'Preventive', 'Breakdown', '', '1', '', '83', '00008', '', 0, 'Low', 0, '', '', '', 0, 0), (81, '00088', 'CF 75091711', '', 1, 1, 1, 6, '2017-02-08', '', 'Warranty', 'Preventive', '', '5', 'outstation', '84', '00012', '', 0, 'High', 0, '', '', '', 0, 0), (82, '00089', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Warranty', 'Preventive', '', '2', 'outstation', '85,86', '00006', '', 0, 'High', 0, '', '', '', 0, 0), (83, '00090', 'BT3509C463', '', 2, 2, 1, 1, '2017-05-13', '', 'Warranty', 'Breakdown', '', '13', 'outstation', '64', '00008', '', 0, 'High', 0, '', 'PM AND CALIBRATION', '', 0, 0), (84, '00091', 'BG85022476', '', 1, 1, 1, 3, '2017-09-25', '', 'Warranty', 'Breakdown', '', '2', 'outstation', '87,88', '00005', '', 0, 'High', 0, '', '', '', 0, 0), (85, '00092', 'BR62029703', '', 1, 1, 1, 4, '', '', 'Warranty', 'Preventive', '', '15', 'outstation', '89', '00009', '', 0, 'High', 0, '', '', '', 0, 0), (86, '00093', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', 'Routine maintenance', 'accept', 13, 0), (87, '00094', 'BR3407B839', '', 2, 2, 1, 1, '', '', 'AMC', 'Breakdown', '', '3', 'outstation', '24,64', '00001', '', 0, 'Low', 0, '', '', '', 0, 0), (88, '00095', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Warranty', 'Breakdown', '', '8', 'outstation', '75', '00018', '', 0, 'Low', 0, '', 'test notes entry', '', 0, 0), (89, '00096', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Warranty', 'Preventive', '', '2', 'outstation', '90,91', '00005', '', 0, 'Low', 0, '', '', 'accept', 5, 0), (90, '00097', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', '1', 'Out Of Warranty', '', '8', 'outstation', '75', '00018,00001', '', 0, 'Low', 0, '', 'testing kljsdklfjklsdf jslkfjlks djfl', 'accept', 18, 0), (91, '00098', 'BT3507C384', '', 2, 2, 1, 1, '', '', 'Rental', 'Breakdown', '', '2', 'outstation', '92', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (92, '00099', 'CC3411A823', '', 1, 1, 1, 4, '2016-11-22', '', '1', 'Breakdown', '', '1', 'outstation', '93,94', '00008', '', 0, 'High', 0, '', '', '', 0, 0), (93, '00100', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Breakdown', '', '8', 'outstation', '95', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (94, '00101', 'BR66065818', '', 1, 1, 1, 4, '2018-01-07', '', '1', 'Breakdown', '', '2', 'outstation', '96', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (95, '00102', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (96, '00103', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, '', 0, '', 'Routine maintenance', 'accept', 13, 0), (97, '00104', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', '1', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, '', 0, '', 'routine maintenance', 'accept', 13, 0), (98, '00105', 'BT31119967', '', 2, 2, 1, 1, '2013-02-18', '', '1', 'Preventive', '', '15', 'outstation', '64', '00009', '', 0, 'High', 0, '', 'CAL&PM', 'accept', 9, 0), (99, '00106', 'CF76062684', '', 1, 1, 1, 5, '2017-08-25', '', '1', 'Preventive', '', '15', 'outstation', '62', '00010', '', 0, 'High', 0, '', 'PM&CAL', 'accept', 10, 0), (100, '00107', 'BR61099413', '', 1, 1, 1, 4, '2017-11-21', '', '1', 'Breakdown', '', '1', 'outstation', '97,98', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (101, '00108', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', '1', 'Breakdown', '', '2', 'outstation', '99', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (102, '00109', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', 'PM&CAL .', 'accept', 13, 0), (103, '00110', 'BT3507C352', '', 2, 2, 1, 1, '2016-12-09', '', '1', 'Preventive', '', '1', 'outstation', '64', '00007', '', 0, 'High', 0, '', 'PM\r\n& CAL', '', 0, 0), (104, '00111', 'BR61099413', '', 1, 1, 1, 4, '2017-11-21', '', '1', 'Breakdown', '', '1', 'outstation', '100', '00007', '', 0, 'High', 0, '', '', '', 0, 0), (105, '00112', 'BG84122390', '', 1, 1, 1, 3, '2017-01-31', '', '1', 'Breakdown', '', '2', 'outstation', '101', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (106, '00113', 'CC3411A823', '', 1, 1, 1, 4, '2016-11-22', '', '1', 'Breakdown', '', '1', 'outstation', '102', '00007', '', 0, 'High', 0, '', '', 'accept', 7, 0), (107, '00114', 'BR61099413', '', 1, 1, 1, 4, '2017-11-21', '', '1', 'Breakdown', '', '1', 'outstation', '89,60', '00007', '', 0, 'High', 0, '', '', '', 0, 0), (108, '00115', 'BT31049420', '', 2, 2, 1, 1, '2012-06-23', '', '1', 'Preventive', '', '15', 'outstation', '103', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (109, '00116', 'CC3212A197', '', 1, 1, 1, 4, '2015-03-17', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '104,105', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (110, '00117', 'BT31099793', '', 2, 2, 1, 1, '2012-12-06', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '24,64', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (111, '00118', 'BG-85042547', '', 1, 1, 1, 3, '2017-09-22', '', 'Chargeable', 'Breakdown', '', '6', 'outstation', '67,66', '00011', '', 0, 'Critical', 0, '', '', 'accept', 11, 0), (112, '00119', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (113, '00120', 'BR69118077', '', 1, 1, 1, 4, '2017-02-22', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '98,60', '00006', '', 0, '', 0, '', '', 'accept', 6, 0), (114, '00121', 'BG85042544', '', 1, 1, 1, 3, '2018-03-19', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '107', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (115, '00122', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (116, '00123', 'CF76062684', '', 1, 1, 1, 5, '2017-08-25', '', 'Chargeable', 'Reverification', '', '15', 'outstation', '108', '00010', '', 0, 'High', 0, '', '', 'accept', 10, 0), (117, '00124', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (118, '00125', 'BR3503C076', '', 2, 2, 1, 1, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '64', '00013', '', 0, 'High', 0, '', 'PM', 'accept', 13, 0), (119, '00126', 'BT3411B981', '', 2, 2, 1, 1, '2016-05-06', '', 'Chargeable', 'Preventive', '', '3', 'outstation', '24,64', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (120, '00127', 'BG84082177', '', 1, 1, 1, 3, '2017-11-08', '', 'Chargeable', 'Preventive', '', '3', 'outstation', '109,110', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (121, '00128', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (122, '00129', 'BT3401B580', '', 2, 2, 1, 1, '2016-03-09', '', 'Chargeable', 'Breakdown', '', '11', 'outstation', '111', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (123, '00130', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Chargeable', 'Preventive', '', '5', 'outstation', '112', '00012,00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (124, '00131', 'BR69118077', '', 1, 1, 1, 4, '2017-02-22', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '113', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (125, '00132', 'BG84092243', '', 1, 1, 1, 3, '2016-10-13', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '114', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (126, '00133', 'BR69108029', '', 1, 1, 1, 4, '2017-07-19', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '115', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (127, '00134', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'maintenance routine', 'accept', 13, 0), (128, '00135', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', 'maintenance', 'accept', 13, 0), (129, '00136', 'BG85052603', '', 1, 1, 1, 3, '2018-02-03', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '66', '00001', '', 0, 'Critical', 0, '', '', 'accept', 1, 0), (130, '00137', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '116', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (131, '00139', 'BJ05042548', '', 1, 1, 1, 3, '2017-04-27', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '117', '00007', '', 0, 'High', 0, '', '', 'accept', 7, 0), (132, '00140', 'CF76062684', '', 1, 1, 1, 5, '2017-08-25', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '118', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (133, '00141', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Reverification', '', '8', 'outstation', '119', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (134, '00142', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (135, '00143', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, '', 0, '', '', 'accept', 13, 0), (136, '00144', '1167208000718', '', 2, 2, 1, 2, '2018-08-17', '', 'Warranty', 'Warranty', '', '2', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (137, '00145', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Reverification', '', '8', 'outstation', '120', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (138, '00146', 'BT3407B837', '', 2, 2, 1, 1, '2016-09-28', '', 'Chargeable', 'Preventive', '', '15', 'outstation', '64', '00009', '', 0, 'High', 0, '', 'PM&CAL', 'accept', 9, 0), (139, '00147', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (140, '00148', 'CC32059880', '', 1, 1, 1, 4, '2015-03-09', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (141, '00149', '1167208000727', '', 2, 2, 1, 2, '', '', '1', '1', '', '8', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (142, '00150', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (143, '00151', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', 'Chargeable', 'Reverification', '', '2', 'on_site', '121', '00005', '', 0, 'Low', 0, '', '', 'accept', 5, 0), (144, '00152', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Reverification', '', '8', 'outstation', '122', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (145, '00153', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Breakdown', '', '8', 'outstation', '123', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (146, '00154', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (147, '00158', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', '', '60', '00013', '', 0, '', 0, '', '', 'accept', 13, 0), (148, '00159', 'BT3506C251', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '15', '', '64', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (149, '00160', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Chargeable', 'Reverification', '', '2', 'on_site', '124', '00005', '', 0, 'Low', 0, '', '', 'accept', 5, 0), (150, '00161', 'CF75041348', '', 1, 1, 1, 5, '', '', 'Chargeable', 'Preventive', '', '1', '', '62', '00007', '', 0, '', 0, '', '', '', 0, 0), (151, '00162', '1166369000664', '', 2, 2, 1, 2, '2018-08-24', '', 'Warranty', 'Warranty', '', '2', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (152, '00163', 'BR600-38278', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '5', '', '60', '00012,00015', '', 0, '', 0, '', '', 'accept', 15, 0), (153, '00164', 'BG84082177', '', 1, 1, 1, 3, '2017-11-08', '', 'Chargeable', 'Preventive', '', '3', 'outstation', '125', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (154, '00165', 'BG84082177', '', 1, 1, 1, 3, '2017-11-08', '', 'Chargeable', 'Preventive', '', '3', 'outstation', '126', '00001', '', 0, 'High', 0, '', '', '', 0, 0), (155, '00166', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (156, '00167', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '127', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (157, '00168', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '127', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (158, '00169', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '127', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (159, '00173', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Preventive', '', '2', 'on_site', '128', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (160, '00174', 'CC3212A195', '', 1, 1, 1, 4, '2018-06-07', '', 'Chargeable', 'Preventive', '', '2', 'on_site', '129', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (161, '00175', '1164196000390', '', 2, 2, 1, 2, '', '', 'Warranty', 'Preventive', '', '2', 'on_site', '130', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (162, '00176', 'BG85022476', '', 1, 1, 1, 3, '2017-09-25', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '131', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (163, '00177', 'BG84122391', '', 1, 1, 1, 3, '2017-07-08', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '132,133', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (164, '00178', 'BT3503C080', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '13', '', '64,64', '00007,00008', '', 0, '', 0, '', '', '', 0, 0), (165, '00179', 'BT3503C089', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '1', '', '64,64', '00007,00008', '', 0, '', 0, '', '', '', 0, 0), (166, '00180', 'BT31019259', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '15', '', '64', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (167, '00181', 'BG86022822', '', 1, 1, 1, 3, '2018-08-28', '', 'Warranty', 'Warranty', '', '5', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (168, '00182', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (169, '00183', 'BR68127526', '', 1, 1, 1, 4, '2018-01-02', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '60', '00007,00008', '', 0, 'High', 0, '', '', '', 0, 0), (170, '00184', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (171, '00185', 'DDS44', '', 1, 1, 1, 5, '2018-07-18', '', 'Warranty', 'Warranty', '', '8', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (172, '00186', 'EEER45', '', 1, 1, 1, 5, '2018-07-24', '', 'Warranty', 'Warranty', '', '8', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (173, '00187', 'FFFR45', '', 1, 1, 1, 5, '2018-07-24', '', 'Warranty', 'Warranty', '', '8', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (174, '00188', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (175, '00189', 'CC3212A195', '', 1, 1, 1, 4, '2018-06-07', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '134', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (176, '00190', 'BG85022476', '', 1, 1, 1, 3, '2017-09-25', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '135', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (177, '00191', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, '', 0, '', '', 'accept', 13, 0), (178, '00192', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', 'Chargeable', 'Reverification', '', '2', 'on_site', '136', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (179, '00193', 'BR68077154', '', 1, 1, 1, 4, '2016-11-29', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '134,137', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (180, '00194', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (181, '00195', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (182, '00196', 'BR69108029', '', 1, 1, 1, 4, '2017-07-19', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '138,139', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (183, '00197', 'CF75051429', '', 1, 1, 1, 5, '2016-09-13', '', 'Chargeable', 'Preventive', '', '15', 'outstation', '140', '00010', '', 0, '', 0, '', '', 'accept', 10, 0), (184, '00198', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Breakdown', '', '8', 'outstation', '141', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (185, '00199', 'BT31099793', '', 2, 2, 1, 1, '2012-12-06', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '64', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (186, '00200', 'CJO7062124', '', 1, 1, 1, 9, '', '', '1', '1', '', '9', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (187, '00201', 'CF75021186', '', 1, 1, 1, 5, '', '', 'Rental', 'Breakdown', '', '11', 'outstation', '142', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (188, '00203', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (189, '00204', 'BG85032478', '', 1, 1, 1, 3, '2017-03-23', '', 'Chargeable', 'Reverification', '', '2', 'on_site', '143', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (190, '00205', 'BJ84112342', '', 1, 1, 1, 3, '', '', 'Chargeable', 'Preventive', '4', '1', '', '66', '00007', '', 0, '', 0, '', '', '', 0, 0), (191, '00206', 'BG85052603', '', 1, 1, 1, 3, '2018-02-03', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '144,145', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (192, '00207', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (193, '00208', 'BR69108029', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '2', '', '60', '00006', '', 0, 'High', 0, '', 'PM&CAL', 'accept', 6, 0), (194, '00209', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '146', '00013', '', 0, 'High', 0, '', '', 'later', 13, 0), (195, '00210', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '147', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (196, '00211', 'CF76052599', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Breakdown', '', '11', 'outstation', '148', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (197, '00212', 'BR63094065', '', 1, 1, 1, 4, '', '', 'Warranty', 'Breakdown', '', '1', 'outstation', '149', '00008', '', 0, 'High', 0, '', '', 'accept', 8, 0), (198, '00213', '1166369000664', '', 2, 2, 1, 2, '2018-08-24', '', 'Warranty', 'Warranty', '', '2', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (199, '00214', '1167208000709', '', 2, 2, 1, 2, '2018-09-24', '', 'Warranty', 'Warranty', '', '2', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (200, '00215', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Chargeable', 'Preventive', '', '5', 'outstation', '150', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (201, '00216', 'CC 31018805', '', 1, 1, 1, 4, '2012-07-11', '', 'Chargeable', 'Reverification', '', '5', 'outstation', '60', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (202, '00217', 'BR63094055', '', 1, 1, 1, 4, '2012-09-12', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '134,60', '00008', '', 0, 'High', 0, '', '', 'accept', 8, 0), (203, '00218', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (204, '00219', 'BG84082177', '', 1, 1, 1, 3, '2018-02-03', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '151,152,66', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (205, '00220', 'BG85042544', '', 1, 1, 1, 3, '2018-03-19', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '153', '00001', '', 0, 'Critical', 0, '', '', 'accept', 1, 0), (206, '00221', 'BT3402B600', '', 2, 2, 1, 1, '2015-12-31', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '154', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (207, '00222', 'BR69121947', '', 1, 1, 1, 4, '2018-01-03', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '155', '00008', '', 0, 'High', 0, '', '', 'accept', 8, 0), (208, '00223', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Reverification', '', '8', 'outstation', '156', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (209, '00224', 'CC3305A349', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Breakdown', '', '5', 'outstation', '157', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (210, '00225', 'CF76052628', '', 1, 1, 1, 6, '', '', 'Rental', 'Breakdown', '', '5', 'outstation', '158', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (211, '00226', 'BT33305B305', '', 2, 2, 1, 1, '', '', 'Warranty', 'Breakdown', '', '15', 'outstation', '159', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (212, '00227', 'BT31119967', '', 2, 2, 1, 1, '', '2018-09-27', '1', '1', '', '15', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (213, '00228', 'BT3603C850', '', 2, 2, 1, 2, '', '', 'Chargeable', 'Preventive', '', '2', 'on_site', '160,161', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (214, '00229', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 0, 0), (215, '00230', 'BJ04062089', '', 1, 1, 1, 3, '2016-04-08', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '162', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (216, '00231', 'CF 75091711', '', 1, 1, 1, 6, '2017-02-08', '', 'Chargeable', 'Demo', '', '5', 'outstation', '68', '00015', '', 0, '', 0, '', '', 'accept', 15, 0), (217, '00232', 'BG86022822', '', 1, 1, 1, 3, '', '', 'Warranty', 'Reverification', '', '5', 'outstation', '163', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (218, '00233', 'BG 84122393', '', 1, 1, 1, 3, '2017-01-06', '', 'Chargeable', 'Breakdown', '', '5', 'outstation', '164', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (219, '00234', 'CF76052628', '', 1, 1, 1, 6, '', '', 'Rental', 'Reverification', '', '5', 'outstation', '68', '00015', '', 0, '', 0, '', '', 'accept', 15, 0), (220, '00235', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (221, '00236', 'CF75021186', '', 1, 1, 1, 5, '', '', 'Rental', 'Breakdown', '', '11', 'outstation', '165', '00014', '', 0, '', 0, '', '', 'accept', 14, 0), (222, '00237', 'BJ05042548', '', 1, 1, 1, 3, '2017-04-27', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '166,167', '00008', '', 0, 'High', 0, '', '', 'accept', 8, 0), (223, '00238', 'BG86022822', '', 1, 1, 1, 3, '', '', 'Warranty', 'Reverification', '', '5', 'outstation', '66', '00015', '', 0, 'Low', 0, '', '', 'accept', 15, 0), (224, '00239', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, '', 0, '', '', 'accept', 13, 0), (225, '00240', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '168', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (226, '00241', 'CF76052599', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Breakdown', '', '5', 'outstation', '169', '00015', '', 0, 'High', 0, '', '', 'accept', 15, 0), (227, '00242', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (228, '00243', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (229, '00244', 'CF75061467', '', 1, 1, 1, 5, '', '', 'Rental', 'Preventive', '', '11', 'outstation', '170', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (230, '00245', 'BR68097289', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '11', 'outstation', '171', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (231, '00246', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '172', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (232, '00247', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '146,60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (233, '00248', 'CF76062684', '', 1, 1, 1, 5, '', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '173', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (234, '00249', '1163684000317', '', 2, 2, 1, 2, '', '', 'Warranty', 'Breakdown', '', '2', 'on_site', '174', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (235, '00250', 'AA38061371', '', 1, 1, 1, 4, '2012-11-18', '', 'Chargeable', 'Reverification', '', '2', 'on_site', '175', '00005', '', 0, '', 0, '', '', 'accept', 5, 0), (236, '00251', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '176', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (237, '00252', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '146,60', '00013', '', 0, '', 0, '', '', 'accept', 13, 0), (238, '00253', 'BG85052603', '', 1, 1, 1, 3, '2018-02-03', '', 'Chargeable', 'Breakdown', '', '3', 'outstation', '67,66', '00001', '', 0, 'High', 0, '', '', 'accept', 1, 0), (239, '00254', 'CF76052618', '', 1, 1, 1, 6, '2017-12-27', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '177', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (240, '00255', 'CC32059880', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (241, '00256', 'BT3407B845', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '5', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (242, '00257', 'BT3407B845', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '5', '', '64', '00015', '', 0, '', 0, '', '', 'accept', 15, 0), (243, '00258', 'BT3604C907', '', 2, 2, 1, 1, '2018-10-15', '', 'Warranty', 'Warranty', '', '11', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (244, '00259', 'BR61089392', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '1', '', '60', '00007', '', 0, '', 0, '', '', '', 0, 0), (245, '00260', 'CF76062684', '', 1, 1, 1, 5, '', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '165,62', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (246, '00261', 'CF76062684', '', 1, 1, 1, 5, '', '', 'Chargeable', 'Breakdown', '', '15', 'outstation', '62', '00009', '', 0, 'High', 0, '', '', 'accept', 9, 0), (247, '00262', 'BR62029703', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Preventive', '', '15', '', '60', '00009', '', 0, '', 0, '', '', 'accept', 9, 0), (248, '00263', 'CC32019673', '', 1, 1, 1, 4, '2017-03-21', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '178', '00005', '', 0, 'Low', 0, '', '', 'accept', 5, 0), (249, '00264', '1163684000332', '', 2, 2, 1, 2, '', '', 'Warranty', 'Breakdown', '', '2', 'on_site', '179', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (250, '00265', 'CF76052599', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Breakdown', '', '11', 'outstation', '180', '00014', '', 0, 'High', 0, '', '', 'accept', 14, 0), (251, '00266', 'BT3410B960', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '15', '', '64', '00009', '', 0, '', 0, '', '', '', 0, 0), (252, '00267', 'BT30089047', '', 2, 2, 1, 1, '', '2017-04-24', 'AMC', 'Preventive', '', '11', '', '64', '00014', '', 0, 'High', 0, '', '', '', 0, 0), (253, '00268', 'BT39027959', '', 2, 2, 1, 1, '', '', 'Chargeable', 'Preventive', '', '15', '', '64', '00009', '', 0, '', 0, '', '', '', 0, 0), (254, '00269', 'BG86012783', '', 1, 1, 1, 3, '', '', 'Warranty', 'Breakdown', '', '2', 'on_site', '110,66', '00005', '', 0, 'High', 0, '', '', 'accept', 5, 0), (255, '00270', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Reverification', '', '8', 'outstation', '181', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (256, '00271', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '60', '00013', '', 0, 'Low', 0, '', '', 'accept', 13, 0), (257, '00272', 'BR61059245', '', 1, 1, 1, 4, '', '', 'Rental', 'Reverification', '', '8', 'outstation', '182', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (258, '00273', 'CC3411A823', '', 1, 1, 1, 4, '', '', 'Chargeable', 'Breakdown', '', '1', 'outstation', '183', '00007,00008', '', 0, 'High', 0, '', '', 'accept', 8, 0), (259, '00274', 'BR68077154', '', 1, 1, 1, 4, '2016-11-29', '', 'Chargeable', 'Breakdown', '', '2', 'on_site', '184', '00006', '', 0, 'High', 0, '', '', 'accept', 6, 0), (260, '00275', 'CF76052618', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Preventive', '', '8', '', '68', '00013', '', 0, '', 0, '', '', '', 0, 0), (261, '00276', 'CF76062669', '', 1, 1, 1, 6, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '185', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (262, '00277', 'BT3604C907', '', 2, 2, 1, 1, '2018-10-15', '', 'Warranty', 'Warranty', '', '11', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (263, '00278', 'CC3301A199', '', 1, 1, 1, 4, '', '', 'Rental', 'Preventive', '', '8', 'outstation', '186', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (264, '00279', '1168270000794', '', 2, 2, 1, 2, '2018-11-17', '', 'Warranty', 'Warranty', '', '14', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (265, '00280', 'CF76052618', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '185,68', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (266, '00281', 'BR69077912', '', 1, 1, 1, 4, '', '', 'AMC', 'Preventive', '', '8', 'outstation', '146,60', '00013', '', 0, 'High', 0, '', '', 'accept', 13, 0), (267, '00282', '5045012', '', 1, 1, 1, 4, '2011-07-01', '', 'Chargeable', 'Breakdown', '', '5', 'outstation', '60,187', '00015', '', 0, 'High', 0, '', '', '', 0, 0), (268, '00283', '1169599000887', '', 2, 2, 1, 2, '', '', 'Warranty', 'Installation', '', '5', 'outstation', '188', '00015', '', 0, '', 0, '', '', '', 0, 0), (269, '00284', 'CF76052599', '', 1, 1, 1, 6, '', '', 'Chargeable', 'Breakdown', '', '5', 'outstation', '189', '00012,00015', '', 0, 'High', 0, '', '', '', 0, 0), (270, '00285', '1167208000728', '', 2, 2, 1, 2, '', '', 'Warranty', 'Breakdown', '', '5', 'outstation', '190', '00015', '', 0, 'High', 0, '', '', 'accept', 0, 0), (271, '00286', '1169599000881', '', 2, 2, 1, 2, '2018-11-19', '', 'Warranty', 'Warranty', '', '17', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (272, '00287', '1169599000881', '', 2, 2, 1, 2, '', '', 'Warranty', 'Preventive', '', '17', 'outstation', '188', '00001,00025', '', 0, 'High', 0, '', '', '', 0, 0), (273, '00288', 'CC32059880', '', 1, 1, 1, 4, '', '', 'CMC', 'Preventive', '', '8', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (274, '00289', 'TESTSR8877', '', 1, 1, 1, 7, '', '', 'Chargeable', 'Breakdown', '', '8', 'outstation', '75', '00018', '', 0, 'Low', 0, '', 'this is test data. please ignore it', 'accept', 18, 0), (275, '00290', '11111', 'afsafasfa', 1, 1, 1, 4, '', '', 'Chargeable', 'AMC', '', '19', 'on_site', '19,60', '00026', '', 0, 'Critical', 0, '', 'asfasdfasfasf', 'accept', 26, 0), (276, '00291', 'DUM0000010', '', 1, 1, 1, 5, '', '', 'Chargeable', 'AMC', '', '19', 'on_site', '142,62', '00026', '', 0, 'Critical', 0, '', 'asfasfdsafasfasfasfasfsafsafsafasfsafsa', 'accept', 26, 0), (277, '00292', '11111', 'afsafasfa', 1, 1, 1, 4, '', '', 'Chargeable', 'AMC', '1', '19', 'on_site', '19,60', '00026', '', 0, 'Critical', 0, '', 'ssssssssssssss', 'accept', 0, 0), (278, '00293', 'DUM0000010', '', 1, 1, 1, 5, '', '', 'Chargeable', 'AMC', '', '19', 'on_site', '8,62', '00026', '', 0, 'Critical', 0, '', 'sadfsafsafasfasfs', '', 0, 0), (279, '00294', '11111', 'afsafasfa', 1, 1, 1, 4, '', '', 'Chargeable', 'AMC', '1', '19', 'on_site', '23,60', '00026', '', 0, 'Critical', 0, '', 'sddfsafasfasf', 'accept', 26, 0), (280, '00295', '124545', '1414', 1, 1, 1, 4, '', '', 'Chargeable', 'AMC', '1', '19', 'on_site', '19,60', '00027', '', 0, 'Critical', 0, '', 'dasfsadfdasfsafsafasfsafsafas', 'accept', 27, 0), (281, '00296', '124545', '1414', 1, 1, 1, 4, '', '', 'Chargeable', 'Out Of Warranty', '1', '19', 'on_site', '19,60', '00026', '', 0, 'Critical', 0, '', 'sasdssdadsssas', 'accept', 26, 0), (282, '00297', '232332', '2323', 1, 1, 1, 8, '', '', 'Chargeable', 'Out Of Warranty', '', '19', 'on_site', '46,82', '00027', '', 0, 'Critical', 0, '', 'gfsdgsdgdsgdsgdsgsdgsdgsdg', 'accept', 27, 0), (283, '00298', '12332', '111', 1, 1, 1, 3, '', '', 'Chargeable', 'AMC', '', '19', 'on_site', '66', '00026', '', 0, 'Critical', 0, '', 'sdgdsgsdgsdgsdgs', 'accept', 26, 0), (284, '00299', 'BR3508C408', '', 2, 2, 1, 1, '2017-05-26', '', 'Chargeable', 'Preventive', '', '6', 'outstation', '63,64', '00011', '', 0, 'Critical', 0, '', 'safsafasfasfafsf', '', 0, 0), (285, '00300', '3456', '', 1, 1, 1, 6, '2019-06-25', '', 'Chargeable', 'AMC', '', '19', 'on_site', '158,68', '00027', '', 0, 'High', 0, '', 'fdsafdasfafaf', '', 0, 0), (286, '00301', '3456', '', 1, 1, 1, 6, '2019-06-25', '', 'Chargeable', 'Preventive', '', '19', 'on_site', '68,192', '00027', '', 0, 'Critical', 0, '', 'safdsafasfafsafass', '', 0, 0), (287, '00302', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Chargeable', 'Preventive', '', '8', 'outstation', '75', '00011', '', 0, '', 0, '', '', '', 0, 0), (288, '00303', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Chargeable', 'AMC', '', '8', 'outstation', '75', '00013', '', 0, '', 0, '', 'asfasfdasfasfsafsa', '', 0, 0), (289, '00304', '3456', '', 1, 1, 1, 6, '2019-06-25', '', 'Chargeable', 'Out Of Warranty', '', '19', 'on_site', '84,68', '00026', '', 0, 'Critical', 0, '', 'dfsgsdgdssdgdss', '', 0, 0), (290, '00305', '3456', '', 1, 1, 1, 6, '2019-06-25', '', 'Chargeable', 'AMC', '', '19', 'on_site', '68', '00026', '', 0, '', 0, '', 'rerfewtrwe', '', 0, 0), (291, '00306', '3456', '', 1, 1, 1, 6, '2019-06-25', '', 'Chargeable', 'Preventive', '', '19', 'on_site', '68', '00027', '', 0, '', 0, '', 'fdsafsafa', '', 0, 0), (292, '00307', 'DUM0000023', '', 1, 1, 4, 12, '2019-07-02 00:00:00', '', 'Warranty', 'AMC', '', '19', '', '193,194', '00026', '', 0, '', 0, '', 'ASFASFDSAFASFASFAFASFAFASF', '', 0, 0), (293, '00311', 's123', '', 1, 1, 1, 6, '', '', 'Preventive', 'Preventive', '', '19', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (294, '00312', 'ts1234', '', 1, 1, 3, 11, '', '', 'Preventive', 'Preventive', '', '19', '', '', '', '', 0, '', 0, '', '', '', 0, 0), (295, '00313', 'TESTSR8877', '', 0, 0, 0, 0, '2018-06-02', '', 'Chargeable', 'soft_up', '4', '8', 'outstation', '195', '00018', '', 0, 'Low', 0, '', 'dcdsfdf', '', 0, 0), (296, '00314', 'TESTSR8877', '', 1, 1, 1, 7, '2018-06-02', '', 'Chargeable', 'soft_up', '', '8', 'outstation', '75', '00018', '', 0, 'Low', 0, '', 'this is test description', '', 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `service_status` -- CREATE TABLE IF NOT EXISTS `service_status` ( `id` int(10) NOT NULL AUTO_INCREMENT, `prod_service_status` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `spares` -- CREATE TABLE IF NOT EXISTS `spares` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_name` varchar(100) NOT NULL, `part_no` varchar(50) NOT NULL, `spare_qty` int(10) NOT NULL, `used_spare` int(10) NOT NULL, `eng_spare` int(10) NOT NULL, `purchase_price` int(10) NOT NULL, `purchase_qty` int(10) NOT NULL, `min_qty` int(10) NOT NULL, `purchase_date` varchar(100) NOT NULL, `sales_price` int(10) NOT NULL, `effective_date` varchar(100) NOT NULL, `invoice_no` varchar(100) NOT NULL, `reason` varchar(500) NOT NULL, `dashboard_show` int(10) NOT NULL, `created_on` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=313 ; -- -- Dumping data for table `spares` -- INSERT INTO `spares` (`id`, `spare_name`, `part_no`, `spare_qty`, `used_spare`, `eng_spare`, `purchase_price`, `purchase_qty`, `min_qty`, `purchase_date`, `sales_price`, `effective_date`, `invoice_no`, `reason`, `dashboard_show`, `created_on`) VALUES (1, '<NAME>', '26009', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (2, 'String Bar -Triangular', '26405', 8, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (3, 'Filter Colorimetry Box', '26538', 52, 0, 0, 3453, 52, 0, '2018-02-15 10:52', 0, '', 'srdgvfdgfsd', 'dsfgdsgsgds', 0, ''), (4, 'Memory Data Novram', '26549', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (5, 'Fuse Holder Cap6, 3 X32', '26664', 13, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (6, 'RED STIRRING BAR 3,2X12,7', '26674', 9, 0, 0, 0, 10, 0, '', 0, '', '', '', 0, ''), (7, 'LAMP HALOGEN', '26699', 22, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (8, 'THERMAL PAPER', '26849', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (9, '3 TUBINGS:NEEDLE-ELECTROVALVE', '27001', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (10, 'PCB Chronometry Analog', '27013', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (11, 'STA Compact PCB Fuse Board', '27018', 5, 0, 0, 0, 5, 0, '', 0, '', '', '', 0, ''), (12, 'PCB Add Component', '27019', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (13, 'PCB Product Detection', '27023', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (14, 'STA Compact Suction Head Chain', '27025', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (15, 'Cuvette Loader Chain', '27026', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (16, 'STA Compact Sample Drawer Chain', '27027', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (17, 'STA Compact Product Drawer Chain', '27028', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (18, 'STA Compact Cuv Loader Switches', '27029', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (19, 'Drawer /Jack Microswitch', '27030', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (20, 'Fuses T03A6 3 x 32 (10)', '27034', 8, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (21, 'Fuses T4A6,3x32(10)', '27037', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (22, 'STA Compact Z Motor', '27038', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (23, 'STA Compact X,Y1, Y2 Motor', '27051', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (24, 'STA Compact Washing Well', '27059', 3, 0, 0, 0, 3, 0, '', 0, '', '', '', 0, ''), (25, 'Glycol Researvoir', '27062', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (26, 'PCB Reagent Display (Round)', '27069', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (27, 'PCB Sample Detection', '27070', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (28, 'PCB PID Version 2', '27082', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (29, 'PCB A/D Photometry Measure', '27110', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (30, 'STB Sample Display Board (Round)', '27148', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (31, 'Membrance Kit Vaccum Pump', '27165', 4, 0, 0, 0, 4, 0, '', 0, '', '', '', 0, ''), (32, 'Cooling Pump Maintenance Kit', '27169', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (33, 'Switch for Container Assy', '27171', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (34, 'Sensor Temprature Multimeter', '27208', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (35, 'Pcb Main Rack', '27209', 3, 0, 0, 0, 3, 0, '', 0, '', '', '', 0, ''), (36, 'Cuvette Temprature', '27223', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (37, 'Fuses (T)10A 6.3x32 UL (10)', '27224', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (38, 'FUSES (T) 8A 6,3X32 (10)', '27225', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (39, 'PCB 4 PORT', '27262', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (40, 'NEEDLE ARM N[3 WITH NUT', '27307', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (41, 'PCB Zero Axis', '27337', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (42, 'Fan Rear Panel', '27347', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (43, 'NEEDLE ARM N[2 WITH NUT B', '27354', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (44, 'Motor Z and Pippetor', '27355', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (45, 'Power Supply Switiching', '27375', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (46, 'Motor Assay x Sta Compact', '27407', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (47, 'Tube Heating Z 3', '27415', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (48, 'Filter Air Bag', '27420', 10, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (49, 'Suction Rubber Head', '27421', 5, 0, 0, 0, 5, 0, '', 0, '', '', '', 0, ''), (50, 'WHITE STIRRING BAR (2X7)', '27425', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (51, 'Electrovalve 2 Way', '27432', 8, 0, 0, 0, 8, 0, '', 0, '', '', '', 0, ''), (52, 'Filter Liquid', '27458', 6, 0, 0, 0, 6, 0, '', 0, '', '', '', 0, ''), (53, 'Motor Optical Module', '27478', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (54, 'Fan Optical Module', '27481', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (55, 'Vacuum Test Tool', '27495', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (56, 'PCB Aton VGA', '27515', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (57, 'O Ring /teflon Tips (X6)', '27530', 18, 0, 0, 0, 18, 0, '', 0, '', '', '', 0, ''), (58, 'SYRINGE AND O RING', '27538', 6, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (59, 'Service Floppy Disk', '27564', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (60, 'Filter Mains', '27574', 7, 0, 0, 300, 30, 0, '2017-12-29 17:00', 100, '', 'dfdsfs', 'sdfsdfs', 0, ''), (61, 'Fuse T 1A 6,3x32(10)', '27579', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (62, 'Fuse T 3A 6.3x32 (10)', '27581', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (63, 'Fibre Optic Harness', '38029', 1, 1, 1, 0, 2, 0, '', 0, '', '', '', 0, ''), (64, 'Vaccum Switch 450mB', '38055', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (65, 'Cuvetter Tem Perature ST Art', '38100', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (66, 'Extractor Eprom Plcc', '38107', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (67, 'PCB Heating 4 & 8 Cells', '38108', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (68, 'Power Supply (+24V)', '38121', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (69, 'Power Supply (+5,+12,-12)', '38122', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (70, 'Filter Colorimetry Box V 3', '38125', 18, 0, 0, 0, 18, 0, '', 0, '', '', '', 0, ''), (71, 'Printer Thermic Assembly', '38133', 1, 1, 1, 0, 0, 0, '', 0, '', '', '', 0, ''), (72, 'PCB Multifunctions V.2', '38136', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (73, 'PCB Connections Motors V.2', '38149', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (74, 'NIPPLE STRAIGHT PU : S TUBING', '38162', -8, 4, 4, 0, 5, 0, '', 50, '', '', '', 0, ''), (75, 'Shutle Belt Driven', '38274', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (76, 'Shuttle Belt Driving', '38275', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (77, 'Y Arm Belt', '38280', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (78, 'Drawer Belt', '38288', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (79, 'Fiber Optic-Receiving L300(X1)', '38292', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (80, 'X1 Conveyor Belt', '38297', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (81, 'X2 Conveyor Belt', '38298', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (82, 'PCB ARM Junction', '38309', 16, 0, 0, 400, 40, 0, '2017-12-29 17:00', 200, '', 'sddsfds', 'dsfsfsdf', 0, ''), (83, 'PCB Heating Head', '38310', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (84, 'PCB Analog Measurement', '38313', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (85, 'PCB Heating Measure', '38314', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (86, 'PCB Multifunctions Main Rack', '38318', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (87, 'PCB Cooling Unit Relay V.2.0', '38321', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (88, 'Cable Zero Y Switch Rack', '38349', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (89, 'Cable T Probe Product Drawer', '38363', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (90, 'Micro Switch with Cable', '38369', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (91, 'Fuse Holder Main', '38372', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (92, 'Motor Product Drawer', '38384', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (93, 'Motor X Stepper', '38387', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (94, 'Motor Y Stepper', '38388', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (95, 'Motor DC Tube Rotation', '38389', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (96, 'Motor Pipetor', '38390', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (97, 'Motor Shuttle Stop -Dual', '38546', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (98, 'Washing Well N2 / N3', '38558', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (99, 'Power Supply Dc+5,+1,-12,+24', '38559', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (100, 'Motor Z Steppper', '38564', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (101, 'Washing Well N1', '38565', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (102, 'Tubing PVC 6x9 L2', '38577', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (103, 'Tubing Teflon Diam=2 L=5', '38583', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (104, 'Electrovalve 2 Way Piercing', '38589', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (105, 'Water Trap', '38608', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (106, 'Fiber Optic 2.2x1220(X1)', '38627', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (107, 'Cover Measurement Assay', '38636', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (108, 'NEEDLE N[1 STADARD V.2', '38646', 6, 0, 0, 0, 6, 0, '', 0, '', '', '', 0, ''), (109, 'PCB Multifunctions Head N4', '38652', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (110, 'Reservoir Vaccum', '38757', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (111, 'Cap Used Liquied Container', '38764', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (112, 'PCB DC Motor Driver', '38790', 5, 0, 0, 0, 5, 0, '', 0, '', '', '', 0, ''), (113, 'PCB Interface I/O PC V.3', '38806', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (114, 'Nipple Straight -PU4 Tubing PP', '38824', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (115, 'Eprom CMDMOT Ver 1.81', '38828', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (116, 'Test Tool Incub.Temprature', '38838', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (117, 'PCB Mother Only / 4 Cells', '38856', 1, 0, 0, 0, 1, 0, '', 0, '', '', 'To SR', 0, ''), (118, 'Distributor Cable J34', '38858', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (119, 'Cable Drawer Sample J15 L=770', '38862', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (120, 'Cable Product Drawer J16 L=910', '38863', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (121, 'Cpu Processor Fan 12v', '38868', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (122, 'Photometery Box Fan', '38869', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (123, 'Tubing PVC 3x2 L10', '38873', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (124, 'Tubing Pur-2.9x4.3L10', '38875', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (125, 'Tubing PE 4x6Lx10', '38911', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (126, 'Tubing PUr 4x6L 10', '38912', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (127, 'PCB Power I/O Star', '38918', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (128, 'Tool V3 Optical Module', '38921', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (129, 'Motor Drawer', '38939', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (130, 'Tool Maping Piercing', '39012', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (131, 'Tool Needle Positon Well', '39013', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (132, 'Motor Dc Y1/Y2 Rack V2', '39014', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (133, 'Motor DC X1/x2 Rack V.2', '39015', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (134, 'Wedge Adjust Cap Piercing', '39020', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (135, 'Needle 1 Piercing V.3', '39022', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (136, 'Piercing Washing Well', '39023', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (137, 'Eprom GSTFB Ver 2.40 Gestion', '39037', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (138, 'Eprom MSTFB Ver.2.40 Measure', '39039', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (139, 'Head +Support Suction Tip', '39127', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (140, 'Wheel Tube Rotation', '39134', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (141, 'Nylon Screws M3x8(X5)', '39152', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (142, 'Suction Tip V.4', '39163', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (143, 'Needle N1 Piercing STA-R A', '39164', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (144, 'Fiber Receiving Optic', '39168', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (145, 'Motor Z DC Piercing', '39208', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (146, 'PCB Colo Measure', '39225', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (147, 'Head Measure VMIN=150ul COLO', '39234', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (148, 'PUMP VALCOR', '39240', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (149, 'Needle N1 Standard V.3B', '39249', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (150, 'Needle N2 V2B', '39250', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (151, 'Tubing PE 3x4 3L 10', '39278', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (152, 'Electrovalve 3 Wat 24v', '39306', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (153, 'Needle Equiped', '39356', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (154, 'Assay Lamp Support', '39369', 6, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (155, 'Qwerty Keyboard', '39394', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (156, 'Cutter Motor', '39399', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (157, 'Acc Axis Entry Rotation Screw', '39444', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (158, 'Flow Meter', '39481', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (159, 'Chain Pipetting Head', '39497', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (160, 'Key Board ST ART NG', '39549', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (161, 'Cable Block Measure Temp. Probe', '39599', 8, 0, 0, 0, 8, 0, '', 0, '', '', '', 0, ''), (162, 'Electrovalve 2 Way Sirai', '39610', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (163, 'Cables Flates J20 J41', '39617', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (164, 'Tools ILS Swtich', '39628', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (165, 'Electrovalve Well Equiped X3', '39629', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (166, 'Mapping Tool', '39635', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (167, 'PCB Motor Interface', '39643', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (168, 'Filter Liquid X1', '39738', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (169, 'Positioner Of Carrousel', '39760', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (170, 'Mapping Tool (Cuvette)', '39769', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (171, 'Sample Mapping Tool', '39857', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (172, 'Cooler Fan CPU', '39861', 6, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (173, 'Equipped Printer + Cover', '39894', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (174, 'Measurement CPU Board', '39978', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (175, 'PCB Rotord Interface', '39979', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (176, 'Tool Assembly Optical Fiber', '39990', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (177, 'KIT PELTIER V.2(X2)', '80022', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (178, 'Ev Cuvette Base Plate', '80060', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (179, 'M5 Cuv.Base Plate Silencer', '80063', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (180, 'Bridge DIODE 35A 600V', '80070', 10, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (181, 'Cooling Pump Maintenance KT V2', '80084', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (182, 'ROTOR PRODUCTS N0*1', '80091', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (183, 'PCB Multifunctions Head 3', '80105', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (184, 'PCB Multifunctions Head 1+2', '80106', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (185, 'CONNECTED PIPETTE', '80109', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (186, 'Reservoir Intermediate Cleaner', '80121', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (187, 'CASSETTE PRODUCT DRAWER V2', '80175', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (188, 'EU Removable Power Cord', '80224', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (189, 'Fluid Connector + Tubing Kit', '80235', 0, 1, 1, 0, 0, 0, '', 0, '', '', '', 0, ''), (190, 'Optical Sensor + Adaptors', '80236', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (191, 'Equipped Z Motor', '80238', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (192, 'Rail Temporature Sensor Board', '80247', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (193, 'Equiped Fuses Board', '80251', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (194, 'Equipped Petter Assy', '80255', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (195, 'Assy Rail', '80259', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (196, 'Measurement CPU Board+Bracket', '80262', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (197, 'Motor Cuvette Roll Drive', '80432', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (198, 'PCB Temperature Regulation', '80437', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (199, 'Rail Nearness Sensor', '80514', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (200, 'Reed Rotor Switch Trap', '80515', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (201, 'Infrared Light Board', '80648', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (202, 'Filter Rinsing Asay Air', '80675', 16, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (203, 'LLD Cable (X3)', '80787', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (204, 'Liquid Level Dectect Cable', '80792', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (205, 'Electrovave N1', '80901', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (206, 'PCB 4 Axis (Mpp4)', '80924', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (207, 'MPP4 Board Front Plate', '80949', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (208, 'Printer Installation SOFT V06', '80972', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (209, 'Satellite Techn.Manual (CDROM)', '80982', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (210, 'Rail Moter', '80994', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (211, 'Moteur Agitateur', '86554', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (212, 'Module Incubation', '86556', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (213, 'Kit Ventilateur', '86558', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (214, 'Kit Ecran', '86559', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (215, 'Carte Mere START MAX', '86565', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (216, 'YEARLY ADDITIONAL PM KIT', '87032', 3, 0, 0, 0, 3, 0, '', 0, '', '', '', 0, ''), (217, 'Bar Code Reader Cable V2', '87034', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (218, 'Rinsing EV Block V2', '87054', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (219, 'Suction Tip V5(X2)', '87063', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (220, 'Gripping Nipples + Tubing Kit', '87077', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (221, 'PCb CPU Pentium ETX V2', '87095', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (222, 'Equipped Photo Motor Support', '87097', -1, 0, 0, 0, -1, 0, '', 0, '', '', '', 0, ''), (223, 'Suction Tip V5 Mapping Tools', '88329', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (224, 'Plate Bar Code Conveyor V4', '88332', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (225, 'Tourchscreen Control', '88367', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (226, 'Cuvette Loader STA Compact', '88394', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (227, 'CPU Measurement PCB', '88402', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (228, 'Intermediate Reservor', '88431', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (229, 'Eprom Comdmat Ver.10.90', '88440', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (230, 'Eprom CMDMOT Ver.1.90', '88441', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (231, 'Erom MCC Ver.1.20', '88442', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (232, 'Photomotor Current Reducer', '88461', 4, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (233, '1.41 & 2.01 Firmware Up Kit', '88462', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (234, 'ILS Reservoirs Test Adaptor', '88464', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (235, 'Nuts Connector Needle (X2)', '88473', 5, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (236, 'COOLING LIQUID PUMP V3', '88492', 0, 1, 1, 0, 1, 0, '', 0, '', '', '', 0, ''), (237, 'Cooling Pump Membranes V2 & V3', '88493', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (238, 'Photometry Control Board V6', '88496', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (239, 'ARM1W/O Piercing Tubing Guide', '88512', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (240, 'SBCATLAS Motherboard', '88519', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (241, 'ARMS AND DRAWERS BELT', '88539', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (242, 'DVD Windows Embedded Standard', '88554', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (243, 'Software STC Version 424', '88556', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (244, 'Motor Cuvette Loader', '88557', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (245, 'Asys Cuvette Loader V.2', '88558', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (246, 'MAINTENANCE KIT', '88596', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (247, 'YEARLY ADDITIONAL MAINT KIT', '88597', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (248, 'Pipetting Head Heating PCB', '88623', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (249, 'Version 3 (Pid Board Verion 2)', '88657', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (250, 'Preventive Maintence Kit', '88690', 5, 0, 0, 0, 5, 0, '', 0, '', '', '', 0, ''), (251, 'Software 108.06 / 208.06', '88712', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (252, 'Input/output Board Front Plate', '88724', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (253, 'Equipped Pneumatic Base', '88757', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (254, 'Flash Memory 256MO', '88795', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (255, 'Equippech Power Supply V2', '88809', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (256, 'Bar Code Sample Installation Kit', '88812', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (257, 'PDR Assy', '88842', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (258, 'Equipped Theta Motor', '88847', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (259, 'Vaccum Pump', '88857', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (260, 'Equipped Camera + Bracket', '88890', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (261, 'Shuttle Stop-Dual Retrofit Kit', '88949', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (262, 'Photometry Board + FIBERS', '88963', -1, 1, 1, 0, 0, 0, '', 0, '', '', '', 0, ''), (263, 'MOTOR DC-FRONT PUSHER', '89003', 2, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (264, 'Motor CC Rateau Arriere', '89004', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (265, 'Y Conveyor Belts (X4)', '89010', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (266, 'PIPETING HEAD HEATING PCB', '89041', 3, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (267, 'Windos Embedded Std Usb Key', '89079', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (268, 'Module Mesure', '89185', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (269, 'Carte CDE Convoyeur Racks V2', '89204', 1, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (270, 'Carte Zero Pipeteur', '89206', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (271, 'CLE USB ACRONIS TRUE IMAGE', '89277', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (272, 'Membrance Key Pads', '111111111', 30, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (273, 'Thermal Print Heads', '38133', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (274, 'ASSY PC', '', 1, 1, 1, 0, 1, 0, '', 0, '', '', '', 0, ''), (275, '4 SERIAL PORTS BOARD CPR RS232', '86605', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (276, 'pcb multifunctions carte multifunction', '89223', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (277, 'STANDARD MAINTENANCE KIT', '89035', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (278, 'Assy Measure Peltier Kits V2 ', '88778', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (279, 'Block 4 Measure Head V3 ', '39228', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (280, 'Bottle Glass Vacuum Reservoir', '38755', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (281, 'CABLE DRAWER TEMPRATURE PROBE', '89211/38086', 3, 0, 0, 0, 3, 0, '', 0, '', '', '', 0, ''), (282, 'Cable Head Gripping L', '39148', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (283, 'Cable Platine Measure Tiroir ', '89207', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (284, 'Cable Flats J24 J29 J30', '39326', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (285, 'Carte Commande Moteur C.C.V3 /DC MOTOR PCB V3', '89159', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (286, 'Carte Mere ETX V3/PCB CPU ETX V3', '89294', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (287, 'CONVEYOR HEIGHT MAPPING TOOL ', '89279', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (288, 'Dual Reed Switch ', '27065', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (289, 'Electrovalve 3 Way', '88797', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (290, 'Equiped Axis Cuvette Roll', '80199', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (291, 'Glycol Tygon Tubing Fittings', '88849', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (292, 'Head Measurement V3', '39227', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (293, 'Microtainer Reducer X2 (Satellite)', '80057', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (294, 'Nipple Y Type', '38261', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (295, 'O Ring 42X2.6 ', '38254', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (296, 'PCB Head', '88961', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (297, 'PCB Interface I/o PC V.4', '80162', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (298, 'PCB Power I/O', '39309', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (299, 'PCB POWER I/O V2', '89066', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (300, 'Product Peltier Assy V3', '88783', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (301, 'stirring motor V3', '88779', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (302, 'Thermal Switch ', '88781', 0, 0, 0, 0, 0, 0, '', 0, '', '', '', 0, ''), (303, 'Vacuum Pump With Fittings', '27360', 1, 0, 0, 0, 1, 0, '', 0, '', '', '', 0, ''), (304, 'Fiber Optic 2.2x530(X1)', '38628', 2, 0, 0, 0, 2, 0, '', 0, '', '', '', 0, ''), (305, 'LLD CABLE (X1)', '80785', -3, 0, 0, 200, 21, 0, '2017-12-29 17:00', 50, '', 'fdfd', 'fddgd', 0, ''), (306, 'PCB Shuttle Conveyor', '38885', 6, 0, 0, 23432, 6, 0, '2018-02-15 11:00', 0, '', 'sdafdsafas', 'fsafasfasfasfasf', 0, ''), (307, 'ssss1', '4343434', -1, 0, 0, 456, 2, 3, '2018-02-09 10:00', 234, '2018-02-09', 'sfgfds', 'gdsfgdsgggg', 0, ''), (308, 'lvrs', '14', 15, 0, 0, 2323, 17, 3, '2018-02-14 12:00', 141414, '2018-02-14', 'dfgdg', 'dfgfggfgfd', 0, ''), (309, 'dellnew', '876', 6, 2, 2, 1234, 10, 3, '2018-02-14 15:00', 876, '2018-02-14', 'asdsdds', 'fdasfasfasfas', 0, ''), (310, 'awaw', '121222', 4, 2, 2, 6565, 10, 3, '2018-02-14 16:00', 43254353, '2018-02-14', 'gfdsgfsdg', 'gsdfgdsgsdgsgsd', 0, ''), (311, 'prince', '7896544', 0, 0, 0, 0, 0, 2, '', 8000, '2018-06-26', '', '', 0, '26-06-2018 17:42:32'), (312, 'princees', '454', 0, 0, 0, 0, 0, 4, '', 525, '2018-06-26', '', '', 0, '2018-06-26'); -- -------------------------------------------------------- -- -- Table structure for table `spares_effective_date_history` -- CREATE TABLE IF NOT EXISTS `spares_effective_date_history` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_name` varchar(100) NOT NULL, `part_no` varchar(50) NOT NULL, `sales_price` int(10) NOT NULL, `effective_date` varchar(100) NOT NULL, `min_qty` int(10) NOT NULL, `created_on` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=155 ; -- -- Dumping data for table `spares_effective_date_history` -- INSERT INTO `spares_effective_date_history` (`id`, `spare_name`, `part_no`, `sales_price`, `effective_date`, `min_qty`, `created_on`) VALUES (1, 'YEARLY ADDITIONAL PM KIT', '', 0, '', 0, ''), (2, 'YEARLY ADDITIONAL PM KIT', '', 0, '', 0, ''), (3, 'Photometry Board + FIBERS', '', 0, '', 0, ''), (4, 'YEARLY ADDITIONAL PM KIT', '', 0, '', 0, ''), (5, 'YEARLY ADDITIONAL MAINT KIT', '', 0, '', 0, ''), (6, 'Y Conveyor Belts (X4)', '', 0, '', 0, ''), (7, 'Windos Embedded Std Usb Key', '', 0, '', 0, ''), (8, 'Version 3 (Pid Board Verion 2)', '', 0, '', 0, ''), (9, 'Vaccum Pump', '', 0, '', 0, ''), (10, 'Tourchscreen Control', '', 0, '', 0, ''), (11, 'Tourchscreen Control', '', 0, '', 0, ''), (12, 'Tool Assembly Optical Fiber', '', 0, '', 0, ''), (13, 'Thermal Print Heads', '', 0, '', 0, ''), (14, 'Suction Tip V5(X2)', '', 0, '', 0, ''), (15, 'Suction Tip V5 Mapping Tools', '', 0, '', 0, ''), (16, 'Software STC Version 424', '', 0, '', 0, ''), (17, 'Software 108.06 / 208.06', '', 0, '', 0, ''), (18, 'Shuttle Stop-Dual Retrofit Kit', '', 0, '', 0, ''), (19, 'SBCATLAS Motherboard', '', 0, '', 0, ''), (20, 'Satellite Techn.Manual (CDROM)', '', 0, '', 0, ''), (21, 'ROTOR PRODUCTS N0*1', '', 0, '', 0, ''), (22, 'Rinsing EV Block V2', '', 0, '', 0, ''), (23, 'Rail Temporature Sensor Board', '', 0, '', 0, ''), (24, 'Rail Nearness Sensor', '', 0, '', 0, ''), (25, 'Rail Moter', '', 0, '', 0, ''), (26, 'Qwerty Keyboard', '', 0, '', 0, ''), (27, 'Printer Thermic Assembly', '', 0, '', 0, ''), (28, 'Printer Installation SOFT V06', '', 0, '', 0, ''), (29, 'Preventive Maintence Kit', '', 0, '', 0, ''), (30, 'Plate Bar Code Conveyor V4', '', 0, '', 0, ''), (31, 'Reservoir Intermediate Cleaner', '', 0, '', 0, ''), (32, 'Pipetting Head Heating PCB', '', 0, '', 0, ''), (33, 'PIPETING HEAD HEATING PCB', '', 0, '', 0, ''), (34, 'Reed Rotor Switch Trap', '', 0, '', 0, ''), (35, 'PCB Temperature Regulation', '', 0, '', 0, ''), (36, 'Photomotor Current Reducer', '', 0, '', 0, ''), (37, 'Photometry Control Board V6', '', 0, '', 0, ''), (38, 'PDR Assy', '', 0, '', 0, ''), (39, 'PCB Rotord Interface', '', 0, '', 0, ''), (40, 'PCB Multifunctions Head 3', '', 0, '', 0, ''), (41, 'PCB Multifunctions Head 1+2', '', 0, '', 0, ''), (42, 'PCB Motor Interface', '', 0, '', 0, ''), (43, 'PCb CPU Pentium ETX V2', '', 0, '', 0, ''), (44, 'PCB 4 Axis (Mpp4)', '', 0, '', 0, ''), (45, 'Optical Sensor + Adaptors', '', 0, '', 0, ''), (46, 'Optical Sensor + Adaptors', '', 0, '', 0, ''), (47, 'Nuts Connector Needle (X2)', '', 0, '', 0, ''), (48, 'MPP4 Board Front Plate', '', 0, '', 0, ''), (49, 'Motor Cuvette Roll Drive', '', 0, '', 0, ''), (50, 'MOTOR DC-FRONT PUSHER', '', 0, '', 0, ''), (51, 'Motor Cuvette Loader', '', 0, '', 0, ''), (52, 'Motor CC Rateau Arriere', '', 0, '', 0, ''), (53, 'Moteur Agitateur', '', 0, '', 0, ''), (54, 'Module Mesure', '', 0, '', 0, ''), (55, 'Module Incubation', '', 0, '', 0, ''), (56, 'Membrance Key Pads', '', 0, '', 0, ''), (57, 'Measurement CPU Board+Bracket', '', 0, '', 0, ''), (58, 'Measurement CPU Board', '', 0, '', 0, ''), (59, 'MAINTENANCE KIT', '', 0, '', 0, ''), (60, 'M5 Cuv.Base Plate Silencer', '', 0, '', 0, ''), (61, 'LLD Cable (X3)', '', 0, '', 0, ''), (62, 'Liquid Level Dectect Cable', '', 0, '', 0, ''), (63, 'Kit Ventilateur', '', 0, '', 0, ''), (64, 'KIT PELTIER V.2(X2)', '', 0, '', 0, ''), (65, 'Kit Ecran', '', 0, '', 0, ''), (66, 'Intermediate Reservor', '', 0, '', 0, ''), (67, 'Input/output Board Front Plate', '', 0, '', 0, ''), (68, 'Infrared Light Board', '', 0, '', 0, ''), (69, 'ILS Reservoirs Test Adaptor', '', 0, '', 0, ''), (70, 'Gripping Nipples + Tubing Kit', '', 0, '', 0, ''), (71, 'Fluid Connector + Tubing Kit', '', 0, '', 0, ''), (72, 'Flash Memory 256MO', '', 0, '', 0, ''), (73, 'Ev Cuvette Base Plate', '', 0, '', 0, ''), (74, 'Filter Rinsing Asay Air', '', 0, '', 0, ''), (75, 'EU Removable Power Cord', '', 0, '', 0, ''), (76, 'Erom MCC Ver.1.20', '', 0, '', 0, ''), (77, 'Equipped Z Motor', '', 0, '', 0, ''), (78, 'Equipped Theta Motor', '', 0, '', 0, ''), (79, 'Equipped Printer + Cover', '', 0, '', 0, ''), (80, 'Equipped Printer + Cover', '', 0, '', 0, ''), (81, 'Equipped Pneumatic Base', '', 0, '', 0, ''), (82, 'Equipped Pneumatic Base', '', 0, '', 0, ''), (83, 'Equipped Photo Motor Support', '', 0, '', 0, ''), (84, 'Equipped Petter Assy', '', 0, '', 0, ''), (85, 'Equipped Camera + Bracket', '', 0, '', 0, ''), (86, 'Eprom Comdmat Ver.10.90', '', 0, '', 0, ''), (87, 'Equippech Power Supply V2', '', 0, '', 0, ''), (88, 'Equiped Fuses Board', '', 0, '', 0, ''), (89, 'Eprom CMDMOT Ver.1.90', '', 0, '', 0, ''), (90, 'Electrovave N1', '', 0, '', 0, ''), (91, 'Electrovalve 3 Wat 24v', '', 0, '', 0, ''), (92, 'DVD Windows Embedded Standard', '', 0, '', 0, ''), (93, 'Cuvette Loader STA Compact', '', 0, '', 0, ''), (94, 'Cutter Motor', '', 0, '', 0, ''), (95, 'CPU Measurement PCB', '', 0, '', 0, ''), (96, 'Cooling Pump Membranes V2 & V3', '', 0, '', 0, ''), (97, 'Cooling Pump Maintenance KT V2', '', 0, '', 0, ''), (98, 'COOLING LIQUID PUMP V3', '', 0, '', 0, ''), (99, 'CONNECTED PIPETTE', '', 0, '', 0, ''), (100, 'CLE USB ACRONIS TRUE IMAGE', '', 0, '', 0, ''), (101, 'Bridge DIODE 35A 600V', '', 0, '', 0, ''), (102, 'CASSETTE PRODUCT DRAWER V2', '', 0, '', 0, ''), (103, 'Carte Zero Pipeteur', '', 0, '', 0, ''), (104, 'Carte Mere START MAX', '', 0, '', 0, ''), (105, 'Carte CDE Convoyeur Racks V2', '', 0, '', 0, ''), (106, 'Bar Code Sample Installation Kit', '', 0, '', 0, ''), (107, 'Bar Code Reader Cable V2', '', 0, '', 0, ''), (108, 'Asys Cuvette Loader V.2', '', 0, '', 0, ''), (109, 'Assy Rail', '', 0, '', 0, ''), (110, 'ARMS AND DRAWERS BELT', '', 0, '', 0, ''), (111, 'ARM1W/O Piercing Tubing Guide', '', 0, '', 0, ''), (112, '1.41 & 2.01 Firmware Up Kit', '', 0, '', 0, ''), (113, 'ASSY PC', '', 0, '', 0, ''), (114, '4 SERIAL PORTS BOARD CPR RS232', '86605', 0, '', 0, ''), (115, 'pcb multifunctions carte multifunction', '89223', 0, '', 0, ''), (116, 'STANDARD MAINTENANCE KIT', '89035', 0, '', 0, ''), (117, 'Assy Measure Peltier Kits V2 ', '88778', 0, '', 0, ''), (118, 'Block 4 Measure Head V3 ', '39228', 0, '', 0, ''), (119, 'Bottle Glass Vacuum Reservoir', '38755', 0, '', 0, ''), (120, 'CABLE DRAWER TEMPRATURE PROBE', '89211/38086', 0, '', 0, ''), (121, 'Cable Head Gripping L', '39148', 0, '', 0, ''), (122, 'Cable Platine Measure Tiroir ', '89207', 0, '', 0, ''), (123, 'Cable Flats J24 J29 J30', '39326', 0, '', 0, ''), (124, 'Carte Commande Moteur C.C.V3 /DC MOTOR PCB V3', '89159', 0, '', 0, ''), (125, 'Carte Mere ETX V3/PCB CPU ETX V3', '89294', 0, '', 0, ''), (126, 'CONVEYOR HEIGHT MAPPING TOOL ', '89279', 0, '', 0, ''), (127, 'Dual Reed Switch ', '27065', 0, '', 0, ''), (128, 'Electrovalve 3 Way', '88797', 0, '', 0, ''), (129, 'Equiped Axis Cuvette Roll', '80199', 0, '', 0, ''), (130, 'Glycol Tygon Tubing Fittings', '88849', 0, '', 0, ''), (131, 'Head Measurement V3', '39227', 0, '', 0, ''), (132, 'Microtainer Reducer X2 (Satellite)', '80057', 0, '', 0, ''), (133, 'Nipple Y Type', '38261', 0, '', 0, ''), (134, 'O Ring 42X2.6 ', '38254', 0, '', 0, ''), (135, 'PCB Head', '88961', 0, '', 0, ''), (136, 'PCB Interface I/o PC V.4', '80162', 0, '', 0, ''), (137, 'PCB Power I/O', '39309', 0, '', 0, ''), (138, 'PCB POWER I/O V2', '89066', 0, '', 0, ''), (139, 'Product Peltier Assy V3', '88783', 0, '', 0, ''), (140, 'stirring motor V3', '88779', 0, '', 0, ''), (141, 'Thermal Switch ', '88781', 0, '', 0, ''), (142, 'Vacuum Pump With Fittings', '27360', 0, '', 0, ''), (143, 'Fiber Optic 2.2x530(X1)', '38628', 0, '', 0, ''), (144, 'LLD CABLE (X1)', '80785', 0, '', 0, ''), (145, 'PCB Shuttle Conveyor', '38885', 0, '', 0, ''), (146, 'Filter Mains', '', 100, '', 0, ''), (147, 'PCB ARM Junction', '', 200, '', 0, ''), (148, 'LLD CABLE (X1)', '', 50, '', 0, ''), (149, 'NIPPLE STRAIGHT PU : S TUBING', '', 50, '', 0, ''), (150, 'ssss1', '4343434', 234, '2018-02-09', 3, ''), (151, 'lvrs', '14', 141414, '2018-02-14', 3, ''), (152, 'dellnew', '876', 876, '2018-02-14', 3, ''), (153, 'awaw', '121222', 43254353, '2018-02-14', 3, ''), (154, 'princees', '454', 525, '2018-06-26', 4, '2018-06-26'); -- -------------------------------------------------------- -- -- Table structure for table `spare_details` -- CREATE TABLE IF NOT EXISTS `spare_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_id` int(10) NOT NULL, `cat_id` int(10) NOT NULL, `subcat_id` int(10) NOT NULL, `brand_id` int(10) NOT NULL, `model_id` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=815 ; -- -- Dumping data for table `spare_details` -- INSERT INTO `spare_details` (`id`, `spare_id`, `cat_id`, `subcat_id`, `brand_id`, `model_id`) VALUES (1, 1, 1, 1, 1, '4'), (2, 1, 1, 1, 1, '5'), (3, 1, 1, 1, 1, '6'), (4, 2, 2, 2, 1, '1'), (5, 2, 2, 2, 1, '2'), (6, 3, 1, 1, 1, '4'), (7, 3, 1, 1, 1, '5'), (8, 3, 1, 1, 1, '6'), (9, 4, 2, 2, 1, '1'), (10, 4, 2, 2, 1, '2'), (11, 5, 1, 1, 1, '4'), (12, 5, 1, 1, 1, '5'), (13, 5, 1, 1, 1, '6'), (14, 6, 1, 1, 1, '4'), (15, 6, 1, 1, 1, '5'), (16, 6, 1, 1, 1, '6'), (17, 7, 1, 1, 1, '4'), (18, 7, 1, 1, 1, '5'), (19, 7, 1, 1, 1, '6'), (20, 8, 2, 2, 1, '1'), (21, 8, 1, 1, 1, '3'), (22, 9, 1, 1, 1, '4'), (23, 9, 1, 1, 1, '5'), (24, 9, 1, 1, 1, '6'), (25, 10, 1, 1, 1, '4'), (26, 10, 1, 1, 1, '5'), (27, 10, 1, 1, 1, '6'), (28, 11, 1, 1, 1, '4'), (29, 11, 1, 1, 1, '5'), (30, 11, 1, 1, 1, '6'), (31, 12, 1, 1, 1, '4'), (32, 12, 1, 1, 1, '5'), (33, 12, 1, 1, 1, '6'), (34, 13, 1, 1, 1, '4'), (35, 13, 1, 1, 1, '5'), (36, 13, 1, 1, 1, '6'), (37, 14, 1, 1, 1, '4'), (38, 14, 1, 1, 1, '5'), (39, 14, 1, 1, 1, '6'), (40, 15, 1, 1, 1, '4'), (41, 15, 1, 1, 1, '5'), (42, 15, 1, 1, 1, '6'), (43, 16, 1, 1, 1, '4'), (44, 16, 1, 1, 1, '5'), (45, 16, 1, 1, 1, '6'), (46, 17, 1, 1, 1, '4'), (47, 17, 1, 1, 1, '5'), (48, 17, 1, 1, 1, '6'), (49, 18, 1, 1, 1, '4'), (50, 18, 1, 1, 1, '5'), (51, 18, 1, 1, 1, '6'), (52, 19, 1, 1, 1, '4'), (53, 19, 1, 1, 1, '5'), (54, 19, 1, 1, 1, '6'), (55, 20, 1, 1, 1, '4'), (56, 20, 1, 1, 1, '5'), (57, 20, 1, 1, 1, '6'), (58, 21, 1, 1, 1, '4'), (59, 21, 1, 1, 1, '5'), (60, 21, 1, 1, 1, '6'), (61, 22, 1, 1, 1, '4'), (62, 22, 1, 1, 1, '5'), (63, 22, 1, 1, 1, '6'), (64, 23, 1, 1, 1, '4'), (65, 23, 1, 1, 1, '5'), (66, 23, 1, 1, 1, '6'), (67, 24, 1, 1, 1, '4'), (68, 24, 1, 1, 1, '5'), (69, 24, 1, 1, 1, '6'), (70, 25, 1, 1, 1, '4'), (71, 25, 1, 1, 1, '5'), (72, 25, 1, 1, 1, '6'), (73, 26, 1, 1, 1, '4'), (74, 26, 1, 1, 1, '5'), (75, 26, 1, 1, 1, '6'), (76, 27, 1, 1, 1, '4'), (77, 27, 1, 1, 1, '5'), (78, 27, 1, 1, 1, '6'), (79, 28, 1, 1, 1, '4'), (80, 28, 1, 1, 1, '5'), (81, 28, 1, 1, 1, '6'), (82, 29, 1, 1, 1, '4'), (83, 29, 1, 1, 1, '5'), (84, 29, 1, 1, 1, '6'), (85, 30, 1, 1, 1, '4'), (86, 30, 1, 1, 1, '5'), (87, 30, 1, 1, 1, '6'), (88, 31, 1, 1, 1, '4'), (89, 31, 1, 1, 1, '5'), (90, 31, 1, 1, 1, '6'), (91, 32, 1, 1, 1, '4'), (92, 32, 1, 1, 1, '5'), (93, 32, 1, 1, 1, '6'), (94, 33, 1, 1, 1, '4'), (95, 33, 1, 1, 1, '5'), (96, 33, 1, 1, 1, '6'), (97, 33, 1, 1, 1, '7'), (98, 33, 1, 1, 1, '8'), (99, 33, 1, 1, 1, '9'), (100, 34, 1, 1, 1, '4'), (101, 34, 1, 1, 1, '5'), (102, 34, 1, 1, 1, '6'), (103, 34, 1, 1, 1, '3'), (104, 35, 1, 1, 1, '4'), (105, 35, 1, 1, 1, '5'), (106, 35, 1, 1, 1, '6'), (107, 36, 1, 1, 1, '4'), (108, 36, 1, 1, 1, '5'), (109, 36, 1, 1, 1, '6'), (110, 37, 1, 1, 1, '4'), (111, 37, 1, 1, 1, '5'), (112, 37, 1, 1, 1, '6'), (113, 38, 1, 1, 1, '4'), (114, 38, 1, 1, 1, '5'), (115, 38, 1, 1, 1, '6'), (116, 39, 1, 1, 1, '4'), (117, 39, 1, 1, 1, '5'), (118, 39, 1, 1, 1, '6'), (119, 40, 1, 1, 1, '4'), (120, 40, 1, 1, 1, '5'), (121, 40, 1, 1, 1, '6'), (122, 41, 1, 1, 1, '4'), (123, 41, 1, 1, 1, '5'), (124, 41, 1, 1, 1, '6'), (125, 42, 1, 1, 1, '4'), (126, 42, 1, 1, 1, '5'), (127, 42, 1, 1, 1, '6'), (128, 43, 1, 1, 1, '4'), (129, 43, 1, 1, 1, '5'), (130, 43, 1, 1, 1, '6'), (131, 44, 1, 1, 1, '4'), (132, 44, 1, 1, 1, '5'), (133, 44, 1, 1, 1, '6'), (134, 45, 1, 1, 1, '4'), (135, 45, 1, 1, 1, '5'), (136, 45, 1, 1, 1, '6'), (137, 46, 1, 1, 1, '4'), (138, 46, 1, 1, 1, '5'), (139, 46, 1, 1, 1, '6'), (140, 47, 1, 1, 1, '4'), (141, 47, 1, 1, 1, '5'), (142, 47, 1, 1, 1, '6'), (143, 48, 1, 1, 1, '4'), (144, 48, 1, 1, 1, '5'), (145, 48, 1, 1, 1, '6'), (146, 49, 1, 1, 1, '4'), (147, 49, 1, 1, 1, '5'), (148, 49, 1, 1, 1, '6'), (149, 50, 1, 1, 1, '4'), (150, 50, 1, 1, 1, '5'), (151, 50, 1, 1, 1, '6'), (152, 51, 1, 1, 1, '4'), (153, 51, 1, 1, 1, '5'), (154, 51, 1, 1, 1, '6'), (155, 52, 1, 1, 1, '4'), (156, 52, 1, 1, 1, '5'), (157, 52, 1, 1, 1, '6'), (158, 53, 1, 1, 1, '4'), (159, 53, 1, 1, 1, '5'), (160, 53, 1, 1, 1, '6'), (161, 54, 1, 1, 1, '4'), (162, 54, 1, 1, 1, '5'), (163, 54, 1, 1, 1, '6'), (164, 55, 1, 1, 1, '4'), (165, 55, 1, 1, 1, '5'), (166, 55, 1, 1, 1, '6'), (167, 56, 1, 1, 1, '4'), (168, 56, 1, 1, 1, '5'), (169, 56, 1, 1, 1, '6'), (170, 57, 1, 1, 1, '4'), (171, 57, 1, 1, 1, '5'), (172, 57, 1, 1, 1, '6'), (173, 58, 1, 1, 1, '4'), (174, 58, 1, 1, 1, '5'), (175, 58, 1, 1, 1, '6'), (176, 59, 1, 1, 1, '4'), (177, 59, 1, 1, 1, '5'), (178, 59, 1, 1, 1, '6'), (185, 61, 1, 1, 1, '4'), (186, 61, 1, 1, 1, '5'), (187, 61, 1, 1, 1, '6'), (188, 62, 2, 2, 1, '1'), (189, 62, 2, 2, 1, '2'), (190, 63, 1, 1, 1, '4'), (191, 63, 1, 1, 1, '5'), (192, 63, 1, 1, 1, '6'), (193, 64, 1, 1, 1, '4'), (194, 64, 1, 1, 1, '5'), (195, 64, 1, 1, 1, '6'), (196, 65, 1, 1, 1, '4'), (197, 65, 1, 1, 1, '5'), (198, 65, 1, 1, 1, '6'), (199, 66, 1, 1, 1, '4'), (200, 66, 1, 1, 1, '5'), (201, 66, 1, 1, 1, '6'), (202, 67, 1, 1, 1, '4'), (203, 67, 1, 1, 1, '5'), (204, 67, 1, 1, 1, '6'), (205, 68, 2, 2, 1, '1'), (206, 68, 2, 2, 1, '2'), (207, 69, 2, 2, 1, '1'), (208, 69, 2, 2, 1, '2'), (209, 70, 1, 1, 1, '4'), (210, 70, 1, 1, 1, '5'), (211, 70, 1, 1, 1, '6'), (213, 72, 1, 1, 1, '4'), (214, 72, 1, 1, 1, '5'), (215, 72, 1, 1, 1, '6'), (216, 73, 1, 1, 1, '4'), (217, 73, 1, 1, 1, '5'), (218, 73, 1, 1, 1, '6'), (226, 75, 1, 1, 1, '4'), (227, 75, 1, 1, 1, '5'), (228, 75, 1, 1, 1, '6'), (229, 76, 1, 1, 1, '4'), (230, 76, 1, 1, 1, '5'), (231, 76, 1, 1, 1, '6'), (232, 77, 1, 1, 1, '4'), (233, 77, 1, 1, 1, '5'), (234, 77, 1, 1, 1, '6'), (235, 78, 1, 1, 1, '4'), (236, 78, 1, 1, 1, '5'), (237, 78, 1, 1, 1, '6'), (238, 79, 1, 1, 1, '7'), (239, 79, 1, 1, 1, '8'), (240, 79, 1, 1, 1, '9'), (241, 80, 1, 1, 1, '4'), (242, 80, 1, 1, 1, '5'), (243, 80, 1, 1, 1, '6'), (244, 81, 1, 1, 1, '4'), (245, 81, 1, 1, 1, '5'), (246, 81, 1, 1, 1, '6'), (250, 83, 1, 1, 1, '4'), (251, 83, 1, 1, 1, '5'), (252, 83, 1, 1, 1, '6'), (253, 84, 1, 1, 1, '4'), (254, 84, 1, 1, 1, '5'), (255, 84, 1, 1, 1, '6'), (256, 85, 1, 1, 1, '4'), (257, 85, 1, 1, 1, '5'), (258, 85, 1, 1, 1, '6'), (259, 86, 1, 1, 1, '4'), (260, 86, 1, 1, 1, '5'), (261, 86, 1, 1, 1, '6'), (262, 87, 1, 1, 1, '7'), (263, 87, 1, 1, 1, '8'), (264, 87, 1, 1, 1, '9'), (265, 88, 1, 1, 1, '7'), (266, 88, 1, 1, 1, '8'), (267, 88, 1, 1, 1, '9'), (268, 89, 1, 1, 1, '7'), (269, 89, 1, 1, 1, '8'), (270, 89, 1, 1, 1, '9'), (271, 90, 1, 1, 1, '7'), (272, 90, 1, 1, 1, '8'), (273, 90, 1, 1, 1, '9'), (274, 91, 1, 1, 1, '4'), (275, 91, 1, 1, 1, '5'), (276, 91, 1, 1, 1, '6'), (277, 91, 1, 1, 1, '7'), (278, 92, 1, 1, 1, '7'), (279, 92, 1, 1, 1, '8'), (280, 92, 1, 1, 1, '9'), (281, 93, 1, 1, 1, '7'), (282, 93, 1, 1, 1, '8'), (283, 93, 1, 1, 1, '9'), (284, 94, 1, 1, 1, '7'), (285, 94, 1, 1, 1, '8'), (286, 94, 1, 1, 1, '9'), (287, 95, 1, 1, 1, '7'), (288, 95, 1, 1, 1, '8'), (289, 95, 1, 1, 1, '9'), (290, 96, 1, 1, 1, '7'), (291, 96, 1, 1, 1, '8'), (292, 96, 1, 1, 1, '9'), (293, 97, 1, 1, 1, '7'), (294, 97, 1, 1, 1, '8'), (295, 97, 1, 1, 1, '9'), (296, 98, 1, 1, 1, '7'), (297, 98, 1, 1, 1, '8'), (298, 98, 1, 1, 1, '9'), (299, 99, 1, 1, 1, '7'), (300, 99, 1, 1, 1, '8'), (301, 99, 1, 1, 1, '9'), (302, 100, 1, 1, 1, '7'), (303, 100, 1, 1, 1, '8'), (304, 100, 1, 1, 1, '9'), (305, 101, 1, 1, 1, '7'), (306, 101, 1, 1, 1, '8'), (307, 101, 1, 1, 1, '9'), (308, 102, 1, 1, 1, '4'), (309, 102, 1, 1, 1, '5'), (310, 102, 1, 1, 1, '6'), (311, 103, 1, 1, 1, '4'), (312, 103, 1, 1, 1, '5'), (313, 103, 1, 1, 1, '6'), (314, 103, 1, 1, 1, '7'), (315, 103, 1, 1, 1, '3'), (316, 104, 1, 1, 1, '4'), (317, 104, 1, 1, 1, '5'), (318, 104, 1, 1, 1, '6'), (319, 105, 1, 1, 1, '7'), (320, 105, 1, 1, 1, '8'), (321, 105, 1, 1, 1, '9'), (322, 106, 1, 1, 1, '7'), (323, 106, 1, 1, 1, '8'), (324, 106, 1, 1, 1, '9'), (325, 107, 1, 1, 1, '4'), (326, 107, 1, 1, 1, '5'), (327, 107, 1, 1, 1, '6'), (328, 108, 1, 1, 1, '4'), (329, 108, 1, 1, 1, '5'), (330, 108, 1, 1, 1, '6'), (331, 108, 1, 1, 1, '7'), (332, 109, 1, 1, 1, '7'), (333, 109, 1, 1, 1, '8'), (334, 109, 1, 1, 1, '9'), (335, 110, 1, 1, 1, '4'), (336, 110, 1, 1, 1, '5'), (337, 110, 1, 1, 1, '6'), (338, 110, 1, 1, 1, '7'), (339, 111, 1, 1, 1, '4'), (340, 111, 1, 1, 1, '5'), (341, 111, 1, 1, 1, '6'), (342, 111, 1, 1, 1, '7'), (343, 112, 1, 1, 1, '4'), (344, 112, 1, 1, 1, '5'), (345, 112, 1, 1, 1, '6'), (346, 112, 1, 1, 1, '7'), (347, 113, 1, 1, 1, '7'), (348, 113, 1, 1, 1, '8'), (349, 113, 1, 1, 1, '9'), (350, 114, 1, 1, 1, '4'), (351, 114, 1, 1, 1, '5'), (352, 114, 1, 1, 1, '6'), (353, 114, 1, 1, 1, '7'), (354, 114, 1, 1, 1, '3'), (355, 115, 1, 1, 1, '4'), (356, 115, 1, 1, 1, '5'), (357, 115, 1, 1, 1, '6'), (358, 116, 2, 2, 1, '1'), (359, 116, 2, 2, 1, '2'), (360, 117, 2, 2, 1, '1'), (361, 117, 2, 2, 1, '2'), (362, 118, 1, 1, 1, '4'), (363, 118, 1, 1, 1, '5'), (364, 118, 1, 1, 1, '6'), (365, 119, 1, 1, 1, '4'), (366, 119, 1, 1, 1, '5'), (367, 119, 1, 1, 1, '6'), (368, 120, 1, 1, 1, '4'), (369, 120, 1, 1, 1, '5'), (370, 120, 1, 1, 1, '6'), (371, 121, 1, 1, 1, '7'), (372, 121, 1, 1, 1, '8'), (373, 121, 1, 1, 1, '9'), (374, 122, 1, 1, 1, '4'), (375, 122, 1, 1, 1, '5'), (376, 122, 1, 1, 1, '6'), (377, 122, 1, 1, 1, '7'), (378, 123, 1, 1, 1, '3'), (379, 124, 1, 1, 1, '4'), (380, 124, 1, 1, 1, '5'), (381, 124, 1, 1, 1, '6'), (382, 124, 1, 1, 1, '7'), (383, 125, 1, 1, 1, '4'), (384, 125, 1, 1, 1, '5'), (385, 125, 1, 1, 1, '6'), (386, 125, 1, 1, 1, '7'), (387, 125, 1, 1, 1, '3'), (388, 126, 1, 1, 1, '4'), (389, 126, 1, 1, 1, '5'), (390, 126, 1, 1, 1, '6'), (391, 126, 1, 1, 1, '7'), (392, 127, 1, 1, 1, '7'), (393, 127, 1, 1, 1, '8'), (394, 127, 1, 1, 1, '9'), (395, 128, 1, 1, 1, '4'), (396, 128, 1, 1, 1, '5'), (397, 128, 1, 1, 1, '6'), (398, 128, 1, 1, 1, '7'), (399, 129, 1, 1, 1, '4'), (400, 129, 1, 1, 1, '5'), (401, 129, 1, 1, 1, '6'), (402, 130, 1, 1, 1, '4'), (403, 130, 1, 1, 1, '5'), (404, 130, 1, 1, 1, '6'), (405, 131, 1, 1, 1, '4'), (406, 131, 1, 1, 1, '5'), (407, 131, 1, 1, 1, '6'), (408, 132, 1, 1, 1, '7'), (409, 132, 1, 1, 1, '8'), (410, 132, 1, 1, 1, '9'), (411, 133, 1, 1, 1, '7'), (412, 133, 1, 1, 1, '8'), (413, 133, 1, 1, 1, '9'), (414, 134, 1, 1, 1, '4'), (415, 134, 1, 1, 1, '5'), (416, 134, 1, 1, 1, '6'), (417, 135, 1, 1, 1, '4'), (418, 135, 1, 1, 1, '5'), (419, 135, 1, 1, 1, '6'), (420, 136, 1, 1, 1, '4'), (421, 136, 1, 1, 1, '5'), (422, 136, 1, 1, 1, '6'), (423, 137, 2, 2, 1, '1'), (424, 137, 2, 2, 1, '2'), (425, 138, 2, 2, 1, '1'), (426, 138, 2, 2, 1, '2'), (427, 139, 1, 1, 1, '4'), (428, 139, 1, 1, 1, '5'), (429, 139, 1, 1, 1, '6'), (430, 140, 1, 1, 1, '7'), (431, 140, 1, 1, 1, '8'), (432, 140, 1, 1, 1, '9'), (433, 141, 1, 1, 1, '7'), (434, 141, 1, 1, 1, '8'), (435, 141, 1, 1, 1, '9'), (436, 142, 1, 1, 1, '7'), (437, 142, 1, 1, 1, '8'), (438, 142, 1, 1, 1, '9'), (439, 143, 1, 1, 1, '7'), (440, 143, 1, 1, 1, '8'), (441, 143, 1, 1, 1, '9'), (442, 144, 1, 1, 1, '4'), (443, 144, 1, 1, 1, '5'), (444, 144, 1, 1, 1, '6'), (445, 145, 1, 1, 1, '4'), (446, 145, 1, 1, 1, '5'), (447, 145, 1, 1, 1, '6'), (448, 145, 1, 1, 1, '7'), (449, 145, 1, 1, 1, '8'), (450, 145, 1, 1, 1, '9'), (451, 146, 1, 1, 1, '4'), (452, 146, 1, 1, 1, '5'), (453, 146, 1, 1, 1, '6'), (454, 147, 1, 1, 1, '7'), (455, 147, 1, 1, 1, '8'), (456, 147, 1, 1, 1, '9'), (457, 148, 1, 1, 1, '4'), (458, 148, 1, 1, 1, '5'), (459, 148, 1, 1, 1, '6'), (460, 148, 1, 1, 1, '7'), (461, 148, 1, 1, 1, '8'), (462, 148, 1, 1, 1, '9'), (463, 149, 1, 1, 1, '7'), (464, 149, 1, 1, 1, '8'), (465, 149, 1, 1, 1, '9'), (466, 150, 1, 1, 1, '7'), (467, 150, 1, 1, 1, '8'), (468, 150, 1, 1, 1, '9'), (469, 151, 1, 1, 1, '3'), (470, 151, 1, 1, 1, '4'), (471, 151, 1, 1, 1, '5'), (472, 151, 1, 1, 1, '6'), (473, 151, 1, 1, 1, '7'), (474, 151, 1, 1, 1, '8'), (475, 151, 1, 1, 1, '9'), (476, 153, 1, 1, 1, '3'), (477, 154, 1, 1, 1, '4'), (478, 154, 1, 1, 1, '5'), (479, 154, 1, 1, 1, '6'), (480, 154, 1, 1, 1, '7'), (481, 154, 1, 1, 1, '8'), (482, 154, 1, 1, 1, '9'), (483, 157, 1, 1, 1, '7'), (484, 157, 1, 1, 1, '8'), (485, 157, 1, 1, 1, '9'), (486, 158, 1, 1, 1, '4'), (487, 158, 1, 1, 1, '5'), (488, 158, 1, 1, 1, '6'), (489, 159, 1, 1, 1, '4'), (490, 159, 1, 1, 1, '5'), (491, 159, 1, 1, 1, '6'), (492, 160, 2, 2, 1, '1'), (493, 161, 1, 1, 1, '4'), (494, 161, 1, 1, 1, '5'), (495, 161, 1, 1, 1, '6'), (496, 162, 1, 1, 1, '7'), (497, 162, 1, 1, 1, '8'), (498, 162, 1, 1, 1, '9'), (499, 163, 1, 1, 1, '4'), (500, 163, 1, 1, 1, '5'), (501, 163, 1, 1, 1, '6'), (502, 164, 1, 1, 1, '3'), (503, 165, 1, 1, 1, '7'), (504, 165, 1, 1, 1, '8'), (505, 165, 1, 1, 1, '9'), (506, 166, 1, 1, 1, '3'), (507, 168, 1, 1, 1, '4'), (508, 168, 1, 1, 1, '5'), (509, 168, 1, 1, 1, '6'), (510, 168, 1, 1, 1, '7'), (511, 168, 1, 1, 1, '8'), (512, 168, 1, 1, 1, '9'), (513, 169, 1, 1, 1, '3'), (514, 170, 1, 1, 1, '3'), (515, 171, 1, 1, 1, '3'), (516, 172, 1, 1, 1, '3'), (517, 262, 1, 1, 1, '3'), (518, 216, 1, 1, 1, '9'), (519, 216, 1, 1, 1, '7'), (520, 216, 1, 1, 1, '8'), (521, 247, 1, 1, 1, '4'), (522, 247, 0, 0, 0, ''), (523, 265, 1, 1, 1, '7'), (524, 267, 1, 1, 1, '5'), (525, 267, 1, 1, 1, '4'), (526, 267, 1, 1, 1, '6'), (527, 267, 1, 1, 1, '9'), (528, 267, 1, 1, 1, '7'), (529, 249, 1, 1, 1, '4'), (530, 259, 0, 0, 0, ''), (531, 176, 1, 1, 1, '3'), (532, 273, 2, 2, 1, '1'), (533, 273, 1, 1, 1, '3'), (534, 219, 1, 1, 1, '7'), (535, 219, 1, 1, 1, '9'), (536, 219, 0, 0, 0, ''), (537, 223, 1, 1, 1, '9'), (538, 223, 1, 1, 1, '7'), (539, 243, 1, 1, 1, '3'), (540, 251, 1, 1, 1, '4'), (541, 261, 1, 1, 1, '7'), (542, 261, 1, 1, 1, '8'), (543, 240, 1, 1, 1, '4'), (544, 209, 1, 1, 1, '3'), (545, 182, 1, 1, 1, '3'), (546, 218, 1, 1, 1, '5'), (547, 218, 1, 1, 1, '4'), (548, 218, 1, 1, 1, '6'), (549, 192, 1, 1, 1, '3'), (550, 199, 1, 1, 1, '3'), (551, 210, 1, 1, 1, '3'), (552, 155, 1, 1, 1, '3'), (553, 71, 2, 2, 1, '1'), (554, 208, 1, 1, 1, '4'), (555, 208, 1, 1, 1, '3'), (556, 250, 1, 1, 1, '3'), (557, 224, 1, 1, 1, '7'), (558, 186, 1, 1, 1, '7'), (559, 248, 1, 1, 1, '5'), (560, 248, 1, 1, 1, '4'), (561, 248, 1, 1, 1, '6'), (562, 266, 1, 1, 1, '5'), (563, 200, 1, 1, 1, '3'), (564, 198, 1, 1, 1, '4'), (565, 198, 1, 1, 1, '5'), (566, 232, 1, 1, 1, '7'), (567, 232, 1, 1, 1, '4'), (568, 238, 1, 1, 1, '4'), (569, 238, 1, 1, 1, '5'), (570, 238, 1, 1, 1, '7'), (571, 257, 1, 1, 1, '3'), (572, 257, 1, 1, 1, '7'), (573, 257, 1, 1, 1, '8'), (574, 175, 1, 1, 1, '3'), (575, 183, 1, 1, 1, '7'), (576, 184, 1, 1, 1, '9'), (577, 167, 1, 1, 1, '3'), (578, 221, 1, 1, 1, '7'), (579, 206, 1, 1, 1, '4'), (580, 206, 1, 1, 1, '5'), (581, 206, 1, 1, 1, '3'), (582, 206, 1, 1, 1, '7'), (583, 206, 1, 1, 1, '9'), (585, 190, 1, 1, 1, '3'), (586, 235, 1, 1, 1, '3'), (587, 235, 1, 1, 1, '7'), (588, 235, 1, 1, 1, '9'), (589, 207, 1, 1, 1, '4'), (590, 197, 1, 1, 1, '4'), (591, 263, 1, 1, 1, '7'), (592, 263, 1, 1, 1, '9'), (593, 244, 1, 1, 1, '7'), (594, 244, 1, 1, 1, '9'), (595, 264, 1, 1, 1, '9'), (596, 264, 1, 1, 1, '7'), (597, 211, 2, 2, 1, '2'), (598, 268, 2, 2, 1, '2'), (599, 212, 2, 2, 1, '2'), (600, 272, 2, 2, 1, '2'), (601, 196, 1, 1, 1, '3'), (602, 174, 1, 1, 1, '3'), (603, 246, 1, 1, 1, '4'), (604, 246, 1, 1, 1, '5'), (605, 246, 1, 1, 1, '6'), (606, 179, 1, 1, 1, '4'), (607, 179, 1, 1, 1, '5'), (608, 179, 0, 0, 0, ''), (609, 203, 1, 1, 1, '7'), (610, 203, 1, 1, 1, '9'), (611, 204, 1, 1, 1, '4'), (612, 204, 1, 1, 1, '5'), (613, 204, 1, 1, 1, '6'), (614, 213, 2, 2, 1, '2'), (615, 177, 1, 1, 1, '4'), (616, 177, 1, 1, 1, '5'), (617, 177, 1, 1, 1, '6'), (618, 214, 2, 2, 1, '2'), (619, 228, 1, 1, 1, '4'), (620, 228, 1, 1, 1, '5'), (621, 228, 1, 1, 1, '6'), (622, 252, 1, 1, 1, '4'), (623, 201, 1, 1, 1, '3'), (624, 234, 1, 1, 1, '7'), (625, 234, 1, 1, 1, '3'), (626, 234, 1, 1, 1, '4'), (627, 234, 1, 1, 1, '9'), (628, 220, 1, 1, 1, '7'), (629, 220, 1, 1, 1, '9'), (630, 189, 1, 1, 1, '3'), (631, 189, 1, 1, 1, '7'), (632, 189, 1, 1, 1, '9'), (633, 189, 1, 1, 1, '8'), (634, 189, 1, 1, 1, ''), (635, 254, 1, 1, 1, '4'), (636, 178, 1, 1, 1, '4'), (637, 178, 1, 1, 1, '5'), (638, 178, 1, 1, 1, '6'), (639, 202, 1, 1, 1, '4'), (640, 202, 1, 1, 1, '5'), (641, 202, 1, 1, 1, '5'), (642, 188, 1, 1, 1, '9'), (643, 188, 1, 1, 1, '4'), (644, 188, 1, 1, 1, '7'), (645, 188, 1, 1, 1, '5'), (646, 188, 1, 1, 1, '6'), (647, 231, 1, 1, 1, '7'), (648, 231, 1, 1, 1, '9'), (649, 191, 1, 1, 1, '3'), (650, 258, 1, 1, 1, '3'), (652, 173, 1, 1, 1, '3'), (654, 253, 1, 1, 1, '4'), (655, 253, 1, 1, 1, '5'), (656, 253, 1, 1, 1, '6'), (657, 222, 1, 1, 1, '7'), (658, 222, 1, 1, 1, '9'), (659, 222, 1, 1, 1, '5'), (660, 222, 1, 1, 1, '4'), (661, 222, 1, 1, 1, '6'), (662, 194, 1, 1, 1, '3'), (663, 260, 1, 1, 1, '3'), (664, 229, 1, 1, 1, '4'), (665, 229, 1, 1, 1, '5'), (666, 229, 1, 1, 1, '6'), (667, 255, 1, 1, 1, '3'), (668, 193, 1, 1, 1, '3'), (669, 230, 1, 1, 1, '4'), (670, 230, 1, 1, 1, '5'), (671, 205, 1, 1, 1, '4'), (672, 205, 1, 1, 1, '5'), (673, 205, 1, 1, 1, '6'), (674, 152, 1, 1, 1, '4'), (675, 152, 1, 1, 1, '5'), (676, 152, 1, 1, 1, '6'), (677, 242, 1, 1, 1, '4'), (678, 242, 1, 1, 1, '7'), (679, 226, 1, 1, 1, '4'), (680, 226, 1, 1, 1, '5'), (681, 226, 1, 1, 1, '6'), (682, 156, 1, 1, 1, '3'), (683, 227, 1, 1, 1, '4'), (684, 227, 1, 1, 1, '7'), (685, 227, 1, 1, 1, '5'), (686, 237, 1, 1, 1, '4'), (687, 181, 1, 1, 1, '4'), (688, 181, 1, 1, 1, '5'), (689, 236, 1, 1, 1, '4'), (690, 185, 2, 2, 1, '1'), (691, 271, 1, 1, 1, '9'), (692, 271, 1, 1, 1, '9'), (693, 271, 1, 1, 1, '5'), (694, 180, 1, 1, 1, '7'), (695, 180, 1, 1, 1, '9'), (696, 180, 1, 1, 1, '4'), (697, 180, 1, 1, 1, '5'), (698, 180, 1, 1, 1, '6'), (699, 187, 1, 1, 1, '7'), (700, 270, 1, 1, 1, '4'), (701, 270, 1, 1, 1, '5'), (702, 270, 1, 1, 1, '6'), (703, 215, 2, 2, 1, '2'), (704, 269, 1, 1, 1, '7'), (705, 269, 1, 1, 1, '9'), (706, 256, 1, 1, 1, '7'), (707, 217, 1, 1, 1, '3'), (708, 245, 1, 1, 1, '7'), (709, 195, 1, 1, 1, '3'), (710, 241, 1, 1, 1, '4'), (711, 241, 1, 1, 1, '5'), (712, 239, 1, 1, 1, '7'), (713, 233, 1, 1, 1, '7'), (714, 233, 1, 1, 1, '4'), (715, 274, 1, 1, 1, '3'), (716, 275, 1, 1, 1, '4'), (717, 275, 0, 0, 0, '3'), (718, 275, 0, 0, 0, '5'), (719, 275, 0, 0, 0, '7'), (720, 276, 1, 1, 1, '3'), (721, 277, 1, 1, 1, '9'), (722, 277, 1, 1, 1, '7'), (723, 278, 1, 1, 1, '4'), (724, 279, 2, 2, 1, '1'), (725, 280, 1, 1, 1, '5'), (726, 280, 1, 1, 1, '4'), (727, 280, 1, 1, 1, '7'), (728, 280, 1, 1, 1, '9'), (729, 281, 1, 1, 1, '4'), (730, 281, 1, 1, 1, '5'), (731, 282, 1, 1, 1, '4'), (732, 283, 1, 1, 1, '4'), (733, 284, 1, 1, 1, '4'), (734, 285, 1, 1, 1, '4'), (735, 285, 1, 1, 1, '5'), (736, 285, 1, 1, 1, '7'), (737, 285, 1, 1, 1, '9'), (738, 286, 1, 1, 1, '9'), (739, 286, 1, 1, 1, '4'), (740, 286, 1, 1, 1, '7'), (741, 287, 1, 1, 1, '9'), (742, 288, 1, 1, 1, '4'), (743, 289, 1, 1, 1, '9'), (744, 289, 1, 1, 1, '4'), (745, 289, 1, 1, 1, '5'), (746, 289, 1, 1, 1, '7'), (747, 290, 1, 1, 1, '4'), (748, 290, 1, 1, 1, '7'), (749, 290, 1, 1, 1, '5'), (750, 290, 1, 1, 1, '9'), (751, 291, 1, 1, 1, '9'), (752, 291, 1, 1, 1, '4'), (753, 291, 1, 1, 1, '5'), (754, 292, 1, 1, 1, '4'), (755, 293, 1, 1, 1, '3'), (756, 294, 1, 1, 1, '4'), (757, 294, 1, 1, 1, '7'), (758, 294, 1, 1, 1, '9'), (759, 295, 1, 1, 1, '7'), (760, 295, 1, 1, 1, '9'), (761, 295, 1, 1, 1, '4'), (762, 296, 0, 0, 0, '3'), (763, 297, 1, 1, 1, '4'), (764, 297, 1, 1, 1, '5'), (765, 297, 1, 1, 1, '9'), (766, 297, 1, 1, 1, '7'), (767, 298, 0, 0, 0, '4'), (768, 298, 1, 1, 1, '3'), (769, 298, 1, 1, 1, '5'), (770, 299, 1, 1, 1, '9'), (771, 299, 1, 1, 1, '7'), (772, 300, 1, 1, 1, '4'), (773, 300, 1, 1, 1, '5'), (774, 301, 1, 1, 1, '4'), (775, 301, 2, 2, 1, '1'), (776, 301, 1, 1, 1, '5'), (777, 302, 1, 1, 1, '4'), (778, 302, 1, 1, 1, '5'), (779, 303, 1, 1, 1, '4'), (780, 303, 1, 1, 1, '5'), (781, 304, 1, 1, 1, '9'), (782, 304, 1, 1, 1, '7'), (785, 306, 1, 1, 1, '7'), (786, 306, 1, 1, 1, '9'), (787, 306, 1, 1, 1, '8'), (788, 60, 1, 1, 1, '4'), (789, 60, 1, 1, 1, '5'), (790, 60, 1, 1, 1, '6'), (791, 60, 1, 1, 1, '7'), (792, 60, 1, 1, 1, '8'), (793, 60, 1, 1, 1, '9'), (794, 82, 1, 1, 1, '7'), (795, 82, 1, 1, 1, '8'), (796, 82, 1, 1, 1, '9'), (797, 305, 1, 1, 1, '9'), (798, 305, 1, 1, 1, '7'), (799, 74, 1, 1, 1, '4'), (800, 74, 1, 1, 1, '5'), (801, 74, 1, 1, 1, '6'), (802, 74, 1, 1, 1, '7'), (803, 74, 1, 1, 1, '8'), (804, 74, 1, 1, 1, '9'), (805, 74, 1, 1, 1, '3'), (806, 307, 2, 2, 1, '2'), (807, 307, 1, 1, 1, '4'), (808, 308, 1, 1, 1, '4'), (809, 308, 2, 2, 1, '1'), (810, 309, 1, 1, 1, '8'), (811, 309, 1, 1, 1, '7'), (812, 310, 1, 1, 1, '3'), (813, 312, 1, 1, 1, '6'), (814, 312, 1, 1, 1, '7'); -- -------------------------------------------------------- -- -- Table structure for table `spare_minimum_level` -- CREATE TABLE IF NOT EXISTS `spare_minimum_level` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_id` int(10) NOT NULL, `spare_name` varchar(100) NOT NULL, `spare_qty` int(10) NOT NULL, `min_qty` int(10) NOT NULL, `alert_on` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `spare_purchase_details` -- CREATE TABLE IF NOT EXISTS `spare_purchase_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `spare_id` int(50) NOT NULL, `purchase_qty` int(50) NOT NULL, `return_qty` int(50) NOT NULL, `purchase_date` varchar(50) NOT NULL, `purchase_price` int(50) NOT NULL, `invoice_no` varchar(50) NOT NULL, `reason` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=158 ; -- -- Dumping data for table `spare_purchase_details` -- INSERT INTO `spare_purchase_details` (`id`, `spare_id`, `purchase_qty`, `return_qty`, `purchase_date`, `purchase_price`, `invoice_no`, `reason`) VALUES (1, 117, 0, 1, '', 0, '', ''), (2, 117, 1, 0, '', 0, '', ''), (3, 117, 2, 0, '', 0, '', ''), (4, 117, 0, 1, '', 0, '', 'To SR'), (5, 274, 1, 0, '', 0, '', ''), (6, 275, 1, 0, '', 0, '', ''), (7, 241, 2, 0, '', 0, '', ''), (8, 241, 3, 0, '', 0, '', ''), (9, 241, 0, 2, '', 0, '', ''), (10, 148, 0, 1, '', 0, '', ''), (11, 148, 2, 0, '', 0, '', ''), (12, 111, 0, 1, '', 0, '', ''), (13, 111, 2, 0, '', 0, '', ''), (14, 112, 1, 0, '', 0, '', ''), (15, 112, 4, 0, '', 0, '', ''), (16, 0, 0, 0, '', 0, '', ''), (17, 112, 0, 2, '', 0, '', ''), (18, 277, 2, 0, '', 0, '', ''), (19, 40, 0, 3, '', 0, '', ''), (20, 40, 3, 0, '', 0, '', ''), (21, 0, 0, 0, '', 0, '', ''), (22, 279, 1, 0, '', 0, '', ''), (23, 278, 2, 0, '', 0, '', ''), (24, 280, 2, 0, '', 0, '', ''), (25, 161, 7, 0, '', 0, '', ''), (26, 161, 1, 0, '', 0, '', ''), (27, 281, 3, 0, '', 0, '', ''), (28, 282, 1, 0, '', 0, '', ''), (29, 283, 1, 0, '', 0, '', ''), (30, 284, 1, 0, '', 0, '', ''), (31, 163, 2, 0, '', 0, '', ''), (32, 163, 1, 0, '', 0, '', ''), (33, 285, 1, 0, '', 0, '', ''), (34, 286, 1, 0, '', 0, '', ''), (35, 270, 2, 0, '', 0, '', ''), (36, 276, 3, 0, '', 0, '', ''), (37, 287, 1, 0, '', 0, '', ''), (38, 32, 0, 2, '', 0, '', ''), (39, 32, 3, 0, '', 0, '', ''), (40, 288, 1, 0, '', 0, '', ''), (41, 51, 8, 0, '', 0, '', ''), (42, 289, 1, 0, '', 0, '', ''), (43, 289, 1, 0, '', 0, '', ''), (44, 115, 0, 1, '', 0, '', ''), (45, 115, 3, 0, '', 0, '', ''), (46, 290, 1, 0, '', 0, '', ''), (47, 63, 2, 0, '', 0, '', ''), (48, 63, 1, 0, '', 0, '', ''), (49, 3, 0, 1, '', 0, '', ''), (50, 3, 18, 0, '', 0, '', ''), (51, 70, 0, 1, '', 0, '', ''), (52, 70, 19, 0, '', 0, '', ''), (53, 52, 0, 6, '', 0, '', ''), (54, 52, 12, 0, '', 0, '', ''), (55, 291, 2, 0, '', 0, '', ''), (56, 292, 2, 0, '', 0, '', ''), (57, 177, 0, 1, '', 0, '', ''), (58, 177, 2, 0, '', 0, '', ''), (59, 246, 3, 0, '', 0, '', ''), (60, 31, 4, 0, '', 0, '', ''), (61, 293, 1, 0, '', 0, '', ''), (62, 44, 2, 0, '', 0, '', ''), (63, 153, 3, 0, '', 0, '', ''), (64, 108, 6, 0, '', 0, '', ''), (65, 74, 5, 0, '', 0, '', ''), (66, 294, 2, 0, '', 0, '', ''), (67, 295, 1, 0, '', 0, '', ''), (68, 57, 18, 0, '', 0, '', ''), (69, 206, 3, 0, '', 0, '', ''), (70, 39, 2, 0, '', 0, '', ''), (71, 112, 2, 0, '', 0, '', ''), (72, 296, 1, 0, '', 0, '', ''), (73, 297, 1, 0, '', 0, '', ''), (74, 35, 3, 0, '', 0, '', ''), (75, 72, 1, 0, '', 0, '', ''), (76, 299, 1, 0, '', 0, '', ''), (77, 198, 2, 0, '', 0, '', ''), (78, 262, 1, 0, '', 0, '', ''), (79, 248, 1, 0, '', 0, '', ''), (80, 68, 1, 0, '', 0, '', ''), (81, 156, 0, 0, '', 0, '', ''), (82, 273, 0, 0, '', 0, '', ''), (83, 300, 1, 0, '', 0, '', ''), (84, 218, 2, 0, '', 0, '', ''), (85, 11, 5, 0, '', 0, '', ''), (86, 24, 3, 0, '', 0, '', ''), (87, 23, 2, 0, '', 0, '', ''), (88, 301, 1, 0, '', 0, '', ''), (89, 63, 1, 0, '', 0, '', ''), (90, 219, 1, 0, '', 0, '', ''), (91, 156, 1, 0, '', 0, '', ''), (92, 216, 3, 0, '', 0, '', ''), (93, 247, 3, 0, '', 0, '', ''), (94, 303, 1, 0, '', 0, '', ''), (95, 285, 2, 0, '', 0, '', ''), (96, 285, 0, 1, '', 0, '', ''), (97, 50, 0, 4, '', 0, '', ''), (98, 50, 4, 0, '', 0, '', ''), (99, 6, 0, 10, '', 0, '', ''), (100, 6, 11, 0, '', 0, '', ''), (101, 246, 1, 0, '', 0, '', ''), (102, 246, 0, 3, '', 0, '', ''), (103, 6, 9, 0, '', 0, '', ''), (104, 50, 1, 0, '', 0, '', ''), (105, 63, 0, 2, '', 0, '', ''), (106, 241, 0, 1, '', 0, '', ''), (107, 163, 0, 1, '', 0, '', ''), (108, 222, 0, 1, '', 0, '', ''), (109, 106, 0, 1, '', 0, '', ''), (110, 106, 3, 0, '', 0, '', ''), (111, 304, 2, 0, '', 0, '', ''), (112, 268, 1, 0, '', 0, '', ''), (113, 268, 1, 0, '', 0, '', ''), (114, 43, 0, 1, '', 0, '', ''), (115, 43, 3, 0, '', 0, '', ''), (116, 236, 0, 1, '', 0, '', ''), (117, 236, 2, 0, '', 0, '', ''), (118, 175, 0, 1, '', 0, '', ''), (119, 175, 2, 0, '', 0, '', ''), (120, 174, 2, 0, '', 0, '', ''), (121, 262, 0, 0, '', 0, '', ''), (122, 262, 0, 1, '', 0, '', ''), (123, 289, 1, 0, '', 0, '', ''), (124, 289, 0, 2, '', 0, '', ''), (125, 305, 1, 0, '', 0, '', ''), (126, 306, 1, 0, '', 0, '', ''), (127, 246, 0, 0, '', 0, '', ''), (128, 246, 0, 1, '', 0, '', ''), (129, 247, 0, 1, '', 0, '', ''), (130, 250, 0, 1, '', 0, '', ''), (131, 250, 6, 0, '', 0, '', ''), (132, 41, 0, 1, '', 0, '', ''), (133, 41, 3, 0, '', 0, '', ''), (134, 177, 0, 1, '', 0, '', ''), (135, 276, 0, 1, '', 0, '', ''), (136, 153, 0, 1, '', 0, '', ''), (137, 271, 0, 5, '', 0, '', ''), (138, 271, 5, 0, '', 0, '', ''), (139, 49, 0, 1, '', 0, '', ''), (140, 49, 6, 0, '', 0, '', ''), (141, 19, 0, 1, '', 0, '', ''), (142, 19, 3, 0, '', 0, '', ''), (143, 206, 0, 1, '', 0, '', ''), (144, 206, 0, 1, '', 0, '', ''), (145, 246, 1, 0, '', 0, '', ''), (146, 276, 0, 1, '', 0, '', ''), (147, 305, 20, 0, '2017-12-29 17:00', 200, 'fdfd', 'fddgd'), (148, 60, 30, 0, '2017-12-29 17:00', 300, 'dfdsfs', 'sdfsdfs'), (149, 82, 40, 0, '2017-12-29 17:00', 400, 'sddsfds', 'dsfsfsdf'), (150, 307, 2, 0, '2018-02-09 10:00', 456, 'sfgfds', 'gdsfgdsgggg'), (151, 308, 7, 0, '2018-02-14 10:23', 14, 'dsgdsgsdgsd', 'gsdfgdsgdsgs'), (152, 308, 10, 0, '2018-02-14 12:00', 2323, 'dfgdg', 'dfgfggfgfd'), (153, 309, 10, 0, '2018-02-14 15:00', 1234, 'asdsdds', 'fdasfasfasfas'), (154, 310, 10, 0, '2018-02-14 16:00', 6565, 'gfdsgfsdg', 'gsdfgdsgsdgsgsd'), (155, 1, 2, 0, '', 0, '', ''), (156, 306, 5, 0, '2018-02-15 11:00', 23432, 'sdafdsafas', 'fsafasfasfasfasf'), (157, 3, 35, 0, '2018-02-15 10:52', 3453, 'srdgvfdgfsd', 'dsfgdsgsgds'); -- -------------------------------------------------------- -- -- Table structure for table `spare_to_engineers` -- CREATE TABLE IF NOT EXISTS `spare_to_engineers` ( `id` int(10) NOT NULL AUTO_INCREMENT, `emp_id` varchar(100) NOT NULL, `spare_id` int(10) NOT NULL, `qty_out` int(10) NOT NULL, `qty_in` int(10) NOT NULL, `engineer_date` varchar(100) NOT NULL, `req_id` int(255) NOT NULL, `cust_name` varchar(255) NOT NULL, `reason` varchar(500) NOT NULL, `spare_receipt` varchar(255) NOT NULL, `auto_cnt` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ; -- -- Dumping data for table `spare_to_engineers` -- INSERT INTO `spare_to_engineers` (`id`, `emp_id`, `spare_id`, `qty_out`, `qty_in`, `engineer_date`, `req_id`, `cust_name`, `reason`, `spare_receipt`, `auto_cnt`) VALUES (1, '00012', 114, 0, 0, '', 49, '00057', '', 'with_service', 0), (2, '00012', 189, 0, 0, '', 49, '00057', '', 'with_service', 0), (3, '00009', 63, 1, 0, '2017-06-30', 1, '00201', '', 'with_service', 0), (4, '00012', 114, 1, 0, '', 49, '00057', '', 'with_service', 0), (5, '00012', 189, 1, 0, '', 49, '00057', '', 'with_service', 0), (6, '00012', 114, 0, 1, '', 49, '00057', '', 'with_service', 0), (7, '00012', 189, 0, 0, '', 49, '00057', '', 'with_service', 0), (8, '00013', 236, 1, 0, '2017-08-08', 78, '00007', '', 'with_service', 0), (9, '00013', 111, 0, 0, '', 100, '00003', '', 'with_service', 0), (10, '00013', 236, 0, 0, '', 78, '00007', '', 'with_service', 0), (11, '00012', 114, 0, 0, '', 49, '00057', '', 'with_service', 0), (12, '00012', 189, 0, 0, '', 49, '00057', '', 'with_service', 0), (13, '13', 111, 0, 0, '', 100, '00003', '', 'with_service', 0), (14, '0', 274, 0, 0, '', 84, '00218', '', 'with_service', 0), (15, '0', 274, 0, 0, '', 84, '00218', '', 'with_service', 0), (16, '0', 274, 0, 0, '', 84, '00218', '', 'with_service', 0), (17, '0', 40, 0, 0, '', 54, '00201', '', 'with_service', 0), (18, '0', 262, 0, 0, '', 50, '00136', '', 'with_service', 0), (19, '0', 114, 0, 0, '', 49, '00057', '', 'with_service', 0), (20, '0', 189, 0, 0, '', 49, '00057', '', 'with_service', 0), (21, '0', 114, 0, 0, '', 49, '00057', '', 'with_service', 0), (22, '0', 189, 0, 0, '', 49, '00057', '', 'with_service', 0), (23, '1', 262, 1, 0, '2017-11-16', 253, '00140', '', 'with_service', 0), (24, '18', 74, 2, 0, '2018-02-08', 289, '00327', 'dffdhdfhdf', 'with_service', 0), (25, '18', 74, 2, 0, '2018-02-08', 289, '00327', 'dsfdsgfds', 'with_service', 0), (26, '18', 305, 2, 0, '2018-02-08', 289, '00327', 'ggsfdgdsgs', 'with_service', 0), (27, '18', 82, 2, 0, '2018-02-08', 289, '00327', 'dgsfdgsdfg', 'with_service', 0), (28, '18', 74, 2, 0, '2018-02-08', 289, '00327', 'dfgdsgds', 'with_service', 0), (29, '18', 305, 0, 0, '', 289, '00327', '', 'with_service', 0), (30, '18', 82, 0, 0, '', 289, '00327', '', 'with_service', 0), (31, '18', 74, 2, 0, '2018-02-08', 289, '00327', '', 'with_service', 0), (32, '18', 305, 2, 0, '2018-02-08', 289, '00327', '', 'with_service', 0), (33, '18', 82, 2, 0, '2018-02-08', 289, '00327', '', 'with_service', 0), (34, '18', 60, 3, 0, '2018-02-08', 289, '00327', '', 'with_service', 0), (35, '0', 307, 0, 0, '', 292, '00422', '', 'with_service', 0), (36, '0', 307, 0, 0, '', 292, '00422', '', 'with_service', 0), (37, '0', 307, 0, 0, '', 292, '00422', '', 'with_service', 0), (38, '0', 307, 0, 0, '', 292, '00422', '', 'with_service', 0), (39, '26', 307, 0, 0, '', 294, '00422', '', 'with_service', 0), (40, '26', 307, 1, 0, '2018-02-13', 294, '00422', 'sdgdsgdsgsgsd', 'with_service', 0), (41, '26', 307, 0, 0, '', 294, '00422', '', 'with_service', 0), (42, '26', 307, 0, 0, '', 294, '00422', '', 'with_service', 0), (43, '26', 307, 0, 0, '', 294, '00422', '', 'with_service', 0), (44, '26', 307, 0, 0, '', 294, '00422', '', 'with_service', 0), (45, '26', 307, 1, 0, '2018-02-13', 294, '00422', 'sretretewte', 'with_service', 0), (46, '27', 308, 2, 0, '2018-02-14', 295, '00423', 'llllllll', 'with_service', 0), (47, '27', 309, 2, 0, '2018-02-14', 297, '00423', 'dfgsdgsdgs', 'with_service', 0), (48, '26', 310, 2, 0, '2018-02-14', 298, '00423', 'sdafdasf', 'with_service', 0), (49, '26', 310, 0, 0, '', 298, '00423', '', 'with_service', 0), (50, '26', 310, 2, 0, '2018-02-14', 298, '00423', 'ertetrewtewte', 'with_service', 0); -- -------------------------------------------------------- -- -- Table structure for table `stamping_details` -- CREATE TABLE IF NOT EXISTS `stamping_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `req_id` varchar(10) NOT NULL, `year` int(20) NOT NULL, `quarter` varchar(10) NOT NULL, `kg` varchar(50) NOT NULL, `stamping_charge` int(50) NOT NULL, `agn_charge` int(50) NOT NULL, `penalty` int(50) NOT NULL, `conveyance` int(50) NOT NULL, `tot_charge` int(50) NOT NULL, `cmr_paid` int(10) NOT NULL, `payment_mode` varchar(100) NOT NULL, `pending_amt` int(10) NOT NULL, `stamping_received` varchar(250) NOT NULL, `created_on` varchar(50) NOT NULL, `updated_on` varchar(50) NOT NULL, `user_id` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `state` -- CREATE TABLE IF NOT EXISTS `state` ( `id` int(10) NOT NULL AUTO_INCREMENT, `state` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ; -- -- Dumping data for table `state` -- INSERT INTO `state` (`id`, `state`) VALUES (1, 'Andaman and Nicobar Islands'), (2, 'Andhra Pradesh'), (3, 'Arunachal Pradesh'), (4, 'Assam'), (5, 'Bihar'), (6, 'Chandigarh'), (7, 'Chhattisgarh'), (8, 'Dadra and Nagar Haveli'), (9, 'Daman and Diu'), (10, 'Delhi'), (11, 'Goa'), (12, 'Gujarat'), (13, 'Haryana'), (14, 'Himachal Pradesh'), (15, 'Jammu and Kashmir'), (16, 'Jharkhand'), (17, 'Karnataka'), (18, 'Kerala'), (19, 'Lakshadweep'), (20, 'Madhya Pradesh'), (21, 'Maharashtra'), (22, 'Manipur'), (23, 'Meghalaya'), (24, 'Mizoram'), (25, 'Nagaland'), (26, 'Odisha'), (27, 'Puducherry'), (28, 'Punjab'), (29, 'Rajasthan'), (30, 'Sikkim'), (31, 'Tamil Nadu'), (32, 'Telangana'), (33, 'Tripura'), (34, 'Uttar Pradesh'), (35, 'Uttarakhand'), (36, 'West Bengal'); -- -------------------------------------------------------- -- -- Table structure for table `status` -- CREATE TABLE IF NOT EXISTS `status` ( `id` int(10) NOT NULL AUTO_INCREMENT, `status` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; -- -- Dumping data for table `status` -- INSERT INTO `status` (`id`, `status`) VALUES (1, 'Quote Approved'), (2, 'QC'), (3, 'Call Completed'), (4, 'Delivered'), (5, 'Quote In Progress'), (6, 'Quote Review'), (7, 'Awaiting Approval'), (8, 'Quote Rejected'), (9, 'On Hold'), (10, 'Cancel'), (16, 'Job Done'); -- -------------------------------------------------------- -- -- Table structure for table `tax_details` -- CREATE TABLE IF NOT EXISTS `tax_details` ( `id` int(10) NOT NULL AUTO_INCREMENT, `tax_name` varchar(50) NOT NULL, `tax_percentage` float NOT NULL, `tax_default` tinyint(1) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `tax_details` -- INSERT INTO `tax_details` (`id`, `tax_name`, `tax_percentage`, `tax_default`, `status`) VALUES (1, 'SERVICE TAX', 0, 1, 0), (2, 'VAT', 0, 0, 1), (3, 'asasa', 33, 0, 0), (4, 'gfdgd', 5443, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `test` -- CREATE TABLE IF NOT EXISTS `test` ( `id` int(3) unsigned zerofill NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `user_name` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `user_type` varchar(100) NOT NULL, `emp_id` int(10) NOT NULL, `user_access` varchar(100) NOT NULL, `status` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=46 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `user_name`, `password`, `user_type`, `emp_id`, `user_access`, `status`) VALUES (1, 'Admin', 'admin', 'welcome', '1', 0, '', 0), (26, 'anil', 'anil', 'anil', '7', 1, 'stamping_user', 0), (27, 'amit', 'amit', 'amit', '7', 7, 'nonstamping_user', 0), (28, 'rahul', 'rahul', 'rahul', '7', 3, 'nonstamping_user', 0), (29, 'Anshul', 'an<PASSWORD>', '<PASSWORD>', '5', 4, 'nonstamping_user', 0), (30, 'jitendra', 'jitendra', 'jitendra', '7', 8, '', 0), (31, 'Test User', 'testuser', '1234', '7', 1, '', 0), (32, '<PASSWORD>', '<PASSWORD>', '<PASSWORD>', '7', 13, 'nonstamping_user', 0), (33, '<NAME>', 'arvind', 'arvind', '7', 9, 'nonstamping_user', 0), (34, 'Bhaskar', '<PASSWORD>', '<PASSWORD>', '7', 12, 'nonstamping_user', 0), (35, 'Sravan', 'sravan', 'sravan', '7', 14, 'nonstamping_user', 0), (36, 'Upendra', 'upendra', 'upendra', '7', 11, 'nonstamping_user', 0), (37, '<NAME>', 'kesva', 'kesva', '7', 15, 'nonstamping_user', 0), (38, 'J.suresh', 'suresh', 'suresh', '7', 16, 'nonstamping_user', 0), (39, 'Asutosh', 'asutosh', 'asutosh', '7', 5, 'nonstamping_user', 0), (40, 'vishal', 'vishal', 'vishal', '7', 6, 'nonstamping_user', 0), (41, '<NAME>', 'dashrath', 'dashrath', '5', 0, 'nonstamping_user', 0), (42, '<NAME>', 'uday', 'uday', '7', 10, 'nonstamping_user', 0), (43, 'TestEmployee', 'testlogin', 'testlogin123', '7', 18, '', 0), (44, 'spudhaya', '1sp', '1234', '7', 26, '', 0), (45, 'spram', 'spram', '1234', '7', 27, '', 0); -- -------------------------------------------------------- -- -- Table structure for table `zone_pincodes` -- CREATE TABLE IF NOT EXISTS `zone_pincodes` ( `id` int(10) NOT NULL AUTO_INCREMENT, `zone_code` int(10) NOT NULL, `area_name` varchar(100) NOT NULL, `pincode` int(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=297 ; -- -- Dumping data for table `zone_pincodes` -- INSERT INTO `zone_pincodes` (`id`, `zone_code`, `area_name`, `pincode`) VALUES (1, 1, 'Goregaon', 400062), (2, 1, 'Vidyavihar', 400070), (3, 1, 'Parel', 400012), (4, 1, '<NAME>', 400026), (5, 1, '<NAME>', 400004), (6, 1, '<NAME>', 400053), (7, 1, 'Chembur', 400094), (8, 1, 'Thane', 400604), (9, 1, '<NAME>', 400026), (10, 1, 'Andheri west', 400049), (11, 1, 'Dahisar', 400068), (12, 1, 'Ghatkopar', 400086), (13, 1, '<NAME>', 400069), (14, 1, 'Dadar', 400014), (15, 1, 'Kalyan', 421301), (16, 1, 'Gamdevi', 400007), (17, 1, 'Bandra', 400), (18, 1, 'Sanpada', 400705), (19, 2, '<NAME>', 226014), (20, 2, '<NAME>', 226016), (21, 2, '<NAME>', 248016), (22, 2, 'Lucknow', 206012), (23, 2, 'agra', 282002), (24, 2, 'Azamgarh', 276127), (25, 2, 'Meerut', 250004), (26, 2, '<NAME>', 226010), (27, 2, 'VARANASI', 221005), (28, 2, 'chowk', 226003), (29, 2, '<NAME> ', 226020), (30, 2, 'allhabad', 221001), (31, 2, ' <NAME>', 263129), (32, 2, 'gorakhpur', 233015), (33, 2, 'ALLHABAD', 211002), (34, 2, '<NAME>', 226021), (35, 2, '<NAME>', 226031), (36, 2, '<NAME>', 226020), (37, 2, 'allhabad', 211001), (38, 2, 'GORAKHPUR', 273013), (39, 2, ' ghaila ', 226020), (40, 2, 'BAREILLY', 243006), (41, 2, 'Jankipuram ', 226021), (42, 2, '<NAME>', 226010), (43, 2, '<NAME>', 226029), (44, 2, 'chowk ', 226003), (45, 2, ' noida ', 201303), (46, 2, '<NAME> ', 226010), (47, 2, 'kanpur', 208002), (48, 2, 'jhansi', 284001), (49, 2, 'LUCKNOW', 226012), (50, 2, 'LUCKNOW', 201303), (51, 2, 'LUCKNOW', 226003), (52, 2, 'Dehradun', 248001), (53, 2, 'Etawa', 206130), (54, 3, 'BHOPAL', 462030), (55, 3, 'BHOPAL', 462016), (56, 3, 'BHOPAL', 462024), (57, 3, 'BHOPAL', 462003), (58, 3, 'RAIPUR', 492001), (59, 3, 'BHILAI', 490001), (60, 3, 'JABALPUR', 482001), (61, 3, 'UJJAIN', 456010), (62, 3, 'INDORE', 452014), (63, 3, 'INDORE', 452001), (64, 3, 'INDORE', 452018), (65, 3, 'INDORE', 453555), (66, 3, 'INDORE', 452010), (67, 3, 'CHITRAKOOT', 210204), (68, 3, 'BHOPAL', 462001), (69, 3, 'JABALPUR', 482002), (70, 3, 'INDORE', 452008), (71, 3, 'INDORE', 452003), (72, 3, 'SATNA', 485005), (73, 3, 'GWALIOR', 474002), (74, 3, 'JABALPUR', 482003), (75, 3, 'UMARIYA', 484661), (76, 3, 'SHAHDOL', 484001), (77, 3, 'ANUPPUR', 484224), (78, 5, '<NAME>', 560013), (79, 5, 'BG rd', 560069), (80, 5, 'BG rd', 560076), (81, 5, 'Thippasandra', 560075), (82, 5, 'Yelahanka', 560064), (83, 5, 'MSRIT', 560054), (84, 5, '<NAME>', 560092), (85, 5, 'Lakkasandra', 560029), (86, 6, 'Patna', 801505), (87, 6, 'Motihari', 800014), (88, 6, 'Darbhanga', 846003), (89, 6, 'Patna', 800020), (90, 6, 'Patna', 800026), (91, 6, 'Ranchi', 834009), (92, 6, 'Patna', 800014), (93, 6, 'Purnea', 854301), (94, 6, 'Patna', 800013), (95, 8, 'Teynampet', 600035), (96, 8, '<NAME>', 600006), (97, 8, 'Nungambakkam', 600034), (98, 8, 'Vadapalani', 600026), (99, 8, 'Chetpet', 600031), (100, 8, 'Kilpauk', 600010), (101, 8, '<NAME>', 600040), (102, 8, 'Adyar', 600020), (103, 8, 'Perumbakkam', 600100), (104, 8, 'Nandanam', 600035), (105, 8, 'Perambur', 600023), (106, 8, '<NAME>', 600017), (107, 8, 'Westmambalam', 600033), (108, 9, 'Vellore', 632009), (109, 10, 'Chitoor', 517219), (110, 11, 'PANJAGUTTA', 500082), (111, 11, '<NAME>', 500033), (112, 11, '<NAME>', 500034), (113, 11, '<NAME>', 500029), (114, 11, 'MALAKPET', 500036), (115, 11, 'GACHIBOWLI', 500035), (116, 11, 'Hyderabad , <NAME>', 505417), (117, 11, 'TURAKAPALLI', 500078), (118, 11, 'CHADERGHAT', 500024), (119, 11, 'KARKANA', 500015), (120, 11, '<NAME>', 500001), (121, 11, 'VISAKHAPATNAM', 530005), (122, 11, '<NAME>', 500074), (123, 11, 'KACHIGUDA', 500072), (124, 11, 'MALKAJGIRI', 500015), (125, 11, 'KANCHANBAGH', 500258), (126, 11, 'NIZAMPET', 500072), (127, 11, 'SECUNDERABAD', 500015), (128, 11, '<NAME>', 530002), (129, 11, 'Rockdale Layout', 530002), (130, 11, 'SARINILGAMPALLY', 500019), (131, 11, 'Hyderguda', 500029), (132, 11, 'VIJAYAWADA', 522501), (133, 11, 'IDA,Pashamylaram', 502307), (134, 11, 'MIYAPUR', 500049), (135, 12, 'NEHRU PHARMA CITY (SEZ)', 531019), (136, 12, '<NAME>', 500033), (137, 12, 'GUNTUR', 522004), (138, 12, 'VIJAYAWADA', 520010), (139, 13, 'Kharghar', 410210), (140, 13, 'Vashi', 400703), (141, 14, 'Rajasthan', 305001), (142, 14, 'Rajasthan', 301001), (143, 14, 'Rajasthan', 344022), (144, 14, 'Rajasthan', 325205), (145, 14, 'Rajasthan', 327001), (146, 14, 'Rajasthan', 305901), (147, 14, 'Rajasthan', 321001), (148, 14, 'Rajasthan', 311001), (149, 14, 'Rajasthan', 334001), (150, 14, 'Rajasthan', 323001), (151, 14, 'Rajasthan', 331001), (152, 14, 'Rajasthan', 303303), (153, 14, 'Rajasthan', 328001), (154, 14, 'Rajasthan', 341303), (155, 14, 'Rajasthan', 314001), (156, 14, 'Rajasthan', 322201), (157, 14, 'Rajasthan', 335512), (158, 14, 'Rajasthan', 302001), (159, 14, 'Rajasthan', 326001), (160, 14, 'Rajasthan', 333001), (161, 14, 'Rajasthan', 342005), (162, 14, 'Rajasthan', 322230), (163, 14, 'Rajasthan', 305404), (164, 14, 'Rajasthan', 305801), (165, 14, 'Rajasthan', 324005), (166, 14, 'Rajasthan', 303108), (167, 14, 'Rajasthan', 341023), (168, 14, 'Rajasthan', 305601), (169, 14, 'Rajasthan', 313301), (170, 14, 'Rajasthan', 313324), (171, 14, 'Rajasthan', 303103), (172, 14, 'Rajasthan', 332001), (173, 14, 'Rajasthan', 307001), (174, 14, 'Rajasthan', 311507), (175, 14, 'Rajasthan', 304001), (176, 14, 'Rajasthan', 313001), (177, 15, 'Pune', 411003), (178, 15, 'Pune', 411016), (179, 15, 'Pune', 411001), (180, 15, 'Pune', 411019), (181, 15, 'Pune', 411004), (182, 15, 'Pune', 412115), (183, 15, 'Pune', 411014), (184, 15, 'Pune', 412108), (185, 15, 'Pune', 411033), (186, 15, 'Pune', 411040), (187, 15, 'Barshi', 413001), (188, 15, 'Solapur', 413002), (189, 15, 'Nashik', 422001), (190, 15, 'Pune', 422013), (191, 15, 'Nanded', 431601), (192, 15, 'Aurangabad', 431005), (193, 15, 'Pune', 413736), (194, 15, 'Aurangabad', 431210), (195, 15, 'Sangali', 416416), (196, 15, 'Ahamednagar', 414001), (197, 15, 'Kolhapur', 416001), (198, 15, 'Kolhapur', 416003), (199, 15, 'Kolhapur', 416008), (200, 15, 'Latur', 413512), (201, 15, 'Latur', 413531), (202, 15, 'Barshi', 413401), (203, 15, 'Goa', 403004), (204, 15, 'karad', 415539), (205, 15, 'Sangali', 416410), (206, 15, 'Pune', 411008), (207, 15, 'Nashik', 422005), (208, 15, 'Pune', 41102), (209, 15, 'Pune', 411041), (210, 15, 'Nagpur', 440003), (211, 15, 'Amaravati', 444601), (212, 5, 'yashwantpur', 560022), (213, 2, '<NAME>', 221010), (214, 2, '<NAME>', 226006), (215, 1, 'Aurangabad', 431005), (216, 1, 'TARDEO', 400007), (217, 15, 'Daund', 413801), (218, 3, 'SAGAR', 470001), (219, 3, 'BHOPAL', 462042), (220, 2, 'Meerut', 250002), (221, 2, 'SAHAHRANPUR ', 247001), (222, 2, 'SULTANPUR', 228001), (223, 2, 'Bareilly', 243001), (224, 2, 'allhabad', 211002), (225, 2, 'Allhabad', 211003), (226, 2, 'JAUNPUR', 222001), (227, 2, 'ALIGARH', 202001), (228, 2, 'GORAKHPUR', 273001), (229, 2, '<NAME>', 272001), (230, 2, 'GHAZIABAD', 201009), (231, 2, 'HAPUR', 245101), (232, 2, '<NAME>', 209101), (233, 2, '<NAME>', 208001), (234, 2, 'AGRA', 282001), (235, 2, '<NAME>', 221304), (236, 2, 'Mau', 275101), (237, 2, 'LUCKNOW', 226001), (238, 2, 'Gonda', 271001), (239, 2, 'FIROZABAD', 283203), (240, 2, 'MATHURA', 281001), (241, 2, 'Farrukhabad', 209605), (242, 2, 'Kaushambi', 212207), (243, 2, 'Fatehpur', 212601), (244, 2, 'PRATAPGARH', 230001), (245, 2, 'BANDA', 210001), (246, 2, 'BALLIA', 277001), (247, 2, 'AZAMGARH', 276001), (248, 2, 'SONBHADRA', 231216), (249, 2, 'VARANASI', 221002), (250, 2, 'DEORIA', 274001), (251, 2, 'MEERUT', 250004), (252, 2, 'BULANDSHAHAR', 203001), (253, 2, 'KANPUR', 208002), (254, 2, 'ETAWAH', 206001), (255, 2, 'BAHRAICH', 271801), (256, 2, '<NAME>', 206130), (257, 2, 'Varanasi', 221001), (258, 2, '<NAME>', 262701), (259, 2, 'AMROHA', 244221), (260, 2, 'RAMPUR', 244901), (261, 2, 'JHANSI', 284002), (262, 2, 'KUSHINAGAR', 276507), (263, 2, 'SAMBHAL', 244302), (264, 2, 'LUCKNOW', 226018), (265, 9, 'VELLORE', 632004), (266, 2, 'HAMIRPUR', 210301), (267, 2, 'MORADABAD', 244001), (268, 2, 'RAIBARLI', 229001), (269, 2, 'BIJNOR', 250001), (270, 2, 'LALITPUR', 284403), (271, 2, 'SAMLI', 247776), (272, 5, '<NAME>', 560052), (273, 4, 'BHILWARA', 311001), (274, 1, '<NAME>', 400051), (275, 1, 'Badlapur', 421503), (276, 1, 'mulund(w)', 400080), (277, 1, 'KOLHAPUR', 416012), (278, 1, '<NAME>', 416414), (279, 1, 'SANGLI', 416416), (280, 1, 'kolhapur', 416230), (281, 11, 'KUKATPALLY', 500072), (282, 5, 'bommasandra', 560099), (283, 17, 'TIRUPPUR', 641606), (284, 5, 'MANGALORE', 575004), (285, 3, 'gwalior', 474009), (286, 15, 'Karad', 415110), (287, 17, 'coimbatore', 641005), (288, 5, 'CHIKKASANDRA', 560090), (289, 14, 'udaipur', 313001), (290, 14, 'jodhpur', 342011), (291, 14, 'KOTA', 324001), (292, 13, 'BELAPUR', 400614), (293, 18, 'Avadi', 600025), (294, 18, 'vvvvv', 600025), (295, 18, 'Avadi', 600025), (296, 19, 'Adhichapuram', 614717); /*!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>/application/views/viewclaimpop.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <style> .divider{ border-bottom:1px solid #ccc; margin-bottom:10px; } .ft{ float:left; } .selectelement{ width:25%; margin-bottom:10px; } .inputelement{ width:25%; margin-bottom:10px; } .inputelement_second{ width:25%; float:right; position:relative; right:260px; } .fancybox-skin{ height:100% !important; } h3{ color: #6C217E; } </style> <h3>Warranty Mode Status</h3> <div class="divider"></div> <div class="col-md-12"> <form name="myForm" action="<?php echo base_url();?>service/updateclaim" method="POST" onsubmit="return validateForm()"> <div class="selectelement"> <?php foreach($list as $roww){?> <select name="status_warran" id="status_warran" class="form-control waran"> <option value="">Select Warranty Mode</option> <option value="credit"<?php if($roww->warranty_mode == 'credit') echo 'selected="selected"'; ?>>Credit</option> <option value="replacement"<?php if($roww->warranty_mode == 'replacement') echo 'selected="selected"'; ?>>Replacement</option> </select><?php } ?> <div id="errorBox111" style="color:red;"></div> </div> <input type="hidden" value="<?php echo $ide;?>" name="request_id"> <?php foreach($list as $row){ ?> <div style="width:75%"> <div class="inputelement ft"> <input type="text" name="code_no" class="firsttext form-control" placeholder="Credit Note Number" value="<?php if($row->code_no==''){ echo "";}else{echo $row->code_no;} ?>"> <div id="errorBox" style="color:red;"></div> </div> <div class="inputelement_second" id="rep"> <input type="text" name="date" class="firsttext form-control datepicker" placeholder="Date" value="<?php if($row->code_date==''){ echo "";}else{echo $row->code_date;} ?>"><div id="errorBox1" style="color:red;"></div> </div> </div><?php } ?> <div class="inputelement"> <input type="submit" class="btn btn-primary " value="Update" > </div> </form> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery-1.10.1.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <script> $(function(){ $(".firsttext").show(); if($(this).find("option:selected").attr("value")=="replacement"){ //alert("ashd"); $(".firsttext").hide(); } $("#status_warran").change(function(){ if($(this).find("option:selected").attr("value")=="credit"){ //alert("ashd"); $(".firsttext").show(); } else{ $(".firsttext").hide(); } }); $(".datepicker").datepicker({ dateFormat:'dd-mm-yy', changeMonth:true, changeYear:true }) }); </script> <script> function validateForm() { var status_warran = document.myForm.status_warran.value, code_no = document.myForm.code_no.value, code_date = document.myForm.date.value; if( status_warran == "" ) { document.myForm.status_warran.focus(); document.getElementById("errorBox111").innerHTML = "Select the warranty mode"; return false; } if(status_warran == "credit") { if(code_no==""){ document.myForm.code_no.focus(); document.getElementById("errorBox").innerHTML = "Enter the Code No."; return false; } if(code_date==""){ document.myForm.date.focus(); document.getElementById("errorBox1").innerHTML = "Enter the Code Date."; return false; } } } </script> <script> $(document).ready(function(){ $(".btn").click(function(event){ if($("waran").val()=="") { $(".waranerror").text("Please select Warranty Mode").show(); event.preventDefault(); } }); $("waran").change(function(){ if($(this).val()==""){ $(".waranerror").show(); } else{ $(".waranerror").fadeOut('slow'); } }); $("#cate").keyup(function(){ if($(this).val()==""){ $("#errorBox").show(); } else{ $("#errorBox").fadeOut('slow'); } }); $("#model").click(function(){ if($(this).val()==""){ $("#dpt_error1").show(); } else{ $("#dpt_error1").fadeOut('slow'); } }); }); </script> <file_sep>/application/models/Employee_model.php <?php class Employee_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_emp($data){ $this->db->insert('employee',$data); return $this->db->insert_id(); } public function add_city($data){ $this->db->insert('city',$data); return true; } public function checkemployeename($name) { $this->db->select('emp_name'); $this->db->from('employee'); $this->db->where_in('emp_name',$name); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function check_emp($id){ $this->db->select("*",FALSE); $this->db->from('employee'); $this->db->where('emp_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_zone_list(){ $this->db->select("*",FALSE); $this->db->from('service_location'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function product_list(){ $this->db->select("products.id As id, products.product_name As pname, products.model As model, products.description As description, products.addlinfo As addlinfo, prod_category.product_category As category, prod_subcategory.subcat_name As subcategory, brands.brand_name As brand_name",FALSE); $this->db->from('products'); $this->db->join('prod_category', 'products.category=prod_category.id'); $this->db->join('prod_subcategory', 'products.subcategory=prod_subcategory.id'); $this->db->join('brands', 'products.brand=brands.id'); $this->db->order_by('products.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_cat_list(){ $this->db->select("id,service_category",FALSE); $this->db->from('service_category'); $query = $this->db->get(); return $query->result(); } public function add_service($data){ $this->db->insert_batch('employee_service_skill',$data); return true; } public function employee_list(){ $this->db->select("employee.id,employee.emp_id,employee.emp_name,employee.emp_designation,employee.emp_mobile,employee.emp_email,employee.emp_city",FALSE); $this->db->from('employee'); $query = $this->db->get(); return $query->result(); } public function emp_cnt(){ $this->db->select("id",FALSE); $this->db->from('employee'); $this->db->order_by('id', 'desc'); $this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function state_list(){ $this->db->select("id,state",FALSE); $this->db->from('state'); $this->db->order_by('state', 'asc'); //$this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function get_cities($id){ $this->db->distinct(); $this->db->select("city",FALSE); $this->db->from('city'); $this->db->like('city', $id, 'after'); //$this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function getemployeebyid($id){ $this->db->select("id, emp_id, emp_name, emp_designation, emp_mobile, emp_email, emp_edu, emp_exp, doj, emp_addr, emp_addr1, emp_city, emp_state, emp_pincode, service_zone",FALSE); $this->db->from('employee'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getemployeeserviceskillbyid($id){ $this->db->select("id, empid, p_category, sub_category, p_model, service_category",FALSE); $this->db->from('employee_service_skill'); $this->db->where('empid', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_employee($data,$id){ $this->db->where('id',$id); $this->db->update('employee',$data); } public function delete_employee_service_skill($id){ $this->db->where('empid',$id); $this->db->delete('employee_service_skill'); } public function del_emp($id){ $this->db->where('id',$id); $this->db->delete('employee'); } public function mobile_validation($mobile) { $this->db->where('emp_mobile',$mobile); $this->db->from('employee'); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $numrow = $query->num_rows(); } }<file_sep>/application/models/Sparereport_model.php <?php class Sparereport_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function engnamelist(){ $this->db->select('*'); $this->db->from('employee'); $this->db->order_by('emp_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function sparenamelist() { $this->db->select('*'); $this->db->from('spares'); $this->db->order_by('spare_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sparereport($spare_name,$from_date,$to_date) { $query=$this->db->query("select sp.spare_name,sp.spare_qty,sp.purchase_price,sp.sales_price,sp.effective_date,sp.used_spare,emp.emp_name from spares as sp left join employee as emp on emp.id=emp.emp_id where sp.id='$spare_name' OR sp.effective_date BETWEEN '$from_date' AND '$to_date 23:59:59.993' "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } <file_sep>/application/views_bkMarch_0817/prod_cat_list.php <style> .ui-state-default { background: #fff !important; border: 3px solid #fff !important; color: #303f9f !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=text] { background-color: transparent; border: none; font-size: 12px; border-radius: 7; width: 55% !important; font-size: 1.5 rem; margin: 0 0 3px 0; padding: 5px; box-shadow: #ccc; /* -webkit-box-sizing: content-box; */ -moz-box-sizing: content-box; /* box-sizing: content-box; */ /* transition: all .3s; */ height: 12px; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 6px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} .ui-widget-header { border: 1px solid white; background: white; height: 35px; } .ui-state-default { color: #000; font-size: 13px !important; font-weight: bold; } .ui-state-default .ui-icon { float: right; } .ui-button { min-width: 1.5em; padding: 0.5em 1em; margin-left: 10px !important; text-align: center; background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%); } .dataTables_paginate{ float:right; } .dataTables_info{ float:left; } /* input, textarea, .uneditable-input { margin-left: 940px; margin-top: -68px; } */ .dataTables_length{ float: left; margin-left: -110px; } .dataTables_filter{ float:right; } label { display: block; margin-bottom: 34px; margin-left: 25px; } .dtable {display:none} .dtable_custom_controls {display:none;position: absolute;z-index: 50;margin-left: 5px;margin-top:1px} .dtable_custom_controls .dataTables_length {width:auto;float:none} .dataTables_filter input{ border:1px solid #ccc; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); cat_name = $("#prod_cat_name_"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Productcategory/update_prod_category', data: {'id' : id, 'category_name' : cat_name}, dataType: "text", cache:false, success: function(data){ alert("Product Category updated"); } }); }); } function InactiveStatus(id){ //alert("add"); // alert("add1"); $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Productcategory/update_status_prod_category', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Product Category made Inactive"); window.location = "<?php echo base_url(); ?>pages/prod_cat_list"; } }); } function activeStatus(id){ //$(function() // { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Productcategory/update_status_prod_category1', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Product Category made active"); window.location = "<?php echo base_url(); ?>pages/prod_cat_list"; } }); // }); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Product Category List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addcat.png" title="Add Product Category" style="width:24px;height:24px;">Add Product Category</button>--> <a href="<?php echo base_url();?>pages/add_prod_cat"> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Product Category" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> </a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="dtable table-bordered table-responsive display table" cellspacing="0" > <thead> <tr> <td style="text-align:center;font-size:13px;">Category Name</td> <td style="text-align:center;font-size:13px;">Action</td> </tr> </thead> <tbody> <?php foreach($list as $key){ ?> <tr> <td ><input type="text" value="<?php echo $key->product_category; ?>" class="" name="prod_cat_name" id="prod_cat_name_<?php echo $key->id; ?>" readonly></td> <td class="options-width" style="text-align:center;"> <a href="<?php echo base_url(); ?>Productcategory/update_prod_category/<?php echo $key->id; ?>" style="padding-right:10px;"><i class="fa fa-floppy-o fa-2x"></i></a> <?php if($key->status!='1') { ?> <a onclick="InactiveStatus('<?php echo $key->id; ?>')" >InActive</a><?php } ?><?php if($key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $key->id; ?>')" >Active</a><?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { /* * Find and assign actions to filters */ $.fn.dataTableExt.afnFiltering = new Array(); var oControls = $('.dtable').prevAll('.dtable_custom_controls:first').find(':input[name]'); oControls.each(function() { var oControl = $(this); //Add custom filters $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { if ( !oControl.val() || !oControl.hasClass('dtable_filter') ) return true; for ( i=0; i<aData.length; i++ ) if ( aData[i].indexOf(oControl.val()) != -1 ) return true; return false; }); }); options = { "sDom" : 'R<"H"lfr>t<"F"ip<', "bProcessing" : true, "bJQueryUI" : true, "bStateSave" : false, "iDisplayLength" : 8, "aLengthMenu" : [[8, 25, 50, -1], [8, 25, 50, "All"]], "sPaginationType" : "full_numbers", "aoColumnDefs": [{ 'bSortable': true, 'aTargets': [ 0,7,9 ] }], // "ordering": false, //"ordering": [[ 2, "false" ]], "aoColumnDefs": [ { 'bSortable': true, 'aTargets': [ 0 ] } ], "aaSorting" : [[ 0, "asc" ]], "fnDrawCallback" : function(){ //Without the CSS call, the table occasionally appears a little too wide $(this).show().css('width', '100%'); //Don't show the filters until the table is showing $(this).closest('.dataTables_wrapper').prevAll('.dtable_custom_controls').show(); }, /*"fnStateSaveParams": function ( oSettings, sValue ) { //Save custom filters oControls.each(function() { if ( $(this).attr('name') ) sValue[ $(this).attr('name') ] = $(this).val().replace('"', '"'); }); return sValue; },*/ "fnStateLoadParams" : function ( oSettings, oData ) { //Load custom filters oControls.each(function() { var oControl = $(this); $.each(oData, function(index, value) { if ( index == oControl.attr('name') ) oControl.val( value ); }); }); return true; } }; var oTable = $('.dtable').dataTable(options); //var table = $('#example').dataTable(); // Perform a filter oTable.fnSort( [ [0,'desc'] ] ); //oTable.fnSort( [ [0,'desc'] ] ); /* * Trigger the filters when the user interacts with them */ oControls.each(function() { $(this).change(function() { //Redraw to apply filters oTable.fnDraw(); }); }); oTable.fnFilter(''); // oTable.fnFilter(''); // Remove all filtering oTable.fnFilterClear(); }); </script> </body> </html><file_sep>/application/views/serailreport_data.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url() ?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('export', 'W3C Example Table')"> <img src="<?php echo base_url() ?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <?php $h=0; $count=0; ?> <style> table.display { margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } thead { border-bottom: 1px solid #d0d0d0; border: 1px solid #522276; color: #522276; } table.display th, td { padding: 10px; border: 1px solid #522276; } a { color: #712276 !important; } table{ width:98%; margin-left:15px; } </style> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <div class="col-md-4"> <h2>Serialwise Report</h2> </div> <table id="export" class="responsive-table display" cellspacing="0" > <thead> <tr> <th>S.NO</th> <th>Request ID</th> <th>Request Date</th> <th>Purchase Date</th> <th>Model Name</th> <th>Customer Name</th> <th class="hidden">problem</th> <th class="hidden">solution</th> </tr> </thead> <tbody> <?php if(!empty($list)) { $k=1; foreach($list as $row) { $requ = $row->ser; $ser_req = explode(',',$requ); $r = count($ser_req); //echo $r; $sd = $row->problem; $m1 = $row->model; $b = $row->brand_name; $c = $row->customer_name; if($m1 && $b && $c!='') { ?> <tr> <td colspan="5" style="text-align:center"><b>Serial No: <?php echo $row->serial_no;?></b></td> <td></td> </tr> <?php for($i=0;$i<count($ser_req);$i++) { $r1 = explode('//',$ser_req[$i]); ?> <td><?php echo $k;?></td> <td><a id="<?php echo $r1[0];?>" href='#'><?php echo $r1[0];?></a></td> <td><?php if($r1[1]!=""){echo $r1[1];}else{"";}?></td> <td><?php echo $row->purchase_date;?></td> <td><?php echo $row->model;?></td> <td><?php echo $row->customer_name;?></td> <td class="hidden"><?php echo $row->prob_category;?></td> <td class="hidden"><?php echo $row->cs;?></td> </tr> <script> var $= jQuery.noConflict(); $(document).ready(function() { $("#<?php echo $r1[0];?>").click(function() { $.fancybox.open({ href : '<?php echo base_url(); ?>Report/get_serialByStatus/<?php echo $r1[0];?>', type : 'iframe', padding : 5 }); }); }); </script> <?php $k++; } } } } else {?> <tr><td colspan="6"> <?php echo "<h4 align='center'>No Data Available</h4>"; ?></td></tr> <?php } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script> var $= jQuery.noConflict(); </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <file_sep>/application/views_bkMarch_0817/addrow.php <?php $count=$_POST['countid']; ?> <tr> <td style="width: 25.2%;"><input type="text" value="" name="brand_name[]" id="brand-<?php echo $count;?>" class="brandsss"><div id="lname<?php echo $count;?>"></div><div id="dpt_error1<?php echo $count;?>" style="color: #ff0000;position: relative; top: 0px;left: 0px;"></div> </td><td><a class="delRowBtn btn btn-primary fa fa-trash"></a> </tr> <script type="text/javascript"> $(document).ready(function() { $(".category").change(function(){ //alert("ffff"); var catid=$(this).closest(this).attr('id'); var id=$(this).val(); //alert("catttt: "+catid); //alert("iddddd: "+id); var dataString = 'id='+ id; $('#sub'+catid+ "> option").remove(); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Brand/getsub_category", data: dataString, cache: false, success: function(data) { $('#sub'+catid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#sub'+catid).append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script> <script> $(document).ready(function(){ $(document).on("keyup","#brand-<?php echo $count;?>", function(){ var a=$(this).attr('id').split('-').pop(); var brand = $(this).val(); if(brand) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Brand/brand_validation', data: { brand:brand, }, success: function (data) { if(data == 0){ $('#dpt_error1'+a).html(''); } else{ $('#dpt_error1'+a).html('Brand Name Already Exist').delay(1000).fadeOut(); $('#brand-'+a).val(''); return false; } } }); } }); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#brand-<?php echo $count;?>").val()==""){ $("#lname<?php echo $count;?>").text("Enter Brand Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $("#brand-<?php echo $count;?>").keyup(function(){ if($(this).val()==""){ $("#lname<?php echo $count;?>").show(); } else{ $("#lname<?php echo $count;?>").fadeOut('slow'); } }) }); </script><file_sep>/application/views/petty_spare.php <script> $(document).ready(function(){ //alert("sdj"); $('.plus1').keyup(function(){ //alert("hiiio"); var hidden=$('#sample').val(); //alert(hidden); if(!$('.minus1').val()==""){ alert("enter any plus or minus"); $('.plus1').val(''); //$("#plus").attr("disabled", "disabled"); } if($(this).val()>parseInt(hidden)){ alert("Stock Not Available"); $('.plus1').val(''); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').keyup(function(){ //alert("hiiio"); if(!$('.plus1').val()==""){ alert("enter any plus or minus"); $('.minus1').val(''); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $("#test").change(function(){ var sparetxt=$(".plus1").val(); var spare = $(this).val(); var dataString = 'spare='+spare; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/sparevalidation", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#sample').val(data.spare_qty); }); } }); }); }); </script> <link rel="stylesheet" href="css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .fancybox-inner{ height: 700px !important; } .btn, .btn-large, .btn-flat { text-transform: none !important; margin-left:30px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border:1px solid #ccc; border-radius: 5px; outline: none; /* height: 3.9rem; */ width: 100%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 0; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { width: 100% !important; } .tableadd tr td select { margin-bottom: 25px !important; } .tableadd tr td input { width: 210px; height: 33px; border-radius: 5px; padding-left: 10px; } /*table tr td { border:1px solid #C2BEBE; } .catego li{ float: left; width: 175px; padding-left: 5px; padding-right: 5px; } .qua li { padding-right:5px; padding-left:5px; }*/ .tableadd2 tr td select { width: 160px; height: 33px; border-width: medium medium 1px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color #055E87; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; margin: 0px 3px; box-sizing: border-box; -moz-appearance: none; border-radius: 5px; } /*input{ width: 145px !important; border-radius: 5px !important; border-color: #055E87 !important; margin-top:10px !important; text-align:center; } .tab { background:#055E87; color:white; height:50px; }*/ #errorBox1,#errorBox2,#errorBox3{ color:#F00; } .chosen-container-single .chosen-single { position: relative; display: block; overflow: hidden; padding: 0 0 0 8px; height: 30px; width: 100%; border: 1px solid #B3B3B3; border-radius: 5px; background-color: #fff; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4)); background: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background-clip: padding-box; box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1); color: #444; text-decoration: none; white-space: nowrap; line-height: 24px; } .chosen-container .chosen-drop { position: absolute; top: 100%; left: -9999px; z-index: 1010; width: 100%; border: 1px solid #aaa; border-top: 0; background: #fff; box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15); } .wrapper { min-height: 100%; position: static; overflow: inherit; } </style> <script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#subcategory").change(function() { $("#brandname > option").remove(); var subcatid=$(this).val(); categoryid = $("#category").val(); //alert("Subcat: "+subcatid+"Cat:" +categoryid); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_brand", data: dataString, cache: false, success: function(data) { $('#brandname').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#brandname').append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#brandname").change(function() { $("#model > option").remove(); var brandid=$(this).val(); //alert(brandid); categoryid = $("#category").val(); subcategoryid = $("#subcategory").val(); //alert("Subcat: "+subcategoryid+"Cat:" +categoryid+"brandid:" +brandid); var dataString = 'subcatid='+ subcategoryid+'&categoryid='+ categoryid+'&brandid='+ brandid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_model", data: dataString, cache: false, success: function(data) { $('#model').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#model').append("<option value='"+data.id+"'>"+data.model+"</option>"); }); } }); }); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.model').change(function(){//alert("ddddd"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; //alert(id); var dataString = 'modelno='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_productinfobyid", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#category_name-'+vl).val(data.product_category), $('#category-'+vl).val(data.category), $('#subcategory_name-'+vl).val(data.subcat_name), $('#subcategory-'+vl).val(data.subcategory), $('#brand_name-'+vl).val(data.brand_name), $('#brandname-'+vl).val(data.brand) }); } }); }); }); </script> <!--<script> $(document).ready(function(){ $('.btn').click(function(event){ if($('#spare').val()==''){alert($('#spare').val()); $('#spare_error').text('Select the Spare Name').show(); event.preventDefault(); } if($('#employee').val()==''){ alert($('#employee').val()); $('#employee_error').text('Select the Employee Name').show(); event.preventDefault(); } }); }); </script>--> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Spares to Engineer</h2> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-12"> <form action="<?php echo base_url(); ?>spare/addsparedetails" method="post" name="frmSpare"> <div class="col-md-3"> <label>Spare Name</label> <select name="spare" class="spare chosen-select" id="spr"> <option value=''>--select--</option> <?php foreach($spares as $row) { ?> <option value="<?php echo $row->id;?>"><?php echo $row->spare_name;?></option><?php } ?> </select> <div id='spare_error' style="color:red;font-size:11px;"></div> </div> <div class="col-md-3"> <label>Quantity</label> <input type="text" name="plus" id="qtyplus" class="form-control plus1" placeholder="plus"/><span style="float: right;position: relative;top:-44px;left: 20px;">or</span> </div> <div class="col-md-3"> <label></label> <input type="text" name="minus" id="qtyminus" class="form-control minus1" placeholder="minus"/> </div> <input type="hidden" value="" id="sample"> <div class="col-md-3"> <label>Engineer Name</label> <select name="employee" class="chosen-select" id='employee'> <option value=''>--select--</option> <?php foreach($list as $roww) { ?> <option value="<?php echo $roww->id;?>"><?php echo $roww->emp_name;?></option><?php } ?> </select> <span id='employee_error' style="color:red;font-size:11px;"></span> </div> </div> <button class="btn cyan waves-effect waves-light " type="submit" name="Save" value="saveit">Submit</button> </div> </form> </div> </div> </div> </div> </section> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("input[name='datepicker']").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }//]]> </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>--> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(document).ready(function(){ $( "form" ).submit(function( event ) {//alert($( "#spr" ).val()); if ( $( "#spr" ).val() === "" ) { $( "#spare_error" ).text( "Select Spare Name" ).show(); event.preventDefault(); } if ( $( "#employee" ).val() === "" ) { $( "#employee_error" ).text( "Select Engineer Name" ).show(); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#spr").change(function(){ if($(this).val()==""){ $("#spare_error").show(); } else{ $("#spare_error").hide(); } }); $("#employee").change(function(){ if($(this).val()==""){ $("#employee_error").show(); } else{ $("#employee_error").hide(); } }); }); </script> </body> </html><file_sep>/application/models/Subcategory_model.php <?php class Subcategory_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_subcategory($data){ $this->db->insert('prod_subcategory',$data); return true; } public function checksubcatname($pro_cat,$sub_catname) { $this->db->where_in('prod_category_id',$pro_cat); $this->db->where_in('subcat_name',$sub_catname); $this->db->from('prod_subcategory'); $query=$this->db->get(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } //echo "<pre>";print_r($query->result()); //return $numrow = $query->num_rows(); /*$this->db->select('prod_category_id,subcat_name'); $this->db->from('prod_subcategory'); $this->db->where_in('prod_category_id,subcat_name'); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } }*/ public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_list(){ $this->db->select("prod_category.id As procat_id, prod_subcategory.id As prosubcat_id, prod_subcategory.subcat_name, prod_category.product_category, prod_subcategory.prod_category_id As pro_catid, prod_subcategory.status As status",FALSE); $this->db->from('prod_subcategory'); $this->db->join('prod_category', 'prod_subcategory.prod_category_id=prod_category.id'); $this->db->order_by('prod_subcategory.id','DESC'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function prod_sub_cat_listbyid($id){ $this->db->select("prod_category.id As procat_id, prod_subcategory.id As prosubcat_id, prod_subcategory.subcat_name, prod_category.product_category, prod_subcategory.prod_category_id As pro_catid",FALSE); $this->db->from('prod_subcategory'); $this->db->join('prod_category', 'prod_subcategory.prod_category_id=prod_category.id'); $this->db->where('prod_subcategory.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_status_prod_cat($data,$id){ $this->db->where('id',$id); $this->db->update('prod_subcategory',$data); } public function update_status_prod_cat1($data,$id){ $this->db->where('id',$id); $this->db->update('prod_subcategory',$data); } public function update_sub_cat($data,$id){ $this->db->where('id',$id); $this->db->update('prod_subcategory',$data); } public function update_sub_cat_name($data,$id){ $this->db->where('id',$id); $this->db->update('prod_subcategory',$data); } public function del_sub_cat($id){ $this->db->where('id',$id); $this->db->delete('prod_subcategory'); } public function subcategory_validation($category,$sub_category) { $this->db->where('prod_category_id',$category); $this->db->where('subcat_name',$sub_category); $this->db->from('prod_subcategory'); $query=$this->db->get(); //echo "<pre>";print_r($query->result()); return $numrow = $query->num_rows(); } }<file_sep>/application/views/cust_list.php <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> function DelStatus(id){ var r=confirm("Are you sure want to delete"); if (r==true) { var datastring='id='+id; $.ajax({ type: "POST", url: '<?php echo base_url(); ?>customer/del_customer', data: datastring, cache:false, success: function(data){ window.location = "<?php echo base_url(); ?>pages/cust_list"; alert("Customer Deleted Successfully!!!"); } }); } } </script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } /*table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1; }*/ table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #ccc; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 15px !important; } /*table.dataTable.no-footer tr td { border: 1px solid #522276 !important; padding:0px 15px; }*/ table.dataTable.no-footer tr td { border: 1px solid #ccc !important; padding:0px 15px; } a:hover, a:active, a:focus { outline: none; text-decoration: none; color: #444; } a { color: #444; cursor:pointer; } td { text-align: left; font-size: 12px; padding: 15px; } /*th { padding: 0px; text-align: center; font-size: 12px; background-color: white; }*/ /*thead { border-bottom: 1px solid #eeeeee; border: 1px solid #522276; background:#6c477d; color:#fff; font-weight: bold; font-size:12px; }*/ thead { border-bottom: 1px solid #eeeeee; border: 1px solid #522276; /*background:#6c477d;/*/ background:black; /* color:#fff;*/ color:#fed700; font-weight: bold; font-size:12px; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } #data-table-simple_length { display: block; } .fa-folder{ color:#522276; } .fa-eye{ color:#522276; } .fa-pencil-square-o{ color:#444; } .h1, .h2, .h3, h1, h2, h3 { margin-top: 20px; margin-bottom: 0px; } hr { margin-top: 0px; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Customer List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/cusadd.png" title="Add Customer" style="width:24px;height:24px;">Add Customer</button>--> <a href="<?php echo base_url(); ?>pages/add_cust" style="position: relative; bottom: 27px;left: 88%;"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Customer"></i></a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>ID</th> <th style="width:250 !important">Customer Name</th> <th>Mobile</th> <th>Location</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($list as $key){ ?> <tr> <td><?php echo $key->id; ?></td> <td><?php echo $key->customer_name; ?></td> <td><?php echo $key->mobile; ?></td> <td><?php echo $key->city; ?></td> <td class="options-width" style="width:10%"> <a href="<?php echo base_url(); ?>customer/update_customer/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> function clickPopup(idd) { var sitename = $("#sitename_"+idd).val(); $.fancybox.open({ href : '<?php echo base_url(); ?>customer/view_sales/'+idd, type : 'iframe', padding : 5 }); } </script> </body> </html><file_sep>/application/views/edit_cust_list.php <style> .box { position: relative; border-radius: 3px; background: #ffffff; /* border-top:1px solid #ccc !important; */ margin-bottom: 9px; width: 100%; /* box-shadow: 0 1px 1px rgba(0,0,0,0.1); */ } select { border: 1px solid #ccc; margin: 0 0 15px 0; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: #fff; border: 1px solid #ccc !important; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input:read-only{ background:#eee; } .btn{text-transform:none !important;} </style> <style> .close_ { float: right; font-size: 21px; font-weight: 700; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; filter: alpha(opacity=20); opacity: .2; cursor:pointer; } .close_:hover { color:#000; } </style> <script> $( function() { var available_cities = []; //alert($(this).val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), success: function(data) { $.each(data, function(index, data){ available_cities.push(data.city); }); } }); /* var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; */ $( "#tags" ).autocomplete({ source: available_cities }); } ); </script> <script type='text/javascript'> $(window).load(function(){ $(document).ready(function() { var cust_type_id = $("#cust_type").val(); var land = cust_type_id.split('-'); var id = land['0']; var corp = land['1']; //alert(id+'_'+corp); if(corp=='CORPORATE' || corp=='corporate' || corp=='Corporate' || corp=='corporate'){ $(".box").not(".ready").hide(); $(".box1").not(".ready1").hide(); $(".ready").show(); $(".ready1").show(); }else{ $(".box").not(".del").hide(); $(".box1").not(".del1").hide(); $(".del").show(); $(".del1").show(); } var cust_id = $('#customer_id').val(); if(cust_id.length == '5'){ var customerid = id+cust_id; $('#customer_id').val(customerid); }else{ var cust_id2 = cust_id.substring(2, cust_id.length); var customerid = id+cust_id2; $('#customer_id').val(customerid); //var zoneid = cust_id1+zone_id; //$('#customer_id').val(zoneid); } }); }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script>////////////////////////////////field required validation/////////////////////////////////////////// $(document).ready(function(){ $( "#submit" ).click(function( event ) { if ( $( "#cust_type" ).val() === "" ) { $( "#errorBox_type" ).text( " Enter the Types of Customer" ).show(); event.preventDefault(); } if ( $( "#customer_id" ).val() === "" ) { $( "#errorBox_id" ).text( " Enter the Customer Id" ).show(); event.preventDefault(); } if ( $( "#cust_name" ).val() === "" ) { $( "#errorBox_name" ).text( " Enter the Customer Name" ).show(); event.preventDefault(); } if ( $( "#mobile" ).val() === "" ) { $( "#errorBox_mobile" ).text( "Enter the Mobile Number" ).show(); event.preventDefault(); } if($("#mobile").val().length<10){ $( "#errorBox_mobile" ).text( "Phone Number must be atleast 10 digit" ).show(); event.preventDefault(); $(this).focus(); } /*if ( $( "#land_ln" ).val() === "" ) { $( "#errorBox" ).text( "Enter the Landline number" ).show(); event.preventDefault(); }*/ if ( $( "#address" ).val() === "" ) { $( "#errorBox_address" ).text( "Enter the Address" ).show(); event.preventDefault(); } if ( $( "#state" ).val() === "" ) { $( "#errorBox_state" ).text( "Enter the State" ).show(); event.preventDefault(); } if ( $( ".city" ).val() === "" ) { $( "#errorBox_city" ).text( "Enter the City" ).show(); event.preventDefault(); } if ( $( "#pincode" ).val() === "" ) { $( "#errorBox_pincode" ).text( "Enter the Pincode" ).show(); event.preventDefault(); } if($("#pincode").val().length<6){ $( "#errorBox_pincode" ).text( "Pincode Number must be 6 digit" ).show(); event.preventDefault(); $(this).focus(); } if ( $( "#service_zone" ).val() === "" ) { $( "#errorBox_service" ).text( "Enter the Service Zone" ).show(); event.preventDefault(); } if ( $( "#customer_name" ).val() === "" ) { $( "#errorBox_contact" ).text( "Enter the Contact Name" ).show(); event.preventDefault(); } }); $('#mobile').change(function(event){ if($(this).val() !=''){ if($(this).val().length<10){ $( "#errorBox_mobile" ).text( "Phone Number must be atleast 10 digit" ).show(); return false; event.preventDefault(); $(this).focus(); } } }); $('#pincode').change(function(event){ if($(this).val().length<6){ $( "#errorBox_pincode" ).text( "Pincode Number must be 6 digit" ).show(); return false; event.preventDefault(); $(this).focus(); } }); }); </script> <script> $(document).ready(function(){//alert('number'); $(document).on("keyup","#mobile", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var id=$("#mobile").val(); if(id !=''){ var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: datastring, cache: false, success: function(data) { if(data == 0){ $('#errBox_mobile').html(''); } else{ $('#errorBox_mobile').html('Customer Already Exist!').show(); $('#mobile').val(''); return false; } } }); } } }); </script> <script>///////////////////////////////////character & number validation/////////////////////////////////////////// $(document).ready(function(){ $('#cust_name').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); /*$('#service_zone').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); });*/ /*$('.city').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); });*/ $('#address').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z .\/-_,]+$/,'') ); }); $('#mobile').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#pincode').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#customer_name').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $("#cust_name").keyup(function(){ if($(this).val()==""){ $("#errorBox_name").show(); } else{ $("#errorBox_name").hide(); } }); $("#mobile").keyup(function(){ $("#errorBox_mobile").hide(); }); $("#cust_type").click(function(){ if($(this).val()==""){ $("#errorBox_type").show(); } else{ $("#errorBox_type").hide(); } }); $("#address").keyup(function(){ if($(this).val()==""){ $("#errorBox_address").show(); } else{ $("#errorBox_address").hide(); } }); $("#state").click(function(){ if($(this).val()==""){ $("#errorBox_state").show(); } else{ $("#errorBox_state").hide(); } }); $("#customer_id").keyup(function(){ if($(this).val()==""){ $("#errorBox_id").show(); } else{ $("#errorBox_id").hide(); } }); $("#customer_name").keyup(function(){ if($(this).val()==""){ $("#errorBox_contact").show(); } else{ $("#errorBox_contact").hide(); } }); $("#service_zone").click(function(){ if($(this).val()==""){ $("#errorBox_service").show(); } else{ $("#errorBox_service").hide(); } }); $("#pincode").keyup(function(){ if($(this).val()==""){ $("#errorBox_pincode").show(); } else{ $("#errorBox_pincode").hide(); } }); $(".city").keyup(function(){ if($(this).val()==""){ $("#errorBox_city").show(); } else{ $("#errorBox_city").hide(); } }); }); </script> <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold !important; border-radius: 5px; margin-right:20px; cursor:pointer; } .link:hover { color:#fff; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } .box{ box-shadow:none !important; } .box1{ display: none; box-shadow:none !important; } #errorBox_name{ font-size:11px; position: relative; bottom: 10px; } #errorBox_contact{ font-size:11px; position: relative; bottom: 10px; } #errorBox_mobile{ font-size:11px; position: relative; bottom: 10px; } #emailerror{ font-size:11px; position: relative; bottom: 10px; } #errorBox_pincode{ font-size:11px; position: relative; bottom: 10px; } #errorBox_service{ font-size:11px; position: relative; bottom: 10px; } #errorBox_address{ font-size:11px; position: relative; bottom: 10px; } #errorBox_state{ font-size:11px; position: relative; bottom: 10px; } #errorBox_city{ font-size:11px; position: relative; bottom: 10px; } #errorBox_type{ font-size:11px; position: relative; bottom: 10px; } </style> <script> $( function() { var available_cities = []; $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), success: function(data) { $.each(data, function(index, data){ available_cities.push(data.city); }); } }); /* var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; */ $( "#re_city" ).autocomplete({ source: available_cities }); } ); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var zone = $('#service_zone').val(); var zones = zone.split('-'); var zoneid = zones['0']; var zone_coverage = zones['2']; // alert(zoneid); var datastring='countid='+vl1+'&zoneid='+zoneid+'&zone_coverage='+zone_coverage; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('#cust_type').change(function(){ var cust_type_id = $(this).val(); var land = cust_type_id.split('-'); var id = land['0']; var corp = land['1']; //alert(id+'_'+corp); if(corp=='CORPORATE' || corp=='corporate' || corp=='Corporate' || corp=='corporate'){ $(".box").not(".ready").hide(); $(".box1").not(".ready1").hide(); $(".ready").show(); $(".ready1").show(); }else{ $(".box").not(".del").hide(); $(".box1").not(".del1").hide(); $(".del").show(); $(".del1").show(); } var cust_id = $('#customer_id').val(); if(cust_id.length == '5'){ var customerid = id+cust_id; $('#customer_id').val(customerid); }else{ var cust_id2 = cust_id.substring(2, cust_id.length); var customerid = id+cust_id2; $('#customer_id').val(customerid); //var zoneid = cust_id1+zone_id; //$('#customer_id').val(zoneid); } }); $('#service_zone').change(function(){ if(document.getElementById('cust_type').selectedIndex == 0){ alert("Kindly Select Customer Type first"); }else{ var z_id = $(this).val(); var arr = z_id.split('-'); var zonid = arr['0']; var zone_id = arr['1']; var zone_coverage = arr['2']; $('#service_zone_loc option').each(function(){ //alert(zonid); if(zonid==this.value){ //alert("Value: "+this.value); $('#service_loc_coverage').val(zone_coverage); $('#service_zone_loc').val(zonid); } }); //alert(zone_id); var cust_type_id = $('#customer_id').val(); //alert(cust_type_id); if(cust_type_id.length == '7'){ // var cust_id = cust_type_id+zone_id; var position = 2; var output = [cust_type_id.slice(0, position), zone_id, cust_type_id.slice(position)].join(''); //alert(output) $('#customer_id').val(output); }else{ //var cust_id1 = cust_type_id.substring(0, cust_type_id.length 2); //alert(str.replaceAt(2, zone_id)); String.prototype.replaceAt=function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); } strss = cust_type_id.replaceAt(2, zone_id); $('#customer_id').val(strss); } } }); }); </script> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{ float:left; list-style:none; margin:0; padding:0; width:269px; height: 125px; overflow-y: auto; overflow-x: hidden; position: relative; bottom: 15px; border: 1px solid #ccc;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} #suggesstion-box{ position: absolute; z-index: 3; } .plusbutton { border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 0px 4px 4px 4px; border-radius: 5px; color: white; height: 30px; } .delbutton { display: inline-block; padding: 0px 5px !important; margin-bottom: 10px !important; font-size: 14px; height: inherit !important; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; background-color: #dbd0e1; } .delbutton:hover{ background-color: #dbd0e1; color:#fff; border:1px solid #dbd0e1; } </style> <!--<script> $(document).ready(function(){ /*$('.del').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); });*/</script>--> <script> $(document).ready(function(){ $('.ready').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkland_ln", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); }); }); </script> <script> $(document).ready(function(){ $('#pincode').change(function() { var id=$(this).val(); var check=$('#billingtoo').val(); //alert(id); $("#service_zone > option").remove(); $('#area_name').val(""); $('#area_id').val(""); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ if(data.service_loc.length > 0){ $('#service_zone').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#area_name').val(data.area_name); $('#area_id').val(data.area_id); }); } }); }); }); </script> <script> $(document).ready(function(){ $('.re_pincode').change(function() { //var id=$(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var row_id = arr['1']; var id = $('#re-pincode_'+row_id).val(); //alert(pin); $('#service_zone_loc_'+row_id+ "> option").remove(); $('#rearea_name_'+row_id).val(""); $('#rearea_id_'+row_id).val(""); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone_loc_'+row_id).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#service_zone_loc_'+row_id).append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#rearea_name_'+row_id).val(data.area_name); $('#rearea_id_'+row_id).val(data.area_id); }); } }); }); }); </script> <script> $(document).ready(function(){ $('form').submit(function() { var i=1; $('#re_state').removeAttr('disabled'); $('#service_zone_loc_'+i).removeAttr('disabled'); }); }); </script> <script> $(window).on('load', function() { var i=1; if($('#billingtoo').val() == 1){ $('#re_address').css('background-color','#eee').prop('readonly', true); $('#re_address1').css('background-color','#eee').prop('readonly', true); $('#re_city').css('background-color','#eee').prop('readonly', true); $('#re-pincode_'+i).css('background-color','#eee').prop('readonly', true); $('#rearea_name_'+i).css('background-color','#eee').prop('readonly', true); $('#rearea_id').css('background-color','#eee').prop('readonly', true); $('#re_contact_name').css('background-color','#eee').prop('readonly', true); $('#re_emails').css('background-color','#eee').prop('readonly', true); $('#re_mobiles').css('background-color','#eee').prop('readonly', true); $('#service_zone_loc_'+i).css('background-color','#eee').prop('disabled', true); $('#re_state').css('background-color','#eee').prop('disabled', true); } }); </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Edit Customer Details</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/edit_customer" method="post" name="frmCust" onsubmit="return frmValidate()" autocomplete="off"> <!--<div id="errorBox"></div>--> <?php foreach($list as $key){?> <table class="tableadd"> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Type Of Customer<span style="color:red;">*</span></label> <select name="cust_type" id="cust_type" readonly> <option value="">---Select---</option> <?php foreach($customer_type as $custtypekey){ if( $custtypekey->id==$key->customer_type){ ?> <option selected="selected" value="<?php echo $custtypekey->id.'-'.$custtypekey->type; ?>"><?php echo $custtypekey->type; ?></option> <?php } else{?> <option value="<?php echo $custtypekey->id.'-'.$custtypekey->type; ?>"><?php echo $custtypekey->type; ?></option> <?php } }?> </select> <div id="errorBox_type" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Customer ID<span style="color:red;">*</span></label> <input type="text" name="customer_id" id="customer_id" class="customer" maxlength="15" value="<?php echo $key->customer_id; ?>" readonly><input class="" value="<?php echo $key->id; ?>" name="cus_id" type="hidden" value=""> <div id="errorBox_id" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Customer Name<span style="color:red;">*</span></label> <input type="text" name="company_name" class="company custname" id="cust_name" maxlength="80" value="<?php echo $key->company_name; ?>"> <div id="errorBox_name" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <?php if($key->mobile=="" && isset($key->mobile)){?> <label class="del1 box1">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <label class="ready1 box1">Landline No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <label class="del box">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <label class="ready box">Landline No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->mobile=="" && isset($key->mobile)){?> <input type="text" name="mobile" id="mobile" value="" class="del1 box1 mobile" maxlength="15"> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <input type="text" name="land_ln" id="land_ln" value="" class="ready1 box1 landline" maxlength="15"> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <input type="text" name="mobile" id="mobile" value="<?php echo $key->mobile;?>" class="del box mobile" maxlength="15"><input type="hidden" name="mobilehidden" value="<?php echo $key->mobile;?>" class="del box mobile" maxlength="15"> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <input type="text" name="land_ln" id="land_ln" value="<?php echo $key->land_ln;?>" class="ready box landline" maxlength="15"> <?php } ?> <div id="errorBox_mobile" style="color:red;"></div> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Email ID</label> <input type="text" name="email" id="email" class="email emailid" value="<?php echo $key->email_id; ?>"> <div class="emailerror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address<span style="color:red;">*</span></label> <input type="text" name="address" id="address" class="adress custaddress" maxlength="150" value="<?php echo $key->address; ?>"> <div id="errorBox_address" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address1</label> <input type="text" name="address1" class="adress1 custaddress1" id="address1" maxlength="150" value="<?php echo $key->address1; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Delivery Address</label> <input type="text" name="del_address" class="adress1 deliveryaddress" id="del_address" maxlength="150" value="<?php echo $key->del_address; ?>"> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>State<span style="color:red;">*</span></label> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if( $statekey->id==$key->state){ ?> <option selected="selected" value="<?php echo $statekey->id.'-'.$statekey->state; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id.'-'.$statekey->state; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> <div id="errorBox_state"style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label for="tags">City<span style="color:red;">*</span></label> <input type="text" name="city" id="tags" class="city" maxlength="100" value="<?php echo $key->city; ?>"> <div id="errorBox_city" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Pincode<span style="color:red;">*</span></label> <input type="text" name="pincode" id="pincode" class="pin" maxlength="6" value="<?php echo $key->pincode; ?>"> <div id="errorBox_pincode"style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Area</label> <input type="text" name="area_name" class="area" id="area_name" maxlength="50" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key->area_name){echo $pinkey->area_name;}} ?>" readonly> <input type="hidden" name="area_id" class="" id="area_id" value="<?php echo $key->area_name; ?>"> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Service Zone<span style="color:red;">*</span></label> <select name="service_zone" id="service_zone" readonly> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if( $zonekey->id==$key->service_zone){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } } ?> </select> <div id="errorBox_service" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Contact Name<span style="color:red;">*</span></label> <input type="text" name="customer_name" id="customer_name" class="contname" maxlength="80" value="<?php echo $key->customer_name; ?>"> <div id="errorBox_contact" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Number Of Samples Per Day</label> <input type="text" name="no_perday" class="" id="no_perday" maxlength="80" value='<?php echo $key->no_perday;?>'> <div id="errorBox_no_perday" style="color:red;"></div> </div> </div> <!--<tr> <td><label>Type Of Customer<span style="color:red;">*</span></label></td> <td> <select name="cust_type" id="cust_type" readonly> <option value="">---Select---</option> <?php foreach($customer_type as $custtypekey){ if( $custtypekey->id==$key->customer_type){ ?> <option selected="selected" value="<?php echo $custtypekey->id.'-'.$custtypekey->type; ?>"><?php echo $custtypekey->type; ?></option> <?php } else{?> <option value="<?php echo $custtypekey->id.'-'.$custtypekey->type; ?>"><?php echo $custtypekey->type; ?></option> <?php } }?> </select> </td> <td > <?php if($key->mobile=="" && isset($key->mobile)){?> <label class="del1 box1">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <label class="ready1 box1">Landline No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <label class="del box">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <label class="ready box">Landline No<span style="color:red;">*</span></label> <?php } ?> </td> <td> <?php if($key->mobile=="" && isset($key->mobile)){?> <input type="text" name="mobile" id="mobile" value="" class="del1 box1"> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <input type="text" name="land_ln" id="land_ln" value="" class="ready1 box1"> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <input type="text" name="mobile" id="mobile" value="<?php echo $key->mobile;?>" class="del box"> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <input type="text" name="land_ln" id="land_ln" value="<?php echo $key->land_ln;?>" class="ready box"> <?php } ?> </td> <!--<td><label>Mobile No<span style="color:red;">*</span></label></td><td><input type="text" name="mobile" id="mobile" class="mobile" value="<?php echo $key->mobile; ?>"></td>--> <!--</tr> <tr> <td><label>Customer ID<span style="color:red;">*</span></label></td><td><input type="text" name="customer_id" id="customer_id" class="customer" value="<?php echo $key->customer_id; ?>" readonly><input class="" value="<?php echo $key->id; ?>" name="cus_id" type="hidden" value=""></td> <td><label>Customer Name<span style="color:red;">*</span></label></td><td><input type="text" name="company_name" class="company" value="<?php echo $key->company_name; ?>"></td> </tr> <tr> <td><label>Pincode<span style="color:red;">*</span></label></td><td><input type="text" name="pincode" id="pincode" class="pincode" value="<?php echo $key->pincode; ?>"></td> <td><label>Service Zone<span style="color:red;">*</span></label></td> <td> <select name="service_zone" id="service_zone" readonly> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if( $zonekey->id==$key->service_zone){ ?> <option selected="selected" value="<?php echo $zonekey->id.'-'.$zonekey->serv_loc_code.'-'.$zonekey->zone_coverage; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id.'-'.$zonekey->serv_loc_code.'-'.$zonekey->zone_coverage; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td><label>Area</label></td><td><input type="text" name="area_name" class="" id="area_name" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key->area_name){echo $pinkey->area_name;}} ?>"><input type="hidden" name="area_id" class="" id="area_id" value="<?php echo $key->area_name; ?>"></td> <td><label>Contact Name<span style="color:red;">*</span></label></td><td><input type="text" name="customer_name" id="customer_name" class="" value="<?php echo $key->customer_name; ?>"></td> </tr> <tr> <td><label>Email Id</label></td><td><input type="text" name="email" id="email" class="email" value="<?php echo $key->email_id; ?>"></td> <td><label>Address<span style="color:red;">*</span></label></td><td><input type="text" name="address" id="address" class="adress" value="<?php echo $key->address; ?>"></td> </tr> <tr> <td><label>Address1</label></td><td><input type="text" name="address1" class="adress1" id="address1" value="<?php echo $key->address1; ?>"></td> <td><label>Delivery Address</label></td><td><input type="text" name="del_address" class="adress1" id="del_address" value="<?php echo $key->del_address; ?>"></td> </tr> <tr> <td><label>City<span style="color:red;">*</span></label></td><td><input type="text" name="city" class="city" id="search-box" value="<?php echo $key->city; ?>"><div id="suggesstion-box" ></div></td> <td><label>State<span style="color:red;">*</span></label></td><td> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if( $statekey->id==$key->state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td><label>Call Reference<span style="color:red;">*</span></label></td> <td> <select name="cal_ref" id="cal_ref"> <option value="">---Select---</option> <option value="sr" <?php if($key->cal_ref=='sr'){?>selected="selected"<?php }?>>S.R Scales</option> <option value="am" <?php if($key->cal_ref=='am'){?>selected="selected"<?php }?>>Arihant Marketing</option> </select> </td> </tr>--> </table> <?php } ?> <!-- </table> <table id="table1" class="tableadd2" style="margin-bottom: 20px;"> <label style="color: black; font-size: 15px; font-weight: bold; margin-bottom:20px;">Add Product</label> <tr class="back" > <td>Product Name</td> <td>Category</td> <td>Model</td> <td>Serial No</td> </tr> <tr> <td> <select> <option>Motorola</option> <option>Sony Ericsson</option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr> </table> <a id="addRowBtn" style="background: rgb(5, 94, 135) none repeat scroll 0% 0%; padding: 10px; color: white; border-radius:5px;">Add Row</a> <table class="tableadd">--> <div class="col-md-12" id="table2"> <div class="col-md-7 col-sm-6 col-xs-12"> <label>Lab Name</label> <div id="customer_name_error" style="color:red;" maxlength="50"></div> </div> <!--<div class="col-md-3 col-sm-6 col-xs-12"> <label><span style="color:red;"></span></label> </div> --> <!--<div class="col-md-3 col-sm-6 col-xs-12"> <a class="btn plusbutton" id="addRowBtn"><i class="fa fa-plus-circle" aria-hidden="true" style="font-size:10px"></i></a> </div> --> </div> <?php $i=0; if(empty($lablist)){?> <div class="col-md-12" id="table3"> <div class="col-md-3 col-sm-6 col-xs-12"> <select id="route" name="lab_name[]" class="form-control1 myroute "> <option value="">Select lab</option> <?php foreach($lab as $roww) { ?> <option value="<?php echo $roww->id; ?>"><?php echo $roww->lab_name; ?></option> <?php } ?> </select> <div id="customer_name_error" style="color:red;"></div> </div> <input type="hidden" name="lab_id[]" value=""> <div class="col-md-3 col-sm-6 col-xs-12"> <input type="text" class="form-control" name="lab_value[]" /> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <a class="btn plusbutton" id="addRowBtn" ><i class="fa fa-plus-square"aria-hidden="true" style="font-size:10px;color: #5d2e81;"></i></a> </div> </div> <?php }else{ foreach($lablist as $roww){ ++$i;?> <div class="col-md-12" id="table3"> <div class="col-md-3 col-sm-6 col-xs-12"> <select id="route" name="lab_name[]" class="form-control1 myroute "> <option value="">Select lab</option> <?php if($roww->customer_id == $key->id){ ?> <option selected="selected" value="<?php echo $roww->id; ?>"><?php echo $roww->lab_name; ?></option> <?php } else{ ?> <option value="<?php echo $roww->id; ?>"><?php echo $roww->lab_name; ?></option> <?php } ?> </select> <div id="customer_name_error" style="color:red;"></div> </div> <input type="hidden" name="lab_id[]" value="<?php echo $roww->cutslab;?>"> <div class="col-md-3 col-sm-6 col-xs-12"> <input type="text" class="form-control" name="lab_value[]" value="<?php echo $roww->lab_value;?>"/> </div> <?php if($i ==1){?> <div class="col-md-3 col-sm-6 col-xs-12"> <a class="btn plusbutton" id="addRowBtn" ><i class="fa fa-plus-square" aria-hidden="true" style="font-size:10px"></i></a> </div> <?php }?> <?php if($i !=1){?> <div class="col-md-3 col-sm-6 col-xs-12"> <a class="btn delRowBtn delbutton" id="<?php echo $roww->cutslab;?>" href="#"><i class="fa fa-trash" aria-hidden="true"></i></a> </div> <?php }?> </div> <?php }?> <script> $(function(){ $('.delRowBtn').click(function(event) { //alert("asfh"); var currentElemID = $(this).attr("id"); //alert(currentElemID); var dataString = 'currentElemID='+currentElemID; //alert(dataString); $.post('<?php echo base_url(); ?>Customer/delete_status',dataString,function(data){ }); }); }); </script> <?php } ?> <div class="lastdiv"></div> <table id="myTable" class="tableadd" > <?php $i=1; foreach($list1 as $key1){ if($key1->branch_name!=""){?> <input type="hidden" value="<?php echo $key1->id;?>" id="closeidd" name="closeid[]"> <?php if($i !=1){ ?> <div class="col-md-12" style="border: 1px solid #ccc; background-color: whitesmoke; margin-bottom: 8px;"> <h4><strong>Add Service Location</strong><a class="close" onclick="$(this).closest('div').remove();">x</a></h4> <input type="hidden" value="<?php echo $key1->id;?>" id="closeid" name="close[]"> <?php } else{?> <div class="col-md-12" > <h4><strong>Add Service Location</strong></h4> <input type="hidden" value="<?php echo $key1->id;?>" id="closeid" name="close[]"> <?php }?> <!--<tr> <td><label style="font-weight: bold;font-size: 14px;color: #000;line-height: 4;">Add Service Location</label></td> </tr>--> <?php if($i==1){?> <!--<tr> <td colspan="2"> <input type="checkbox" name="billingtoo" id="billingtoo" style="margin-left:-95px;height: 14px !important;"> <em style="font-style: normal; color: rgb(5, 94, 135); margin-left: -80px;">Same as above address</em></td> </tr>--> <?php } ?> <?php if($i==1){ foreach($list as $key){ if($key->checkbox ==1){?> <div class="col-md-12"> <input type="checkbox" name="billingtoo" id="billingtoo" maxlength="150" checked value="<?php echo $key->checkbox;?> "> <em style="font-style: normal; color: rgb(5, 94, 135);margin-bottom: 13px; ">Same as above address</em> </div> <?php }else{?> <div class="col-md-12"> <input type="checkbox" name="billingtoo" id="billingtoo" maxlength="150" value="<?php echo $key->checkbox;?> "> <em style="font-style: normal; color: rgb(5, 94, 135);margin-bottom: 13px; ">Same as above address</em> </div> <?php } }}?> <div class="col-md-12" > <div class="col-md-3 col-sm-6 col-xs-12"> <label>Branch Name</label> <input type="text" name="branch_name[]" class="branch_name branch" maxlength="50" value="<?php echo $key1->branch_name; ?>"><input class="" value="<?php echo $key1->id; ?>" name="cust_id[]" type="hidden" value=""> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Landline No</label> <input type="text" name="phone[]" id="phone" class="mobile add-mobile" maxlength="15" value="<?php echo $key1->landline; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address</label> <input type="text" name="re_address[]" class="re_address custaddress" id="re_address" maxlength="150" value="<?php echo $key1->address; ?>" > </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address 1</label> <input type="text" name="re_address1[]" class="re_address1 custaddress1" id="re_address1" maxlength="150" value="<?php echo $key1->address1; ?>" > </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>State</label> <!--<input type="text" name="re_state[]" class="re_state" maxlength="50" id="re_state" value="<?php echo $key1->state; ?>">--> <select name="re_state[]" id="re_state" > <option value="0">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id == $key->state){?> <option selected="selected" value="<?php echo $statekey->state; ?>"><?php echo $statekey->state; ?></option> <?php }else{ ?> <option value="<?php echo $statekey->state; ?>"><?php echo $statekey->state; ?></option><?php }} ?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label for="re_city">City </label> <input type="text" name="re_city[]" class="city" maxlength="50" id="re_city" value="<?php echo $key1->city; ?>" > <div id="suggesstion-box1"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Pincode</label> <input type="text" name="re_pincode[]" id="re-pincode_<?php echo $i; ?>" maxlength="6" class="re_pincode pin" value="<?php echo $key1->pincode; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Area</label> <input type="text" name="area_name" class="add-area" id="rearea_name_<?php echo $i; ?>" maxlength="50" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key1->area){echo $pinkey->area_name;}} ?>" > <input type="hidden" name="area_idd[]" class="rearea_id" id="rearea_id_<?php echo $i; ?>" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key1->area){echo $key1->area;}} ?> "> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Service Zone</label> <select name="service_zone_loc[]" id="service_zone_loc_<?php echo $i; ?>" > <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $key1->service_zone_loc){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php }}?> </select> <input type="hidden" name="service_loc_coverage[]" id="service_loc_coverage" class="contact_name" value="<?php echo $key1->zone_coverage; ?>"> </div> </div> <!--<tr> <td><label>Branch Name</label></td><td><input type="text" name="branch_name[]" class="branch_name" value="<?php echo $key1->branch_name; ?>"><input class="" value="<?php echo $key1->id; ?>" name="cust_id[]" type="hidden" value=""></td> <td><label>Landline No</label></td><td><input type="text" name="phone[]" id="phone" class="mobile" value="<?php echo $key1->landline; ?>"></td> </tr> <tr> <td><label>Address</label></td><td><input type="text" name="re_address[]" class="re_address" id="re_address" value="<?php echo $key1->address; ?>"></td> <td><label>Address 1</label></td><td><input type="text" name="re_address1[]" class="re_address1" id="re_address1" value="<?php echo $key1->address1; ?>"></td> </tr> <tr> <td><label>City </label></td><td><input type="text" name="re_city[]" class="city" id="re_city" value="<?php echo $key1->city; ?>"></td><td><label>State</label></td><td><input type="text" name="re_state[]" class="re_state" id="re_state" value="<?php echo $key1->state; ?>"></td> </tr> <tr> <td><label>Pincode</label></td><td><input type="text" name="re_pincode[]" id="re-pincode_<?php echo $i; ?>" class="re_pincode" value="<?php echo $key1->pincode; ?>"></td> <td><label>Service Zone</label></td> <td> <select name="service_zone_loc[]" id="service_zone_loc_<?php echo $i; ?>"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $key1->service_zone_loc){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{ ?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } }?> </select> <input type="hidden" name="service_loc_coverage[]" id="service_loc_coverage" class="contact_name" value="<?php echo $key1->zone_coverage; ?>"> </td> </tr> <tr><td><label>Area</label></td><td><input type="text" name="area_name" class="" id="rearea_name_<?php echo $i; ?>" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key1->area){echo $pinkey->area_name;}} ?>"><input type="hidden" name="area_idd[]" class="rearea_id" id="rearea_id_<?php echo $i; ?>" value="<?php foreach($pincode_list as $pinkey){if($pinkey->id==$key1->area){echo $key1->area;}} ?> "></td></tr>--> <!--<tr><td><label style="font-weight: bold;">Add Contact</label></td><td></td></tr> <tr> <td><label>Contact Name</label></td><td><input type="text" name="contact_name[]" id="re_contact_name" class="contact_name" value="<?php echo $key1->contact_name; ?>"></td><td><label>Designation</label></td><td><input type="text" name="designation[]" class="designation" value="<?php echo $key1->designation; ?>"></td> </tr> <tr> <td><label>Mobile</label></td><td><input type="text" name="mobiles[]" id="re_mobiles" class="mobile" value="<?php echo $key1->mobile; ?>"></td> <td><label>Email Id</label></td><td><input type="text" name="emails[]" id="re_emails" class="email" value="<?php echo $key1->email_id; ?>"></td> </tr>--> <h4><strong>Add Contact</strong></h4><br> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Contact Name</label> <input type="text" name="contact_name[]" id="re_contact_name" class="contact_name contname" maxlength="50" value="<?php echo $key1->contact_name; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Designation</label> <input type="text" name="designation[]" class="designation design" maxlength="80" value="<?php echo $key1->designation; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Mobile</label> <input type="text" name="mobiles[]" id="re_mobiles" class="mobile add-mobile" maxlength="15" value="<?php echo $key1->mobile; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Email ID</label> <input type="text" name="emails[]" id="re_emails" class="email add-email" value="<?php echo $key1->email_id; ?>"> <div class="add-emailerror"></div> </div> </div> </div> <?php } $i++; } ?> </table> <input type="hidden" id="countid" name="countid" value="<?php echo $i; ?>"> <br/><br/> <a class="link" id="addMoreRows" >Add Service & Contact</a><button class="btn cyan waves-effect waves-light " type="submit" id="submit">Submit </button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript'> $(function(){ var tbl = $(".lastdiv"); var i = 1; $("#addRowBtn").click(function(){ $('<div class="col-md-12"><div class="col-md-3 col-sm-6 col-xs-12"><select id="route" name="lab_name[]" class="form-control1 myroute "><option value="">Select lab</option><?php foreach($lab as $roww){?><option value="<?php echo $roww->id;?>"><?php echo $roww->lab_name;?></option> <?php } ?></select><div id="customer_name_error" style="color:red;"></div></div><div class="col-md-3 col-sm-6 col-xs-12"><input type="text" class="form-control" name="lab_value[]"/><input type="hidden" name="lab_id[]" value=""></div><div class="col-md-3 col-sm-6 col-xs-12"><a class="btn btn-danger delbutton delRowBtn"><i class="fa fa-trash" aria-hidden="true" style="color: #5d2e81;"></i></a></div></div>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <script> $(document).ready(function(){ $('#billingtoo').click(function(){ if ($(this).is(":checked")) { var id = $(this).val(); var i=1; var cid="#re-pincod_"+i; var z_id = $('#service_zone').val(); var arr = z_id.split('-'); var zonid = arr['0']; //alert(cid); var stateid = $('#state').val(); var sarr = stateid.split('-'); var sid = sarr['1']; $('#billingtoo').val(1); $('#re_address').val($('#address').val()).css('background-color','#eee').prop('readonly', true); $('#re_address1').val($('#address1').val()).css('background-color','#eee').prop('readonly', true); $('#re_city').val($('#search-box').val()).css('background-color','#eee').prop('readonly', true); $('#re_state').val(sid).css('background-color','#eee').prop('disabled', true); $('#re-pincode_'+i).val($('#pincode').val()).css('background-color','#eee').prop('readonly', true); $('#rearea_name_'+i).val($('#area_name').val()).css('background-color','#eee').prop('readonly', true); $('#rearea_id_'+i).val($('#area_id').val()).css('background-color','#eee').prop('readonly', true); $('#re_contact_name').val($('#customer_name').val()).css('background-color','#eee').prop('readonly', true); $('#re_emails').val($('#email').val()).css('background-color','#eee').prop('readonly', true); $('#re_mobiles').val($('#mobile').val()).css('background-color','#eee').prop('readonly', true); $('#service_zone_loc_'+i).val(zonid).css('background-color','#eee').prop('disabled', true); /*$.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_state", data:'stateid='+$('#state').val(), success: function(data) { $.each(data, function(index, data){//alert(data.branch_name); $('#re_state').val(data.state); }); } });*/ } else { var i=1; $('#billingtoo').val(0); $("#re_address").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_address1").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_city").val(" ").css('background-color','#fff').prop('readonly', false); $('#re-pincode_'+i).val("").css('background-color','#fff').prop('readonly', false); $('#rearea_name_'+i).val(" ").css('background-color','#fff').prop('readonly', false); $("#rearea_id").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_contact_name").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_emails").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_mobiles").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_state").val(0).css('background-color','#fff').prop('disabled', false); $('#service_zone_loc_'+i).val(0).css('background-color','#fff').prop('disabled', false); } }); }); </script> <script type='text/javascript'>//<![CDATA[ function FillBilling(f) { if(f.billingtoo.checked == true) { f.re_address.value = f.address.value; f.re_address1.value = f.address1.value; f.re_city.value = f.city.value; f.re_state.value = f.state.value; f.re_pincode.value = f.pincode.value; } } </script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); /*$("#re_city").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#re_city").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box1").show(); $("#suggesstion-box1").html(data); $("#re_city").css("background","#FFF"); } }); });*/ }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } /*function selectCountry(val) { $("#re_city").val(val); $("#suggesstion-box1").hide(); }*/ </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <!--<script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#mobiles').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script>--> <script> $(function(){ var regeditmail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.(com|org|net|co.in|in|mil|edu|gov|gov.in))$/; $(".custname,.contname,.desig,.area,.add-area,.branch").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z. ]/g,'') ); }); $(".custaddress,.custaddress1,.deliveryaddress").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9.,-\/# ]/g,'') ); }); /*$(".mobile,.landline,.add-mobile,.pin").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^0-9-]/g,'') ); });*/ $(".emailid").on("change", function(){ if(!regeditmail.test($(".emailid").val())){ $(".emailerror").text("Invalid Email ID!").show().css({ "font-size":"11px", "color":"#ff0000" }); } }); $(".add-email").change(function(){ if(!regeditmail.test($(this).val())){ $(".add-emailerror").text("Invalid Email ID!").show().css({ "font-size":"11px", "color":"#ff0000" });; } }); $(".emailid").keyup(function(){ $(".emailerror").fadeOut('slow'); }); $(".add-email").keyup(function(){ $(".add-emailerror").fadeOut('slow'); }); }); </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> <!--<script> $(document).ready(function(){ $('#address').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_address').val($('#address').val()); } }); $('#address1').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_address1').val($('#address1').val()); } }); $('#search-box').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_city').val($('#search-box').val()); } }); $('#pincode').change(function(){ //var i=1; if ($('#billingtoo').val() ==1) { $('#re-pincode_1').val($('#pincode').val()); } }); /* $('#area_name').change(function(){ if ($('#billingtoo').val() ==1) { $('#rearea_name_1').val($('#area_name').val()); } });*/ $('#area_id').change(function(){ if ($('#billingtoo').val() ==1) { $('#rearea_id').val($('#area_id').val()); } }); $('#customer_name').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_contact_name').val($('#customer_name').val()); } }); $('#email').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_emails').val($('#email').val()); } }); $('#mobile').change(function(){ if ($('#billingtoo').val() ==1) { $('#re_mobiles').val($('#mobile').val()); } }); $('#service_zone').change(function(){ if ($('#billingtoo').val() ==1) { $('#service_zone_loc_1').removeAttr('disabled'); var z_id = $(this).val(); var arr = z_id.split('-'); var zonid = arr['0']; var zone_id = arr['1']; var zone_coverage = arr['2']; //alert(zone_coverage); $('#service_zone_loc_1 option').each(function(){ $('#service_zone_loc_1').val(zonid).prop('disabled', true); }); } }); }); </script> <script> $(document).ready(function(){ $('#state').change(function(){ var i=1; var check=$('#billingtoo').val(); if(check == 1){ $('#re_state').removeAttr('disabled'); //$('#service_zone_loc_'+i).removeAttr('disabled'); var z_id = $(this).val(); $('#re_state option').each(function(){ $('#re_state').val(z_id).prop('disabled', true); }); } }); }); </script>--> </body> </html><file_sep>/application/views/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>PC</title> <style> /* Reset CSS */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { background: #e0ebeb/*url(<?php echo base_url(); ?>assets/images/purple-gradient.jpg)*//*#ac90b9*/; background-size: cover; /*background: rgba(36,150,199,1); background: -moz-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(36,150,199,1) 57%, rgba(5,94,135,1) 100%); background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(255,255,255,1)), color-stop(57%, rgba(36,150,199,1)), color-stop(100%, rgba(5,94,135,1))); background: -webkit-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(36,150,199,1) 57%, rgba(5,94,135,1) 100%); background: -o-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(36,150,199,1) 57%, rgba(5,94,135,1) 100%); background: -ms-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(36,150,199,1) 57%, rgba(5,94,135,1) 100%); background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(36,150,199,1) 57%, rgba(5,94,135,1) 100%);*/ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#055e87', GradientType=0 ); color: #000; font: 14px Arial; margin: 0 auto; padding: 0; position: relative; } h1{ font-size:28px;} h2{ font-size:26px;} h3{ font-size:18px;} h4{ font-size:16px;} h5{ font-size:14px;} h6{ font-size:12px;} h1,h2,h3,h4,h5,h6{ color:#563D64;} small{ font-size:10px;} b, strong{ font-weight:bold;} a{ text-decoration: none; } a:hover{ text-decoration: underline; } .left { float:left; } .right { float:right; } .alignleft { float: left; margin-right: 15px; } .alignright { float: right; margin-left: 15px; } .clearfix:after, form:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .container { margin: 12% auto; position: relative; width: auto; } #content { background: #336499;/*#f9f9f9*/ background-image: linear-gradient(to bottom right, #336499, #9fbedf, #336499); /* /*background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%); background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,0.9) 100%); background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);*/ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 ); /*-webkit-box-shadow: 0 1px 0 #fff inset; -moz-box-shadow: 0 1px 0 #fff inset; -ms-box-shadow: 0 1px 0 #fff inset; -o-box-shadow: 0 1px 0 #fff inset; box-shadow: 0 1px 0 #fff inset;*/ border: 1px solid #777;/*#c4c6ca*/ box-shadow: 0 0 10px #444; margin: 0 auto; padding: 25px 0 0; position: relative; text-align: center; text-shadow: 0 1px 0 #fff; max-width: 400px; } #content h1 { color: #7E7E7E; font: bold 25px Helvetica, Arial, sans-serif; letter-spacing: -0.05em; line-height: 20px; margin: 10px 0 30px; } #content h1:before, #content h1:after { content: ""; height: 1px; position: absolute; top: 10px; width: 27%; } /*#content h1:after { background: rgb(126,126,126); background: -moz-linear-gradient(left, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%); background: -webkit-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: -o-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: -ms-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); right: 0; } #content h1:before { background: rgb(126,126,126); background: -moz-linear-gradient(right, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%); background: -webkit-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: -o-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: -ms-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); background: linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%); left: 0; }*/ /*#content:after, #content:before { background: #f9f9f9; background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%); background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 ); border: 1px solid #c4c6ca; content: ""; display: block; height: 100%; left: -1px; position: absolute; width: auto; } #content:after { -webkit-transform: rotate(2deg); -moz-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); top: 0; z-index: -1; } #content:before { -webkit-transform: rotate(-3deg); -moz-transform: rotate(-3deg); -ms-transform: rotate(-3deg); -o-transform: rotate(-3deg); transform: rotate(-3deg); top: 0; z-index: -2; }*/ #content form { padding: 0 20px; position: relative } #content form input[type="text"], #content form input[type="password"] { -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; /*-webkit-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset; -moz-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset; -ms-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset; -o-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset; box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;*/ -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -ms-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; background: #eae7e7 url(http://cssdeck.com/uploads/media/items/8/8bcLQqF.png) no-repeat; border: 1px solid #c8c8c8; color: #777; font: 13px Helvetica, Arial, sans-serif; margin: 0 0 10px; padding: 15px 10px 15px 40px; width: 80%; } #content form input[type="text"]:focus, #content form input[type="password"]:focus { /*-webkit-box-shadow: 0 0 2px #ed1c24 inset; -moz-box-shadow: 0 0 2px #ed1c24 inset; -ms-box-shadow: 0 0 2px #ed1c24 inset; -o-box-shadow: 0 0 2px #ed1c24 inset; box-shadow: 0 0 2px #ed1c24 inset;*/ background-color: #fff; border: 1px solid #ed1c24; outline: none; } #username { background-position: 10px 10px !important } #password { background-position: 10px -53px !important } #content form input[type="submit"] { background: transparent -moz-linear-gradient(center top , #055E87 0%, #055E87 100%) repeat scroll 0% 0%; border-radius: 30px; box-shadow: inset 0px 1px 0px #999;/*#6c477d*/ border: 1px solid #ccc;/*#6c477d*/ color: #333; cursor: pointer; float: left; font: bold 15px Helvetica,Arial,sans-serif; height: 35px; margin: 20px 0px 35px 15px; position: relative; text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.5); width: 120px; } #content form input[type="submit"]:hover { background: transparent -moz-linear-gradient(center top , #055E87 0%, #055E87 100%) repeat scroll 0% 0%; } #content form div a { color: #004a80; float: right; font-size: 12px; margin: 30px 15px 0 0; text-decoration: underline; } .button { background: rgb(247,249,250); background: -moz-linear-gradient(top, rgba(247,249,250,1) 0%, rgba(240,240,240,1) 100%); background: -webkit-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%); background: -o-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%); background: -ms-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%); background: linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f9fa', endColorstr='#f0f0f0',GradientType=0 ); -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset; -moz-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset; -ms-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset; -o-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset; box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset; -webkit-border-radius: 0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; -o-border-radius: 0 0 5px 5px; -ms-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; border-top: 1px solid #CFD5D9; padding: 15px 0; } .button a { color: #7E7E7E; font-size: 17px; padding: 2px 0 2px 40px; text-decoration: none; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -ms-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease; } .button a:hover { background-position: 0 -135px; color: #00aeef; } .cyan { background-color: #ffffff !important;/*#6c477d*/ } </style> </head> <body> <div class="container"> <section id="content" class="col-xs-12"> <?php if(! is_null($msg)) echo $msg; ?> <form id="form1" name="form1" method="post" action="<?php echo base_url(); ?>login/process"> <img src="<?php echo base_url(); ?>assets/images/logo.png" alt="materialize logo" style="height:55px;color:#fff;float:left;position:relative;left:100px;padding-top: 20px;padding-bottom: 20px;" class="saturate"> <div> <input type="text" placeholder="Email" required="" name="email" id="email" /> </div> <div> <input type="password" placeholder="<PASSWORD>" required="" name="password" id="password" /> </div> <div> <input name="submit" type="submit" value="Login" class="cyan"/> </div> </form><!-- form --> <!-- button <div class="button"> <a href="#">Lost your password?</a> </div>--> </section><!-- content --> </div><!-- container --> </body> </html><file_sep>/application/views_bkMarch_0817/comp_list.php <style> .tableadd tr td input { width: 210px !important; } .tableadd tr td label{ width:150px !important; } </style> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Company Details</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>company/edit_company" method="post" name="frmComp" autocomplete="off"> <table class="tableadd"> <?php foreach($list as $key){?> <tr> <!--<td><label>Company Id</label></td><td><input type="text" name="comp_id" class="" value="<?php echo $key->comp_id; ?>" ></td>--><td><label>Company Name</label></td><td><input type="text" name="name" class="" value="<?php echo $key->name; ?>" ><input type="hidden" name="compid" class="" value="1" ></td><td><label>Mobile</label></td><td><input type="text" name="mobile" class="" id="mobile" value="<?php echo $key->mobile; ?>" ></td> </tr> <tr> <td><label>Phone</label></td><td><input type="text" name="phone" class="" id="phone" value="<?php echo $key->phone; ?>" ></td><td><label>Company Email ID</label></td><td><input type="text" name="comp_email" class="" value="<?php echo $key->comp_email; ?>" ></td> </tr> <tr> <td><label>Manager Email ID</label></td><td><input type="text" name="mgr_email" class="" value="<?php echo $key->mgr_email; ?>" ></td><td><label>Address 1</label></td><td><input type="text" name="addr1" class="" value="<?php echo $key->addr1; ?>" ></td> </tr> <tr> <td><label>Address 2</label></td><td><input type="text" name="addr2" class="" value="<?php echo $key->addr2; ?>" ></td><td><label>City</label></td><td><input type="text" name="city" id="search-box" class="" value="<?php echo $key->city; ?>" ><div id="suggesstion-box" ></div></td> </tr> <tr> <td><label>State</label></td><td> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id==$key->state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> </td> <td><label>Pincode</label></td><td><input type="text" name="pincode" class="" id="pincode" value="<?php echo $key->pincode; ?>" ></td> </tr> <tr> <td><label>Service Tax#</label></td><td><input type="text" name="service_tax" class="" id="service_tax" value="<?php echo $key->service_tax; ?>" ></td><td><label>PAN</label></td><td><input type="text" name="pan" class="" id="pan" value="<?php echo $key->pan; ?>" ></td> </tr> <tr> <td><label>TNVAT Registration#</label></td><td><input type="text" name="vat_no" class="" id="vat_no" value="<?php echo $key->vat_no; ?>" ></td> </tr> <?php } ?> </table> <table class="tableadd" style="margin-top: 25px;"> <tr > <td > <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>Employee/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> </body> </html><file_sep>/application/controllers/Stampingreport.php <?php class Stampingreport extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('stampingreport_model'); } function get_stamping() { $from_date = $this->input->post('from'); $to_date = $this->input->post('to'); $employee = $this->input->post('employee'); //echo $employee;exit; $data['report'] = $this->stampingreport_model->getstamping_report($from_date,$to_date); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('stampingreport_data',$data); } } <file_sep>/application/models/Dash_model.php <?php class Dash_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function areawise_count(){ $this->db->select("service_location.service_loc, count(service_request_details.request_id) As req_id, service_location.id",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id = service_request_details.request_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where_in('service_request.status', array('1','9')); $this->db->group_by('service_location.service_loc'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function spare_min_alerts(){ //$query = $this->db->query("SELECT * from spare_minimum_level ORDER BY UNIX_TIMESTAMP(alert_on) DESC LIMIT 3"); //echo "<pre>";print_r($query->result());exit; $query=$this->db->query("SELECT * from spares where min_qty >= spare_qty ORDER BY id DESC LIMIT 3"); return $query->result(); } public function spare_stock_cnt(){ $this->db->select("spare_name, spare_qty",FALSE); $this->db->from('spares'); $this->db->where('dashboard_show', '1'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function offsite_cnt(){ $this->db->select("count(site) As site",FALSE); $this->db->from('service_request_details'); $this->db->where('site', 'Customer Site'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function amc_cnt(){ $query = $this->db->query("SELECT count(ord.id) As site from order_details As ord inner join prod_category As pcat ON pcat.id = ord.cat_id inner join prod_subcategory As psubcat ON psubcat.id = ord.subcat_id inner join brands As brnd ON brnd.id = ord.brand_id inner join products As prod ON prod.id = ord.model_id inner join service_location As s_loc ON s_loc.id = ord.service_loc_id WHERE unix_timestamp(ord.amc_end_date) > unix_timestamp(CURDATE())"); //echo $this->db->last_query();exit; //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function onsite_cnt(){ $this->db->select("count(site) As site",FALSE); $this->db->from('service_request_details'); $this->db->where('site', 'Service Center'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function readyfordelivery_cnt(){ $this->db->select("count(status) As status",FALSE); $this->db->from('service_request'); $this->db->where('status', '3'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function onsite_list(){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name,service_request.status",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request_details.site', 'Service Center'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function onsite_list1(){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.site', 'Service Center'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_listforEmp(){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.site', 'Service Center'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_list(){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name,service_request.status",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request_details.site', 'Stamping'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_list1(){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.site', 'Stamping'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_listforEmp(){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.site', 'Stamping'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_cnt(){ $this->db->select("count(site) As site",FALSE); $this->db->from('service_request_details'); $this->db->where('site', 'Stamping'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name,employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->where('service_request_details.assign_to', $id); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.assign_to', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_workinpro_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.status, service_request.request_date, customers.customer_name,employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->where('service_request_details.assign_to', $id); $this->db->where('service_request.status', '1'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_workinpro_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.assign_to', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_onhold_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.status, service_request.request_date, customers.customer_name,employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->where('service_request_details.assign_to', $id); $this->db->where('service_request.status', '9'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_onhold_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.assign_to', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_awaiting_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.status, service_request.request_date, customers.customer_name,employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->where('service_request_details.assign_to', $id); $this->db->where('service_request.status', '7'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_awaiting_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.assign_to', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_ready_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.status, service_request.request_date, customers.customer_name,employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->where('service_request_details.assign_to', $id); $this->db->where('service_request.status', '3'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engg_ready_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id=service_request_details.assign_to'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.assign_to', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function offsite_list(){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name,service_request.status",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request_details.site', 'Customer Site'); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function offsite_list1(){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, service_request_details.site, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.site', 'Customer Site'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function offsite_listforEmp(){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.site', 'Customer Site'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function Areawise_list($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, customers.customer_name",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id=service_request_details.request_id'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->where('service_request_details.zone', $id); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function Areawise_list1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $this->db->where('service_request_details.zone', $id); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function Areawise_listforEmp($id){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.zone', $id); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function req_alert_cnt(){ $this->db->select("count(status) As status",FALSE); $this->db->from('service_request'); $this->db->where_in('status', array('1','9')); //$this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->group_by('request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function request_list(){ $this->db->select("service_request.id, service_request.request_id, products.model, service_request_details.service_type, quote_review.delivery_date, status.status, service_request.status As statusid, customers.customer_name, problem_category.prob_category",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('quote_review', 'quote_review.req_id = service_request.id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('customers', 'customers.id = service_request.cust_name'); $this->db->join('problem_category', 'problem_category.id = service_request_details.problem'); $this->db->join('status', ' status.id = service_request.status'); $this->db->where_in('service_request.status', array('1','2','16')); $this->db->order_by('service_request.id','asc'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_status(){ $this->db->select("employee.emp_name, service_request_details.assign_to, count(service_request_details.request_id) As total_reqs",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_work_inpro(){ $this->db->select("employee.emp_name, service_request_details.assign_to, count(service_request_details.request_id) As total_reqs",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request.status', '1'); $this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_ready_delivery(){ $this->db->select("employee.emp_name, service_request_details.assign_to, count(service_request_details.request_id) As total_reqs",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request.status', '3'); $this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_quote_awaiting_approval(){ $this->db->select("employee.emp_name, service_request_details.assign_to, count(service_request_details.request_id) As total_reqs",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request.status', '7'); $this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_on_hold(){ $this->db->select("employee.emp_name, service_request_details.assign_to, count(service_request_details.request_id) As total_reqs",FALSE); $this->db->from('service_request'); $this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request.status', '9'); $this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spare_name(){ $this->db->select("service_request.request_id,quote_review_spare_details.spare_id,service_request_details.accepted_engg_id,employee.emp_name,GROUP_CONCAT(spares.spare_name)as sname",FALSE); $this->db->from('quote_review_spare_details'); $this->db->join('service_request_details', 'service_request_details.request_id = quote_review_spare_details.request_id'); $this->db->join('service_request', 'service_request.id = service_request_details.request_id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->join('spares', 'spares.id = quote_review_spare_details.spare_id'); $this->db->group_by('service_request.request_id'); //$this->db->where('service_request.status', '9'); //$this->db->group_by('service_request_details.assign_to'); $this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spare_name_all(){ $this->db->select("service_request.request_id,quote_review_spare_details.spare_id,service_request_details.accepted_engg_id,employee.emp_name,GROUP_CONCAT(spares.spare_name)as sname",FALSE); $this->db->from('quote_review_spare_details'); $this->db->join('service_request_details', 'service_request_details.request_id = quote_review_spare_details.request_id'); $this->db->join('service_request', 'service_request.id = service_request_details.request_id'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->join('spares', 'spares.id = quote_review_spare_details.spare_id'); $this->db->group_by('service_request.request_id'); //$this->db->limit(5); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } }<file_sep>/application/controllers/Company.php <?php class company extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Company_model'); } public function edit_company(){ $data=array( 'name'=>$this->input->post('name'), 'mobile'=>$this->input->post('mobile'), 'phone'=>$this->input->post('phone'), 'comp_email'=>$this->input->post('comp_email'), 'mgr_email'=>$this->input->post('mgr_email'), 'addr1'=>$this->input->post('addr1'), 'addr2'=>$this->input->post('addr2'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'pincode'=>$this->input->post('pincode'), 'service_tax'=>$this->input->post('service_tax'), 'pan'=>$this->input->post('pan'), 'vat_no'=>$this->input->post('vat_no') ); $id=$this->input->post('compid'); $data2['city']=$this->input->post('city'); $this->Company_model->add_city($data2); $this->Company_model->update_company($data,$id); echo "<script>alert('Company Updated Successfully!!!');window.location.href='".base_url()."pages/comp_list';</script>"; } }<file_sep>/application/controllers/Quality_check.php <?php class quality_check extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('quality_check_model'); } public function quality_check_status(){ error_reporting(0); $id=$this->uri->segment(3); $data1['req_id'] = $id; $data1['get_status']=$this->quality_check_model->get_status($id); $data1['getQuoteReviewDetByID1']=$this->quality_check_model->getQuoteReviewDetByID1($id); if(!empty($data1['getQuoteReviewDetByID1'])){ $modelid = $data1['getQuoteReviewDetByID1'][0]->model_id; $data1['spareListByModelId1']= $this->quality_check_model->spareListByModelId($modelid); } $data1['getQuoteReviewSpareDetByID']=$this->quality_check_model->getQuoteReviewSpareDetByID($id); if(!empty($data1['getQuoteReviewSpareDetByID'])){ foreach($data1['getQuoteReviewSpareDetByID'] as $ReviewDetKey3){ $spare_id = $ReviewDetKey3->spare_id; $data1['spareIds'][]= $this->quality_check_model->getsparedetForEditbyid($spare_id); $data1['spare_amtt'][] = $ReviewDetKey3->amt; } }//echo "<pre>";print_r($data1['spareIds']);exit; $data1['getQuoteByReqId']=$this->quality_check_model->getQuoteByReqId($id); if(!empty($data1['getQuoteByReqId'])){ if($data1['getQuoteByReqId'][0]->modelid!=""){ $service_modelid = $data1['getQuoteByReqId'][0]->modelid; }else{ $service_modelid = ""; } if($data1['getQuoteByReqId'][0]->service_cat!=""){ $service_service_cat = $data1['getQuoteByReqId'][0]->service_cat; }else{ $service_service_cat = ""; } } $data1['getProbforQuoteByReqId']=$this->quality_check_model->getProbforQuoteByReqId($id); $data1['getServiceCatbyID']=$this->quality_check_model->getServiceCatbyID($service_service_cat, $service_modelid); if(empty($data1['getServiceCatbyID'])){ $data1['getservicecharge'] = '0'; } $data1['status_list']=$this->quality_check_model->status_list(); $data1['status_listForquoteInpro']=$this->quality_check_model->status_listForquoteInpro(); $data1['status_listForqc']=$this->quality_check_model->status_listForqc(); $data1['service_req_listforEmp1']=$this->quality_check_model->service_req_listforEmp1($id); $data1['getTaxDefaultInfo']=$this->quality_check_model->getTaxDefaultInfo(); $data1['problemlist1']=$this->quality_check_model->problemlist(); $data1['getWarrantyInfo']=$this->quality_check_model->getWarrantyInfo($id); //$data1['getQuoteReviewSpareDetByID']=$this->quality_check_model->getQuoteReviewSpareDetByID($id); //$data1['getQuoteReviewDetByID']=$this->Quotereview_model->getQuoteReviewDetByID($id); if(!empty($data1['getQuoteReviewDetByID1'])){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('quality_check_view',$data1); }else{ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('service_status_new',$data1); } } public function addrow(){ $data['count']=$this->input->post('countid'); $modelid=$this->input->post('modelid'); $data['spareListByModelId']=$this->Quotereview_model->spareListByModelId($modelid); $this->load->view('add_spares_row',$data); } public function getsparedet(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Quotereview_model->getsparedetbyid($id))); } public function add_quotereview(){ //echo "<pre>";print_r($_POST);exit; $reqid = $this->input->post('req_id'); $data['req_id']=$this->input->post('req_id'); $data['model_id']=$this->input->post('modelid'); $data['spare_tax']=$this->input->post('spare_tax'); //$data['tax_type']=$this->input->post('tax_type'); $data['spare_tot']=$this->input->post('spare_tot'); $data['labourcharge']=$this->input->post('labourcharge'); $data['concharge']=$this->input->post('concharge'); $data['total_amt']=$this->input->post('total_amt'); $data['delivery_date']=$this->input->post('delivery_date'); $result=$this->Quotereview_model->add_quotereview($data); $data4=array( 'status'=>$this->input->post('status') ); $this->Quotereview_model->update_stats($data4,$reqid); $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $amt=$data1['amt']=$this->input->post('amt'); $c=$spare_name; $count=count($c); if($reqid){ $data1 =array(); for($i=0; $i<$count; $i++) { $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; $used_spare = $spare_qty[$i] + $used_spares[$i]; $data2[] = array( 'id' => $spare_name[$i], 'spare_qty' => $bal_spare, 'used_spare' => $used_spare ); $data1[] = array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i] ); } if(!empty($data2)){ $this->Quotereview_model->update_spare_balance($data2); } if(!empty($data1)){ $this->Quotereview_model->add_quotereview_spares($data1); } echo "<script>alert('Quote Review Added');window.location.href='".base_url()."pages/quote_in_progress_list';</script>"; } } public function edit_quotereview(){ //echo "<pre>";print_r($_POST);exit; $reqid = $this->input->post('req_id'); date_default_timezone_set('Asia/Calcutta'); $data['updated_on'] = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $data['user_id'] = $data111['user_dat'][0]->id; $user_id = $data111['user_dat'][0]->id; //$data['req_id']=$this->input->post('req_id'); $stats=$this->input->post('status'); $data['spare_tax']=$this->input->post('spare_tax'); //$data['tax_type']=$this->input->post('tax_type'); $data['spare_tot']=$this->input->post('spare_tot'); $data['labourcharge']=$this->input->post('labourcharge'); $data['concharge']=$this->input->post('concharge'); $data['total_amt']=$this->input->post('total_amt'); $data['notes']=$this->input->post('notes'); $data4=array( 'status'=>$this->input->post('status'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); foreach ($data4 as $datakey => $datavalue) { //echo $datakey.'-'.$datavalue; if (!empty($datavalue)){ $this->quality_check_model->update_stats($data4,$reqid); if($datavalue=='3'){ $data['delivery_date']=$this->input->post('delivery_date'); $data['comments']=$this->input->post('comment_ready'); $customer_mobile = $this->input->post('cust_mobile'); if(isset($customer_mobile) && $customer_mobile!=""){ $sms= "Your machine is ready for delivery. Thank you.<br>Syndicate Diagnostics<br>"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$customer_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($datavalue=='4'){ $data['delivery_date']=$this->input->post('delivery_date1'); $data['comments']=$this->input->post('comment_deliver'); $data['assign_to']=$this->input->post('assign_to_id'); } } } $this->quality_check_model->update_quotereview($data,$reqid); $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $amt=$data1['amt']=$this->input->post('amt'); //$this->quality_check_model->delete_quote_review($reqid); //$used_spares=$data1['spare_tbl_id']=$this->input->post('spare_tbl_id'); $c=$spare_name; $count=count($c); /* if($reqid){ $data1 = array(); for($i=0; $i<$count; $i++) { if($stats=='2'){ $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; $used_spare = $spare_qty[$i] + $used_spares[$i]; $data2[] = array( 'id' => $spare_name[$i], 'spare_qty' => $bal_spare, 'used_spare' => $used_spare ); } $data1[] = array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i] ); } if(!empty($data2)){ $this->quality_check_model->update_spare_balance($data2); } if(!empty($data1)){ $this->quality_check_model->add_quotereview_spares($data1); } echo "<script>alert('QC Updated');window.location.href='".base_url()."pages/quality_check_list';</script>"; } */ echo "<script>alert('QC Updated');window.location.href='".base_url()."pages/quality_check_list';</script>"; } public function add_service_req(){ //echo "<pre>";print_r($_POST);exit; $data['request_id']=$this->input->post('req_id'); $data['cust_name']=$this->input->post('cust_name'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['request_date']=$this->input->post('datepicker'); $result=$this->Service_model->add_services($data); if($result){ $data1['request_id']=$result; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); $result1=$this->Service_model->add_service_details($data1); } if($result){ echo "<script>alert('Service Request Added');window.location.href='".base_url()."pages/service_req_list';</script>"; } } public function get_custbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function update_service_req(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_req',$data); } public function edit_service_req(){ $data=array( 'request_id'=>$this->input->post('req_id'), 'cust_name'=>$this->input->post('cust_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email_id'), 'request_date'=>$this->input->post('datepicker') ); $id=$this->input->post('servicereqid'); $this->Service_model->update_service_request($data,$id); if($id){ $data1['request_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); //echo "<pre>"; //print_r($data1); $this->Service_model->delete_serv_req_details($id); $result1=$this->Service_model->add_service_details($data1); } echo "<script>alert('Service Request Updated');window.location.href='".base_url()."pages/service_req_list';</script>"; } public function get_branchname(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_branch($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_order(){ $id=$this->input->post('id'); $this->Order_model->delete_order_details($id); $result = $this->Order_model->delete_orders($id); } }<file_sep>/application/models/Productcategory_model.php <?php class Productcategory_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_prod_cat($data1){ $this->db->insert('prod_category',$data1); return true; } public function checkcatname($user) { $this->db->select('product_category'); $this->db->from('prod_category'); $this->db->where_in('product_category',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function prod_cat_list(){ $this->db->select("id,product_category,status",FALSE); $this->db->from('prod_category'); $this->db->order_by('id','DESC'); $query = $this->db->get(); return $query->result(); } public function getprodcatbyid($id){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $this->db->where('id', $id); $query = $this->db->get(); return $query->result(); } public function update_prod_cat($data,$id){ $this->db->where('id',$id); $this->db->update('prod_category',$data); } public function update_status_prod_cat($data,$id){ $this->db->where('id',$id); $this->db->update('prod_category',$data); } public function update_status_prod_cat1($data,$id){ $this->db->where('id',$id); $this->db->update('prod_category',$data); } public function category_validation($product_id) { $query = $this->db->get_where('prod_category', array('product_category' => $product_id)); return $numrow = $query->num_rows(); } }<file_sep>/application/views/prob_cat_list.php <style> .ui-state-default { background:#6c477d; color:#fff; border: 3px solid #fff !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; border: 1px solid #522276 !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } /*select { position: relative; margin: -5px 6px; }*/ #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=text]{ background-color: transparent; border: 0px solid #522276; border-radius: 7; width: 55% !important; font-size: 12px; margin: 0 0 -2px 0; padding: 3px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height:17px; } input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } a { color: #522276; } a:hover { color: #9678ab; } a:focus { color: #522276; } a:active { color: #522276; } body{ background-color: #fff;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); prob_category = $("#prob_category_"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>problemcategory/update_prob_category', data: {'id' : id, 'prob_category' : prob_category}, dataType: "text", cache:false, success: function(data){ alert("Problem Category updated"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>problemcategory/del_prob_category', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/prob_cat_list"; } alert("Problem Category deleted"); } }); }); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Problem Category List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addpro.png" title="Add Problem Category" style="width:24px;height:24px;">Add Problem Category</button>--> <a href="<?php echo base_url(); ?>pages/add_prob_cat"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Sales" style="position: relative; float: right;bottom: 27px;right: 22px;"></i></a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr><th class="hidden">ID</th> <th>S.No.</th> <th style="text-align:center !important;font-size:13px;color:##303f9f;width: 66px;"><b>Problem Code</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Problem Name</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Model</b></th> <!--<th style="text-align:center;font-size:13px;color:##303f9f;"><b>Description</b></th>--> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Action</b></th> </tr> </thead> <tbody> <?php $i=1; foreach($list as $key){ ?> <tr><td class="hidden"><?php echo $key->id;?></td> <td><?php echo $i;?></td> <td><input type="text" value="<?php echo $key->prob_code; ?>" class="" name="prob_code" id="prob_code<?php echo $key->id; ?>" readonly></td> <td><input type="text" value="<?php echo $key->prob_category; ?>" class="" name="prob_category" id="prob_category_<?php echo $key->id; ?>" readonly></td> <td><input type="text" value="<?php foreach($list1 As $key1){ if($key->id==$key1->id){echo $key1->model;}} ?>" class="" name="model" id="model_<?php echo $key->id; ?>" readonly></td> <!--<td><input type="text" value="<?php echo $key->prob_description; ?>" class="" name="p_description" id="p_description<?php echo $key->id; ?>" readonly></td>--> <td class="options-width" style="text-align:center;"> <a href="<?php echo base_url(); ?>problemcategory/update_prob_cat/<?php echo $key->id; ?>" style="padding-right:10px;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr> <?php $i++;} ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/add_cust_row.php <!--<style> input[type=text] { background-color:#fff; } </style>--> <?php $cntid=$_POST['countid']; ?> <div class="col-md-12 append-row_<?php echo $cntid; ?>" style="border:1px solid #ccc;background-color:whitesmoke;margin-bottom:8px;"> <h4><strong>Add Service Location</strong><a class="close_<?php echo $cntid; ?>">x</a></h4> <br/> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Branch Name</label> <input type="text" name="branch_name[]" id="branch_<?php echo $cntid; ?>" class="branch_name" maxlength="100"> <div id="brancherror_<?php echo $cntid; ?>"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Landline No</label> <input type="text" name="phone[]" id="phone_<?php echo $cntid; ?>" class="phone" maxlength="15"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address</label> <input type="text" name="re_address[]" id="re_address_<?php echo $cntid; ?>" class="re_address" maxlength="150"> <input type="hidden" name="service_loc_coverage[]" id="service_loc_coverage" class="contact_name"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address 1</label> <input type="text" name="re_address1[]" id="re_address1_<?php echo $cntid; ?>" class="re_address1" maxlength="150"> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>State</label> <select name="re_state[]" id="re_state_<?php echo $cntid; ?>"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ ?> <option value="<?php echo $statekey->state; ?>"><?php echo $statekey->state; ?></option> <?php } ?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>City </label> <input type="text" name="re_city[]" id="re_city_<?php echo $cntid; ?>" class="city" maxlength="80"> <div id="suggesstion-box2" ></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Pincode</label> <input type="text" name="re_pincode[]" id="pin_<?php echo $cntid; ?>" class="re_pincode" value="" maxlength="6"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Area</label> <input type="text" name="area_name" class="" id="place_name_<?php echo $cntid; ?>"><input type="hidden" name="area_idd[]" class="" id="areacode_id" maxlength="150"> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Service Zone</label> <select name="service_zone_loc[]" id="zone_loc_<?php echo $cntid; ?>"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $zoneid){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } }?> </select> </div> </div> <h4><strong>Add Contact</strong></h4><br> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Contact Name</label> <input type="text" name="contact_name[]" id="contact-name_<?php echo $cntid; ?>" class="contact_name" maxlength="80"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Designation</label> <input type="text" name="designation[]" id="design_<?php echo $cntid; ?>" class="designation" maxlength="150"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Mobile</label> <input type="text" name="mobiles[]" id="mobiles_<?php echo $cntid; ?>" class="mobile" maxlength="15"> <div id="mobileserror_<?php echo $cntid; ?>"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Email ID</label> <input type="text" name="emails[]" id="email_<?php echo $cntid; ?>" class="add-emailid"> <div class="add-emailerror_<?php echo $cntid; ?>"></div> </div> </div> </div> <!--<tr> <td><label style="font-weight: bold;font-size: 14px;color: #000;line-height: 4;">Add Service Location</label></td> </tr> <tr> <td><label>Branch Name</label></td><td><input type="text" name="branch_name[]" class="branch_name"></td> <td><label>Landline No</label></td><td><input type="text" name="phone[]" id="phone" class="phone"></td> </tr> <tr> <td><label>Address</label></td><td><input type="text" name="re_address[]" id="re_address" class="re_address"></td> <td><label>Address 1</label></td><td><input type="text" name="re_address1[]" id="re_address1" class="re_address1"></td> </tr> <tr> <td><label>City </label></td><td><input type="text" name="re_city[]" id="re_city" class="city"></td><td><label>State</label></td><td><input type="text" name="re_state[]" id="re_state" class="re_state"></td> </tr> <tr> <td><label>Pincode</label></td><td><input type="text" name="re_pincode[]" id="pin" class="re_pincode" value=""></td> <td><label>Service Zone</label></td> <td> <select name="service_zone_loc[]" id="zone_loc"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $zoneid){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } }?> </select> <input type="hidden" name="service_loc_coverage[]" id="service_loc_coverage" class="contact_name" value="<?php if(isset($zone_coverage) && $zone_coverage!=""){echo $zone_coverage;} ?>"> </td> <tr> <td><label>Area</label></td><td><input type="text" name="area_name" class="" id="place_name"><input type="hidden" name="area_idd[]" class="" id="areacode_id"></td></tr> </tr> <tr><td><label style="font-weight: bold;">Add Contact</label></td><td></td></tr> <tr> <td><label>Contact Name</label></td><td><input type="text" name="contact_name[]" class="contact_name"></td><td><label>Designation</label></td><td><input type="text" name="designation[]" class="designation"></td> </tr> <tr> <td><label>Mobile</label></td><td><input type="text" name="mobiles[]" id="mobiles" class="mobile"></td> <td><label>Email Id</label></td><td><input type="text" name="emails[]" class="email"></td> </tr>--> <style> .close_<?php echo $cntid; ?> { float: right; font-size: 21px; font-weight: 700; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; filter: alpha(opacity=20); opacity: .2; cursor:pointer; } .close_<?php echo $cntid; ?>:hover { color:#000; } </style> <script> $(document).ready(function(){//alert("hikii"); $('#pin_<?php echo $cntid; ?>').change(function() { //alert("ghdg"); var id=$(this).val(); //alert(id); $("#zone_loc_<?php echo $cntid; ?> > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#zone_loc_<?php echo $cntid; ?>').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#zone_loc_<?php echo $cntid; ?>').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#place_name_<?php echo $cntid; ?>').val(data.area_name); $('#areacode_id').val(data.area_id); }); } }); }); }); </script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#re_city_<?php echo $cntid; ?>").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#re_city_<?php echo $cntid; ?>").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box2").show(); $("#suggesstion-box2").html(data); $("#re_city_<?php echo $cntid; ?>").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#re_city_<?php echo $cntid; ?>").val(val); $("#suggesstion-box2").hide(); } $(".close_<?php echo $cntid; ?>").click(function(){ $(".append-row_<?php echo $cntid; ?>").remove(); }); </script> <script> $(function(){ //alert("append field"); var regeditmail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.(com|org|net|co.in|in|mil|edu|gov|gov.in))$/; $(".custname,.contname,.desig,.area,.add-area,.branch_name").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z. ]/g,'') ); }); $(".custaddress,.custaddress1,.deliveryaddress").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9.,-\/# ]/g,'') ); }); $(".mobile,.phone,.add-mobile,.pin").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^0-9-]/g,'') ); }); $(".add-emailid").on("change", function(){ if(!regeditmail.test($(this).val())){ $(".add-emailerror_<?php echo $cntid; ?>").text("Invalid Email ID!").show().css({ "font-size":"11px", "color":"#ff0000" }); } }); $( "#submit" ).click(function( event ) { if ( $( "#branch_<?php echo $cntid; ?>" ).val() === "" ) { $( "#brancherror_<?php echo $cntid; ?>" ).text( " Enter the Branch Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#mobiles_<?php echo $cntid; ?>" ).val() === "" ) { $( "#mobileserror_<?php echo $cntid; ?>" ).text( " Enter the Mobile Number" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#mobiles_<?php echo $cntid; ?>" ).keyup(function(){ $("#mobileserror_<?php echo $cntid; ?>" ).hide(); }); $("#branch_<?php echo $cntid; ?>" ).keyup(function(){ $("#brancherror_<?php echo $cntid; ?>" ).hide(); }); /*$(".emailid").keyup(function(){ $(".emailerror").fadeOut('slow'); });*/ }); </script> <file_sep>/application/views/add_zone_pin_row.php <tr> <td style="padding:10px 0;"><input type="text" name="area_name[]" id="area_name-0<?php echo $count; ?>"><div id="errorBox1<?php echo $count; ?>"></div></td> <td style="padding:10px 0;"><input type="text" name="pincode[]" id="pincode-0_<?php echo $count; ?>" maxlength="6" class='pincode'><div id="errorBox11<?php echo $count; ?>"></div></td> <td style="border:none;"><a class="delRowBtn" onclick="$(this).closest('tr').remove();"><span class="fa fa-trash" style="color:#5f3282;"></span></a></td> </tr> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(function(){ //alert("hiii"); $( "form" ).submit(function( event ) { if ( $( "#area_name-0<?php echo $count; ?>" ).val() == "" ) { $( "#errorBox1<?php echo $count; ?>" ).text( "Enter the Area Name" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ( $( "#pincode-0_<?php echo $count; ?>" ).val() == "" ) { $( "#errorBox11<?php echo $count; ?>" ).text( "Enter the Pincode" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(document).ready(function(){ $('#pincode-0_<?php echo $count; ?>').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9 ]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $("#area_name-0<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#errorBox1<?php echo $count; ?>").show(); } else{ $("#errorBox1<?php echo $count; ?>").hide(); } }); $("#pincode-0_<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#errorBox11<?php echo $count; ?>").show(); } else{ $("#errorBox11<?php echo $count; ?>").hide(); } }); }); </script> <script> $(function(){ $('input[name^="pincode"]').change(function() { var $current = $(this); $('input[name^="pincode"]').each(function() { if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id')) { $("#pincode-0_<?php echo $count; ?>").val(''); $("#errorBox11<?php echo $count; ?>").text( "Already Exists" ).show().css({'color':'#ff0000','font-size':'10px'}); } }); }); }); </script> <file_sep>/application/views_bkMarch_0817/service_skill.php <script type='text/javascript'>//<![CDATA[ $(function(){ $('[name="cand_no"]').on('change', function() { // Not checking for Invalid input if (this.value != '') { var val = parseInt(this.value, 10); var rows = $('#studentTable tr'), rowCnt = rows.length - 1; // Allow for header row if (rowCnt > val) { for (var i = rowCnt; i > val; i--) { rows[i].remove(); } } if (rowCnt < val) { for (var i = 0; i < val - rowCnt; i++) { // Clone the Template var $cloned = $('.template tbody').clone(); // For each Candidate append the template row $('#studentTable tbody').append($cloned.html()); } } } }); });//]]> </script> <style> #studentTable .skill td { background: #055E87 none repeat scroll 0% 0%; border: 1px solid #B3B3B3; padding: 8px; color: #FFF; } #studentTable tr td { border: 1px solid #B3B3B3; text-align: center; padding: 10px; } #studentTable tr td select:focus { border:1px solid #055E87; } input.number { border-radius:5px; } input{ border:none !important; text-align:center; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">New Employee</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-12"> <form action="<?php echo base_url(); ?>Employee/add_service_skill" method="post" name="frmEmp" > <table id="studentTable" border="0"> <tr class="skill"> <td>Category <input name="empid" type="hidden" value="<?php echo $id; ?>"/></td> <td>Sub-category</td> <td>Brand</td> <td>Model</td> <?php foreach($servicecatlist as $key1){ ?> <td><?php echo $key1->service_category; ?></td> <?php } ?> </tr> <?php foreach($list as $key){ ?> <tr> <td><input name="p_category[]" type="text" value="<?php echo $key->category; ?>"/></td> <td><input name="sub_category[]" type="text" value="<?php echo $key->subcategory; ?>"/></td> <td><input name="brand[]" type="text" value="<?php echo $key->brand_name; ?>"/></td> <td><input name="p_model[]" type="text" value="<?php echo $key->model; ?>"/><input name="ids[]" type="hidden" value="<?php echo $key->id; ?>"/></td> <?php foreach($servicecatlist as $key1){ ?> <td><input name="service_cat<?php echo $key->id; ?>[]" value="<?php echo $key1->service_category; ?>" type="checkbox" /></td> <?php } ?> </tr> <?php } ?> </table> <button class="btn cyan waves-effect waves-light " type="submit" >Submit <i class="fa fa-arrow-right"></i> </button> </div> </form> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/add_tax.php <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <style> body{background-color:#fff;} .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } .star{ color:#ff0000; font-size:15px; } a{ cursor:pointer;} .btn{text-transform:none !important;} </style> <section id="content"> <div class="container"> <div class="section"> <h2>Add Tax</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>tax/add_tax" method="post"> <div id="myTable" class="tableadd"> <div class="col-md-12" style="padding: 0px;"> <div class="col-md-3"> <label><b>Tax Name</b> <span class="star">*</span></label> <input type="text" name="tax_name[]" class="model tax" id="tax" maxlength="30"> <div class="taxerror"></div> </div> <div class="col-md-3"> <label><b>Percentage</b> <span class="star">*</span></label> <input type="text" name="percentage[]" class="model percentage" maxlength="5"> <div class="percenterror"></div> <input type="hidden" id="countid" value="1"> </div> <div class="col-md-3"> <a class="link" id="addRowBtn" ><i class="fa fa-plus-square" aria-hidden="true"style="margin-top: 30px; color: #643886;"></i></a></div> </div> </div> <button class="btn cyan waves-effect waves-light submittax" type="submit" name="action" style="margin-left:20px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('#tax').change(function(){ var tax=$('#tax').val(); //alert("hiii"); var datastring='tax='+tax; $.ajax({ type:"POST", url:"<?php echo base_url(); ?>tax/check_tax", data:datastring, cache:false, success:function(data){ //alert(data); if(data == 0){ $('.taxerror').html(''); } else{ $('.taxerror').html('Tax Name Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'14px','font-size':'10px'}); $('#tax').val(''); return false; } } }); }); }); </script> <!--<script> $(document).ready(function(){ $('.email_check').change(function(){ var ben_email=$(this).val(); // var ben_type = $('#ben_types').val(); var datastring='email='+ben_email; //var datastring='email='+email+'&ben_type='+ben_type; $.ajax({ type:"POST", url:"<?php echo base_url(); ?>home/chk_email", data:datastring, cache:false, success:function(data){ //alert(data); if(data == 0){ $('#email_error').html(''); } else{ $('#email_error').html('Email already Exist!').show().delay(4000).fadeOut(); $('#ben_email').val(''); return false; } } }); }); }); </script>--> <!--<script type='text/javascript'>//<![CDATA[ //$(window).load(function(){ $(function(){ var tbl = $("#myTable"); var i=0; //alert("test"); $("#addRowBtn").click(function(){ $('<div class="col-md-12" style="padding: 0px;"><div class="col-md-3"><input type="text" name="tax_name[]" class="model tax'+i+'" id="tax"><div class="taxerror'+i+'"></div></div><div class="col-md-3"><input type="text" name="percentage[]" class="model percentage'+i+'" maxlength="3"><div class="percenterror'+i+'"></div></div><div class="col-md-3"><a class="delRowBtn"><i class="fa fa-trash"></i></a></div></div>').appendTo(tbl); $('.tax'+i).keyup(function(){ var tax=$(this).val(); //alert(tax); var datastring='tax='+tax; //alert(tax); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>tax/check_tax", data:datastring, cache:false, success:function(data){ //alert(data); if(data == 0){ $('.taxerror'+i).html(''); } else{ $('.taxerror'+i).html('Tax Name Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); $('.tax'+i).val(''); return false; } } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); $(".percentage"+i).bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9%]/g,"")); }); $(".tax"+i).bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $(".submittax").click(function(event){ if($(".tax"+i).val()==""){ $(".taxerror"+i).text("Please Enter Tax Name").show().css({ 'font-size':'11px', 'color':'#ff0000', 'position': 'relative', 'bottom': '10px' }); event.preventDefault(); } if($(".percentage"+i).val()==""){ $(".percenterror"+i).text("Please Enter the Percentage").show().css({ 'font-size':'11px', 'color':'#ff0000', 'position': 'relative', 'bottom': '5px' });; event.preventDefault(); } }); $(".percentage"+i).keyup(function(){ $(".percenterror"+i).fadeOut('slow'); }); $(".tax"+i).keyup(function(){ $(".taxerror"+i).fadeOut('slow'); }); }); i++; }); //});//]]> </script>--> <script> $(document).ready(function(){ $('#addRowBtn').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Tax/add_taxrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <script> $(function(){ //alert("percentage"); $(".submittax").click(function(event){ if($(".tax").val()==""){ $(".taxerror").text("Please Enter Tax Name").show().css({ 'font-size':'10px', 'color':'#ff0000', 'position': 'relative', 'bottom': '15px' }); event.preventDefault(); } if($(".percentage").val()==""){ $(".percenterror").text("Please Enter the Percentage").show().css({ 'font-size':'10px', 'color':'#ff0000', 'position': 'relative', 'bottom': '15px' }); event.preventDefault(); } }); $(".percentage").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9.]/g,"")); }); $(".tax").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $(".percentage").keyup(function(){ $(".percenterror").fadeOut('slow'); }); $(".tax").keyup(function(){ $(".taxerror").fadeOut('slow'); }); }); </script> </body> </html><file_sep>/application/views_bkMarch_0817/view_servicecat_models.php <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="http://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script src="http://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" ></script> <style> h2 { color: #000; font-family: 'Source Sans Pro',sans-serif; } table.dataTable tbody th, table.dataTable tbody td { padding: 3px 10px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; color: #000; font-size: 13px; } table.dataTable tbody tr:nth-child(even) {background: #f9f9f9} table.dataTable tbody tr:nth-child(odd) {background: #eaeaea} </style> </head> <body> <div class="container"> <h2>Service Charge List</h2> <table cellpadding="1" cellspacing="1" id="detailTable"> <thead> <tr> <th>Model</th> <th>Charge</th> </tr> </thead> <tbody> <?php foreach($service_list as $key1){?> <tr> <?php foreach($service_charge as $key){ if($key->service_cat_id==$key1->id){?> <td><?php echo $key->model;?></td> <td><?php echo $key->service_charge;?></td> </tr> <?php } } }?> </tbody> </table> </div> <script> $(document).ready(function() { $('#detailTable').DataTable(); }); </script> </body> </html><file_sep>/application/views/edit_probcat_list.php <style> #addMoreRows{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color:#49186d; } .delRowBtn{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 0px 4px 4px 4px; border-radius: 5px; color: white; height:30px; } </style> <script> $(function(){ $( "form" ).submit(function( event ) { if ( $( "#prob_cat_name" ).val() === "" ) { $( "#prob_cat_name_error" ).text( "Enter the Problem Category Name" ).show().css({ 'color':'#ff0000', 'font-size':'12px' }); event.preventDefault(); } if ( $( "#model" ).val() === "" ) { $( "#model_error" ).text( "Please choose the model" ).show().css({ 'color':'#ff0000', 'font-size':'12px' }); event.preventDefault(); } if ( $( "#prob_code" ).val() === "" ) { $( "#prob_code_error" ).text( "Enter the Problem Category Code" ).show().css({ 'color':'#ff0000', 'font-size':'12px' }); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#prob_cat_name").change(function(){ if($(this).val()==""){ $("#prob_cat_name_error").show(); } else{ $("#prob_cat_name_error").hide(); } }); $("#model").change(function(){ if($(this).val()==""){ $("#model_error").show(); } else{ $("#model_error").hide(); } }); $("#prob_code").change(function(){ if($(this).val()==""){ $("#prob_code_error").show(); } else{ $("#prob_code_error").hide(); } }); $("#prob_code,#prob_cat_name").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9 ]/g,'') ); }); }); </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddssss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>problemcategory/addrow", data: datastring, cache: false, success: function(result) { // alert(result); $('#myTable').append(result); } }); }); }); </script> <script> $(function() { $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }) </script> <script> $(document).ready(function(){ $('#prob_code').change(function(){ var prob_code=$(this).val(); var datastring='code='+prob_code; $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkCode", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ $('#name_error').html('Problem Code already Exist!').show(); $('#prob_code').val(''); } else if(data==0) { $('#name_error').hide(); } } }); }); }); </script> <script> $(document).ready(function(){ //$('#prob_cat_name').change(function(){ //alert("check"); $(document).on("keyup","#prob_cat_name", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var prob_code=$('#prob_cat_name').val(); var model=$('#model').val(); //alert(prob_code); var datastring='code='+model+'&problem='+prob_code; //alert(datastring); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkproblem", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ //alert("hiii"); $('#prob_cat_name_error').html('Problem Category Name Already Exist!').show(); $('#prob_cat_name').val(''); } else { $('#prob_cat_name_error').hide(); } } }); } }); </script> <style> .btn{text-transform:none !important;} .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold !important; border-radius: 5px; cursor:pointer; } .link:hover{ color: white; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { border:1px solid #ccc; margin: 0 0 0px 0; height: 2.9rem; } select { border: 1px solid #ccc !important; } .star{ font-size:15px; color:#ff0000; } table{ margin-bottom:15px; } table, th, td { border: 1px solid #522276; border-collapse: collapse; } th, td { padding: 5px 15px; } table, td:last-child{ border:0px; } thead { border-bottom: 0px solid #d0d0d0; background-color: #dbd0e1; border: 0px solid #055E87; color: #522276; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Edit Problem Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>problemcategory/update_prob_category" method="post"> <table id="myTable"> <thead> <tr> <th>Problem Code <span class="star">*</span></th> <th style="width:30%">Model <span class="star">*</span></th> <th>Problem Category Name <span class="star">*</span></th> <th>Description</th> </tr> </thead> <tbody> <?php //print_r($list); foreach($list As $key){?> <tr> <td> <input type="text" name="prob_code[]" readonly id="prob_code" class="prob_code" maxlength="30" value="<?php echo $key->prob_code; ?>"> <div id="name_error" style="color:red"></div> <div id="prob_code_error" style="color:red"></div> <input type="hidden" name="prob_catid" class="corporate" value="<?php echo $key->id; ?>"> </td> <td> <select name="model[]" id="model"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ if($modelkey->id==$key->modelid){ ?> <option selected="selected" value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } else{?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } } ?> </select> <div id="model_error" style="color:red;"></div> </td> <td> <input type="text" name="prob_cat_name[]" class="corporate" value="<?php echo $key->prob_category; ?>" maxlength="50" id="prob_cat_name"> <div id="prob_cat_name_error" style="color:red"></div> </td> <td> <textarea name="p_description[]" id="p_description" maxlength="500" ><?php echo $key->prob_description; ?></textarea> </td> <input type="hidden" id="countid" value="1"> <td> <a class="link" id="addMoreRows"><i class="fa fa-plus-square" aria-hidden="true"></i></a> </td> </tr> <!--<div class="col-md-12" style="padding:0px"> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Code <span class="star">*</span></label> <input type="text" name="prob_code[]" readonly id="prob_code" class="prob_code" maxlength="30" value="<?php echo $key->prob_code; ?>"> <div id="name_error" style="color:red"></div> <div id="prob_code_error" style="color:red"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Category Name <span class="star">*</span></label> <input type="text" name="prob_cat_name[]" class="corporate" value="<?php echo $key->prob_category; ?>" maxlength="30"> <div id="prob_cat_name_error" style="color:red"></div> <input type="hidden" name="prob_catid" class="corporate" value="<?php echo $key->id; ?>"> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Model <span class="star">*</span></label> <select name="model[]" id="model"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ if($modelkey->id==$key->modelid){ ?> <option selected="selected" value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } else{?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } } ?> </select> <div id="model_error" style="color:red;"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Description</label> <textarea name="p_description[]" id="p_description" maxlength="500" ><?php echo $key->prob_description; ?></textarea> </div> </div>--> <input type="hidden" id="countid" value="1"> <?php } ?> </tbody> </table> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action" id="product">Submit</button> <!-- <a class="link" href='' onclick='$("<tr> <td><input type=\"text\" name=\"prob_code[]\" /></td> <td><input type=\"text\" name=\"prob_cat_name[]\" /></td><td><select name=\"model[]\" data-placeholder=\"Select Model...\" class=\"chosen-select\" tabindex=\"2\"><option value=\"\">---Select---</option><?php //foreach($modellist as $modelkey){ ?><option value=\"<?php //echo $modelkey->id; ?>\"><?php //echo $modelkey->model; ?></option><?php //} ?></select></td> <td><textarea name=\"p_description[]\" /></textarea></td></tr>").appendTo($("#myTable")); return false;'>Add Category</a><button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> --> </form> </div> </div> </div> </div> </div> </div> </section> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views_bkMarch_0817/service_cat_list.php <style> .ui-state-default { background: #fff !important; border: 3px solid #fff !important; color: #303f9f !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=text]{ background-color: transparent; border: 0px solid #eee; border-radius: 7; width: 55% !important; font-size: 12px; margin: 0 0 -2px 0; padding: 3px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height:17px; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); service_cat = $("#service_cat_name_"+id).val(); service_charge = $("#service_charge_"+id).val(); //alert(service_charge); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Servicecategory/update_serv_category', data: {'id' : id, 'service_category' : service_cat, 'service_charge' : service_charge}, dataType: "text", cache:false, success: function(data){ alert("Service Category updated"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Servicecategory/del_serv_category', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/service_cat_list"; } alert("Product Category deleted"); } }); }); } </script> <section id="content"> <div class="container"> <div class="section"> <h2>Service Category List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/servicescat.png" title="Add Service Category" style="width:24px;">Add Service Category</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Service Category" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr> <td style="text-align:center;font-size:13px;color:##303f9f;">Service Category Name</td> <td style="text-align:center;font-size:13px;color:##303f9f;">Action</td> </tr> </thead> <tbody> <?php foreach($list as $key){ ?> <tr> <td><input type="text" value="<?php echo $key->service_category; ?>" class="" name="service_cat_name" id="service_cat_name_<?php echo $key->id; ?>" readonly></td> <td class="options-width" style="text-align:center;"> <a href="<?php echo base_url(); ?>Servicecategory/update_service_cat/<?php echo $key->id; ?>" style="padding-right:10px;"><i class="fa fa-pencil" aria-hidden="true"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> <a href="#" style="padding-right:10px;"><i class="fa fa-trash-o" aria-hidden="true"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/workin_prog_list.php <style> h2{ font-size:1.5em; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border-top: 1px solid #eee !important; border-right: 1px solid #eee !important; border-bottom: 1px solid #eee !important; border-left: 1px solid transparent !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; /*background-color: white;*/ } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff; } table.dataTable.display tbody tr.odd>.sorting_1, table.dataTable.order-column.stripe tbody tr.odd>.sorting_1 { background-color: transparent !important; } b{ font-size:1.1em; } label{ font-weight:normal; } .odd .sorting_1 .color{ border-left:2px solid #ff00D0 !important; padding:5px 0 0 15px; margin:2px; } .even .sorting_1 .color{ border-left:2px solid #ff88A0 !important; padding:5px 0 0 15px; margin:2px; } p { margin: 0 0 3px; } .calendar-icon{ font-size:13px !important; } p > .calendar-icon{ text-align:center !important; } .first-span{ margin-right:10px; } /* Hide header from DataTables */ /*.row th{ display:none; }*/ h2 { /* font-size: 3.56rem; */ /* line-height: 3.916rem; */ margin: 0 !important; } .reqid,.machinestatus,.cusname{ display:block !important; } .respan,.redate{ display:none !important; } @media only screen and (min-width:320px) and (max-width:768px){ .coloricon { background-image: url(http://192.168.1.55/service/assets/images/icon.png); height: 30px; width: 30px; background-repeat: no-repeat; background-size: cover; background-color: transparent; position: relative; left: 385px !important; } .reqid,.machinestatus,.cusname{ display:none !important; } .respan,.redate{ display:block !important; } .row th{ display:none; } .odd .color{ border-left:2px solid #ddd !important; padding:5px 0 0 15px; margin:2px; } .even .color{ border-left:2px solid #eaeaea !important; padding:5px 0 0 15px; margin:2px; } h2{ font-size:1.3em; } .saturate{ width: 200px !important; height: 50px; color: #fff; } input[type=search] { background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 350px !important; font-size: 1.5rem; margin: 0 0 15px 0; /* padding: 1px; */ box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; position: relative; color:#000; } .dataTables_wrapper .dataTables_filter { float: none; text-align: left; } #data-table-simple_filter label { font-size: 15px !important; color: transparent !important; } } .dataTables_filter label{ color:#6C217E !important; } .reqid a{ color:#6C217E !important; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Work In Progress List</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-xs-12 table-responsive"> <table id="data-table-simple" class="display"> <thead> <tr> <th>Request Id</th> <th class="row2">Customer Name</th> <th>Machine Status</th> <!--<th>Service Type</th>--> <!--<th>Requested Date</th> <th>Assign To</th> <th>Site</th> <th>Location</th>--> <!--<th>Problem</th> <th>Status</th>--> </tr> </thead> <tbody> <?php foreach($workin_prog_list as $key){ $reid= sprintf("%05d", $key->id) ?> <tr> <td class="reqid"> <a href="<?php echo base_url(); ?>work_inprogress/workin_prog_status/<?php echo $reid; ?>"><?php echo $key->request_id; ?></a> </td> <td> <div class="color"> <p class="cusname"><?php echo $key->customer_name; ?></p> <p class="respan"> <b><?php echo $key->customer_name; ?></b> <p class="respan"> <span class="first-span"> <a href="<?php echo base_url(); ?>work_inprogress/workin_prog_status/<?php echo $reid; ?>"><?php echo $key->request_id; ?></a> </span> <span class="first-span"> <a href="<?php echo base_url(); ?>work_inprogress/workin_prog_status/<?php echo $reid; ?>">Model 123456789</a> </span> </p> <p class="respan"> <?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?> </p> </p> </div> </td> <!--<td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->model;} } ?></td>--> <td> <p class="machinestatus"><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?> </p> <p class="redate"> <i class="fa fa-calendar calendar-icon"></i> </p> <p class="redate"> 07 Feb'17 </p> </td> <!--<td><?php foreach($service_req_listforserviceCat as $servicecatkey){ if($servicecatkey->request_id==$key->id){ echo $servicecatkey->service_category;} } ?></td>--> <!--<td><?php echo $key->request_date; ?></td>--> <!--<td><?php foreach($service_req_listforEmp as $key2){ if($key2->request_id==$key->id){ echo $key2->emp_name; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->site; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->service_loc; } } ?></td>--> <!--<td><?php foreach($service_req_listforProb as $servprobkey2){ if($servprobkey2->request_id==$key->id){ echo $servprobkey2->prob_category; } } ?></td>--> <!--<td>Work In Progress</td>--> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script> $(function(){ $('.dataTables_filter input').attr("placeholder", "Search"); $('.dataTables_filter input').focus(function(){ $(this).attr("placeholder", ""); }); $('.dataTables_filter input').focusout(function(){ $(this).attr("placeholder", "Search"); }); }); </script> </body> </html><file_sep>/application/controllers/Spare.php <?php class Spare extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Spare_model'); } public function getcust_name(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->getcust_name($id))); } public function get_spares_byReqId(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_spares_byReqId($id))); } public function get_productinfobyid(){ $id=$this->input->post('modelno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_productdetbyid($id))); } public function spareListByModelId(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->spareListByModelId($id))); } public function add_spare(){ //echo "<pre>";print_r($_POST);exit; $user=$this->input->post('spare_name'); if($this->Spare_model->checksparename($user)) { echo "<script>window.location.href='".base_url()."pages/add_new_stock';alert(' Spare Name already exist');</script>"; }else{ if($this->input->post('Save') == "saveit") { $data['spare_name']=$this->input->post('spare_name'); //$data['spare_qty']=$this->input->post('spare_qty'); //$data['stock_spare']=$this->input->post('spare_qty'); //$data['purchase_price']=$this->input->post('purchase_price'); $data['sales_price']=$this->input->post('sales_price'); $data['effective_date']=$this->input->post('datepicker'); $data['part_no']=$this->input->post('part_no'); $data['min_qty']=$this->input->post('reorder'); $pro_cat=$this->input->post('category'); $sub_catname=$this->input->post('subcategory'); $brand_name=$this->input->post('brandname'); $model=$this->input->post('model'); $ids=$this->input->post('countidss'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d"); $c=$pro_cat; $count=count($c); $result=$this->Spare_model->add_spares($data); $resu=$this->Spare_model->add_spares_effective_date_his($data); if($result){ $i=0; $data1 =array(); for($i=0; $i<$count; $i++) { /* $data7['model']['cnt'] = $this->input->post('model'.$idd); if (is_array($data7['model']['cnt'])){ $modelss = implode(",",$data7['model']['cnt']); }else{ $modelss=""; } */ $data1[] = array( 'spare_id' => $result, 'cat_id' => $pro_cat[$i], 'subcat_id' => $sub_catname[$i], 'brand_id' => $brand_name[$i], 'model_id' => $model[$i] ); } /* echo "<pre>"; print_r($data1); exit; */ $result1=$this->Spare_model->add_spare_details($data1); if($result){ echo "<script>alert('Spare Added Successfully!!!');window.location.href='".base_url()."pages/add_spare';</script>"; } } } else { $data['spare_name']=$this->input->post('spare_name'); //$data['spare_qty']=$this->input->post('spare_qty'); //$data['stock_spare']=$this->input->post('spare_qty'); //$data['purchase_price']=$this->input->post('purchase_price'); $data['sales_price']=$this->input->post('sales_price'); $data['effective_date']=$this->input->post('datepicker'); $pro_cat=$this->input->post('category'); $sub_catname=$this->input->post('subcategory'); $brand_name=$this->input->post('brandname'); $model=$this->input->post('model'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d"); $c=$pro_cat; $count=count($c); $result=$this->Spare_model->add_spares($data); $resu=$this->Spare_model->add_spares_effective_date_his($data); if($result){ $data1 =array(); for($i=0; $i<$count; $i++) { $data1[] = array( 'spare_id' => $result, 'cat_id' => $pro_cat[$i], 'subcat_id' => $sub_catname[$i], 'brand_id' => $brand_name[$i], 'model_id' => $model[$i] ); } $result1=$this->Spare_model->add_spare_details($data1); if($result){ echo "<script>alert('Spare Added Successfully!!!');window.location.href='".base_url()."pages/add_new_stock';</script>"; } } } } } public function add_purchase_order(){ //echo "<pre>";print_r($_POST);exit; $data['to_name']=$this->input->post('to_name'); $data['to_addr']=$this->input->post('to_addr'); $data['to_cont_name']=$this->input->post('to_cont_name'); $data['to_cont_no']=$this->input->post('to_cont_no'); $data['to_cont_mail']=$this->input->post('to_cont_mail'); $data['todaydate']=$this->input->post('todaydate'); $data['refno']=$this->input->post('refno'); $data['cst_no']=$this->input->post('cst_no'); $cst1 = $this->input->post('cst1'); $cst1_arr = explode('-',$cst1); $data['tax_id'] = $cst1_arr['0']; $sr_no=$this->input->post('sr_no'); $spare_name=$this->input->post('spare_name'); $spare_qty=$this->input->post('spare_qty'); $rate=$this->input->post('rate'); $spare_tot=$this->input->post('spare_tot'); $data['basicamount']=$this->input->post('basicamount'); $data['cst']=$this->input->post('cst'); $data['freight']=$this->input->post('freight'); $data['totalamount']=$this->input->post('totalamount'); $data['spec_addr']=$this->input->post('spec_addr'); $data['spec_ins']=$this->input->post('spec_ins'); $c=$spare_name; $count=count($c); $result=$this->Spare_model->add_purchase_order($data); if($result){ $i=0; $data1 =array(); for($i=0; $i<$count; $i++){ if($sr_no[$i] !=''){ $data1[] = array( 'purchase_order_id' => $result, 'sr_no' => $sr_no[$i], 'spare_name' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'rate' => $rate[$i], 'spare_tot' => $spare_tot[$i] ); } } /* echo "<pre>"; print_r($data1); exit; */ $result1=$this->Spare_model->add_purchase_order_details($data1); if($result){ echo "<script>alert('Purchase order Added Successfully!!!');window.location.href='".base_url()."pages/purchase_orders';window.open('".base_url()."Spare/print_purchase_order/".$result."')</script>"; } } } public function addrow1(){ $data['count']=$this->input->post('countid'); $prod_cat = $this->input->post('prod_cat'); if($prod_cat!=""){ $data['spare_catId'] = $this->Spare_model->get_sparenamebycat($prod_cat); } // $modelid=$this->input->post('modelid'); //$data['spareListByModelId']=$this->Spare_model->spareListByModelId($modelid); $this->load->view('add_spares_pop',$data); } public function addrowminus(){ $data['count']=$this->input->post('countid'); $prod_cat = $this->input->post('prod_cat'); if($prod_cat!=""){ $data['spare_catId'] = $this->Spare_model->get_sparenamebycat($prod_cat); } // $modelid=$this->input->post('modelid'); //$data['spareListByModelId']=$this->Spare_model->spareListByModelId($modelid); $this->load->view('minus_spares_pop',$data); } public function update_important(){ $id=$this->input->post('id'); $data=array( 'dashboard_show'=>$this->input->post('dashboard_show') ); $s = $this->Spare_model->update_dash_important($data,$id); } public function edit_purchase_order(){ $id = $this->uri->segment(3); $data1['comp_info'] = $this->Spare_model->get_compinfo(); $data1['get_purchase_ordersbyid'] = $this->Spare_model->get_purchase_ordersbyid($id); $data1['get_purchase_orders_sparesbyid'] = $this->Spare_model->get_purchase_orders_sparesbyid($id); $data1['spare_list']=$this->Spare_model->spare_list_engineers(); $data1['tax_list']=$this->Spare_model->tax_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_spare_purchase_order',$data1); } public function print_purchase_order(){ $id = $this->uri->segment(3); $data1['comp_info'] = $this->Spare_model->get_compinfo(); $data1['get_purchase_ordersbyid'] = $this->Spare_model->get_purchase_ordersbyid($id); $data1['get_purchase_orders_sparesbyid'] = $this->Spare_model->get_purchase_orders_sparesbyid($id); $data1['spare_list']=$this->Spare_model->spare_list_engineers(); $data1['tax_list']=$this->Spare_model->tax_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spare_purchase_print',$data1); } public function update_purchase_order(){ //echo "<pre>";print_r($_POST);exit; $po_id=$this->input->post('po_id'); $data['to_name']=$this->input->post('to_name'); $data['to_addr']=$this->input->post('to_addr'); $data['to_cont_name']=$this->input->post('to_cont_name'); $data['to_cont_no']=$this->input->post('to_cont_no'); $data['to_cont_mail']=$this->input->post('to_cont_mail'); $data['todaydate']=$this->input->post('todaydate'); $data['refno']=$this->input->post('refno'); $data['cst_no']=$this->input->post('cst_no'); $sr_no=$this->input->post('sr_no'); $spare_name=$this->input->post('spare_name'); $spare_qty=$this->input->post('spare_qty'); $rate=$this->input->post('rate'); $spare_tot=$this->input->post('spare_tot'); $data['basicamount']=$this->input->post('basicamount'); $data['cst']=$this->input->post('cst'); $data['freight']=$this->input->post('freight'); $data['totalamount']=$this->input->post('totalamount'); $data['spec_addr']=$this->input->post('spec_addr'); $data['spec_ins']=$this->input->post('spec_ins'); $c=$spare_name; $count=count($c); $this->Spare_model->update_purchase_order($data,$po_id); $this->Spare_model->delete_purchase_order($po_id); //$check=$this->input->post('$sr_no'); $data1 =array(); for($i=0; $i<$count; $i++){ if($sr_no[$i] !=''){ $data1[] = array( 'purchase_order_id' => $po_id, 'sr_no' => $sr_no[$i], 'spare_name' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'rate' => $rate[$i], 'spare_tot' => $spare_tot[$i] ); } } $result1=$this->Spare_model->add_purchase_order_details($data1); echo "<script>alert('Purchase order updated Successfully!!!');window.location.href='".base_url()."pages/purchase_orders';</script>"; } public function addrow2(){ $data['count']=$this->input->post('countid'); $data['customerlist']=$this->Spare_model->customerlist(); $data['spare_list']=$this->Spare_model->spare_list_engineers(); $data['engg_list']=$this->Spare_model->engineer_list(); $data['reqview']=$this->Spare_model->reqlist(); // $modelid=$this->input->post('modelid'); //$data['spareListByModelId']=$this->Spare_model->spareListByModelId($modelid); $this->load->view('add_spares_engg_row',$data); } public function addrow_purchase_order(){ $data['count']=$this->input->post('countid'); $data['spare_list']=$this->Spare_model->spare_list_engineers(); $data['engg_list']=$this->Spare_model->engineer_list(); $data['reqview']=$this->Spare_model->reqlist(); // $modelid=$this->input->post('modelid'); //$data['spareListByModelId']=$this->Spare_model->spareListByModelId($modelid); $this->load->view('add_purchase_order_row',$data); } public function edit_spare(){ //echo "<pre>";print_r($_POST);exit; $new=$this->input->post('spare_name'); $old=$this->input->post('spare_name1'); if($new==$old) { $id=$this->input->post('spareid'); $data=array( 'spare_name'=>$this->input->post('spare_name'), 'part_no'=>$this->input->post('part_no'), 'sales_price'=>$this->input->post('sales_price'), 'effective_date'=>$this->input->post('datepicker'), 'min_qty'=>$this->input->post('reorder') ); $this->Spare_model->update_spares($data,$id); $data2['spare_name']=$this->input->post('spare_name'); $data2['sales_price']=$this->input->post('sales_price'); $data2['effective_date']=$this->input->post('datepicker'); $data2['min_qty']=$this->input->post('reorder'); $resu=$this->Spare_model->add_spares_effective_date_his($data2); $pro_cat=$this->input->post('category'); $sub_catname=$this->input->post('subcategory'); $brand_name=$this->input->post('brandname'); $model=$this->input->post('model'); $ids=$this->input->post('countidss'); $c=$pro_cat; $count=count($c); $this->Spare_model->del_spare_details($id); $data1 =array(); for($i=0;$i<$count;$i++){ //$data7['model']['cnt'] = $this->input->post('model'.$idd); //echo "<pre>"; // print_r($data7); /* if(is_array($data7['model']['cnt'])){ $modelss = implode(",",$data7['model']['cnt']); }else{ $modelss=""; } */ $data1[] = array( 'spare_id' => $id, 'cat_id' => $pro_cat[$i], 'subcat_id' => $sub_catname[$i], 'brand_id' => $brand_name[$i], 'model_id' => $model[$i] ); } // exit; $result1=$this->Spare_model->add_spare_details($data1); echo "<script>alert('Spare Updated Successfully!!!');window.location.href='".base_url()."pages/add_spare';</script>"; }else{ $user=$this->input->post('spare_name'); if($this->Spare_model->checksparename($user)) { $spareid=$this->input->post('spareid'); //print_r ($brandid);exit; echo "<script>window.location.href='".base_url()."Spare/update_spare/'+$spareid;alert(' Spare Name already exist');</script>"; } else{ $id=$this->input->post('spareid'); $data=array( 'spare_name'=>$this->input->post('spare_name'), 'part_no'=>$this->input->post('part_no'), 'sales_price'=>$this->input->post('sales_price'), 'effective_date'=>$this->input->post('datepicker'), 'min_qty'=>$this->input->post('reorder') ); $this->Spare_model->update_spares($data,$id); $data2['spare_name']=$this->input->post('spare_name'); $data2['sales_price']=$this->input->post('sales_price'); $data2['effective_date']=$this->input->post('datepicker'); $data2['min_qty']=$this->input->post('reorder'); $resu=$this->Spare_model->add_spares_effective_date_his($data2); $pro_cat=$this->input->post('category'); $sub_catname=$this->input->post('subcategory'); $brand_name=$this->input->post('brandname'); $model=$this->input->post('model'); $ids=$this->input->post('countidss'); $c=$pro_cat; $count=count($c); $this->Spare_model->del_spare_details($id); $data1 =array(); for($i=0;$i<$count;$i++){ //$data7['model']['cnt'] = $this->input->post('model'.$idd); //echo "<pre>"; // print_r($data7); /* if(is_array($data7['model']['cnt'])){ $modelss = implode(",",$data7['model']['cnt']); }else{ $modelss=""; } */ $data1[] = array( 'spare_id' => $id, 'cat_id' => $pro_cat[$i], 'subcat_id' => $sub_catname[$i], 'brand_id' => $brand_name[$i], 'model_id' => $model[$i] ); } // exit; $result1=$this->Spare_model->add_spare_details($data1); echo "<script>alert('Spare Updated Successfully!!!');window.location.href='".base_url()."pages/add_spare';</script>"; } } } public function add_spare_engineers(){ $data['eng_name']=$this->input->post('eng_name'); $data['spare_name']=$this->input->post('spare_name'); $data['qty']=$this->input->post('qty'); $result=$this->Spare_model->add_spares_engineers($data); } /* public function add_spare_engg(){ $eng_name=$data1['emp_id']=$this->input->post('eng_name'); $eng_spare_name=$data1['spare_id']=$this->input->post('eng_spare_name'); $plus=$data1['qty_out']=$this->input->post('plus'); $minus=$data1['qty_in']=$this->input->post('minus'); $engg_date=$data1['engineer_date']=$this->input->post('engg_date'); $engg_reason=$data1['reason']=$this->input->post('engg_reason'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $used_spare=$data1['used_spare']=$this->input->post('used_spare'); $c=$eng_name; $count=count($c); $data1 =array(); for($i=0; $i<$count; $i++) { if($plus[$i]!="" || $minus[$i]!=""){ if($plus[$i]!=""){ $stock_qty = $spare_qty[$i]- $plus[$i]; $used_spare1 = $used_spare[$i] + $plus[$i]; } if($minus[$i]!=""){ $stock_qty = $spare_qty[$i] + $minus[$i]; $used_spare1 = $used_spare[$i] - $minus[$i]; } $data3[] = array( 'id'=>$eng_spare_name[$i], 'spare_qty'=>$stock_qty, 'used_spare'=>$used_spare1 ); $this->Spare_model->update_spare_enggs($data3); } $data1[] = array( 'emp_id'=>$eng_name[$i], 'spare_id'=>$eng_spare_name[$i], 'qty_out'=>$plus[$i], 'qty_in'=>$minus[$i], 'engineer_date'=>$engg_date[$i], 'reason'=>$engg_reason[$i] ); } $this->Spare_model->add_spare_enggs($data1); echo "<script>alert('Spares For Engineers Added');window.location.href='".base_url()."pages/spare_stock';</script>"; } */ public function update_spare_req(){ $id = $this->uri->segment(3); $data['eng_name'] = $this->uri->segment(4); $data['cust'] = $this->uri->segment(5); $data['get_spare_details_reqid']=$this->Spare_model->get_spare_details_reqid($id); $data['get_spare_to_enggByReqid']=$this->Spare_model->get_spare_to_enggByReqid($id); //$data['get_spare_stocks_byreqid']=$this->Spare_model->get_spare_stocks_byreqid($id); $this->load->view('update_spare_req',$data); } public function addsparedetails() { $spare_id = $data['spare_id'] = $this->input->post('spare'); $emp_id = $data['employee'] = $this->input->post('employee'); date_default_timezone_set('Asia/Calcutta'); $data['todaydate'] = date("d-m-Y H:i:s"); if($this->input->post('plus')) { $plus = $data['qty_plus'] = $this->input->post('plus'); $m_data['qty_plus'] = $this->input->post('plus'); $m_data['status']='1'; }else{ $minus = $data['qty_plus'] = $this->input->post('minus'); $m_data['qty_plus'] = $this->input->post('minus'); $m_data['status']='2'; } $m_data['spare_id'] = $this->input->post('spare'); $m_data['employee'] = $this->input->post('employee'); $m_data['todaydate'] = date("d-m-Y H:i:s"); $this->Spare_model->addpettylog($m_data); $list = $this->Spare_model->getpetsparelist($spare_id,$emp_id); if($list > 0) { $result = $this->Spare_model->getpettyspare($spare_id,$emp_id); extract($result); $g = $this->Spare_model->getsparelist($spare_id); extract($g); if($this->input->post('plus')!=""){ $s = $plus + $qty_plus; $p_data=array( 'qty_plus'=>$s, ); $tot_qty = $spare_qty - $plus; $totusdspare = $used_spare + $plus; $totengspare = $eng_spare + $plus; $t_data=array( 'spare_qty'=>$tot_qty ); } if($this->input->post('minus')!=""){ $p = $qty_plus - $minus; $p_data=array( 'qty_plus'=>$p, ); $tot_qty = $spare_qty + $minus; $totusdspare = $used_spare - $minus; $totengspare = $eng_spare - $minus; $t_data=array( 'spare_qty'=>$tot_qty ); } $where = "spare_id=".$spare_id." AND employee=".$emp_id; $this->Spare_model->updatepspare($p_data,$where); $this->Spare_model->updatepettyspare($spare_id,$t_data); }else{ $this->Spare_model->addpettyspare($data); $g = $this->Spare_model->getsparelist($spare_id); extract($g); if($this->input->post('plus')!=""){ $tot_qty = $spare_qty - $plus; $totusdspare = $used_spare + $plus; $totengspare = $eng_spare + $plus; $t_data=array( 'spare_qty'=>$tot_qty ); } if($this->input->post('minus')!=""){ $tot_qty = $spare_qty + $minus; $totusdspare = $used_spare - $minus; $totengspare = $eng_spare - $minus; $t_data=array( 'spare_qty'=>$tot_qty ); } $this->Spare_model->updatepettyspare($spare_id,$t_data); } echo "<script>alert('Petty Spare Updated Successfully!!!');window.location.href='".base_url()."pages/petty_spare';</script>"; } public function add_spare_engg(){ /* $data5['spare_to_engg_cnt']=$this->Spare_model->spare_to_engg_cnt(); if(empty($data5['spare_to_engg_cnt'])){ $sp_id='1'; }else{ $cusid = $data5['spare_to_engg_cnt'][0]->id; $sp_id = $cusid + 1; } */ $eng_name=$data1['emp_id']=$this->input->post('eng_name'); $eng_spare_name=$data1['spare_id']=$this->input->post('eng_spare_name'); $eng_plus=$data1['qty_out']=$this->input->post('plus'); $eng_minus=$data1['qty_in']=$this->input->post('minus'); $engg_date=$data1['engineer_date']=$this->input->post('engg_date'); $engg_reason=$data1['reason']=$this->input->post('engg_reason'); $spare_amt = $this->input->post('amt1'); // $this->Spare_model->add_spare_enggs($data1); //$spare_receipt=$this->input->post('spare_receipt'); $spare_qty = $this->input->post('spare_qty'); $used_spare = $this->input->post('used_spare'); $eng_spare = $this->input->post('eng_spare'); //$eng_spare = $this->input->post('eng_spare'); $plus = $this->input->post('plus'); $minus = $this->input->post('minus'); $req_id = $this->input->post('req_id'); $cust_name = $this->input->post('cust'); $quote_rev_id = $this->input->post('quote_rev_id'); $c=$eng_spare_name; $count=count($c); //$this->Quotereview_model->delete_quote_review($reqid); //$j = $sp_id; $data2 =array(); for($i=0; $i<$count; $i++) { //$spare_arr = explode('-',);$eng_spare_name[$i] $quote_review_id = $quote_rev_id[$i]; $getsparebyid = $this->Spare_model->getsparebyid($eng_spare_name[$i]); $spare_qt = $getsparebyid[0]->spare_qty; $used_spar = $getsparebyid[0]->used_spare; $eng_spar = $getsparebyid[0]->eng_spare; $where = "spare_id=".$eng_spare_name[$i]." AND employee=".$eng_name[$i]; $res = $this->Spare_model->getupspare($where); $qty = $res[0]->qty_plus; if($plus[$i]!=""){ if($qty!="" && $qty!="0"){ $p_qty = $qty + $eng_plus[$i]; $n_data=array( 'qty_plus'=>$p_qty ); $this->Spare_model->updatepspare($n_data,$where); }else{ $p_qty = 0 + $eng_plus[$i]; $n_data=array( 'qty_plus'=>$p_qty, 'spare_id'=>$eng_spare_name[$i], 'employee'=>$eng_name[$i], 'todaydate'=>$engg_date[$i], ); $this->Spare_model->addpettyspare($n_data,$where); } } /* echo "<pre>"; print_r($getsparebyid); exit; */ if(isset($req_id[$i]) && $req_id[$i]!="" && $eng_plus[$i]!="" && $eng_plus[$i]!="0"){ $data12 = array( 'spare_engg_id' => '1', 'approval_status' => $this->input->post('approval_status') ); $this->Spare_model->update_quotereview_spares($data12,$quote_review_id); }else if($this->input->post('approval_status')=='rejected'){ $data12 = array( 'spare_engg_id' => '0', 'approval_status' => $this->input->post('approval_status') ); $this->Spare_model->update_quotereview_spares($data12,$quote_review_id); } /* if(isset($req_id[$i]) && $req_id[$i]!="" && $eng_minus[$i]){ $this->Spare_model->del_eng_spare($req_id[$i],$eng_spare_name[$i]); } */ if($req_id[$i]!=""){ $service_status = 'with_service'; }else{ $service_status = 'without_Service'; } $data2[] = array( 'emp_id' => $eng_name[$i], 'spare_id' => $eng_spare_name[$i], 'qty_out' => $eng_plus[$i], //'qty_in' => $eng_minus[$i], 'engineer_date' => $engg_date[$i], 'req_id' => $req_id[$i], 'cust_name' => $cust_name[$i], 'reason' => $engg_reason[$i], 'spare_receipt' => $service_status, 'auto_cnt' => '0' ); if($plus[$i]!="" || $minus[$i]!=""){ if($plus[$i]!=""){ $eng_spares = $eng_spar + $plus[$i]; } if($minus[$i]!=""){ $eng_spares = $eng_spar - $minus[$i]; } $data5 = array( 'eng_spare'=>$eng_spares ); //$this->Spare_model->update_eng_spare($data5,$eng_spare_name[$i]); } if($plus[$i]!=""){ if($plus[$i]!=""){ $stock_qty = $spare_qt - $plus[$i]; } $data3 = array( 'spare_qty'=>$stock_qty ); $this->Spare_model->update_spare_enggs($data3,$eng_spare_name[$i]); } //$j++; } /* if(!empty($data3)){ $this->Spare_model->update_spare_enggs($data3); } */ /* if(!empty($data5)){ echo "<pre>"; print_r($data5);exit; $this->Spare_model->update_eng_spare($data5); } */ $this->Spare_model->add_spare_enggs($data2); echo "<script>parent.$.fancybox.close();</script>"; //echo "<script>alert('Spares For Engineers Added');window.location.href='".base_url()."pages/spare_stock';</script>"; } public function del_spare_to_enggs(){ $id = $this->input->post('id'); //print_r($id); $spareid = $this->input->post('spareid'); $reqid = $this->input->post('reqid'); $qty = $this->input->post('qty'); $auto_cnt = $this->input->post('auto_cnt'); //print_r("hiii"); //exit; if($qty!="" && $qty!="0"){ $this->Spare_model->del_spare_to_enggs($id); $getsparebyid = $this->Spare_model->getsparebyid($spareid); $spare_qt = $getsparebyid[0]->spare_qty; $used_spar = $getsparebyid[0]->used_spare; $eng_spar = $getsparebyid[0]->eng_spare; $this->Spare_model->del_quote_spares($reqid,$spareid); $stock_qty = $spare_qt + $qty; $used_spare = $used_spar - $qty; $eng_spare = $eng_spar - $qty; $data3 = array( 'spare_qty'=>$stock_qty, 'used_spare'=>$used_spare, 'eng_spare'=>$eng_spare, ); $this->Spare_model->update_spare_status($data3,$spareid); } } public function update_spare_stock(){ $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $qty=$data1['qty']=$this->input->post('qty'); $purchase_date=$data1['purchase_date']=$this->input->post('purchase_date'); $purchase_price=$data1['purchase_price']=$this->input->post('purchase_price'); $invoice_no=$data1['invoice_no']=$this->input->post('invoice_no'); $reason=$data1['reason']=$this->input->post('reason'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spare1=$data1['used_spare1']=$this->input->post('used_spare1'); $purchase_price1=$data1['purchase_price1']=$this->input->post('purchase_price1'); $purchase_qty1=$data1['purchase_qty1']=$this->input->post('purchase_qty1'); $c=$spare_name; $count=count($c); $data1 =array(); for($i=0; $i<$count; $i++) { // if($stats=='2'){ // $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; //$used_spare = $spare_qty[$i] + $used_spares[$i]; $getsparebyid = $this->Spare_model->getsparebyid($spare_name[$i]); $spare_qt = $getsparebyid[0]->spare_qty; $used_spar = $getsparebyid[0]->used_spare; $purchase_qt = $getsparebyid[0]->purchase_qty; $purchase_pric = $getsparebyid[0]->purchase_price; $purchase_qty = $purchase_qt + $qty[$i]; $spare_qty= $purchase_qty - $used_spar; /* if($purchase_date[$i]!=""){ $purchase_date = $purchase_date[$i]; } if($purchase_price[$i]!=""){ $purchase_price = $purchase_price[$i]; } */ $data2 = array( 'purchase_qty'=>$purchase_qty, 'spare_qty'=>$spare_qty, 'used_spare'=>$used_spar, 'purchase_date'=>$purchase_date[$i], 'purchase_price'=>$purchase_price[$i], 'invoice_no'=>$invoice_no[$i], 'reason'=>$reason[$i] ); $data_pur_add = array( 'spare_id'=>$spare_name[$i], 'purchase_qty'=>$qty[$i], 'purchase_date'=>$purchase_date[$i], 'purchase_price'=>$purchase_price[$i], 'invoice_no'=>$invoice_no[$i], 'reason'=>$reason[$i] ); $this->Spare_model->update_spare_balance($data2,$spare_name[$i]); $this->Spare_model->add_purchase_details($data_pur_add); } echo "<script> parent.jQuery.fancybox.close();</script>"; //redirect('pages/spare_stock', 'refresh'); } public function update_spare_stockminus(){ $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $qty=$data1['qty']=$this->input->post('qty'); $purchase_date=$data1['purchase_date']=$this->input->post('purchase_date'); //$purchase_price=$data1['purchase_price']=$this->input->post('purchase_price'); //$invoice_no=$data1['invoice_no']=$this->input->post('invoice_no'); $reason=$data1['reason']=$this->input->post('reason'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spare1=$data1['used_spare1']=$this->input->post('used_spare1'); $purchase_price1=$data1['purchase_price1']=$this->input->post('purchase_price1'); $purchase_qty1=$data1['purchase_qty1']=$this->input->post('purchase_qty1'); $c=$spare_name; $count=count($c); $data1 =array(); for($i=0; $i<$count; $i++) { // if($stats=='2'){ // $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; //$used_spare = $spare_qty[$i] + $used_spares[$i]; $getsparebyid = $this->Spare_model->getsparebyid($spare_name[$i]); $spare_qt = $getsparebyid[0]->spare_qty; $used_spar = $getsparebyid[0]->used_spare; $purchase_qt = $getsparebyid[0]->purchase_qty; //$purchase_pric = $getsparebyid[0]->purchase_price; $purchase_qty = $purchase_qt - $qty[$i]; $spare_qty= $purchase_qty - $used_spar; /* if($purchase_date[$i]!=""){ $purchase_date = $purchase_date[$i]; } if($purchase_price[$i]!=""){ $purchase_price = $purchase_price[$i]; } */ $data2 = array( 'purchase_qty'=>$purchase_qty, 'spare_qty'=>$spare_qty, 'used_spare'=>$used_spar, 'purchase_date'=>$purchase_date[$i], //'purchase_price'=>$purchase_price[$i], //'invoice_no'=>$invoice_no[$i], 'reason'=>$reason[$i] ); $data_pur_add = array( 'spare_id'=>$spare_name[$i], 'return_qty'=>$qty[$i], 'purchase_date'=>$purchase_date[$i], //'purchase_price'=>$purchase_price[$i], //'invoice_no'=>$invoice_no[$i], 'reason'=>$reason[$i] ); $this->Spare_model->update_spare_balance($data2,$spare_name[$i]); $this->Spare_model->add_purchase_details($data_pur_add); } echo "<script>parent.jQuery.fancybox.close();</script>"; } public function getsparedet(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_spareinfobyid($id))); } public function purchase_popup(){ //$id = $this->uri->segment(3); $data1['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); $data1['getbrands']=$this->Spare_model->getbrands(); $data1['getmodels']=$this->Spare_model->getmodels(); //$data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('purchase_spare',$data1); } public function purchase_popupminus(){ //$id = $this->uri->segment(3); $data1['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); $data1['getbrands']=$this->Spare_model->getbrands(); $data1['getmodels']=$this->Spare_model->getmodels(); //$data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('purchase_spareminus',$data1); } public function engineer_stockin(){ //$id = $this->uri->segment(3); //$data1['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); //$data1['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); //$data1['getbrands']=$this->Spare_model->getbrands(); //$data1['getmodels']=$this->Spare_model->getmodels(); //$data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('engineer_stockin'); } public function get_spares(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_sparenamebycat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_sparesbysubcat(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_sparesbysubcat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_sparesbybrand(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_sparesbybrand($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_sparesbymodel(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_sparesbymodel($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_brands())); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Spare_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function addrow(){ $data['count']=$this->input->post('countid'); //echo "Count: ".$data['count']; $data['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); $data['modellist']=$this->Spare_model->modellist(); $this->load->view('add_spare_row',$data); } public function update_spare(){ $id=$this->uri->segment(3); $data['list']=$this->Spare_model->getsparebyid($id); $data['getsparedetbyid']=$this->Spare_model->getsparedetbyid($id); $data['getModels_spareid']=$this->Spare_model->getModels_spareid($id); $data['prodcatlist']=$this->Spare_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Spare_model->prod_sub_cat_dropdownlist(); $data['getbrands']=$this->Spare_model->getbrands(); $data['getmodels']=$this->Spare_model->getmodels(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_spares',$data); } public function getsub_cat(){ $id=$this->input->post('catid');//echo $id; exit; $brid=$this->input->post('brid'); $data=array( 'cat_id'=>$this->input->post('catid') ); $res = $this->Brand_model->update_cat($data,$brid); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Brand_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function updatesub_category(){ $id=$this->input->post('brid'); //$this->input->post('procatid'); $data=array( 'subcat_id'=>$this->input->post('subcatid') ); $s = $this->Brand_model->update_subcat($data,$id); } public function update_brand_name(){ $id=$this->input->post('id'); $data=array( 'brand_name'=>$this->input->post('brand_name') ); $s = $this->Brand_model->update_brandname($data,$id); } public function update_product(){ $id=$this->uri->segment(3); $data['list']=$this->Product_model->getproductbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $data['prodcatlist']=$this->Product_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Product_model->prod_sub_cat_dropdownlist(); $this->load->view('edit_prod_list',$data); } public function edit_product(){ $data = $this->input->post('addlinfo'); $addlnfo= implode(",",$data); // echo $addlnfo;exit; $data=array( 'serial_no'=>$this->input->post('serial_no'), 'product_name'=>$this->input->post('product_name'), 'category'=>$this->input->post('category'), 'subcategory'=>$this->input->post('subcategory'), 'model'=>$this->input->post('model'), 'description'=>$this->input->post('description'), 'addlinfo'=>$addlnfo ); $id=$this->input->post('product_id'); $this->Product_model->edit_products($data,$id); echo "<script>alert('Product Updated');window.location.href='".base_url()."pages/prod_list';</script>"; } public function del_brand(){ $id=$this->input->post('id'); $s = $this->Brand_model->del_brands($id); } public function sparereceipt_service() { $id=$this->uri->segment(3); $data1['servicereceipt']=$this->Spare_model->getengspid($id); $data1['get_tax']=$this->Spare_model->get_tax(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('spareprint_request',$data1); } public function sparereceipt_req(){ // $id=$this->uri->segment(3); // echo $id; $data1['spatax'] = $this->input->post('taxxx'); $data1['tot_amt'] = $this->input->post('tot_amt'); $data1['datepick'] = $this->input->post('returndate'); $data1['para'] = $this->input->post('textarea-input'); $id=$this->input->post('spareenggis'); // echo $id; //echo "hi".$spatax;exit; $data1['receikd']=$this->Spare_model->getengspid($id); //$data1['editreceispare']=$this->Spare_model->getspareengg(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('sparereceipt_request',$data1); } public function view_purchase(){ $id = $this->uri->segment(3); //echo $id; $data1['spare_view']=$this->Spare_model->sparepurchase_view($id); //$data1['sparelist_engg']=$this->Spare_model->sparelist_engg(); //$data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('spare_purchaseview',$data1); } }<file_sep>/application/controllers/Spare_model.php <?php class Spare_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function reqlist() { $this->db->select('*'); $this->db->from('service_request'); $query = $this->db->get(); return $query->result(); } public function get_productdetbyid($id){ $this->db->select("products.id, products.category, products.subcategory, products.brand, products.model, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name",FALSE); $this->db->from('products'); $this->db->join('prod_category', 'prod_category.id = products.category'); $this->db->join('prod_subcategory', 'prod_subcategory.id = products.subcategory'); $this->db->join('brands', 'brands.id = products.brand'); $this->db->where('products.id', $id); $query = $this->db->get(); return $query->result(); } public function modellist(){ $this->db->select("id, model",FALSE); $this->db->from('products'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); return $query->result(); } public function getcust_name($id) { $this->db->select('customers.id as cust,customers.customer_name,service_request.id, products.model, products.id as prod_id, employee.id as emp_id, employee.emp_name',FALSE); $this->db->from('service_request'); $this->db->join('service_request_details','service_request_details.request_id=service_request.id'); $this->db->join('products','products.id=service_request_details.model_id'); $this->db->join('customers','service_request.cust_name=customers.id'); $this->db->join('employee','employee.id=service_request_details.assign_to'); $this->db->where('service_request.id',$id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spares_byReqId($id) { $this->db->select('spares.id, spares.spare_name, quote_review_spare_details.id as quote_review_id',FALSE); $this->db->from('quote_review_spare_details'); $this->db->join('spares','spares.id=quote_review_spare_details.spare_id'); $this->db->where('quote_review_spare_details.request_id',$id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function tax_list(){ $this->db->select("*",FALSE); $this->db->from('tax_details'); $this->db->order_by('tax_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function add_spares($data){ $this->db->insert('spares',$data); return $this->db->insert_id(); } public function add_quotereview_spares($data1){ $this->db->insert_batch('quote_review_spare_details',$data1); } public function update_quotereview_spares($data12,$quote_review_id){ //$this->db->insert_batch('quote_review_spare_details',$data1); $this->db->where('id',$quote_review_id); $this->db->update('quote_review_spare_details',$data12); } public function add_purchase_order($data){ $this->db->insert('purchase_orders',$data); return $this->db->insert_id(); } public function add_purchase_details($data1){ $this->db->insert('spare_purchase_details',$data1); } public function customerlist(){ $this->db->select("id, customer_id, customer_name, customer_type, mobile, email_id, company_name",FALSE); $this->db->from('customers'); $query = $this->db->get(); return $query->result(); } public function spareListByModelId($modelid){ $this->db->select("spares.id, spares.spare_name, spares.spare_qty, spares.used_spare, spares.sales_price, spares.part_no",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.model_id', $modelid); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function add_spares_effective_date_his($data){ $this->db->insert('spares_effective_date_history',$data); } public function add_spare_enggs($data){ $this->db->insert_batch('spare_to_engineers',$data); } public function add_spare_details($data1){ $this->db->insert_batch('spare_details',$data1); } public function add_purchase_order_details($data1){ $this->db->insert_batch('purchase_order_details',$data1); } public function sparelist1(){ $this->db->select("id, spare_name, spare_qty, used_spare, eng_spare, purchase_price, purchase_qty, purchase_date, sales_price, effective_date, dashboard_show, min_qty, part_no",FALSE); $this->db->from('spares'); $this->db->order_by('id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_min_spares(){ $query = $this->db->query("SELECT * from spare_minimum_level ORDER BY UNIX_TIMESTAMP(alert_on) DESC"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function add_min_spares($data){ $this->db->insert('spare_minimum_level',$data); } public function get_purchase_orders(){ $this->db->select("*",FALSE); $this->db->from('purchase_orders'); $this->db->order_by('id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_purchase_ordersbyid($id){ $this->db->select("*",FALSE); $this->db->from('purchase_orders'); $this->db->where('id', $id); $query = $this->db->get(); return $query->result(); } public function get_purchase_orders_sparesbyid($id){ $this->db->select("*",FALSE); $this->db->from('purchase_order_details'); $this->db->where('purchase_order_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_dash_important($data,$id){ $this->db->where('id',$id); $this->db->update('spares',$data); } public function update_purchase_order($data,$id){ $this->db->where('id',$id); $this->db->update('purchase_orders',$data); } public function sparelist_engg(){ $this->db->select("spares.id",FALSE); $this->db->select_sum('spare_to_engineers.qty_out'); $this->db->select_sum('spare_to_engineers.qty_in'); $this->db->from('spares'); $this->db->join('spare_to_engineers', 'spare_to_engineers.spare_id = spares.id'); //$this->db->order_by('spare_to_engineers.id','asc'); $this->db->group_by('spare_to_engineers.spare_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function spare_list_engineers(){ $this->db->select("id, spare_name, spare_qty, used_spare, purchase_price, purchase_qty, purchase_date, sales_price, effective_date",FALSE); $this->db->from('spares'); $this->db->order_by('spare_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function engineer_list(){ $this->db->select("id, emp_name",FALSE); $this->db->from('employee'); $this->db->order_by('emp_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function sparelist(){ $this->db->select("spare_details.spare_id, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model",FALSE); $this->db->from('spare_details'); $this->db->join('prod_category', 'prod_category.id = spare_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = spare_details.subcat_id'); $this->db->join('brands', 'brands.id = spare_details.brand_id'); $this->db->join('products', 'products.id = spare_details.model_id'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_spare_stocks($data,$id){ $this->db->where('id',$id); $this->db->update('spares',$data); } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $this->db->where('status', '0'); $this->db->order_by('product_category', 'asc'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $this->db->where('status', '0'); $this->db->order_by('subcat_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function getbrands(){ $this->db->select("id,brand_name",FALSE); $this->db->from('brands'); $this->db->where('status', '0'); $this->db->order_by('brand_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function getmodels(){ $this->db->select("id,model",FALSE); $this->db->from('products'); $this->db->where('status', '0'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); return $query->result(); } public function get_sparenamebycat($id){ $this->db->select("spares.id, spares.spare_name, spare_details.cat_id",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.cat_id', $id); $this->db->group_by('spares.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sparesbysubcat($id){ $this->db->select("spares.id, spares.spare_name, spare_details.subcat_id",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.subcat_id', $id); $this->db->group_by('spares.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sparesbybrand($id){ $this->db->select("spares.id, spares.spare_name, spare_details.brand_id",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.brand_id', $id); $this->db->group_by('spares.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sparesbymodel($id){ $this->db->select("spares.id, spares.spare_name, spare_details.model_id",FALSE); $this->db->from('spare_details'); $this->db->join('spares', 'spares.id = spare_details.spare_id'); $this->db->where('spare_details.model_id', $id); $this->db->group_by('spares.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_spare_balance($data,$id){ $this->db->where('id',$id); $this->db->update('spares',$data); } public function update_spare_enggs($data,$id){ //$this->db->update_batch('spares',$data,'id'); $this->db->where('id',$id); $this->db->update('spares',$data); } public function update_spare_status($data,$id){ //$this->db->update_batch('spares',$data,'id'); $this->db->where('id',$id); $this->db->update('spares',$data); } public function spare_to_engg_cnt(){ $this->db->select("id",FALSE); $this->db->from('spare_to_engineers'); $this->db->order_by('id', 'desc'); $this->db->limit(1); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_eng_spare($data,$id){ //$this->db->update('spares',$data,'id'); /* $query = $this->db->get_where('spares', array('id' => $id)); return $query->result(); */ $this->db->where('id',$id); $this->db->update('spares',$data); } public function getsparebyid($id){ $query = $this->db->get_where('spares', array('id' => $id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spareinfobyid($id){ $this->db->select("spares.id, spares.spare_name, spares.spare_qty, spares.used_spare, spares.sales_price, spares.purchase_price, spares.purchase_qty, spares.eng_spare, spares.min_qty",FALSE); $this->db->from('spares'); $this->db->where('spares.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_compinfo(){ $this->db->select("*",FALSE); $this->db->from('company_details'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getModels_spareid($id){ $this->db->select("id, spare_id, cat_id, subcat_id, brand_id, model_id",FALSE); $this->db->from('spare_details'); $this->db->where('spare_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsparedetbyid($id){ $query = $this->db->get_where('spare_details', array('spare_id' => $id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_spares($data,$id){ $this->db->where('id',$id); $this->db->update('spares',$data); } public function del_spare_details($id){ $this->db->where('spare_id',$id); $this->db->delete('spare_details'); } public function delete_purchase_order($id){ $this->db->where('purchase_order_id',$id); $this->db->delete('purchase_order_details'); } public function getsub_cat($id){ $query = $this->db->order_by('subcat_name', 'ASC')->get_where('prod_subcategory', array('prod_category_id' => $id, 'status'=> '0')); //echo "<pre>";print_r($query->result());exit; return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function get_brands(){ $this->db->select("brand_name, id",FALSE); $this->db->from('brands'); $this->db->where('status','0'); $query = $this->db->get(); return $query->result(); } public function get_models($categoryid,$subcatid,$brandid){ $query = $this->db->get_where('products', array('category' => $categoryid, 'subcategory' => $subcatid, 'brand' => $brandid)); return $query->result(); } public function update_cat($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_subcat($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function update_brandname($data,$id){ $this->db->where('id',$id); $this->db->update('brands',$data); } public function del_brands($id){ $this->db->where('id',$id); $this->db->delete('brands'); } public function del_spare_to_enggs($id){ $this->db->where('id',$id); $this->db->delete('spare_to_engineers'); } public function del_min_spares($id){ $this->db->where('spare_id',$id); $this->db->delete('spare_minimum_level'); } public function del_quote_spares($reqid,$spareid){ $this->db->where( array('request_id'=>$reqid, 'spare_id'=>$spareid)); $this->db->delete('quote_review_spare_details'); } public function getspareengg() { $this->db->select("spare_to_engineers.id,employee.emp_name,service_request.request_id, service_request.id as reqid,customers.customer_name,spares.spare_name,spares.id as spareid, spare_to_engineers.engineer_date,spare_to_engineers.reason,spare_to_engineers.qty_out,spare_to_engineers.auto_cnt",FALSE); $this->db->from('spare_to_engineers'); //$this->db->join('quote_review', 'quote_review.req_id=service_request.id'); $this->db->join('spares', 'spares.id=spare_to_engineers.spare_id'); $this->db->join('service_request', 'service_request.id=spare_to_engineers.req_id'); $this->db->join('customers', 'customers.id=spare_to_engineers.cust_name'); $this->db->join('employee', 'employee.id=spare_to_engineers.emp_id'); $this->db->where('spare_to_engineers.spare_receipt!=','without_Service'); $this->db->get(); $query1 = $this->db->last_query(); $this->db->select("spare_to_engineers.id,employee.emp_name,'','',customers.customer_name,spares.spare_name,spares.id as spareid,spare_to_engineers.engineer_date,spare_to_engineers.reason,spare_to_engineers.qty_out, spare_to_engineers.auto_cnt",FALSE); $this->db->from('spare_to_engineers'); //$this->db->join('quote_review', 'quote_review.req_id=service_request.id'); $this->db->join('spares', 'spares.id=spare_to_engineers.spare_id'); //$this->db->join('service_request', 'service_request.id=spare_to_engineers.req_id'); $this->db->join('customers', 'customers.id=spare_to_engineers.cust_name'); $this->db->join('employee', 'employee.id=spare_to_engineers.emp_id'); $this->db->where('spare_to_engineers.spare_receipt','without_Service'); $this->db->get(); $query2 = $this->db->last_query(); $query = $this->db->query($query1." UNION ".$query2); //echo $this->db->last_query();exit; //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spare_request() { $query = $this->db->query("SELECT GROUP_CONCAT(spares.id,'//',spares.spare_name) as spare_details, service_request.request_id, service_request.id as reid, service_request.request_date, employee.emp_name, employee.id as empid, customers.company_name, customers.id as cust_id from quote_review_spare_details as quote_review_spare_details inner join service_request as service_request ON service_request.id = quote_review_spare_details.request_id inner join service_request_details as service_request_details ON service_request_details.request_id = service_request.id inner join employee as employee ON employee.id = service_request_details.assign_to inner join customers as customers ON customers.id = service_request.cust_name inner join customer_service_location as customer_service_location ON customer_service_location.id = service_request.br_name inner join spares as spares ON spares.id = quote_review_spare_details.spare_id GROUP BY service_request.request_id "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_spare_details_reqid($id) { $query = $this->db->query("SELECT spares.*, quote_review_spare_details.spare_qty as req_spare_qty, quote_review_spare_details.id as quote_rev_id, quote_review_spare_details.request_id as req_id, quote_review_spare_details.approval_status from quote_review_spare_details as quote_review_spare_details inner join spares as spares ON spares.id = quote_review_spare_details.spare_id WHERE quote_review_spare_details.request_id = $id "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } /* public function get_spare_stocks_byreqid($id) { $query = $this->db->query("SELECT sum(qty_out) as qty_out, sum(qty_in) as qty_in from spare_to_engineers as spare_to_engineers inner join quote_review_spare_details as quote_review_spare_details ON quote_review_spare_details.request_id=spare_to_engineers.req_id WHERE quote_review_spare_details.request_id = $id GROUP BY spare_to_engineers.req_id "); return $query->result(); } */ public function getengspid($id) { $this->db->select("engg.id,service_request.request_id,employee.emp_name,service_request.mobile,customers.customer_name,spares.spare_name,engg.engineer_date,engg.reason,engg.qty_out,spares.sales_price,engg.spare_receipt"); $this->db->from('spare_to_engineers as engg'); $this->db->join('spares','spares.id=engg.spare_id'); $this->db->join('service_request','service_request.id=engg.req_id'); $this->db->join('customers','customers.id=engg.cust_name'); $this->db->join('employee','employee.id=engg.emp_id'); $this->db->where('engg.id',$id); $this->db->where('engg.spare_receipt!=','without_Service'); $this->db->get(); $query1 = $this->db->last_query(); $this->db->select("engg.id,'',employee.emp_name,customers.mobile,customers.customer_name,spares.spare_name,engg.engineer_date,engg.reason,engg.qty_out,spares.sales_price,engg.spare_receipt"); $this->db->from('spare_to_engineers as engg'); $this->db->join('spares','spares.id=engg.spare_id'); //$this->db->join('service_request','service_request.id=engg.req_id'); $this->db->join('customers','customers.id=engg.cust_name'); $this->db->join('employee','employee.id=engg.emp_id'); $this->db->where('engg.id',$id); $this->db->where('engg.spare_receipt','without_Service'); $this->db->get(); $query2 = $this->db->last_query(); $query = $this->db->query($query1." UNION ".$query2); //echo $this->db->last_query();exit; //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_tax(){ $this->db->select("*",FALSE); $this->db->from('tax_details'); $query = $this->db->get(); return $query->result(); } }<file_sep>/application/views/addrow.php <?php $count=$_POST['countid']; ?> <div class="col-md-12"> <div class="col-md-3"> <input type="text" name="brand_name[]" id="brand-<?php echo $count;?>" class="brandsss" maxlength="50"> <div id="fname<?php echo $count;?>"></div> </div> <div><a class="delRowBtn btn btn-primary fa fa-trash"></a></div> </div> <script> $(function(){ $(".registersubmit").on("click", function(event){ if($("#brand-<?php echo $count;?>").val()==""){ $("#fname<?php echo $count;?>").text("Enter the Brand Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#brand-<?php echo $count;?>").keyup(function(){ if($(this).val()==""){ $("#fname<?php echo $count;?>").show(); } else{ $("#fname<?php echo $count;?>").fadeOut('slow'); } }); $("#brand-<?php echo $count;?>").keyup(function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); }); </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ //alert("hiii"); $(document).on("keyup","#brand-<?php echo $count;?>", function(){ var timer; clearTimeout(timer); timer = setTimeout(brand, 3000); }); //alert(brand); function brand(){ var brand = $('#brand-<?php echo $count;?>').val(); if(brand) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Brand/brand_validation', data: { brand:brand, }, success: function (data) { if(data == 0){ $('#fname<?php echo $count;?>').html(''); } else{ $('#fname<?php echo $count;?>').html('Brand Name Already Exist').show().css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); $('#brand-<?php echo $count;?>').val(''); return false; } } }); } } }); </script> <script> $(function(){ $('input[name^="brand_name"]').change(function() { var $current = $(this); $('input[name^="brand_name"]').each(function() { if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id')) { $('#fname<?php echo $count;?>').html('Brand Name Already Exist').show().css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); $('#brand-<?php echo $count;?>').val(''); return false; } }); }); }); </script> <file_sep>/application/controllers/Cronreport.php <?php class cronreport extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Cron_model'); $this->load->library('excel'); } //customer report public function viewcron() { $month = date('m'); $year = date('Y'); $last_month = $month-1%12; $s = ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month); $year1 = explode('-',$s); $y = $year1[0]; $m = $year1[1]; $users = $this->Cron_model->get_report($y,$m); //activate worksheet number 1 $this->excel->setActiveSheetIndex(0); //name the worksheet $this->excel->getActiveSheet()->setTitle('Customers list'); $this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true); $this->excel->getActiveSheet()->getStyle("A1:I1")->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'Customer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'Company Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'Address'); $this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'Address1'); $this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'City'); $this->excel->setActiveSheetIndex(0)->setCellValue('F1', 'Mobile'); $this->excel->setActiveSheetIndex(0)->setCellValue('G1', 'Email'); $this->excel->setActiveSheetIndex(0)->setCellValue('H1', 'Customer Type'); $this->excel->setActiveSheetIndex(0)->setCellValue('I1', 'Customer Location'); // get all users in array formate $this->excel->getActiveSheet()->fromArray($users, null, 'A2'); // read data to active sheet $this->excel->getActiveSheet()->fromArray($users); $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007'); //force user to download the Excel file without writing it to server's HD ob_end_clean(); $objWriter->save('uploads/Customer.xls'); $this->load->view('cron'); } //Service report public function viewservice() { $month = date('m'); $year = date('Y'); $last_month = $month-1%12; $s = ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month); $year1 = explode('-',$s); $y1 = $year1[0]; $m1 = $year1[1]; $users1 = $this->Cron_model->get_servicereport($y1,$m1); //echo "<pre>"; //print_r($users1);exit; //activate worksheet number 1 $this->excel->setActiveSheetIndex(0); //name the worksheet $this->excel->getActiveSheet()->setTitle('Service list'); $this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true); $this->excel->getActiveSheet()->getStyle("A1:N1")->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'RequestID'); $this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'RequestDate'); $this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'Model Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'Customer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'Branch Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('F1', 'Customer Address'); $this->excel->setActiveSheetIndex(0)->setCellValue('G1', 'Mobile'); $this->excel->setActiveSheetIndex(0)->setCellValue('H1', 'Service Charge'); $this->excel->setActiveSheetIndex(0)->setCellValue('I1', 'Spare Charge'); $this->excel->setActiveSheetIndex(0)->setCellValue('J1', 'Engineer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('K1', 'Status'); $this->excel->setActiveSheetIndex(0)->setCellValue('L1', 'Area'); $this->excel->setActiveSheetIndex(0)->setCellValue('M1', 'Zone'); $this->excel->setActiveSheetIndex(0)->setCellValue('N1', 'Zone Coverage'); // get all users in array formate //$this->excel->getActiveSheet()->fromArray($users1, null, 'A2'); // read data to active sheet $this->excel->getActiveSheet()->fromArray($users1, null, 'A2'); /* $filename='Customer.xlsx'; //save our workbook as this file name header('Content-Type: application/vnd.ms-excel'); //mime type header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name header('Cache-Control: max-age=0'); */ //no cache //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type) //if you want to save it as .XLSX Excel 2007 format $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007'); //force user to download the Excel file without writing it to server's HD ob_end_clean(); $objWriter->save('uploads/Service.xls'); $this->load->view('servicecron'); } //revenue report public function revenueview() { $resp = 0; $month = date('m'); $year = date('Y'); $last_month = $month-1%12; $s = ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month); $year1 = explode('-',$s); $y = $year1[0]; $m = $year1[1]; $users = $this->Cron_model->get_revenuereport($y,$m); $a = count($users); $c = $a+3; $serv = $c+1; $labourcharge=0; foreach($users as $row) { $profit=$row['spare_tax']+$row['spare_tot']; $resp+=$profit; $stot+=$row['labourcharge']; $ctot+=$row['concharge']; $total = $stot+$ctot; $tot = $total+$resp; } $this->excel->setActiveSheetIndex(0); //name the worksheet $this->excel->getActiveSheet()->setTitle('Revenue list'); $this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true); $this->excel->getActiveSheet()->getStyle("A1:N1")->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'RequestID'); $this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'RequestDate'); $this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'Model Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'Customer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'Branch Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('F1', 'Customer Address'); $this->excel->setActiveSheetIndex(0)->setCellValue('G1', 'Mobile'); $this->excel->setActiveSheetIndex(0)->setCellValue('H1', 'Service Charge'); $this->excel->setActiveSheetIndex(0)->setCellValue('I1', 'Spare Charge'); $this->excel->setActiveSheetIndex(0)->setCellValue('J1', 'Engineer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('K1', 'Status'); $this->excel->setActiveSheetIndex(0)->setCellValue('L1', 'Area'); $this->excel->setActiveSheetIndex(0)->setCellValue('M1', 'Zone'); $this->excel->setActiveSheetIndex(0)->setCellValue('N1', 'Zone Coverage'); // get all users in array formate //$this->excel->getActiveSheet()->fromArray($users, null, 'A2'); // read data to active sheet $this->excel->getActiveSheet()->fromArray($users,null,'A2'); $this->excel->getActiveSheet()->getStyle("D".($c).":E".($c))->applyFromArray(array("font" => array("bold" => true))); $this->excel->getActiveSheet()->getStyle("D".($serv).":E".($serv))->applyFromArray(array("font" => array("bold" => true))); $this->excel->getActiveSheet()->getStyle("D".($serv+1).":E".($serv+1))->applyFromArray(array("font" => array("bold" => true))); $this->excel->getActiveSheet()->getStyle("D".($serv+2).":E".($serv+2))->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.$c, 'Total Spare Charge : '.$resp); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.$serv, 'Total Service Charge : '.$stot); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.($serv+1), 'Total Conveyance Charges : '.$ctot); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.($serv+2), 'Total Charges : '.$tot); $this->excel->getActiveSheet()->mergeCells("D".($c).":E".($c)); $this->excel->getActiveSheet()->mergeCells("D".($serv).":E".($serv)); $this->excel->getActiveSheet()->mergeCells("D".($serv+1).":E".($serv+1)); $this->excel->getActiveSheet()->mergeCells("D".($serv+2).":E".($serv+2)); $this->excel->getActiveSheet()->getStyle("D".($c).":E".($c))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $this->excel->getActiveSheet()->getStyle("D".($serv).":E".($serv))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $this->excel->getActiveSheet()->getStyle("D".($serv+1).":E".($serv+1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $this->excel->getActiveSheet()->getStyle("D".($serv+2).":E".($serv+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007'); //force user to download the Excel file without writing it to server's HD ob_end_clean(); $objWriter->save('uploads/Revenue.xls'); $this->load->view('revenuecron'); } //serialwise report public function serialcron() { $month = date('m'); $year = date('Y'); $last_month = $month-1%12; $s = ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month); $year1 = explode('-',$s); $y = $year1[0]; $m = $year1[1]; // print_r($m);exit; $serial = $this->Cron_model->get_serialreport($y,$m); $this->excel->setActiveSheetIndex(0); //name the worksheet $this->excel->getActiveSheet()->setTitle('Serial list'); $this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); $this->excel->getActiveSheet()->getStyle("A1:E1")->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'RequestID'); $this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'RequestDate'); $this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'PurchaseDate'); $this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'Model'); $this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'Customer Name'); $rownumber=2; foreach($serial as $row) { $requ = $row['ser']; // echo "<pre>"; // print_r($requ); $serial_no = $row['serial_no']; $ser_req = explode(',',$requ); $this->excel->setActiveSheetIndex(0)->setCellValue('A'.($rownumber),'Serial No: '.$row['serial_no']); $this->excel->getActiveSheet()->mergeCells("A".($rownumber).":E".($rownumber)); $this->excel->getActiveSheet()->getStyle("A".($rownumber).":E".($rownumber))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $this->excel->getActiveSheet()->getStyle("A".($rownumber).":E".($rownumber))->applyFromArray(array("font" => array("bold" => true))); $rownumber++; //echo $scnt; for($i=0;$i<count($ser_req);$i++) { $r1 = explode('//',$ser_req[$i]); $r11 = isset($r1[0]) ? $r1[0] : ''; $r12 = isset($r1[1]) ? $r1[1] : ''; $this->excel->setActiveSheetIndex(0)->setCellValue('A'.$rownumber, $r11); $this->excel->setActiveSheetIndex(0)->setCellValue('B'.$rownumber, $r12); $this->excel->setActiveSheetIndex(0)->setCellValue('C'.$rownumber, $row['purchase_date']); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.$rownumber, $row['model']); $this->excel->setActiveSheetIndex(0)->setCellValue('E'.$rownumber, $row['customer_name']); $rownumber++; } } $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007'); //force user to download the Excel file without writing it to server's HD ob_end_clean(); $objWriter->save('uploads/Serialreport.xls'); $this->load->view('serialcron'); } //Spare report public function spareview() { $month = date('m'); $year = date('Y'); $last_month = $month-1%12; $s = ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month); $year1 = explode('-',$s); $y = $year1[0]; $m = $year1[1]; // print_r($m);exit; $spare = $this->Cron_model->get_sparereport($y,$m); $spcnt = count($spare); $this->excel->setActiveSheetIndex(0); //name the worksheet $this->excel->getActiveSheet()->setTitle('Spare list'); $this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); $this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); $this->excel->getActiveSheet()->getStyle("A1:E1")->applyFromArray(array("font" => array("bold" => true))); $this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'RequestId'); $this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'Customer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'Model'); $this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'Engineer Name'); $this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'Problem'); $rownumber=2; foreach($spare as $roww) { $srequest = $roww['serv_request']; $sp = $roww['spare_name']; //print_r($roww); $spareser = explode(',',$srequest); $cnt = count($spareser); $this->excel->setActiveSheetIndex(0)->setCellValue('A'.($rownumber),'SpareName: '.$roww['spare_name']); $this->excel->getActiveSheet()->mergeCells("A".($rownumber).":E".($rownumber)); $this->excel->getActiveSheet()->getStyle("A".($rownumber).":E".($rownumber))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $this->excel->getActiveSheet()->getStyle("A".($rownumber).":E".($rownumber))->applyFromArray(array("font" => array("bold" => true))); $rownumber++; for($i=0;$i<count($spareser);$i++) { $r1 = explode('//',$spareser[$i]); $r11 = isset($r1[0]) ? $r1[0] : ''; $r12 = isset($r1[1]) ? $r1[1] : ''; $r13 = isset($r1[2]) ? $r1[2] : ''; $r14 = isset($r1[3]) ? $r1[3] : ''; $this->excel->setActiveSheetIndex(0)->setCellValue('A'.$rownumber, $r14); $this->excel->setActiveSheetIndex(0)->setCellValue('B'.$rownumber, $r12); $this->excel->setActiveSheetIndex(0)->setCellValue('C'.$rownumber, $r13); $this->excel->setActiveSheetIndex(0)->setCellValue('D'.$rownumber, $r11); $this->excel->setActiveSheetIndex(0)->setCellValue('E'.$rownumber, $roww['desc_failure']); $rownumber++; } } $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007'); //force user to download the Excel file without writing it to server's HD ob_end_clean(); $objWriter->save('uploads/Sparereport.xls'); $this->load->view('sparecron'); } } ?><file_sep>/application/controllers/Subcategory.php <?php class subcategory extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Subcategory_model'); } public function add_sub_category(){ $pro_cat=$this->input->post('pro_cat'); $sub_catname=$this->input->post('sub_catname'); $c=$pro_cat; $count=count($c); for($i=0; $i<$count; $i++) { if($pro_cat[$i]!=""){ $data1 = array('prod_category_id' => $pro_cat[$i], 'subcat_name' => $sub_catname[$i]); $result=$this->Subcategory_model->add_subcategory($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/prod_subcat_list';alert('Please enter Sub Category');</script>"; } */ } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/prod_subcat_list';alert('Sub Category Added Successfully!!!');</script>"; } } public function update_sub_category(){ $id=$this->uri->segment(3); $data1['list']=$this->Subcategory_model->prod_sub_cat_listbyid($id); $data1['droplists']=$this->Subcategory_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_prod_sub_cat',$data1); } public function edit_sub_category(){ $id=$this->input->post('subcatid'); $data=array( 'prod_category_id'=>$this->input->post('pro_cat'), 'subcat_name'=>$this->input->post('sub_catname') ); $s = $this->Subcategory_model->update_sub_cat_name($data,$id); echo "<script>alert('Sub Category Updated Successfully!!!');window.location.href='".base_url()."pages/prod_subcat_list';</script>"; } public function update_status_sub_category(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Subcategory_model->update_status_prod_cat($data,$id); } public function update_status_sub_category1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Subcategory_model->update_status_prod_cat1($data,$id); } public function subcategory_validation() { $category = $this->input->post('category'); $sub_category = $this->input->post('sub_category'); $res = $this->Subcategory_model->subcategory_validation($category,$sub_category); print_r($res); } public function add_subcatrow(){ $data['count']=$this->input->post('countid'); $data['droplist']=$this->Subcategory_model->prod_cat_dropdownlist(); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_subcat',$data); } }<file_sep>/application/libraries/pdf.php <?php include_once 'MPDF54/mpdf.php'; class PDF extends mPDF { private $ci; public function __construct(){ parent::__construct(); $this->ci = & get_instance(); } function genPdfAttachFile($html,$file_name=NULL) { $this->ci->load->helper('file'); $dt=$this->WriteHTML($html); $data = 'Some file data'; $name=time().".pdf"; $this->debug = true; $base=str_replace("system/","",BASEPATH); $data=$this->Output('','S'); //exit; if (write_file($base.'tmp_upload/'.$name,$data)) { return $base.'tmp_upload/'.$name; } else { return false; } } function downloadPdf($html,$file_name=NULL,$mark=NULL) { if($mark) { $this->SetWatermarkImage($mark); $this->showWatermarkImage = true; } $this->ci->load->helper('file'); $dt=$this->WriteHTML($html); $data = 'Some file data'; $name=time(); if($file_name) $name .= $file_name; $name .=".pdf"; $this->debug = true; $base=str_replace("system/","",BASEPATH); $data=$this->Output($name,'D'); } } <file_sep>/application/views/location_list.php <style> table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } #data-table-simple_filter, #data-table-simple_length { display:block; } #data-table-simple_wrapper{ width: 50%; margin: auto; } .select-wrapper { display: inline-block; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width:75%; } #table-datatables { margin-top: 15px; } </style> <script> $(document).ready(function(){ $('[id^="pro_cat_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split(','); var procatid = arr['0']; var subid = arr['1']; var data_String; data_String = 'id='+subid+'&procatid='+procatid; $.post('<?php echo base_url(); ?>subcategory/update_sub_category',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Category changed"); //$('#actaddress').val(data.Address1), }); }); }); function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); location_name = $("#location_name"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Location/update_location', data: {'id' : id, 'location_name' : location_name}, dataType: "text", cache:false, success: function(data){ alert("Location updated"); } }); }); } function Updatedefault(id) { if(document.getElementById('tax_default'+id).checked) { var tax_default = '1'; //alert(tax_default); } else { var tax_default = '0'; //alert(tax_default); } $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/update_default', data: {'id' : id, 'tax_default' : tax_default}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("Tax Selected"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/del_tax', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/tax_list"; } alert("Tax deleted"); } }); }); } </script> <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Location List</h4> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <form id="form1"> <table id="data-table-simple" cellspacing="0" style="margin-top:2%;"> <thead> <tr> <td>Location Name</td> <td>Action</td> </tr> </thead> <tbody> <?php foreach($location_list as $key){ ?> <tr> <td> <input type="text" value="<?php echo $key->location_name; ?>" class="" name="location_name" id="location_name<?php echo $key->id; ?>"> </td> <td class="options-width"> <a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/workin_prog_list - updated on 06-02-2017.php <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Work In Progress List</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-xs-12 table-responsive"> <table id="data-table-simple" class="display"> <thead> <tr> <th>Request Id</th> <th>Customer Name</th> <!--<th>Product Name</th>--> <th>Machine Status</th> <!--<th>Service Type</th>--> <!--<th>Requested Date</th> <th>Assign To</th> <th>Site</th> <th>Location</th>--> <!--<th>Problem</th> <th>Status</th>--> </tr> </thead> <tbody> <?php foreach($workin_prog_list as $key){ $reid= sprintf("%05d", $key->id) ?> <tr> <td> <a href="<?php echo base_url(); ?>work_inprogress/workin_prog_status/<?php echo $reid; ?>"><?php echo $key->request_id; ?></a> </td> <td> <?php echo $key->customer_name; ?></td> <!--<td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->model;} } ?></td>--> <td> <?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?> </td> <!--<td><?php foreach($service_req_listforserviceCat as $servicecatkey){ if($servicecatkey->request_id==$key->id){ echo $servicecatkey->service_category;} } ?></td>--> <!--<td><?php echo $key->request_date; ?></td>--> <!--<td><?php foreach($service_req_listforEmp as $key2){ if($key2->request_id==$key->id){ echo $key2->emp_name; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->site; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->service_loc; } } ?></td>--> <!--<td><?php foreach($service_req_listforProb as $servprobkey2){ if($servprobkey2->request_id==$key->id){ echo $servprobkey2->prob_category; } } ?></td>--> <!--<td>Work In Progress</td>--> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/models/Product_model.php <?php class Product_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_prod($data){ $this->db->insert('products',$data); return true; } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $this->db->where('status', '0'); $this->db->order_by('product_category', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $this->db->where('status', '0'); $this->db->order_by('subcat_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function brandlist(){ $this->db->select("id, brand_name",FALSE); $this->db->from('brands'); $this->db->where('status', '0'); $this->db->order_by('brand_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function getsub_cat($id){ $query = $this->db->order_by('subcat_name', 'ASC')->get_where('prod_subcategory', array('prod_category_id' => $id, 'status'=> '0')); //$this->db->order_by('product_category', 'asc'); //echo "<pre>";print_r($query->result());exit; return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function get_brands($categoryid,$subcatid){ $query = $this->db->get_where('brands', array('cat_id' => $categoryid, 'subcat_id' => $subcatid)); return $query->result(); } public function brandlists(){ $query = $this->db->order_by('brand_name', 'asc')->get_where('brands', array('status' => '0')); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function accessories_list(){ $this->db->select("id, accessory",FALSE); $this->db->from('accessories'); $this->db->order_by('accessory', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function product_list(){ $this->db->select("products.id As id, products.model As model, products.description As description, products.status As status, prod_category.product_category As category, prod_subcategory.subcat_name As subcategory",FALSE); $this->db->from('products'); $this->db->join('prod_category', 'products.category=prod_category.id'); $this->db->join('prod_subcategory', 'products.subcategory=prod_subcategory.id'); $this->db->order_by('products.id', 'DESC'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getproductbyid($id){ $this->db->select("id, category, subcategory, model, description, stock_qty",FALSE); $this->db->from('products'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function edit_products($data,$id){ $this->db->where('id',$id); $this->db->update('products',$data); } public function del_products($id){ $this->db->where('id',$id); $this->db->delete('products'); } public function update_status_prod($data,$id){ $this->db->where('id',$id); $this->db->update('products',$data); } public function update_status_prod1($data,$id){ $this->db->where('id',$id); $this->db->update('products',$data); } public function update_stock_in_hand($qty,$pid){ $this->db->query("UPDATE products SET stock_qty = stock_qty + $qty WHERE id = $pid", FALSE); //echo $this->db->last_query(); } }<file_sep>/application/views_bkMarch_0817/subcategory_list.php <ul id="country-list"> <?php foreach($category_list as $key) { ?> <li onClick="selectCountry1('<?php echo $key->subcat_name; ?>','<?php echo $key->id; ?>');"><?php echo $key->subcat_name; ?></li> <?php } ?> </ul> <file_sep>/application/views/templates/header - updated on 04-02-2017.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo base_url(); ?>assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">--> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link href="<?php echo base_url(); ?>assets/js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/AdminLTE.min.css"> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addrow.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <!--<script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> --> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addtable.js'></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!--<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>--> <link href="<?php echo base_url(); ?>assets/css/print.css" type="text/css" rel="stylesheet" media="print" /> <style> .btn-box-tool:active { background-color: rgb(5, 94, 135); } .side-nav.fixed a { display: block; padding: 0px 2px 0px 1px !important; color: #055E87; } .side-nav li ul li a { margin: 0px 1rem 0px 0rem !important; } /*.saturate { -webkit-filter: saturate(50); filter: saturate(50); }*/ @media only screen and (min-width:240px) and (max-width:768px){ .nav{ display:none; } .navbar-toggle{ display:none; } .right{ float: none !important; position: relative !important; bottom: 0px !important; width: 134px !important; top:-46px !important; left: 0px; background: #303f9f; } .img-welcome { width: 25px; height: 25px; float: right; position: relative; left: 0px !important; top: 2px; /* border: 1px solid #ccc; */ } ol, ul { margin-top: 0; margin-bottom: -24px !important; } } /* Mega Menu New */ .nav, .nav a, .nav ul, .nav li, .nav div, .nav form, .nav input { margin: 0; padding: 0; border: none; outline: none; } .nav a { text-decoration: none; } .nav li { list-style: none; } .nav { display: inline-block; position: relative; cursor: default; z-index: 500; left:80px; background: #303f9f; } .nav > li { display: block; float: left; } .nav > li > a { position: relative; display: block; z-index: 510; height: 54px; padding: 0 20px !important; line-height: 54px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #fcfcfc; text-shadow: 0 0 1px rgba(0,0,0,.35); background: #303f9f; border-left: 1px solid #303f9f; border-right: 1px solid #303f9f; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li:hover > a { /*background: #303f9f;*/ } .nav > li:first-child > a { border-radius: 3px 0 0 3px; border-left: none; } .nav > li.nav-search > form { position: relative; width: inherit; height: 54px; z-index: 510; border-left: 1px solid #4b4441; } .nav > li.nav-search input[type="text"] { display: block; float: left; width: 1px; height: 24px; padding: 15px 0; line-height: 24px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #999999; text-shadow: 0 0 1px rgba(0,0,0,.35); background: #372f2b; -webkit-transition: all .3s ease 1s; -moz-transition: all .3s ease 1s; -o-transition: all .3s ease 1s; -ms-transition: all .3s ease 1s; transition: all .3s ease 1s; } .nav > li.nav-search input[type="text"]:focus { color: #fcfcfc; } .nav > li.nav-search input[type="text"]:focus, .nav > li.nav-search:hover input[type="text"] { width: 110px; padding: 15px 20px; -webkit-transition: all .3s ease .1s; -moz-transition: all .3s ease .1s; -o-transition: all .3s ease .1s; -ms-transition: all .3s ease .1s; transition: all .3s ease .1s; } .nav > li.nav-search input[type="submit"] { display: block; float: left; width: 20px; height: 54px; padding: 0 25px; cursor: pointer; background: #372f2b url(../img/search-icon.png) no-repeat center center; border-radius: 0 3px 3px 0; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li.nav-search input[type="submit"]:hover { background-color: #4b4441; } .nav > li > div { position: absolute; display: block; width: 43em; top: 54px; left: 0; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav .nav-column { float: left; width: auto; padding: 0px 1.5%; } .nav .nav-column h3 { margin: 20px 0 10px 0; line-height: 18px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #2e3192; text-transform: uppercase; } .nav .nav-column h3.orange { color: #ff722b; } .nav .nav-column li a { display: block; line-height: 26px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 12px; color: #888888; text-decoration:none; } .nav .nav-column li a:hover { color: #666666; } .nav>li>a:hover, .nav>li>a:visited .nav>li>a:active, .nav>li>a:focus { color: #039be5; background: #d0d4d7; } .divider{ background-color: #967d58 !important; } .right { float: right !important; position: relative !important; right: 40px !important; top: -50px; background: #303f9f; } .right li > div a{ color:#fff; font-size:1em; } .waves-block { display: block; color: #fff; } .waves-light{ font-size:13px; font-weight:bold; } .right li > a i.fa-sign-out{ font-size:16px !important; } .fa-arrows-alt{ margin-right:10px; } a.waves-light:hover, a.waves-light:active, a.waves-light:focus { color: #fff !important; } header{ padding:0 !important; height:55px; } .navbar-nav>li>a { padding-top: 10px; padding-bottom: 10px; line-height: 54px !important; } /* Responsive Menu Style */ .navbar-toggle { position: relative; float: right; padding: 9px 10px; /* margin-top: 8px; */ margin-right: 15px; margin-bottom: 8px; background-color: transparent; background-image: none; border: 1px solid transparent; border-radius: 4px; position: relative; bottom: 40px; } .navbar-toggle .icon-bar { display: block; width: 22px; height: 2px; border-radius: 1px; border:solid #fff; } .in .nav{ left: 0px; position: relative; width: 415px; } .in .nav li{ float: none; position: inherit; border-bottom: 1px solid #ccc; } .collapse.in { display: block; position: relative; z-index: 11; bottom: 50px; background: #fff; padding-left: 0px; height:auto; } .in .nav > li > div{ z-index: 1111; width: 250px; } .in .nav .nav-column{ float: none; width: 70%; padding: 0px 1.5%; } .in .nav .nav-column > ul{ width: 244px; } .in .nav .nav-column > ul >li{ border-bottom:none; } .in .nav .nav-column .divider{ width:244px; } .in ul.right{ float: none !important; position: relative !important; bottom: 0px !important; width: 413px; left: 0px; background: #303f9f; } .img-welcome{ width:25px; height:25px; float:right; position:relative; left:5px; /*border:1px solid #ccc;*/ } .in .right .img-welcome{ width:25px; height:25px; position:relative; left: -260px; bottom: 0px; /*border:1px solid #ccc;*/ } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function(){ $(".navbar-toggle").click(function(){ $("ul.nav li").addClass("accordion"); var acc = $(".accordion > div"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } } } }); }); </script> </head> <body> <!--<div id="loader-wrapper"> <!-- <div id="loader"></div> --> <!-- <div class="loader-section section-left"></div> <div class="loader-section section-right"></div> </div>--> <header id="header" class="page-topbar"> <div class="navbar-header"> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type!='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <img src="<?php echo base_url(); ?>assets/images/newlogo.png" alt="materialize logo" style="width:230px;height:50px;color:#fff" class="saturate"> </a> <?php } }?> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type=='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <img src="<?php echo base_url(); ?>assets/images/newlogo.png" alt="materialize logo" style="width:230px;height:50px"></a> <?php } }?> </div> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".js-navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse js-navbar-collapse"> <ul class="nav navbar-nav"> <li> <a href="#">Sales<span class="caret"></span></a> <div> <div class="nav-column col-md-3"> <h3>Sales Details</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/order_list">Sales List</a></li> <li><a href="<?php echo base_url(); ?>pages/amc_list">AMC List</a></li> <li><a href="<?php echo base_url(); ?>pages/expiry_closed">Chargeables</a></li> <li><a href="<?php echo base_url(); ?>pages/add_order">New Sales</a></li> </ul> </div> <div class="nav-column col-md-3"> <h3>Expiring Products</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list">Expiring Contracts</a></li> </ul> </div> </div> </li> <li> <a href="#">Services<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Service</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/add_service_req">New Request</a></li> <li><a href="<?php echo base_url(); ?>pages/service_req_list">All Request</a></li> <li><a href="<?php echo base_url(); ?>pages/quote_in_progress_list">Quote In-progress</a></li> </ul> </div> <div class="nav-column"> <h3>Service</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/quote_approved">Awaiting Approvals</a></li> <li><a href="<?php echo base_url(); ?>pages/workin_prog_list">Work In-progress</a></li> <li><a href="<?php echo base_url(); ?>pages/comp_engg_list">Completed By Engineer</a></li> </ul> </div> <div class="nav-column"> <h3>Service</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/quality_check_list">QC</a></li> <li><a href="<?php echo base_url(); ?>pages/ready_delivery_list">Ready Delivery</a></li> <li><a href="<?php echo base_url(); ?>pages/delivered_list">Delivered / Invoices</a></li> </ul> </div> </div> </li> <li> <a href="#">Spares<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Spare</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/add_spare">Spare Master</a></li> <li><a href="<?php echo base_url(); ?>pages/spare_stock">Spare Stock</a></li> <li><a href="<?php echo base_url(); ?>pages/add_new_stock">New Spare</a></li> <li><a href="<?php echo base_url(); ?>pages/add_spare_engineers">Spare to Engineer</a></li> </ul> </div> <div class="nav-column"> <h3>Spare</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/sparereceipt">Spare Receipt List</a></li> <li><a href="<?php echo base_url(); ?>pages/spare_purchase_order">Create Purchase Order</a></li> <li><a href="<?php echo base_url(); ?>pages/purchase_orders">Purchase Order</a></li> <li><a href="<?php echo base_url(); ?>pages/min_spare_alerts">Min Spare Alerts</a></li> </ul> </div> </div> </li> <li> <a href="#">Master<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Customers</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_list">Customer List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_cust">Add Customer</a></li> </ul> <div class="divider"></div> <h3>Product Brand</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/brandList">Brand List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_brand">New Brand</a></li> </ul> <div class="divider"></div> <h3>Transporter</h3> <ul> <li><a href="#">Transporter List</a></li> <li><a href="#">New Transporter</a></li> </ul> <div class="divider"></div> <h3>Users</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/user_cate_list">User List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_user_cate">New User</a></li> </ul> <div class="divider"></div> <h3>Location</h3> <ul> <li><a href="#">Location List</a></li> <li><a href="#">New Location</a></li> </ul> </div> <div class="nav-column"> <h3>Products</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_list">Product List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_prod">Add Product</a></li> </ul> <div class="divider"></div> <h3>Problem Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prob_cat_list">Problem List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_prob_cat">New Problem</a></li> </ul> <div class="divider"></div> <h3>Customer Type</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_type_list">Customer Type List</a></li> <li><a href="<?php echo base_url(); ?>pages/cust_type">New Customer Type</a></li> </ul> <div class="divider"></div> <h3>Employee</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/emp_list">Employee List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_emp">New Employee</a></li> </ul> <div class="divider"></div> <h3>Accessories</h3> <ul> <li><a href="<?php echo base_url(); ?>service/pages/accessories_list">Accessories</a></li> </ul> </div> <div class="nav-column"> <h3>Product Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_cat_list">Category List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_prod_cat">New Category</a></li> </ul> <div class="divider"></div> <h3>Service Zone</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/service_loc_list">Zone List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_service_loc">New Zone</a></li> </ul> <div class="divider"></div> <h3>Couriers</h3> <ul> <li><a href="#">Couriers List</a></li> <li><a href="#">New Couriers</a></li> </ul> <div class="divider"></div> <h3>Vendor</h3> <ul> <li><a href="#">Vendor List</a></li> <li><a href="#">New Vendor</a></li> </ul> <div class="divider"></div> <h3>Company Details</h3> <ul> <li><a href="<?php echo base_url(); ?>service/pages/comp_list">Company Details</a></li> </ul> </div> <div class="nav-column"> <h3>Sub Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_subcat_list">Sub-Category List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_prod_subcat">New Sub-Category</a></li> </ul> <div class="divider"></div> <h3>Tax</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/tax_list">Tax List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_tax">New Tax</a></li> </ul> <div class="divider"></div> <h3>Service Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/service_cat_list">Service Category List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_service_cat">New Service Category</a></li> <li><a href="<?php echo base_url(); ?>pages/add_service_charge">New Service Charge</a></li> <li><a href="<?php echo base_url(); ?>pages/service_charge_list">Service Charge List</a></li> </ul> </div> </div> </li> <li> <a href="#">Reports<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Reports</h3> <ul> <li><a href="<?php echo base_url();?>pages/revenuereport">Service Report</a></li> <li><a href="<?php echo base_url();?>pages/report_list">Revenue Report</a></li> <li><a href="<?php echo base_url();?>pages/engineer_servicereport_list">Enigneers Report</a></li> <li><a href="<?php echo base_url();?>pages/customerreport_list">Customer Report</a></li> <li><a href="<?php echo base_url();?>pages/service_mach_report">Service Machines Report</a></li> </ul> </div> <div class="nav-column"> <h3>Reports</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list1">Warranty Expired Report</a></li> <li><a href="<?php echo base_url();?>pages/agingreport">Aging Report</a></li> <li><a href="<?php echo base_url();?>pages/sparereport_list">Spare Report</a></li> <li><a href="<?php echo base_url();?>pages/engineerreport_list">Spare to Engineer Report</a></li> </ul> </div> <div class="nav-column"> <h3>Reports</h3> <ul> <li><a href="<?php echo base_url();?>pages/sparepurchase_list">Spare Purchase Report</a></li> <li><a href="<?php echo base_url();?>pages/sparecharge_list">Spare Charge Report</a></li> <li><a href="<?php echo base_url();?>pages/stampingreport_list">Stamping Report</a></li> <li><a href="<?php echo base_url();?>pages/monthlyreport_list">Stamping Monthly</a></li> </ul> </div> </div> </li> </ul> </div> <div class="navbar-header right"> <ul class="hide-on-med-and-down"> <li> <div> <a href="#">Welcome Admin</a> <img class="img-circle img-responsive img-welcome" src="<?php echo base_url(); ?>assets/images/user.png"> </div> <a href="<?php echo base_url(); ?>login/logout" class="waves-effect waves-block waves-light"><i class="fa fa-sign-out"></i> Logout</a> </li> </ul> </div> <!--<div class="navbar-fixed"> <nav class=""> <div class=""> <ul class="left"> <li><h1 class="logo-wrapper"><?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type!='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <!--<img src="<?php echo base_url(); ?>assets/images/newlogo.png" alt="materialize logo" style="width:230px;height:50px"> </a> <?php } }?> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type=='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <!--<img src="<?php echo base_url(); ?>assets/images/newlogo.png" alt="materialize logo" style="width:230px;height:50px"> </a> <?php } }?> </h1></li> </ul> <ul class="right hide-on-med-and-down"> <li><a href="javascript:void(0);" class="waves-effect waves-block waves-light toggle-fullscreen"> <i class="fa fa-arrows-alt"></i> </a> </li> <li><a href="<?php echo base_url(); ?>login/logout" class="waves-effect waves-block waves-light"><?php //foreach($user_dat As $Ses_key){echo "Welcome: ".$Ses_key->name; } ?> Logout</a> </li> </ul> </div> </nav> </div>--> </header> <div id="main"> <div class="picker-wrapper"> <button class="btn coloricon"></button> <div class="color-picker"> </div> </div> <div class="wrapper"> <style> .fa { font-size:21px !important; } .fa-user { font-size: 2.4rem !important; padding-left: 3px; } #slide-out li a i { padding-left: 7px; } .fa-arrow-right { font-size:14px !important; } .coloricon{ background-image:url("<?php echo base_url(); ?>assets/images/icon.png"); height:50px; width:50px; background-repeat: no-repeat; background-size: cover; left:1298px; } .color-picker { background: rgba(255, 255, 255, 0.75); /* padding: 10px; */ border: 1px solid rgba(203, 203, 203, 0.6); border-radius: 2px; position: absolute; width: 150px; right: 60px; bottom: 435px; } .picker-wrapper { padding: 0px !important; } .color-picker > div { width: 15px !important; display: inline-block; height: 15px !important; margin: 2px !important; border-radius: inherit !important; opacity: 0.7; } .color-picker > div:before { content: ""; border-left: 17px solid #fff; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -13px; z-index: 1001; } .color-picker > div:after { content: ""; border-left: 17px solid #ccc; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -15px; z-index: 800; } .toggle-fullscreen:hover { color:white !important; text-decoration:none; } .toggle-fullscreen:focus { color:white !important; text-decoration:none; } .Accordion li.active a { color:black; } @media only screen and (max-width: 992px){ .hide-on-med-and-down { display: block !important; } /*header .brand-logo img { width: 172px !important; position: relative; right: 75px; bottom: 8px; }*/ .waves-effect { position: relative; left: 0px; } .sidebar-collapse { position: absolute; left: -170px; top: -70px; } } @media only screen and (min-width: 301px){ nav, nav .nav-wrapper i, nav a.button-collapse, nav a.button-collapse i { height: 64px !important; line-height: 64px !important; } } </style> <script type="text/javascript"> $(function(){ $('.Accordion a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active') // $('.hhhh a').click(function(){ // $(this).parent().addClass('active').siblings().removeClass('active') //}) }) </script> <!--<aside id="left-sidebar-nav"> <br/> <ul id="slide-out" class="side-nav fixed leftside-navigation Accordion"> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type!='7'){ ?> <li ><a href="<?php echo base_url(); ?>pages/dash" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">dashboard</i> Dashboard</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='3' || $Ses_key1->user_type=='6'){ ?> <li><span><i class="fa fa-user"></i> Customers <i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_cust"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add Customer</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li ><span><i class="material-icons">shopping_basket</i> Product<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Product List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add Product</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li ><span><i class="material-icons">supervisor_account</i>Employee<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/emp_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Employee List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_emp"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Employee</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url(); ?>pages/comp_list" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">store</i> Company Details</a> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='3' || $Ses_key1->user_type=='5'){ ?> <li ><span><i class="material-icons">shopping_basket</i> Sales Details <i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/order_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i> Sales List</a> </li> <li><a href="<?php echo base_url(); ?>pages/amc_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i> AMC List</a> </li> <li><a href="<?php echo base_url(); ?>pages/expiry_closed"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Chargeables</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Sales</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='6'){ ?> <li ><span><i class="material-icons">assignment</i>Service<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/add_service_req"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Request</a> </li> <li><a href="<?php echo base_url(); ?>pages/service_req_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>All Request</a> </li> <li><a href="<?php echo base_url(); ?>pages/quote_in_progress_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Quote In-progress</a> </li> <!--<li><a href="<?php echo base_url(); ?>pages/quote_review"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Quote Review</a> </li>--> <!--<li><a href="<?php echo base_url(); ?>pages/quote_approved"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Awaiting Approvals</a> </li> <li><a href="<?php echo base_url(); ?>pages/workin_prog_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Work InProgress</a> </li> <li><a href="<?php echo base_url(); ?>pages/comp_engg_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Completed by Engg</a> </li> <li><a href="<?php echo base_url(); ?>pages/quality_check_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>QC</a> </li> <li><a href="<?php echo base_url(); ?>pages/ready_delivery_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Ready - Delivery</a> </li> <li><a href="<?php echo base_url(); ?>pages/delivered_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Delivered / Invoices</a> </li> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url(); ?>pages/add_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Sales</a> </li> <?php }}?> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li ><span><i class="material-icons">new_releases</i>Spares<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/add_spare"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Master</a> </li> <li><a href="<?php echo base_url(); ?>pages/spare_stock"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Stock</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_new_stock"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Spare</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_spare_engineers"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare to Engrs</a> </li> <li><a href="<?php echo base_url(); ?>pages/sparereceipt"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Receipt List</a> </li> <li><a href="<?php echo base_url(); ?>pages/spare_purchase_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Create purchase order</a> </li> <li><a href="<?php echo base_url(); ?>pages/purchase_orders"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Purchase orders</a> </li> <li><a href="<?php echo base_url(); ?>pages/min_spare_alerts"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Min spare alerts</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li ><span><i class="material-icons">new_releases</i> Expiring Product<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Expiring Contracts</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <!--<li><span><i class="fa fa-cogs"></i> Product Service Status<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_service_stat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Status List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_service_stat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Status</a> </li> </ul> </li>--> <!--<li><span><i class="fa fa-folder-open"></i> Product Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Category List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Category</a> </li> </ul> </li> <li><span><i class="fa fa-indent"></i> Sub-Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_subcat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SubCategory List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_subcat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New SubCategory</a> </li> </ul> </li> <li ><span><i class="fa fa-chrome"></i> Product Brand<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/brandList"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Brand List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_brand"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Brand</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Service Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/service_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service category List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Service category</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_charge"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Service Charge</a> </li> <li><a href="<?php echo base_url(); ?>pages/service_charge_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service charge List</a> </li> </ul> </li> <li ><span><i class="fa fa-map"></i>Service Zone<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/service_loc_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Zone List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_loc"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Zone</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Problem Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prob_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Problem List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prob_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Problem</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Tax<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/tax_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Tax List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_tax"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Tax</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Customer Type<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_type_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer Type List</a> </li> <li><a href="<?php echo base_url(); ?>pages/cust_type"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Customer Type</a> </li> </ul> </li> <li ><a href="<?php echo base_url(); ?>pages/accessories_list" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">store</i> Accessories</a> </li> <li><span><i class="material-icons">people</i> Users<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/user_cate_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>User List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_user_cate"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add User</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='5' || $Ses_key1->user_type=='6' || $Ses_key1->user_type=='4'){ ?> <li><span><i class="fa fa-cog"></i> Reports<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/revenuereport" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url();?>pages/report_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Revenue Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/engineer_servicereport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Engineers Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/customerreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/service_mach_report" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service Machines Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url(); ?>pages/expiry_list1"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Warranty Expired Reports</a> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/agingreport" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Aging Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparereport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/engineerreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare to Engineer Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparepurchase_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SparePurchase Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparecharge_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SpareCharge Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='6'){ ?> <li><a href="<?php echo base_url();?>pages/stampingreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>StampingReport1</a></li> <li><a href="<?php echo base_url();?>pages/monthlyreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Stamping Monthly</a></li> <?php }}?> </ul> </li> <?php }}?> </ul> <a href="#" data-activates="slide-out" class="sidebar-collapse btn-floating btn-medium waves-effect waves-light hide-on-large-only cyan"><i class="fa fa-bars"></i></a> </aside>--> <!--color plugin--> <!-- Font Awesome --> <!--<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script> <!-- Material Design for Bootstrap --> <link href="<?php echo base_url(); ?>assets/css/material-wfont.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/ripples.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/custom.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/piklor.js"></script> <script src="<?php echo base_url(); ?>assets/js/handlers.js"></script> <file_sep>/application/views/serailpopup_data.php <?php error_reporting(0);?> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <script> $( function() { $( ".datepicker" ).datepicker({ dateFormat:"dd-mm-yy", changeMonth:true, changeYear:true, yearRange:'1950:2016' }); } ); </script> <style> #select_value { height: 33px; width: 210px; border:1px solid #055E87; border-image: none; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; border-radius: 0px; margin: 0px; box-sizing: border-box; -moz-appearance: none; } .form-control { border:none; } </style> <style> .btn { border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; border: 1px solid transparent; } .btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } .waves-effect { position: relative; cursor: pointer; display: inline-block; overflow: hidden; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; vertical-align: middle; z-index: 1; will-change: opacity, transform; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; transition: all 0.3s ease-out; } .btn, .btn-large { text-decoration: none; color: #FFF; background-color: #ff4081; text-align: center; letter-spacing: .5px; -webkit-transition: 0.2s ease-out; -moz-transition: 0.2s ease-out; -o-transition: 0.2s ease-out; -ms-transition: 0.2s ease-out; transition: 0.2s ease-out; cursor: pointer; } .btn, .btn-large, .btn-flat { border: none; border-radius: 2px; display: inline-block; height: 36px; line-height: 36px; outline: 0; padding: 0 2rem; text-transform: uppercase; vertical-align: middle; -webkit-tap-highlight-color: transparent; } .z-depth-1, nav, .card-panel, .card, .toast, .btn, .btn-large, .btn-floating, .dropdown-content, .collapsible, .side-nav { box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); } .cyan { background-color: #00bcd4 !important; background-color: #25555C !important; background-color: #055E87 !important; } button, input, select, textarea { font-family: inherit; font-size: inherit; line-height: inherit; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button, select { text-transform: none; } button { overflow: visible; } button, input, optgroup, select, textarea { margin: 0; font: inherit; color: inherit; } html input[type="button"], button, input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button, select { text-transform: none; } button { overflow: visible; } button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0; } table { border-color: grey; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { text-align: center; border: 1px solid #ccc; } .tableadd1 thead tr th { border: 1px solid #ccc; } .tableadd1 tr { height: 50px; } .tableadd1 tr td select { border: 1px solid #ebebeb; border-radius: 3px; width: 150px; height: 35px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:white; } .tableadd1 tr td.plus { padding-top: 0px; } .tableadd1 tr td.plus input { width: 115px; border: 1px solid gray; } .tableadd1 tr td input { height: 33px; border-radius: 3px; padding-left: 0px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { width:51%; margin-top:20px; } #addtable tr td { border:1px solid #ccc; text-align:left; } #addtable tr td label { color:black; } #errorBox{ color:#F00; } #errorBox1{ color:#F00; } #errorBox2{ color:#F00; } #errorBox3{ color:#F00; } #errorBox4{ color:#F00; } #errorBox5{ color:#F00; } #errorBox6{ color:#F00; } #errorBox7{ color:#F00; } #errorBox8{ color:#F00; } #errorBox9{ color:#F00; } #errorBox10{ color:#F00; } input[id=basicamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 5px; left: 29px; } input[id=cst]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 20px; left: 208px; } input[id=freight]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 35px; left: 364px; } input[id=totalamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 50px; left: 560px; } .purchasedetail{ position: relative; top: -63px; left: 50px; } .pipurchasedetail{ position: relative; top: -63px; left: 90px; } .cstpurchasedetail{ position: relative; top: -63px; left: 95px; } .tableadd tr td input { width:100%; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 5px; padding-left: 10px; } .recvd_qty_cl{ color:#F00; } </style> <style> table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } .tableadd1 thead tr th { border: 1px solid #522276; } .tableadd1 tr td { text-align: center; border: 1px solid #522276; } </style> <script> /* function frmValidate(){ var r=confirm("Are you sure you want to force close the PO?"); if (r==true) { return true; location.reload(); } else{ return false; } } */ </script> <section id="content"> <div class="container"> <div class="section"> <h4 class="header" style="margin-top:8px; font-size: 22px; color: #6C217E;;">SerialWise Report</h4> <hr style="border: 1px solid #522276; margin-top: -17px;"> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <form > <table class="tableadd1" cellspacing="0" style="width:100%; margin-top:2%;"> <thead> <tr style="background-color: #dbd0e1; color: #522276;"> <th>Brand</th> <th>Zone</th> <th>Machine Status</th> <th>Problem</th> <th>Service Type</th> <th>Service Category</th> </tr> </thead> <tbody> <?php foreach($serial as $key) { $sd = $key->problem; ?> <tr> <td><?php echo $key->brand_name;?></td> <td><?php echo $key->service_loc;?></td> <td><?php echo $key->machine_status;?></td> <td><?php if($sd) { $query=$this->db->query("SELECT group_concat(prob_category) as pc FROM problem_category WHERE id in ($sd)"); extract($query->row_array()); echo $pc;}?></td> <td><?php echo $key->service_type;?></td> <td><?php echo $key->categoryname;?></td> </tr> <?php } ?> <tr style="height: 50px; background-color: white; border-bottom: 1px solid #ddd;"> </tr> </tbody> </table> </form> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/controllers/Sparereport_engg_list.php <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="sample" cellspacing="0" style="width:50%; margin-top:2%;"> <thead> <tr> <td>Spare_Name</td> <td>Stock In Hand</td> <td>Purchase Price</td> <td>Engineer Name</td> <td>Qty</td> </tr> </thead> <tbody> <?php if(!empty($sparereport)) { foreach($sparereport as $row) {?> <tr> <td><?php echo $row->spare_name;?></td> <td></td> <td><?php echo $row->purchase_price;?></td> <td><?php echo $row->emp_name;?></td> <td></td> </tr> <?php } }?> </tbody> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script><file_sep>/application/views_bkMarch_0817/quote_review_view.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $(' <tr><td> <select> <option>---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="ready"){ $(".box").not(".ready").hide(); $(".ready").show(); } else if($(this).attr("value")=="delivery"){ $(".box").not(".delivery").hide(); $(".delivery").show(); } else if($(this).attr("value")=="blue"){ $(".box").not(".blue").hide(); $(".blue").show(); } else{ $(".box").hide(); } }); }).change(); }); </script> <style> .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td label{ width:150px !important; font-weight:bold; } .box{ padding: 20px; display: none; margin-top: 20px; box-shadow:none !important; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Quote Review</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form > <table class="tableadd"> <tr> <td><label>Customer Name</label>:</td><td><input type="text" name="" class="" value="Manikandan" ></td><td><label>Product Name</label>:</td><td><input type="text" name="" class="" value="Motorola" readonly></td> </tr> <tr> <td><label>Date Of Request</label>:</td><td><input type="text" name="" class="date" value="29/8/2015" ></td><td><label>Engineer Name</label>:</td><td><input type="text" name="" class="" value="Vishnu" ></td> </tr> <tr> <td><label>Site</label>:</td><td><input type="text" name="" class="" value="OnSite" ></td><td><label>Location</label>:</td><td><input type="text" name="" class="" value="Chennai" ></td> </tr> <tr> <td><label>Problem</label>:</td><td><input type="text" name="" class="" value="Repair" ></td><td><label>Machine Status</label>:</td><td><input type="text" name="" class="" value="Warranty" ></td> </tr> <!-- <tr> <td><label>Spare Charges</label>:</td><td><input type="text" name="" class="" value="700" ></td><td><label>Service Location</label>:</td><td><input type="text" name="" class="" value="Chennai" ></td> </tr> <tr> <td><label>Labour Charges</label>:</td><td><input type="text" name="" class="" value="300" ></td> </tr> <tr> <td><label>Conveyance Charges</label></td><td><input type="text" name="" class="" value="0" readonly></td> </tr> <tr> <td><label>Total Amount</label>:</td><td><input type="text" name="" class="" value="1000" ></td> </tr> <tr> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="" class="" value="4/9/2015" ></td> </tr>--> </table> <table id="table1" class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>Spare Name</td> <td>Quantity</td> <td>Amount</td> </tr> <tr> <td> <select> <option>---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr> </table> <a id="addRowBtn" style="background: rgb(179, 179, 179) none repeat scroll 0% 0% !important; padding: 10px; color: white; border-radius:5px;">Add Row</a> <table class="tableadd"> <tr> <td><label>Spare Tax Amount</label>:</td><td><input type="text" name="" class="" value="70" ></td><td><label>Spare Total Charges</label>:</td><td><input type="text" name="" class="" value="700" ></td> </tr> <tr> <td><label>Labour Charges</label>:</td><td><input type="text" name="" class="" value="300" ></td><td><label>Conveyance Charges</label>:</td><td><input type="text" name="" class="" value="0" ></td> </tr> <tr> <td><label>Total Amount</label>:</td><td><input type="text" name="" class="" value="1000" ></td><td><label>Service Location</label>:</td><td><input type="text" name="" class="" value="Chennai" ></td> </tr> <tr> <td><label >Status</label></td> <td> <select> <option>---Select---</option> <option value="ready">Ready For Delivery</option> <option value="delivery">Delivered</option> </select> </td> </tr> <tr class="ready box"> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="" class="date" value="4/9/2015" ></td> </tr> <tr class="ready box"> <td><label>Comments</label>:</td><td><input type="text" name="" class="" value="Delivered" ></td> </tr> <tr class="delivery box"> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="" class="date" value="4/9/2015" ></td> </tr> <tr class="delivery box"> <td><label>Comments</label>:</td><td><input type="text" name="" class="" value="Delivered" ></td> </tr> <tr class="delivery box"> <td><label>Assign To</label>:</td><td><input type="text" name="" class="" value="Vishnu" ></td> </tr> </table> <table class="tableadd" style="margin-top: 25px;"> <tr > <td ><button class="btn cyan waves-effect waves-light " type="submit" name="action">Send Quote to Customer <i class="fa fa-arrow-right"></i> </button> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Confirm <i class="fa fa-arrow-right"></i> </button> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }); }); }//]]> </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/add_row_prod.php <div class="col-md-12" style="padding: 0px"> <div class="col-md-3 col-sm-6 col-xs-12"> <input type="text" name="cat_name[]" id="UserName<?php echo $count; ?>" class="firstname"> <div class="fname" id="lname<?php echo $count; ?>" style="color:red"> </div> <div class="fname" id="lnamee<?php echo $count; ?>" style="color:red"> </div> </div><div class="col-md-1 col-sm-6 col-xs-12" style="padding:0px"><a class="delRowBtn btn btn-primary fa fa-trash" style="height:30px;"></a></div> </div> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ //$("#UserName<?php echo $count; ?>").keyup(function(){ $(document).on("keyup","#UserName<?php echo $count; ?>", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var name1=$('#UserName<?php echo $count; ?>').val(); //var name1=document.getElementById( "UserName<?php echo $count; ?>" ).value; //alert(name1); if(name1) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name1, }, success: function (data) { // alert(data); if(data == 0){ $('#lnamee<?php echo $count; ?>').html(''); } else{ //alert("else called"); $('#lnamee<?php echo $count; ?>').text('Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); $('#UserName<?php echo $count; ?>').val(''); return false; } } }); } } $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName<?php echo $count; ?>").val()==""){ $("#lname<?php echo $count; ?>").text("Enter Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); event.preventDefault(); } }); $("#UserName<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#lname<?php echo $count; ?>").show(); } else{ $("#lname<?php echo $count; ?>").fadeOut('slow'); } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); </script> <file_sep>/application/views_bkMarch_0817/spare_stock.php <head> <style> select{width:200px;} thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:white; } input[readonly] { border:none; } .data{ border: 1px solid gray !important; width: 25% !important; margin-right:4px !important; } .data1{ border: 1px solid gray !important; width: 20% !important; margin-right:4px !important; } .date { border: 1px solid gray !important; width: 32% !important; margin-right:4px !important; } </style> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=text]{ background-color: transparent; border: none; width: 100%; font-size: 12px; margin: 0 0 -2px 0; padding: 5px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <!-- Add jQuery library --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery-1.10.1.min.js"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); $(document).ready(function() { $("#fancybox-manual-b").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); $.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popup', type : 'iframe', padding : 5 }); }); $("#fancybox-manual-bc").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); $.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popupminus', type : 'iframe', padding : 5 }); }); }); </script> </head> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare Stock</h2> <hr> <!--DataTables example--> <div id="table-datatables" style="width:90%; margin-left:5%;"> <div class="row"> <div class="col-md-12"> <div style="float: right; height:50px; "> <a id="fancybox-manual-b" href="javascript:;" style="margin-right: 20px;"><img src="<?php echo base_url(); ?>assets/images/spare_add1.png" alt="materialize logo"></a> <a id="fancybox-manual-bc" href="javascript:;"><img src="<?php echo base_url(); ?>assets/images/spare_delete1.png" alt="materialize logo"></a> </div> <table id="data-table-simple" class="responsive-table display" cellspacing="0" style=" margin-top:2%;"> <thead> <tr> <td>Spare Name</td> <td>Stock In Hand</td> <td>Spare With Engineers</td> <td>Used Spare</td> </tr> </thead> <tbody> <?php foreach($spare_stock as $sparekey){ ?> <tr> <td><input type="text" value="<?php echo $sparekey->spare_name; ?>" class="" name="spare_name" id="spare_name" readonly></td> <td><input type="text" value="<?php echo $sparekey->spare_qty; ?>" class="" name="total_spare" id="total_spare_<?php echo $sparekey->id; ?>" readonly></td> <td><input type="text" value="<?php echo $sparekey->eng_spare; ?>" class="" name="engg_spare" id="engg_spare_<?php echo $sparekey->id; ?>" readonly></td> <td><input type="text" value="<?php echo $sparekey->used_spare; ?>" class="" name="used_spare" id="used_spare_<?php echo $sparekey->id; ?>" readonly></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ $(document).ready(function () { $('#data-table-simple').dataTable({ "order": [[0,"desc"]], "aoColumns": [ { "sType": "cust-txt" }, { "sType": "cust-txt" }, { "sType": "cust-txt" }, { "sType": "cust-txt" } ]}); }); </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script>--> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/edit_cust_type.php <style> input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(document).ready(function(){ $(document).on("keyup","#custtype", function(){ var timer1; clearTimeout(timer1); timer1 = setTimeout(brand1, 3000); }); //alert("hii"); function brand1(){ var id=$("#custtype").val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/custtype_validation", data: datastring, cache: false, success: function(data) { //alert(data); if(data == 0){ $('#fname').html(''); } else{ $('#fname').html('Customer Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('.corporate').val(''); return false; } } }); } }); </script> <script> $(document).ready(function(){ $('.corporate').change(function() { //alert("hii"); var id=$(this).val(); var datastring = 'id='+id; }); $("#registersubmit").click(function(event){ //alert("xcfg"); if($(".corporate").val()==""){ $("#fname").text("Enter Customer Type").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $(".corporate").keyup(function(){ if($(this).val()==""){ $("#fname").show(); } else{ $("#fname").hide(); } }) }); </script> <style> .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold !important; border-radius: 5px; cursor:pointer; } .link:hover{ color: white; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .btn{text-transform:none !important;} </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Customer Type</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/edit_customer_type" method="post"> <table id="myTable" class="tableadd"> <div class="col-md-3 col-sm-6 col-xs-12"> <label><font color="red">*</font>Customer Type</label> <input type="text" name="cust_type" class="corporate" value="<?php foreach($list as $key){ echo $key->type; } ?>" maxlength="30" id='custtype'><input type="hidden" name="cust_typeid" class="corporate" value="<?php foreach($list as $key){ echo $key->id;} ?>"> <input type="hidden" name="cust_type1" class="corporate1" value="<?php foreach($list as $key){ echo $key->type; } ?>"> <div id="fname"></div> </div> <!--<tr> <td><label style="width:180px;font-weight:bold;">Customer Type</label></td> </tr> <tr> <td><input type="text" name="cust_type" class="corporate" value="<?php echo $key->type; ?>"><input type="hidden" name="cust_typeid" class="corporate" value="<?php echo $key->id; ?>"></td> </tr>--> </table> <button class="btn cyan waves-effect waves-light " type="submit" name="action" id="registersubmit" style="margin-left:14px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/edit_prod_cat.php <style> .btn{text-transform:none !important;} .tableadd tr td input { width: 237px; /* height: 22px !important; */ /* border: 1px solid #B3B3B3; */ border-radius: 2px; /* padding-left: 10px; */ margin-left: 14px; } .tableadd tr td input { height: 22px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).on("keyup","#UserName1", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var name=$('#UserName1').val(); //alert(name); if(name !=''){ $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name, }, success: function (data) { //alert(data); if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '11px'}); $('#UserName1').val(''); return false; } } }); } } }); </script> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($(".corporate").val()==""){ $("#lname1").text("Enter the Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'11px'}); event.preventDefault(); } }); $(".corporate").keyup(function(){ if($(this).val()==""){ $("#lname1").show(); } else{ $("#lname1").fadeOut('slow'); } }) }); </script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { border-radius:5px; /* margin-bottom: 25px !important;*/ } .tableadd tr td input { width: 215px; } .tableadd { margin-bottom:35px; } .tableadd tr td label { font-weight:bold; } .star{ color:#ff0000; font-size:15px; } a:hover, a:active, a:focus { outline: none; text-decoration: none; color: #522276; } a { color: #522276; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Product Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"></div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Productcategory/edit_prod_category"" method="post"> <table id="myTable" class="tableadd"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category Name <span class="star">*</span></label> <input type="text" name="cat_name" class="corporate" value="<?php foreach($list As $key){ echo $key->product_category; } ?>" maxlength="80" id="UserName1"> <input type="hidden" name="cat_name1" class="corporate1" value="<?php foreach($list As $key){ echo $key->product_category; } ?>" maxlength="30"> <input type="hidden" name="catid" class="corporate" value="<?php foreach($list As $key){ echo $key->id; }?>"> <div id="lname1" ></div> </div> </table> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" style="margin-left:15px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"></td> </tr> </table> </form> </div> </div> <div class="col-md-1"></div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/comp_list.php <style> .tableadd tr td input { width: 210px !important; } .tableadd tr td label{ width:150px !important; } </style> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} input[type=text]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 100%; height:30px; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select{border: 1px solid #eee;} .btn{text-transform:none !important;} </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Company Details</h2> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>company/edit_company" method="post" name="frmComp" autocomplete="off"> <table class="tableadd"> <?php foreach($list as $key){?> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Company Name</label> <input type="text" name="name" class="compname" value="<?php echo $key->name; ?>" maxlength="50"><input type="hidden" name="compid" class="" value="1" > </div> <div class="col-md-3"> <label>Mobile</label> <input type="text" name="mobile" class="mobileno" id="mobile" value="<?php echo $key->mobile; ?>" maxlength="15"> <div class="mobileerror"></div> </div> <div class="col-md-3"> <label>Phone</label> <input type="text" name="phone" class="phoneno" id="phone" value="<?php echo $key->phone; ?>" maxlength="15"> <div class="phoneerror"></div> </div> <div class="col-md-3"> <label>Company Email ID</label> <input type="text" name="comp_email" class="mailid" value="<?php echo $key->comp_email; ?>" > <div class="emailerror"></div> </div> </div> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>Manager Email ID</label> <input type="text" name="mgr_email" class="memailid" value="<?php echo $key->mgr_email; ?>" > <div class="memailerror"></div> </div> <div class="col-md-3"> <label>Address 1</label> <input type="text" name="addr1" class="" value="<?php echo $key->addr1; ?>" > </div> <div class="col-md-3"> <label>Address 2</label> <input type="text" name="addr2" class="" value="<?php echo $key->addr2; ?>" > </div> <div class="col-md-3"> <label>City</label> <input type="text" name="city" id="search-box" class="city" value="<?php echo $key->city; ?>" maxlength="100"><div id="suggesstion-box" ></div> </div> </div> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>State</label> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id==$key->state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> </div> <div class="col-md-3"> <label>Pincode</label> <input type="text" name="pincode" class="pin" id="pincode" value="<?php echo $key->pincode; ?>" maxlength="6"> <div class="pinerror"></div> </div> <div class="col-md-3"> <label>Service Tax#</label> <input type="text" name="service_tax" class="service" id="service_tax" value="<?php echo $key->service_tax; ?>" maxlength="10"> <div class="serviceerror"></div> </div> <div class="col-md-3"> <label>PAN</label> <input type="text" name="pan" class="pancard" id="pan" value="<?php echo $key->pan; ?>" maxlength="10"> <div class="panerror"></div> </div> </div> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3"> <label>TNVAT Registration#</label> <input type="text" name="vat_no" class="vatreg" id="vat_no" value="<?php echo $key->vat_no; ?>" maxlength="10"> </div> </div> <!---<tr> <!--<td><label>Company Id</label></td><td><input type="text" name="comp_id" class="" value="<?php echo $key->comp_id; ?>" ></td> <td><label>Company Name</label></td><td><input type="text" name="name" class="" value="<?php echo $key->name; ?>" ><input type="hidden" name="compid" class="" value="1" ></td> <td><label>Mobile</label></td><td><input type="text" name="mobile" class="" id="mobile" value="<?php echo $key->mobile; ?>" ></td> </tr> <tr> <td><label>Phone</label></td><td><input type="text" name="phone" class="" id="phone" value="<?php echo $key->phone; ?>" ></td><td><label>Company Email ID</label></td><td><input type="text" name="comp_email" class="" value="<?php echo $key->comp_email; ?>" ></td> </tr> <tr> <td><label>Manager Email ID</label></td><td><input type="text" name="mgr_email" class="" value="<?php echo $key->mgr_email; ?>" ></td><td><label>Address 1</label></td><td><input type="text" name="addr1" class="" value="<?php echo $key->addr1; ?>" ></td> </tr> <tr> <td><label>Address 2</label></td><td><input type="text" name="addr2" class="" value="<?php echo $key->addr2; ?>" ></td> <td><label>City</label></td><td><input type="text" name="city" id="search-box" class="" value="<?php echo $key->city; ?>" ><div id="suggesstion-box" ></div></td> </tr> <tr> <td><label>State</label></td><td> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id==$key->state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> </td> <td><label>Pincode</label></td><td><input type="text" name="pincode" class="" id="pincode" value="<?php echo $key->pincode; ?>" ></td> </tr> <tr> <td><label>Service Tax#</label></td><td><input type="text" name="service_tax" class="" id="service_tax" value="<?php echo $key->service_tax; ?>" ></td><td><label>PAN</label></td><td><input type="text" name="pan" class="" id="pan" value="<?php echo $key->pan; ?>" ></td> </tr> <tr> <td><label>TNVAT Registration#</label></td><td><input type="text" name="vat_no" class="" id="vat_no" value="<?php echo $key->vat_no; ?>" ></td> </tr>-- <?php } ?> </table>--> <table class="tableadd" style="margin-top: 25px;"> <tr > <td > <button class="btn cyan waves-effect waves-light companysubmit" type="submit" name="action" style="margin-left:20px;">Submit </button> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <!--<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>--> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>Employee/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <!-- <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script>--> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script> $(function(){ var pan=/^([A-Z]{5})([0-9]{4})([A-Z]{1})$/; var regeditmail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.(com|org|net|co.in|mil|edu|gov|gov.in))$/; //var pancard=$(".pan").val(); $(".companysubmit").click(function(event){ if($(".memailid").val()==""){ $(".memailerror").text("Please enter Manager Mail ID").show().css({'color':'#ff0000','font-size':'11px'}); event.preventDefault(); } if($(".pancard").val()==""){ $(".panerror").text("Please enter pancard number").show().css({'color':'#ff0000','font-size':'11px'}); event.preventDefault(); } }); $(".mobileno,.phoneno,.pin").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9]/g,"")); }); $(".compname,.service,.vatreg").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9]/g,"")); }); $(".city").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z]/g,"")); }); $(".pancard").change(function(){ if(!pan.test($(this).val())){ $(".panerror").text("Invalid Pan Number").show().css({'color':'#ff0000','font-size':'11px'}); return false; $(this).focus(); } }); $(".mailid").on("change", function(event){ if(!regeditmail.test($(this).val())){ $(".emailerror").text("Invalid Email ID").show().css({'color':'#ff0000','font-size':'11px'}); event.preventDefault(); $(this).focus(); } }); $(".memailid").change(function(){ if(!regeditmail.test($(this).val())){ $(".memailerror").text("Invalid Email ID").show().css({'color':'#ff0000','font-size':'11px'}); return false; $(this).focus(); } }); $(".pancard").on("keyup", function(event){ $(".panerror").fadeOut('slow'); }); $(".mailid").on("keyup", function(event){ if($(this).val()==""){ $(".emailerror").show(); } else{ $(".emailerror").fadeOut('slow'); } }); $(".memailid").on("keyup", function(event){ $(".memailerror").fadeOut('slow'); }); }); </script> <!--<script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script>--> </body> </html><file_sep>/application/controllers/QC_Master.php <?php class QC_Master extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('qc_master_model'); } public function add_qc_parameter(){ $model=$this->input->post('model'); if($this->qc_master_model->checkqcmodel($model)) { echo "<script>window.location.href='".base_url()."pages/qc_masters';alert(' Model Name already exist');</script>"; }else{ date_default_timezone_set('Asia/Calcutta'); $created_on = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $model=$this->input->post('model'); $qc_param=$this->input->post('qc_param'); $qc_value=$this->input->post('qc_value'); for($i=0; $i<count($qc_param); $i++) { $data1 = array('model' => $model, 'qc_param' => $qc_param[$i], 'qc_value' => $qc_value[$i], 'created_on' => $created_on, 'updated_on' => $updated_on, 'user_id' => $user_id); $this->qc_master_model->add_qc_master($data1); } echo "<script>window.location.href='".base_url()."pages/qc_masters_list';alert('QC parameters added');</script>"; } } public function view_models(){ $id = $this->uri->segment(3); //echo $id; //$id=$this->uri->segment(3); //$data['modelid']=$this->uri->segment(3); $data1['getqcparametersbyid1']=$this->qc_master_model->getqcparametersbyid($id); $data1['modellist']=$this->qc_master_model->modellist(); //print_r($data1); $this->load->view('view_qc_model',$data1); } public function update_qc_parameter(){ $id=$this->uri->segment(3); $data['modelid']=$this->uri->segment(3); $data['getqcparametersbyid']=$this->qc_master_model->getqcparametersbyid($id); $data['modellist']=$this->qc_master_model->modellist(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_qc_master',$data); } public function edit_qc_parameter(){ error_reporting(0); date_default_timezone_set('Asia/Calcutta'); $created_on = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $modelid=$this->input->post('model'); $model=$this->input->post('model'); $qc_param=$this->input->post('qc_param'); $qc_value=$this->input->post('qc_value'); $qc_param_id=$this->input->post('qc_param_id'); $qc_param_id_real=$this->input->post('qc_param_id_real'); $diff_arr = array_values(array_diff($qc_param_id_real,$qc_param_id)); if(!empty($diff_arr)){ for($j=0;$j<count($diff_arr);$j++){ /* echo "<pre>"; print_r($dif_arr1); */ $this->qc_master_model->delete_qc_master($diff_arr[$j]); } } for($i=0; $i<count($qc_param); $i++) { $data1 = array('model' => $model, 'qc_param' => $qc_param[$i], 'qc_value' => $qc_value[$i], 'created_on' => $created_on, 'updated_on' => $updated_on, 'user_id' => $user_id); if($qc_param_id[$i]!="" && isset($qc_param_id[$i])){ $where = "model=".$modelid." AND id=".$qc_param_id[$i]; $result=$this->qc_master_model->update_qc_param($data1,$where); }else{ $result=$this->qc_master_model->add_qc_master1($data1); } } echo "<script>window.location.href='".base_url()."pages/qc_masters_list';alert('QC parameters updated');</script>"; } public function add_service_charge(){ $service_cat=$this->input->post('service_cat'); date_default_timezone_set('Asia/Calcutta'); $created_on = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $model=$data1['model']=$this->input->post('model'); $service_charge=$data1['service_charge']=$this->input->post('service_charge'); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $c=$model; $count=count($c); $data2 =array(); for($i=0; $i<$count; $i++) { if($model[$i]!=""){ $data2 = array( 'service_cat_id' => $service_cat, 'model' => $model[$i], 'service_charge' => $service_charge[$i], 'created_on' => $created_on, 'updated_on' => $updated_on, 'user_id' => $user_id ); $this->Servicecategory_model->add_service_charge($data2); echo "<script>alert('Service Charge added');window.location.href='".base_url()."pages/service_charge_list';</script>"; }else{ echo "<script>window.location.href='".base_url()."pages/add_service_charge';alert('Please select model');</script>"; } } } public function update_servicecharge(){ $id=$this->uri->segment(3); $data['list']=$this->Servicecategory_model->getservicecatbyid($id); $data['getservicechargeInfobyid']=$this->Servicecategory_model->getservicechargeInfobyid($id); $data['service_cat_list']=$this->Servicecategory_model->service_cat_list(); $data['modellist']=$this->Servicecategory_model->modellist(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_service_charge',$data); } public function edit_service_charge(){ $service_cat_id=$this->input->post('service_cat'); $rowid=$data1['service_charge_id']=$this->input->post('service_charge_id'); $model=$data1['model']=$this->input->post('model'); $service_charge=$data1['service_charge']=$this->input->post('service_charge'); date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $c=$model; $count=count($c); $data8 =array(); for($i=0; $i<$count; $i++) { $data8 = array( 'model' => $model[$i], 'service_charge' => $service_charge[$i], 'updated_on' => $updated_on, 'user_id' => $user_id ); if($rowid[$i]!="" && isset($rowid[$i])){ $where = "service_cat_id=".$service_cat_id." AND id=".$rowid[$i]; $result=$this->Servicecategory_model->update_service_charges($data8,$where); } } echo "<script>alert('Service Charge Updated');window.location.href='".base_url()."pages/service_charge_list';</script>"; } public function del_serv_category(){ $id=$this->input->post('id'); $s = $this->Servicecategory_model->del_serv_cat($id); } public function addrow2(){ //echo "hello world";exit; $data['count']=$this->input->post('countid'); $data['modellist']=$this->qc_master_model->modellist(); $this->load->view('add_qc_master_row',$data); } public function service_validation() { $product_id = $this->input->post('p_id'); $this->output->set_content_type("application/json")->set_output(json_encode($this->Servicecategory_model->service_validation($product_id))); } }<file_sep>/application/views/spare_purchase_print.php <head> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd tr td label{ width: 180px; } .tableadd1 tr td { border: 1px solid gray; padding: 0px 10px; } .tableadd1 tr { height: 33px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:#000; } .tableadd1{ border:1px solid gray; } .tableadd2 tr td{ border:0px; width: 130px; padding-left:50px; } .tableadd2 tr td label{ width: 150px; margin-left: 38px; position: relative; left: -55px; } .tableadd3 tr td{ border:0px; width: 130px; } .tableadd1 tr td.plus { padding-top: 14px; text-align:center; } .tableadd1 tr td.plus input { width:70px; border:1px solid gray; } .tableadd1 tr td.item { padding-top: 14px; } .tableadd1 tr td.item input { width:155px; border:1px solid gray; } .tableadd1 tr td input { height: 33px; border-radius: 5px; padding-left: 10px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { width:57%; margin-top:20px; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:#000; } #errorBox{ color:#F00; } /*input[id=basicamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 5px; float:right; position: relative; top: 5px; left: 29px; } input[id=cst]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 5px; float:right; position: relative; top: 20px; left: 208px; } input[id=freight]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 5px; float:right; position: relative; top: 35px; left: 364px; } input[id=totalamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 5px; float:right; position: relative; top: 50px; left: 560px; }*/ .purchasedetail{ position: relative; top: -63px; left: 50px; } .pipurchasedetail{ position: relative; top: -63px; left: 90px; } .cstpurchasedetail{ position: relative; top: -63px; left: 95px; } .tableadd tr td input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 5px; padding-left: 10px; } .calc input[type=text]{ width: 111px; border: 1px solid gray; border-radius: 5px; padding: 5px; float:left; position: relative; left: -192px; } #mytextarea{ outline:0px; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow2", data: datastring, cache: false, success: function(result) { //alert(result); // $('#table1').append(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('minus-0').value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus-0').value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); function UpdateStatus1(id){ //alert(id);alert($("#enggdate_"+id).val()); var eng_name = $("#eng_name-"+id).val(); var eng_spare_name = $("#eng_spare_name-"+id).val(); var engg_date = $("#enggdate_"+id).val(); if(eng_name==""){ alert("Enter the Engineer Name"); }else if(eng_spare_name==""){ alert("Enter the Spare Name"); }else if(engg_date==""){ alert("Enter the Date"); }else{ var plus = $("#plus-"+id).val(); var minus = $("#minus-"+id).val(); //alert(engg_date); var engg_reason = $("#engg_reason-"+id).val(); var spare_qty = $("#spare_qty-"+id).val(); var used_spare = $("#used_spare-"+id).val(); var eng_spare = $("#eng_spare-"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/add_spare_engg', data: {'eng_name' : eng_name, 'eng_spare_name' : eng_spare_name, 'plus' : plus, 'minus' : minus, 'engg_date' : engg_date, 'engg_reason' : engg_reason, 'spare_qty' : spare_qty, 'used_spare' : used_spare, 'eng_spare' : eng_spare}, dataType: "text", cache:false, success: function(data){ alert("Spares For Engineers Added"); } }); }); } } </script> <script> $(document).ready(function(){ //alert("bfh"); $('#sample').change(function(){ //alert("hiiio"); var id = $(this).val(); // var idd=$(this).closest(this).attr('id'); //alert(idd); // var arr= idd.split('-'); // var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_0').val(data.customer_name), $('#cust_id_0').val(data.cust) }); } }); }); /*$(".tstfig").change(function(){ alert("hiiio"); var id=$(this).attr('id'); var field=$(this).attr('id').split('_').pop(); var v=$('#'+id).val(); var dataString='id='+v; //alert(vl); //alert("spareid: "+idd); // var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_'+field).val(data.customer_name), $('#cust_id_'+field).val(data.cust) }); } }); });*/ }); </script> <script> function frmValidate(){ //alert("hii"); //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var eng_name = document.frmSpareEng.eng_name.value; spare_receipt = document.frmSpareEng.spare_receipt.value; if(eng_name == "") { document.frmSpareEng.eng_name.focus(); document.getElementById("errorBox").innerHTML = "select the engineer name"; return false; } if(spare_receipt == "") { document.frmSpareEng.spare_receipt.focus(); document.getElementById("errorBox").innerHTML = "select the service type"; return false; } } </script> </head> <section id="content"> <div class="container"> <div class="section"> <form action="<?php echo base_url(); ?>Spare/spare_purchase_print" method="post" name="frmSpareEngg" autocomplete="off"> <div id="printableArea"> <table class="tableadd" width="89%"> <tr> <td class="noborder" colspan="5" style="font-weight:bold;width: 345px;position: relative;top: 30px;left:50px"><div class="pull-left"><h1 class="headingprint" style="font-size: 25px;margin-top: 0px;width:500px;">Syndicate Diagnostics<br>127B Bricklin Road,Purusaiwalkam, Chennai 600007</h1> <!--<h2 class="headingprint" style="font-size: 25px;margin-top: 0px;">No:4/6, BADRI VEERASAMY LANE,</h2> <h2 class="headingprint" style="font-size: 25px;margin-top: 50px;">NSC BOSE ROAD, CHENNAI-79.</h2>--></div></td> <!--<td class="noborder" colspan="5" style="font-weight:bold;text-align: right;position: relative;top: 30px;right:60px"><div class="pull-right" ><p><b>Date : <?php echo $key->engineer_date;?></b></div></p></td> --> </tr> <tr><td><div class="fir" style="width: 600px !important; text-align: justify;margin-left: -5px;margin-bottom: 30px;"></div></td></tr> </table> <!--<h4 class="header">Spares Purchase Order Receipt</h4>--> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <div id="errorBox"></div> <?php foreach($comp_info as $comkey){ ?> <div class="col-md-6 col-xs-6"> <div class="col-md-12"><b>From,</b></div> <div class="col-md-12"> <div class="col-md-3"><b>Company Name</b></div> <div class="col-md-3"><?php echo $comkey->name; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Address</b></div> <div class="col-md-3"><?php echo $comkey->addr1.' '.$comkey->addr2; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Contact Person</b></div> <div class="col-md-3"> Sandhya</div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Contact No</b></div> <div class="col-md-3">7401557722</div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Mail id:</b></div> <div class="col-md-3"><EMAIL></div> </div> </div> <div class="col-md-6 col-xs-6"> <div id="errorBox"></div> <?php foreach($get_purchase_ordersbyid as $key2){ ?> <div class="col-md-12"> <div class="col-md-3"><b>Date</b></div> <div class="col-md-3"><?php echo $key2->todaydate;?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>P.I / Ref No</b></div> <div class="col-md-3"><?php echo $key2->refno;?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Tin / CST No</b></div> <div class="col-md-3"><?php echo $key2->cst_no;?></div> </div> <?php } ?> </div> <?php } ?> </div> </div> <div class="col-md-12"> <?php foreach($get_purchase_ordersbyid as $vendorkey){ ?> <div class="col-md-12"><b>To,</b></div> <div class="col-md-12"> <div class="col-md-3"><b>Vendor Name</b></div> <div class="col-md-3"><?php echo $vendorkey->to_name; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Address</b></div> <div class="col-md-3"><?php echo $vendorkey->to_addr; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Contact Person</b></div> <div class="col-md-3"><?php echo $vendorkey->to_cont_name; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Contact no</b></div> <div class="col-md-3"><?php echo $vendorkey->to_cont_no; ?></div> </div> <div class="col-md-12"> <div class="col-md-3"><b>Mail id</b></div> <div class="col-md-3"><?php echo $vendorkey->to_cont_mail; ?></div> </div> </div> <?php } ?> <div style="margin:10px;"> <table id="table1" class="tableadd1" style="width:100%;border:1px solid gray;" border="1"> <tr style="background: #6b4289; border: 1px solid gray;"><td style="text-align:center"><label style="color:#fff;">SI No</label></td><td style="text-align:center"><label style="color:#fff;">Part Number & Item Name</label></td><td style="text-align:center"><label style="color:#fff;">Qty</label></td><td style="text-align:center"><label style="color:#fff;">Rate per Unit</label></td><td style="text-align:center"><label style="color:#fff;">Total Amount</label></td></tr> <?php foreach($get_purchase_orders_sparesbyid as $sparekey){ ?> <tr> <td class="plus" style="text-align:center"><?php echo $sparekey->sr_no;?></td> <td class="item" style="text-align:center"> <?php foreach($spare_list as $sparekey1){ if($sparekey1->id==$sparekey->spare_name){ echo $sparekey1->spare_name; } } ?> </td> <td class="plus" style="text-align:center"><?php echo $sparekey->spare_qty;?></td> <td class="plus" style="text-align:center"><?php echo $sparekey->rate;?></td> <td class="plus" style="text-align:center"><?php echo $sparekey->spare_tot;?></td> </tr> <?php } ?> <!--</table> <br> <table class="tableadd2" style="width:57%;float:right;margin-right: -228px;">--> <?php foreach($get_purchase_ordersbyid as $key3){ ?> <tr> <td colspan="4" style="text-align:right;padding-right:50px"><label>Basic Amount</label></td>&nbsp; <td style="text-align:center"><?php echo $key3->basicamount; ?></td> </tr> <tr> <td colspan="4" style="text-align:right;padding-right:50px"><label><?php foreach($tax_list as $taxkey){if($taxkey->id==$key3->tax_id){echo $taxkey->tax_name.' '.$taxkey->tax_percentage; } }?>%</label></td>&nbsp; <td style="text-align:center"><?php echo $key3->cst; ?></td> </tr> <tr> <td colspan="4" style="text-align:right;padding-right:50px"><label>Freight</label></td>&nbsp; <td style="text-align:center"><?php echo $key3->freight; ?></td> </tr> <tr> <td colspan="4" style="text-align:right;padding-right:50px"><label>Total Amount</label></td>&nbsp; <td style="text-align:center"><?php echo $key3->totalamount; ?></td> </tr> <?php } ?> </table> </div> <br><br> <!--<a id="addMoreRows" class="rowadd" style="padding: 8.5px; margin-right: 20px;">Add Row</a>--> </div> </div> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> <p><b>Imp Note:</b> Minimum order value should be Rs. 3000/- for spare parts.</p> <p><b>Note:</b> If Shipping address is different form above address pls mention here.</p> <?php foreach($get_purchase_ordersbyid as $key4){ ?> <p style="margin-top:20px;width: 375px;"><b>ADDRESS:</b> <span><?php echo $key4->spec_addr; ?></span></p> <p><b>Any Specific instruction:</b> <?php echo $key4->spec_ins; ?></p><br> <?php } ?> <p><b>Terms and Conditions:</b><br> <ol> <li>Payment 100% Advance Payment by DD/ Cash in our HDFC Bank account in favor of Arihant Marketing</li> <li>If "C" form not received on date, interest @24% per annum will be charged from the actual amount.</li> <li>All disputes subject to jurisdication of Chennai Courts.</li> <li>Kindly fill your order form with Part Name No clearly and send to concern person.</li> <li>For Parts under warranty compulsory send faulty spares for getting replacement of new; with m/c serial no, wherever applicable.</li> <li>Order processing will take minimum 2-3 working days.</li> <li>No orders will be processsed if PO value is less than Rs 3000/-</li> <li>Chick for stock availability before placing order.</li> <li>Payment details must be sent for timely dispatch.</li> </ol> </div> <br><br> <button class="btn cyan waves-effect waves-light" onClick="printDiv('printableArea')" style="float:right;position: relative;right: 130px;width:90px;">Print</button> <br><br><br><br> </form> </div> </div> </section> <!--</div>--> <script> $(function(){ $(".date").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: "1950:2055" }); }) </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function() { $(".eng_spare_name").select2(); /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); </script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>customer/add_quickforspares/'+id, type : 'iframe', padding : 5 }); } </script> <script> function setSelectedUser(customer_name,cust_idd,spare_rowid) { //alert("JII"); $('#custtest_'+spare_rowid).val(customer_name); $('#cust_id_'+spare_rowid).val(cust_idd); } </script> </body> </html><file_sep>/application/controllers/Monthreport.php <?php class Monthreport extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('monthreport_model'); } function get_monthreport() { $from_date = $this->input->post('from'); //echo $from_date;exit; $to_date = $this->input->post('to'); $data['month'] = $this->monthreport_model->getstampingmonth_report($from_date,$to_date); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('monthreport_data',$data); } } ?><file_sep>/application/views_bkMarch_0817/problemaddrow.php <?php $count=$_POST['countid']; ?> <div class="col-md-12" style="padding:0px"> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Category Name</label> <input type="text" name="prob_cat_name[]" id="lname-<?php echo $count;?>"><div id="uname-<?php echo $count;?>" style="color:red"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Model</label> <select name="model[]" id="fname-<?php echo $count;?>"> <option value="0">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="sname-<?php echo $count;?>" style="color:red;"></div> </div> <div class="col-md-3"> <a class="delRowBtn btn btn-primary fa fa-trash"></a> </div> </div> <script> $(document).ready(function(){ $(document).on("change","#fname-<?php echo $count;?>", function(){ var a=$(this).attr('id').split('-').pop(); var model = $(this).val(); var category=$("#lname"+a).val(); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>problemcategory/category_validation', data: { category:category, model:model, }, success: function (data) { // alert(data); if(data == 0){ $('#sname-'+a).fadeOut('slow'); } else{ $('#sname-'+a).text('Model Name Already Exist').show().delay(1000).fadeOut(); $('#fname-'+a).val(''); return false; } } }); }); $(".registersubmit").click(function(event){ if($('#fname-<?php echo $count;?>').val()=="0"){ $('#sname-<?php echo $count;?>').text("Select Model Name").css({'color':'#ff0000','font-size':'15px'}); } if($('#lname-<?php echo $count;?>').val()==""){ $('#uname-<?php echo $count;?>').text("Enter Problem Category Name").css({'color':'#ff0000','font-size':'15px'}); } }); $("#lname-<?php echo $count;?>").keyup(function(){ if($(this).val()==""){ $("#uname-<?php echo $count;?>").show(); } else{ $("#uname-<?php echo $count;?>").fadeOut('slow'); } }); $("#fname-<?php echo $count;?>").click(function(){ if($(this).val()=="0"){ $("#sname-<?php echo $count;?>").show(); } else{ $("#sname-<?php echo $count;?>").fadeOut('slow'); } }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <style> .delRowBtn{ position: relative; top: 20px; } </style><file_sep>/application/views_bkMarch_0817/agingreport_list.php <style> body{background-color:#fff;} table.dataTable tbody td{ padding: 8px 10px !important; } input { height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } /*input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #000; border-bottom: 1px solid #055E87; border-radius: 0; outline: none; height: 3.9rem; width: 100%; font-size: 1.5rem; margin: 0 0 0 0; padding: 0; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height: 3rem !important; }*/ #search { height: 3rem !important; margin-top: 10px; margin-left: 30px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <?php //print_r($enggname_list);exit;?> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Aging Report</h2> <hr> <form name="myForm" action="<?php echo base_url(); ?>report/get_agingreport" method="post" onsubmit="return validateForm()"> <div class="col-md-12"> <div class="col-md-3"> <div><label>From Date:</label></div> <div><input type="text" name="from" class="date"></div> </div> <div class="col-md-3"> <div><label>Date Range:</label></div> <div> <select name="range" > <option value="">--select--</option> <option value="0-7">0-7 days</option> <option value="8-15">8-15 days</option> <option value="16-30">16-30 days</option> <option value="31-60">31-60 days</option> <option value="61-90">61-90 days</option> <option value="91-91">91 and above</option> </select> </div> </div> <div class="col-md-3"> <div><label>Model Name:</label></div> <div> <select name="model"> <option value="">--select--</option> <?php foreach($model as $spare) {?> <option value="<?php echo $spare->id;?>"><?php echo $spare->model;?></option><?php } ?> </select> </div> </div> <div class="col-md-3"> <div><label>Customer Name:</label></div> <div> <select name="customer"> <option value="">--select--</option> <?php foreach($custom as $row) {?> <option value="<?php echo $row->id;?>"><?php echo $row->customer_name;?></option><?php } ?> </select> </div> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <div><label>Product Category:</label></div> <div> <select name="product"> <option value="">--select--</option> <?php foreach($product as $row) {?> <option value="<?php echo $row->id;?>"><?php echo $row->product_category;?></option><?php } ?> </select> </div> </div> <div class="col-md-3"> <div><label>Engineer Name:</label></div> <div> <select name="employee"> <option value="">--select--</option> <?php foreach($engineer as $row) {?> <option value="<?php echo $row->id;?>"><?php echo $row->emp_name;?></option><?php } ?> </select> </div> </div> <div class="col-md-3"> <div><label>Zone:</label></div> <div> <select name="zone"> <option value="">--select--</option> <?php foreach($zone as $row) {?> <option value="<?php echo $row->id;?>"><?php echo $row->service_loc;?></option><?php } ?> </select> </div> </div> </div> <!--<div><label>To Date:</label></div><div><input type="text" name="to" class="date"></div>--> <!--<div><label>Engineer Name:</label></div> <div><select name="engineer" > <option value="">---select---</option> <?php foreach($enggname_list as $eng) {?> <option value="<?php echo $eng->id;?>"><?php echo $eng->emp_name;?></option><?php } ?></select></div><br><br><br>--> <input type="submit" name="search" id="search" value="Search" class="submit_button btn btn-primary" > </form> <!--DataTables example--> </div> </div> </section> </div> </div> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ $(document).ready(function(){//alert("hfhh"); $(".date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); });//]]> </script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> </body> </html> <script> function validateForm() { var x = document.forms["myForm"]["from"].value; var y = document.forms["myForm"]["range"].value; if (x == null || x == "" && y == null || y == "") { alert("Choose From Date & Select Date Range"); return false; } } </script> <file_sep>/application/views_bkMarch_0817/prod_subcat_list.php <style> .ui-state-default { background: #fff !important; border: 3px solid #fff !important; color: #303f9f !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=text]{ background-color: transparent; border:none; border-radius: 7; width: 55% !important; font-size:12px; margin: 0 0 7px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <script> $(document).ready(function(){ $('[id^="pro_cat_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split(','); var procatid = arr['0']; var subid = arr['1']; var data_String; data_String = 'id='+subid+'&procatid='+procatid; $.post('<?php echo base_url(); ?>subcategory/update_sub_category',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Category changed"); //$('#actaddress').val(data.Address1), }); }); }); function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); subcat_name = $("#subcat_name_"+id).val(); //alert(subcat_name); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>subcategory/update_sub_category_name', data: {'id' : id, 'subcat_name' : subcat_name}, dataType: "text", cache:false, success: function(data){ alert("Sub Category updated"); } }); }); } function InactiveStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>subcategory/update_status_sub_category', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Sub Category made Inactive"); window.location = "<?php echo base_url(); ?>pages/prod_subcat_list"; } }); }); } function activeStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>subcategory/update_status_sub_category1', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Sub Category made Active"); window.location = "<?php echo base_url(); ?>pages/prod_subcat_list"; } }); }); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Product Sub-Category List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addsubcat.png" title="Add Product Sub-Category" style="width:24px;height:24px;">Add Product Sub-Category</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add Product Sub-Category" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0" style="margin-top:2%;"> <thead> <tr> <td style="text-align:center;font-size:13px;color:##303f9f;">Category Name</td> <td style="text-align:center;font-size:13px;color:##303f9f;">Sub-Category Name</td> <td style="text-align:center;font-size:13px;color:##303f9f;">Action</td> </tr> </thead> <tbody> <?php foreach($list as $key){ ?> <tr> <td><input type="text" value="<?php echo $key->product_category; ?>" class="" name="subcat_name" readonly></td> <td><input type="text" value="<?php echo $key->subcat_name; ?>" class="" name="subcat_name" readonly> </td> <td class="options-width" style="text-align:center;"> <a href="<?php echo base_url(); ?>subcategory/update_sub_category/<?php echo $key->prosubcat_id; ?>" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <?php if($key->status!='1') { ?> <a href="#" onclick="InactiveStatus('<?php echo $key->prosubcat_id; ?>')">InActive</a><?php } ?><?php if($key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $key->prosubcat_id; ?>')" >Active</a><?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/serialcron.php <p>Your file is ready. You can download it from <a href="<?php echo base_url();?>uploads/Serialreport.xls">here!</a></p> <?php $path = base_url('uploads/Serialreport.xls'); $to = "<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>"; //$to = "<EMAIL>"; $filename = $subject = 'Hi'; $email = "<EMAIL>"; $headers = 'From: ' . $email . "\r\n" . 'Reply-To: ' . $email . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $message = '<table width="100%" cellspacing="0" cellpadding="5" border="0" style="border: 1px solid black;">'; $message .= '<tr><th style="border: 1px solid black; background-color: #f2f2f2">Serialwise Reports</th></tr>'; $message .= '<tr><td style="border: 1px solid black;"><a href="'.$path.'">On Click Download Excel File </a></td></tr>'; $message .= '</table>'; echo $message; // Send mail mail($to, $subject, $message, $headers); ?><file_sep>/application/views/add_row_custtype.php <tr> <td style="width: 25.5%";> <input type="text" name="cust_type[]" class="firstname1" id="UserName<?php echo $count; ?>" maxlength="30"> <div class="fname" style="color:red;margin-left: 15px;" id="lname1<?php echo $count; ?>"></div> </td> <td> <a class="delRowBtn btn btn-primary" style="margin-top:-17px;width: 25px;height: 28px;"><i class="fa fa-trash"></i></a> </td> </tr> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ ///alert("hiii"); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName<?php echo $count; ?>" ).val()==""){ $("#lname1<?php echo $count; ?>" ).text("Enter Customer Type").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#UserName<?php echo $count; ?>" ).keyup(function(){ if($(this).val()==""){ $("#lname1<?php echo $count; ?>" ).show(); } else{ $("#lname1<?php echo $count; ?>" ).fadeOut('slow'); } }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script> <script> $(document).ready(function(){ $(document).on("keyup","#UserName<?php echo $count; ?>", function(){ var timer1; clearTimeout(timer1); timer1 = setTimeout(brand1, 3000); }); //alert("hii"); function brand1(){ var id=$('#UserName<?php echo $count; ?>').val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/custtype_validation", data: datastring, cache: false, success: function(data) { //alert(data); if(data == 0){ $('#lname1<?php echo $count; ?>').html(''); } else{ $('#lname1<?php echo $count; ?>').html('Customer Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#UserName<?php echo $count; ?>').val(''); return false; } } }); } }); </script> <file_sep>/application/views_bkMarch_0817/add_spares_row.php <tr> <td> <input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="" class="spare_qty"> <select name="spare_name[]" id="sparename_<?php echo $count; ?>" class="spare_name"> <option value="">---Select---</option> <?php foreach($spareListByModelId as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; ?></option> <?php } ?> </select> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Description of Failure</label> <textarea name="desc_failure[]" id="desc_failure" value="" class="noresize"></textarea> </div> </td> <td> <input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Why & When did it occur?</label> <textarea name="why_failure[]" id="why_failure" value="" class="noresize"></textarea> </div> </td> <td> <input type="text" value="" name="amt[]" id="amt<?php echo $count; ?>" class="" readonly><input type="hidden" value="" name="amt1" id="amt1<?php echo $count; ?>" class=""> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Corrective Action</label> <textarea name="correct_action[]" id="correct_action" value="" class="noresize"></textarea> </div> </td> <td></td> <td> <select name="warranty_claim_status[]" class="warranty" id="warranty<?php echo $count; ?>"> <option value="">---select---</option> <option value="to_claim">To claim</option> </select> </td> <td style="border:none;"><a class="delRowBtn1" style="font-size:20px;color: #000" id="delRowBtn1_<?php echo $count; ?>"><span class="fa fa-trash-o" style="margin-right: 0px;"></span></a></td> </tr> <!--<tr class="appendtr"> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> </tr>--> <script> $(function(){ $(".appendtr<?php echo $count; ?>").hide(); $("#warranty<?php echo $count; ?>").change(function(){ if($(this).find("option:selected").attr("value")=="to_claim"){ $(".appendtr<?php echo $count; ?>").show(); } else{ $(".appendtr<?php echo $count; ?>").hide(); } }); }); </script> <script> $('.spare_qty').keyup(function() { //alert($('#tax_type').val()); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); //alert(amc_type); var qty = $(this).val(); //alert("value"+$(this).val()); // var actual_qty = $('#spare_qty1'+ctid).val(); if(parseInt($(this).val())!="" && $(this).val()!=""){//alert("true"); if(parseInt($(this).val()) > parseInt($('#spare_qty1'+ctid).val())){ alert("Qty is only: "+ $('#spare_qty1'+ctid).val() + " nos. So please enter below that."); }else{ var cal_amt = parseInt($(this).val()) * parseInt($('#amt1'+ctid).val()); if(parseInt(cal_amt)){ $('#amt'+ctid).val(cal_amt); } } }else{ //alert("else"); $('#amt'+ctid).val(''); } var vals = 0; $('input[name="amt[]"]').each(function() { //alert("dsd"); //alert($(this).val()); vals += Number($(this).val()); //alert(val); $('#spare_tot').val(vals); }); var tax_amt = (vals * $('#tax_type').val()) / 100; if(warran=='Preventive' || warran=='Warranty' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); $('#total_amt1').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); //alert(Total_amount); $('#total_amt').val(Total_amount); $('#total_amt1').val(Total_amount); $('#service_pending_amt').val(Total_amount); $('#service_pending_amt1').val(Total_amount); } //$('input[name="res"]').val(val); }); </script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id = $(this).val(); //alert("spareid: "+id); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1'+ctid).val(data.spare_qty), $('#amt1'+ctid).val(data.sales_price), $('#used_spare'+ctid).val(data.used_spare) }); } }); }); }); </script> <style> label{ border:none !important; font-size: 0.85em !important; } textarea{ border:1px solid #ccc !important; width:95% !important; border-radius:5px !important; } .noresize{ resize:none; } </style><file_sep>/application/views/add_row_tax.php <style> .delRowBtn{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } </style> <div class="col-md-12" style="padding: 0px;"> <div class="col-md-3"> <input type="text" name="tax_name[]" class="model tax<?php echo $count; ?>" id="tax"> <div class="taxerror<?php echo $count; ?>"> </div> </div> <div class="col-md-3"> <input type="text" name="percentage[]" class="model percentage<?php echo $count; ?>" maxlength="5"> <div class="percenterror<?php echo $count; ?>"></div> </div> <div class="col-md-3"><a class="delRowBtn"><i class="fa fa-trash" style=" color: #643886;"></i></a></div> </div> <script> $(document).ready(function(){ $('.tax<?php echo $count; ?>').change(function(){ var tax=$(this).val(); //alert(tax); var datastring='tax='+tax; //alert(tax); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>tax/check_tax", data:datastring, cache:false, success:function(data){ //alert(data); if(data == 0){ $('.taxerror<?php echo $count; ?>').html(''); } else{ $('.taxerror<?php echo $count; ?>').html('Tax Name Already Exist!').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('.tax<?php echo $count; ?>').val(''); return false; } } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); $(".percentage<?php echo $count; ?>").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9.]/g,"")); }); $(".tax<?php echo $count; ?>").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $(".submittax").click(function(event){ if($(".tax<?php echo $count; ?>").val()==""){ $(".taxerror<?php echo $count; ?>").text("Please Enter Tax Name").show().css({ 'font-size':'10px', 'color':'#ff0000', 'position': 'relative', 'bottom': '15px' }); event.preventDefault(); } if($(".percentage<?php echo $count; ?>").val()==""){ $(".percenterror<?php echo $count; ?>").text("Please Enter the Percentage").show().css({ 'font-size':'10px', 'color':'#ff0000', 'position': 'relative', 'bottom': '15px' });; event.preventDefault(); } }); $(".percentage<?php echo $count; ?>").keyup(function(){ $(".percenterror<?php echo $count; ?>").fadeOut('slow'); }); $(".tax<?php echo $count; ?>").keyup(function(){ $(".taxerror<?php echo $count; ?>").fadeOut('slow'); }); }); </script><file_sep>/application/views/edit_cust.php <script> $( function() { var available_cities = []; //alert($(this).val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), success: function(data) { $.each(data, function(index, data){ available_cities.push(data.city); }); } }); /* var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; */ $( "#tags" ).autocomplete({ source: available_cities }); } ); </script> <script> $( function() { var available_cities = []; $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), success: function(data) { $.each(data, function(index, data){ available_cities.push(data.city); }); } }); /* var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; */ $( "#re_city" ).autocomplete({ source: available_cities }); } ); </script> <script> $(document).ready(function(){ // alert("djfh"); $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var zone = $('#service_zone').val(); var zones = zone.split('-'); var zoneid = zones['0']; var zone_coverage = zones['2']; //alert(zone_coverage); var datastring='countid='+vl1+'&zoneid='+zoneid+'&zone_coverage='+zone_coverage; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .btn-danger { color: #613281; background-color: #d9534f; border-color: #d43f3a; } .btn { display: inline-block; padding: 2px 12px; text-transform:none !important; } .cyan { background-color: black !important; width: 90px; color:#fed700; margin-left:30px; } .box { position: relative; border-radius: 3px; background: #ffffff; /* border-top:1px solid #ccc !important; */ margin-bottom: 9px; width: 100%; /* box-shadow: 0 1px 1px rgba(0,0,0,0.1); */ } select { border: 1px solid #ccc; margin: 0 0 15px 0; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: #fff; border: 1px solid #ccc !important; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script type="text/javascript"> $(document).ready(function() { $(".myroute").select2(); }); </script> <link rel="stylesheet" href="<?php echo base_url();?>assets/select/select2.css"> <!--<script src="select/jquery-1.8.0.min.js"></script>--> <script src="<?php echo base_url();?>assets/select/select2.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td> <select> <option>Motorola</option> <option><NAME></option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td><td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <!--<script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var customer_id = document.frmCust.customer_id.value, if( mobile == "" && land_ln == "") { document.frmCust.mobile.focus(); document.getElementById("errorBox").innerHTML = "enter the mobile"; return false; } } </script>--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script>////////////////////////////////field required validation/////////////////////////////////////////// $(document).ready(function(){ $( "#submit" ).click(function( event ) { if ( $( "#cust_name" ).val() === "" ) { $( "#errorBox_name" ).text( " Enter the Customer Name" ).show(); event.preventDefault(); } if ( $( "#mobile" ).val() === "" ) { $( "#errorBox_mobile" ).text( "Enter the Mobile Number" ).show(); event.preventDefault(); } if ( $( "#address" ).val() === "" ) { $( "#errorBox_address" ).text( "Enter the Address" ).show(); event.preventDefault(); } if ( $( "#state" ).val() === "" ) { $( "#errorBox_state" ).text( "Enter the State" ).show(); event.preventDefault(); } if ( $( ".city" ).val() === "" ) { $( "#errorBox_city" ).text( "Enter the City" ).show(); event.preventDefault(); } if ( $( "#pincode" ).val() === "" ) { $( "#errorBox_pincode" ).text( "Enter the Pincode" ).show(); event.preventDefault(); } if ( $( "#customer_name" ).val() === "" ) { $( "#errorBox_contact" ).text( "Enter the Contact Name" ).show(); event.preventDefault(); } }); }); </script> <script>///////////////////////////////////character & number validation/////////////////////////////////////////// $(document).ready(function(){ $('#cust_name').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); //$('#service_zone').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); //}); $('.city').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('#address').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z ./-_,]+$/,'') ); }); $('#mobile').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#mobile').change(function(){ if($(this).val() !=''){ if($(this).val().length<10){ //alert("hiii"); $( "#errorBox_mobile" ).text( "Phone Number must be atleast 10 digit" ).show(); return false; $(this).focus(); } } }); $('#pincode').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#customer_name').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $("#cust_name").keyup(function(){ if($(this).val()==""){ $("#errorBox_name").show(); } else{ $("#errorBox_name").hide(); } }); $("#cust_type").click(function(){ if($(this).val()==""){ $("#errorBox_type").show(); } else{ $("#errorBox_type").hide(); } }); $("#address").keyup(function(){ if($(this).val()==""){ $("#errorBox_address").show(); } else{ $("#errorBox_address").hide(); } }); $("#state").click(function(){ if($(this).val()==""){ $("#errorBox_state").show(); } else{ $("#errorBox_state").hide(); } }); $("#customer_id").keyup(function(){ if($(this).val()==""){ $("#errorBox_id").show(); } else{ $("#errorBox_id").hide(); } }); $("#customer_name").keyup(function(){ if($(this).val()==""){ $("#errorBox_contact").show(); } else{ $("#errorBox_contact").hide(); } }); $("#service_zone").click(function(){ if($(this).val()==""){ $("#errorBox_service").show(); } else{ $("#errorBox_service").hide(); } }); $("#pincode").keyup(function(){ if($(this).val()==""){ $("#errorBox_pincode").show(); } else{ $("#errorBox_pincode").hide(); } }); $(".city").keyup(function(){ if($(this).val()==""){ $("#errorBox_city").show(); } else{ $("#errorBox_city").hide(); } }); }); </script> <!--<script> $(document).ready(function(){ $("#mobile").keyup(function(){ $("#mobile").keyup(function(evt){ $("#errorBox_mobile").hide(); evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { alert("Please enter only Numbers."); $('#mobile').val(''); } }); $("#pincode").keyup(function(evt){ evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { alert("Please enter only Numbers."); $('#pincode').val(''); } }); }); }); </script>--> <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold !important; border-radius: 5px; margin-right:20px; cursor:pointer; } .link:hover { color:#fff; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } .box{ display: none; box-shadow:none !important; } .del { display:block; } body{background-color:#fff;} .plusbutton { display: inline-block; padding: 0px 5px !important; margin-bottom: 10px !important; font-size: 14px; height: inherit !important; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; background-color: #dbd0e1; } .plusbutton:hover{ background-color: #dbd0e1; color:#fff; border:1px solid #dbd0e1; } .delbutton { display: inline-block; padding: 0px 5px !important; margin-bottom: 10px !important; font-size: 14px; height: inherit !important; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; background-color: #dbd0e1; } .delbutton:hover{ background-color: #dbd0e1; color:#fff; border:1px solid #dbd0e1; } input:read-only{ background:#eee; } .addservice{ } #errorBox_name{ font-size:11px; position: relative; bottom: 10px; } #errorBox_contact{ font-size:11px; position: relative; bottom: 10px; } #errorBox_mobile{ font-size:11px; position: relative; bottom: 10px; } #emailerror{ font-size:11px; position: relative; bottom: 10px; } #errorBox_pincode{ font-size:11px; position: relative; bottom: 10px; } #errorBox_service{ font-size:11px; position: relative; bottom: 10px; } #errorBox_address{ font-size:11px; position: relative; bottom: 10px; } #errorBox_state{ font-size:11px; position: relative; bottom: 10px; } #errorBox_city{ font-size:11px; position: relative; bottom: 10px; } #errorBox_type{ font-size:11px; position: relative; bottom: 10px; } </style> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{ float:left; list-style:none; margin:0; padding:0; width:269px; height: 125px; overflow-y: auto; overflow-x: hidden; position: relative; bottom: 15px; border: 1px solid #ccc; } #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} #suggesstion-box{ position: absolute; z-index: 3; } </style> <script> $(document).ready(function(){ $('#pincode').change(function() { var id=$(this).val(); //alert(id); $("#service_zone > option").remove(); $('#area_name').val(""); $('#area_id').val(""); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#service_zone').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#area_name').val(data.area_name); $('#area_id').val(data.area_id); }); } }); }); /*$('#mobile').keyup(function() { var id=$("#mobile").val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: datastring, cache: false, success: function(data) { if(data == 0){ $('#errBox_mobile').html(''); } else{ $('#errorBox_mobile').html('Customer Already Exist!').show(); $('#mobile').val(''); return false; } } }); }); $('.ready').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkland_ln", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); });*/ }); </script> <script> $(document).ready(function(){ $(document).on("keyup","#mobile", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var id=$("#mobile").val(); var datastring = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: datastring, cache: false, success: function(data) { if(data == 0){ $('#errBox_mobile').html(''); } else{ if($('#mobile').val() !=''){ $('#errorBox_mobile').html('Customer Already Exist!').show(); $('#mobile').val(''); return false; } } } }); } }); </script> <script> $(document).ready(function(){ $('#re-pincode').change(function() { var id=$(this).val(); //alert(id); $("#service_zone_loc > option").remove(); $('#rearea_name').val(); $('#rearea_id').val(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone_loc').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#service_zone_loc').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#rearea_name').val(data.area_name); $('#rearea_id').val(data.area_id); }); } }); }); }); </script> <script> $(document).ready(function(){ $('form').submit(function() { $('#re_state').removeAttr('disabled'); $('#service_zone_loc').removeAttr('disabled'); }); }); </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Edit Customer</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/edit_customer" method="post" name="frmCust" onsubmit="return frmValidate()" autocomplete="off"> <?php foreach($list as $keyy){?> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Customer Name<span style="color:red;">*</span></label> <input type="text" name="company_name" class="company custname" id="cust_name" maxlength="50" value="<?php echo $keyy->customer_name; ?>" readonly> <input type="hidden" name="cust_id" class="company custname" id="cust_id" maxlength="150" value="<?php echo $keyy->id; ?>"> <div id="errorBox_name" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Mobile<span style="color:red;">*</span></label> <input type="text" name="mobile" id="mobile" class="mobile" value="<?php echo $keyy->mobile; ?>" maxlength="15"> <div id="errorBox_mobile" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address <span style="color:red;">*</span></label> <input type="text" name="address" id="address" value="<?php echo $keyy->address; ?>" class="adress custaddress" maxlength="250"> <div id="errorBox_address" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12 "> <label for="tags">City<span style="color:red;">*</span></label> <input type="text" name="city" id="tags" value="<?php echo $keyy->city; ?>" class="city" maxlength="100"> <!--<div id="suggesstion-box" ></div>--> <div id="errorBox_city" style="color:red;"></div> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>State<span style="color:red;">*</span></label> <select name="state" id="state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id==$keyy->state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php }else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php }} ?> </select> <div id="errorBox_state" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Pincode<span style="color:red;">*</span></label> <input type="text" name="pincode" id="pincode" class="pincode pin" maxlength="6" value="<?php echo $keyy->pincode; ?>"> <div id="errorBox_pincode" style="color:red;"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>E-Mail<span style="color:red;">*</span></label> <input type="text" name="email_id" id="email_id" class="email_id" maxlength="50" value="<?php echo $keyy->email_id; ?>"> <div id="errorBox_email" style="color:red;"></div> </div> </div> <?php } ?> <button class="btn cyan waves-effect waves-light addservice" type="submit" id="submit" >Submit</button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!--<script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#search-box").keyup(function(e){ var code = e.keyCode || e.which; $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); }, focus: function (event, ui) { this.value = ui.item.label; // or $('#autocomplete-input').val(ui.item.label); // Prevent the default focus behavior. event.preventDefault(); } }); }); /*$("#re_city").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#re_city").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box1").show(); $("#suggesstion-box1").html(data); $("#re_city").css("background","#FFF"); } }); });*/ }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } /*function selectCountry1(value) { $("#re_city").val(value); $("#suggesstion-box1").hide(); }*/ </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <!--<script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#mobiles').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script>--> <script> $(function(){ var regeditmail=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.(com|org|net|co.in|in|mil|edu|gov|gov.in))$/; $(".custname,.contname,.desig,.area,.add-area,.branch").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z. ]/g,'') ); }); $(".custaddress,.custaddress1,.deliveryaddress").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9.,-\/# ]/g,'') ); }); $(".mobile,.landline,.add-mobile,.pin").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^0-9-]/g,'') ); }); $(".emailid").on("change", function(){ if(!regeditmail.test($(".emailid").val())){ $(".emailerror").text("Invalid Email ID!").show().css({ "font-size":"11px", "color":"#ff0000" }); } }); $(".add-email").change(function(){ if(!regeditmail.test($(this).val())){ $(".add-emailerror").text("Invalid Email ID!").show().css({ "font-size":"10px", "color":"#ff0000" });; } }); $(".emailid").keyup(function(){ $(".emailerror").fadeOut('slow'); }); $(".add-email").keyup(function(){ $(".add-emailerror").fadeOut('slow'); }); }); </script> <!--<script> $(function(){ $( "form" ).submit(function( event ) { if ( $( "#mobile" ).val() === "" ) { $( "#mobile_error" ).text( "Please enter the mobile number" ).show(); event.preventDefault(); } if ( $( "#land_ln" ).val() === "" ) { $( "#land_ln_error" ).text( "Please enter the landline number" ).show(); event.preventDefault(); } if ( $( "#customer_id" ).val() === "" ) { $( "#customer_id_error" ).text( "please enter the customer id" ).show(); event.preventDefault(); } if ( $( "#company_name" ).val() === "" ) { $( "#company_error" ).text( "please enter the customer name" ).show(); event.preventDefault(); } if ( $( "#cust_type" ).val() == "" ) { $( "#cust_type_error" ).text( "please enter the type of customer" ).show(); event.preventDefault(); } if ( $( "#pincode" ).val() == "" ) { $( "#pincode_error" ).text( "please enter the pincode" ).show(); event.preventDefault(); } if ( $( "#service_zone" ).val() == "" ) { $( "#service_zone_error" ).text( "please enter the service zone" ).show(); event.preventDefault(); } if ( $( ".contactv_name" ).val() === "" ) { $( "#customer_name_error" ).text( "please enter the contact name" ).show(); event.preventDefault(); } if ( $( "#address" ).val() === "" ) { $( "#address_error" ).text( "please enter the address" ).show(); event.preventDefault(); } if ( $( ".city" ).val() === "" ) { $( ".city_error" ).text( "please enter the city" ).show(); event.preventDefault(); } if ( $( "#state" ).val() === "" ) { $( "#state_error" ).text( "please enter the state" ).show(); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#mobile").keyup(function(){ if($(this).val()==""){ $("#mobile_error").show(); } else{ $("#mobile_error").hide(); } }); $("#land_ln").keyup(function(){ if($(this).val()==""){ $("#land_ln_error").show(); } else{ $("#land_ln_error").hide(); } }); $("#customer_id").keyup(function(){ if($(this).val()==""){ $("#customer_id_error").show(); } else{ $("#customer_id_error").hide(); } }); $("#company_name").keyup(function(){ if($(this).val()==""){ $("#company_error").show(); } else{ $("#company_error").hide(); } }); $("#cust_type").change(function(){ if($(this).val()==""){ $("#cust_type_error").show(); } else{ $("#cust_type_error").hide(); } }); $("#pincode").keyup(function(){ if($(this).val()==""){ $("#pincode_error").show(); } else{ $("#pincode_error").hide(); } }); $("#service_zone").change(function(){ if($(this).val()==""){ $("#service_zone_error").show(); } else{ $("#service_zone_error").hide(); } }); $(".contactv_name").keyup(function(){ if($(this).val()==""){ $("#customer_name_error").show(); } else{ $("#customer_name_error").hide(); } }); $("#address").keyup(function(){ if($(this).val()==""){ $("#address_error").show(); } else{ $("#address_error").hide(); } }); $(".city").keyup(function(){ if($(this).val()==""){ $(".city_error").show(); } else{ $(".city_error").hide(); } }); $("#state").change(function(){ if($(this).val()==""){ $("#state_error").show(); } else{ $("#state_error").hide(); } }); }); </script>--> <script type='text/javascript'> $(function(){ var tbl = $(".innerdiv"); var i = 1; $("#addRowBtn").click(function(){ $('<div class="col-md-12"><div class="col-md-3 col-sm-6 col-xs-12"> <select id="route" name="lab_name[]" class="form-control1 myroute "><option value="">Select lab</option><?php foreach($lab as $roww){?><option value="<?php echo $roww->id;?>"><?php echo $roww->lab_name;?></option> <?php } ?></select><div id="customer_name_error" style="color:red;"></div></div><div class="col-md-3 col-sm-6 col-xs-12"><input type="text" class="form-control" name="lab_value[]"/></div><div class="col-md-3 col-sm-6 col-xs-12"><a class="btn delbutton btn-danger delRowBtn"><i class="fa fa-trash" aria-hidden="true"></i></a></div></div>').appendTo(tbl); i++; }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <script> $(document).ready(function(){ //alert("df"); $('#cust_type').change(function(){ //alert("dnf"); var cust_type_id = $(this).val(); var land = cust_type_id.split('-'); var id = land['0']; var corp = land['1']; //alert(id+'_'+corp); if(corp=='CORPORATE' || corp=='corporate' || corp=='Corporate' || corp=='corporate'){ $(".box").not(".ready").hide(); $(".ready").show(); }else{ $(".box").not(".del").hide(); $(".del").show(); } var cust_id = $('#customer_id').val(); if(cust_id.length == '5'){ var customerid = id+cust_id; $('#customer_id').val(customerid); }else{ var cust_id2 = cust_id.substring(2, cust_id.length); var customerid = id+cust_id2; $('#customer_id').val(customerid); //var zoneid = cust_id1+zone_id; //$('#customer_id').val(zoneid); } }); $('#service_zone').change(function(){ // alert($(this).val()); if(document.getElementById('cust_type').selectedIndex == 0){ alert("Kindly Select Customer Type first"); }else{ var z_id = $(this).val(); var arr = z_id.split('-'); var zonid = arr['0']; var zone_id = arr['1']; var zone_coverage = arr['2']; //alert(zone_coverage); $('#service_zone_loc option').each(function(){ //alert(zonid); if(zonid==this.value){ //alert(zone_coverage); $('#service_loc_coverage').val(zone_coverage); //$('#service_zone_loc').val(zonid); } }); //alert(zone_id); var cust_type_id = $('#customer_id').val(); //alert(cust_type_id); if(cust_type_id.length == '7'){ // var cust_id = cust_type_id+zone_id; var position = 2; var output = [cust_type_id.slice(0, position), zone_id, cust_type_id.slice(position)].join(''); //alert(output) $('#customer_id').val(output); }else{ //var cust_id1 = cust_type_id.substring(0, cust_type_id.length 2); //alert(str.replaceAt(2, zone_id)); String.prototype.replaceAt=function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); } strss = cust_type_id.replaceAt(2, zone_id); $('#customer_id').val(strss); } } }); }); </script> <script> $(document).ready(function(){ $('#state').change(function(){ var z_id = $(this).val(); $('#re_state option').each(function(){ $('#re_state').val(z_id); }); }); }); </script> <!--<script> $(document).ready(function(){ $('#pincode').blur(function() { var id=$(this).val(); //alert(id); $("#service_zone > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#service_zone').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#area_name').val(data.area_name); $('#area_id').val(data.area_id); }); } }); }); }); </script>--> <!--<script> $(document).ready(function(){ $('#re-pincode').keyup(function() { var id=$(this).val(); //alert(id); $("#service_zone_loc > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone_loc').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#service_zone_loc').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#rearea_name').val(data.area_name); $('#rearea_id').val(data.area_id); }); } }); }); }); </script>--> <!--<script> $(document).ready(function(){ $('#billingtoo').click(function(){//alert("haiiii"); //$addr = $('#address').val(); var id = $(this).val(); //alert(id); //var stateid = $('#state').val(); $('#re_address').val($('#address').val()); $('#re_address1').val($('#address1').val()); $('#re_city').val($('#search-box').val()); //$('#re_state').val($('#state').val()); $('#re-pincode').val($('#pincode').val()); $('#rearea_name').val($('#area_name').val()); $('#rearea_id').val($('#area_id').val()); $('#re_contact_name').val($('#customer_name').val()); $('#re_emails').val($('#email').val()); $('#re_mobiles').val($('#mobile').val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_state", data:'stateid='+$('#state').val(), success: function(data) { $.each(data, function(index, data){//alert(data.branch_name); $('#re_state').val(data.state); }); } }); }); }); </script>--> <!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>--> <script type="text/javascript"> $(function () { $("#billingtoo").click(function () { if ($(this).is(":checked")) { var id = $(this).val(); //alert(id); var stateid = $('#state').val(); var sarr=stateid.split('-'); var svalue=sarr['1']; //alert(stateid); //var serlocid=$('#service_zone').val(); var z_id = $('#service_zone').val(); var arr = z_id.split('-'); var zonid = arr['0']; //alert(zonid); $("#billingtoo").val(1); $('#re_address').val($('#address').val()).css('background-color','#eee'); $('#re_address').prop('readonly', true); $('#re_address1').val($('#address1').val()).css('background-color','#eee').prop('readonly', true); $('#re_city').val($('#tags').val()).css('background-color','#eee').prop('readonly', true); $('#re_state').val(svalue).css('background-color','#eee').prop('disabled', true); $ $('#re-pincode').val($('#pincode').val()).css('background-color','#eee').prop('readonly', true); $('#rearea_name').val($('#area_name').val()).css('background-color','#eee').prop('readonly', true); $('#rearea_id').val($('#area_id').val()).css('background-color','#eee').prop('readonly', true); $('#re_contact_name').val($('#customer_name').val()).css('background-color','#eee').prop('readonly', true); $('#re_emails').val($('#email').val()).css('background-color','#eee').prop('readonly', true); $('#re_mobiles').val($('#mobile').val()).css('background-color','#eee').prop('readonly', true); $('#service_zone_loc').val(zonid).css('background-color','#eee').prop('disabled', true); /*$.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_state", data:'stateid='+$('#state').val(), success: function(data) { $.each(data, function(index, data){//alert(data.branch_name); $('#re_state').val(data.state); }); } });*/ //}); } else { $("#billingtoo").val(0); $("#re_address").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_address1").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_city").val(" ").css('background-color','#fff').prop('readonly', false); $("#re-pincode").val(" ").css('background-color','#fff').prop('readonly', false); $("#rearea_name").val(" ").css('background-color','#fff').prop('readonly', false); $("#rearea_id").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_contact_name").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_emails").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_mobiles").val(" ").css('background-color','#fff').prop('readonly', false); $("#re_state").val(0).css('background-color','#fff').prop('disabled', false); $('#service_zone_loc').val(0).css('background-color','#fff').prop('disabled', false); } }); }); </script> <script type='text/javascript'>//<![CDATA[ function FillBilling(f) { if(f.billingtoo.checked == true) { alert(f.search-box.value); f.re_address.value = f.address.value; f.re_address1.value = f.address1.value; f.re_city.value = f.search-box.value; //f.re_state.value = f.state.value; f.re_pincode.value = f.pincode.value; f.rearea_id.value = f.area_id.value; } } </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script>--> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script>--> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/models/Problemcategory_model.php <?php class Problemcategory_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_problem_category($data1){ $this->db->insert('problem_category',$data1); return true; } public function modellist(){ $this->db->select("id,model",FALSE); $this->db->from('products'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); return $query->result(); } public function problem_category_list(){ $this->db->select("id,prob_category,prob_code,prob_description",FALSE); $this->db->from('problem_category'); $this->db->order_by('id','DESC'); $query = $this->db->get(); return $query->result(); } public function problem_category_list1(){ $this->db->select("problem_category.id,problem_category.prob_category,problem_category.prob_code,problem_category.prob_description,products.model",FALSE); $this->db->from('problem_category'); $this->db->join('products', 'products.id = problem_category.model'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getprobcatbyid($id){ $this->db->select("problem_category.id,problem_category.prob_category,problem_category.prob_code,problem_category.prob_description,products.id As modelid",FALSE); $this->db->from('problem_category'); $this->db->join('products', 'products.id = problem_category.model'); $this->db->where('problem_category.id',$id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_prob_cat($data1,$id){ $this->db->where('id',$id); $this->db->update('problem_category',$data1); } public function del_prob_cat($id){ $this->db->where('id',$id); $this->db->delete('problem_category'); } public function category_validation($prob_cat_name,$model) { $this->db->select('*'); $this->db->from('problem_category'); $this->db->where('prob_category',$category); $this->db->where('model',$model); $query=$this->db->get(); return $query->result(); //echo "<pre>";print_r($query->result());exit; } public function code_validation($code) { $query = $this->db->get_where('problem_category', array('prob_code' => $code)); echo $numrow = $query->num_rows(); } public function problem_validation($problem,$model) { $this->db->select('*'); $this->db->from('problem_category'); $this->db->where('prob_category',$problem); $this->db->where('model',$model); $query=$this->db->get(); return $query->num_rows(); //echo "<pre>";print_r($query->result());exit; } }<file_sep>/application/views/add_service_cat.php <script> $(function(){ //alert("xcfg"); $(".registersubmit").click(function(event){ //alert("xcfg"); if($(".firstname").val()==""){ $(".fname").text("Enter Service Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $(".firstname").keyup(function(){ if($(this).val()==""){ $(".fname").show(); } else{ $(".fname").fadeOut('slow'); } }) }); </script> <script> $(document).ready(function(){ $('#addRowBtn1').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Servicecategory/add_scatrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <!-- <script> $(function(){ var tb2 = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ i++; $('<div class="col-md-12"><div class="col-md-3"><input type="text" name="service_catname[]" id="UserName'+i+'" class="firstname" maxlength="80"><div class="fname" id="lname'+i+'" style="color:red"></div></div><div><a class="delRowBtn btn btn-primary fa fa-trash"></a></div></div>').appendTo(tb2); $(".subcat").keyup(function(){ var a=$(this).attr('id').split('-').pop(); //alert(a); var name1=$(this).val(); //alert(name1); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Servicecategory/service_validation', data: { p_id:name1, }, success: function (data) { // alert(data); if(data == 0){ $('#lname'+i).html(''); } else{ //alert("else called"); $('#lname'+i).text('Service Category Name Already Exist').show(); $('#UserName'+i).val(''); return false; } } }); }); $('#UserName'+i).bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z ]/g,"")); }); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName"+i).val()==""){ $("#lname"+i).text("Enter Service Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $(".subcat").keyup(function(){ //alert("xdfn"); if($(this).val()==""){ $("#lname"+i).show(); } else{ $("#lname"+i).fadeOut('slow'); } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); //$('.firstname').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); //}); }); </script>--> <style> body{background-color:#fff;} .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } .link:focus{ color: white; text-decoration:none; } .delRowBtn{ background-color: #dbd0e1 none repeat scroll 0% 0% !important; border-color: transparent !important; color:#522276 !important; padding: 0px 4px 4px 4px; } .mandatory{color:red;} input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } a{ color:#522276; } a:hover{ color:#522276; cursor:pointer; } a:focus{ color:#522276; } a:active{ color:#522276; } </style> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; //alert(document.frmService.serial_no.value); var service_catname = document.frmServicecat.service_catname.value; if(service_catname == "") { document.frmServicecat.service_catname.focus() ; document.getElementById("errorBox").innerHTML = "enter the service category name."; return false; } if(model == "") { document.frmServicecat.model.focus() ; document.getElementById("errorBox").innerHTML = "enter the model name"; return false; } } </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('.firstname').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z. ]/g,'') ); }); /*$('#UserName1').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); });*/ }); </script> <section id="content"> <div class="container"> <div class="section"> <h2>Add Service Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Servicecategory/add_service_category" method="post" name="frmServicecat"> <div id="errorBox"></div> <div id="myTable" class="tableadd"> <div class="col-md-12"> <div class="col-md-3"> <label style="font-weight:bold;width:180px;">Service Category Name <span class="mandatory" style="color:red;">*</span></label> <input type="text" name="service_catname[]" id="UserName" class="firstname" maxlength="80"> <div class="fname" id="lname1" style="color:red; font-size: 10px;"></div> </div> <div><a class="link" id="addRowBtn1" style=" height: 30px;"><i class="fa fa-plus-square" aria-hidden="true" style="margin-top: 30px;color:#58277a;"></i></a></div> </div> </div> <input type="hidden" id="countid" value="1"> <div class="col-md-12"> <div class="col-md-4"> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action">Submit</button> </div> </div> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $(document).on("keyup","#UserName", function(){ var name=$(this).val(); //alert(name); if(name) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Servicecategory/service_validation', data: { p_id:name, }, success: function (data) { if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Service Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#UserName').val(''); return false; } } }); } }); </script> </body> </html><file_sep>/application/views/add_quick_prod.php <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"> <style> hr { border-style: solid; border-width: 1px; color: #303F9F; } body{background-color:#fff;} #errorBox { color:#F00; } .tableadd1 select { border: 1px solid #000; background-image:none; border-radius: 5px; width: 100%; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .limitedNumbChosen { width: 100%; } .chosen-container { width: 100% !important; } .chosen-container-multi .chosen-choices { border: 1px solid #ccc; } textarea.materialize-textarea { overflow: auto; padding: 3px; resize: none; min-height: 10rem; } .chosen-container-multi .chosen-choices li.search-field input[type=text] { color: #333; } select { border: 1px solid #ccc !important; } .star{ color:#ff0000; font-size:15px; } .btn{text-transform:none !important;} </style> <script> $(function(){ $("button").click(function(event){ //alert("clcl"); if($("#product_name").val()==""){ $("#proderror").text("Enter the Product Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } if($("#category").val()==""){ $("#caterror").text("Please select the Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#subcategory").val()==""){ $("#subcaterror").text("Please select the Sub-Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#brand").val()==""){ $("#branderror").text("Please select the Brand Name").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#model").val()==""){ $("#modelerror").text("Enter the Model Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } /*if($(".limitedNumbChosen").find("option:selected").length < 1){ $("#infoerror").text("Please select the Addtional Information").show().css({ 'font-size':'12px', 'color':'#ff0000' }); }*/ }); $("#product_name").keyup(function(){ if($(this).val()==""){ $("#proderror").show(); } else{ $("#proderror").fadeOut('slow'); } }); $("#category").change(function(){ if($(this).val()==""){ $("#caterror").show(); } else{ $("#caterror").fadeOut('slow'); } }); $("#subcategory").change(function(){ if($(this).val()==""){ $("#subcaterror").show(); } else{ $("#subcaterror").fadeOut('slow'); } }); $("#brand").change(function(){ if($(this).val()==""){ $("#branderror").show(); } else{ $("#branderror").fadeOut('slow'); } }); $("#model").keyup(function(){ if($(this).val()==""){ $("#modelerror").show(); } else{ $("#modelerror").fadeOut('slow'); } }); $(".limitedNumbChosen").change(function(){ if($(this).val()==""){ $("#infoerror").show(); } else{ $("#infoerror").fadeOut('slow'); } }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> /* $(document).ready(function() { $("#subcategory").change(function() { $("#brand > option").remove(); var subcatid=$(this).val(); categoryid = $("#category").val(); //alert("Subcat: "+id+"Cat:" +category); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/get_brand", data: dataString, cache: false, success: function(data) { $('#brand').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data); $('#brand').append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); }); */ </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Product Details</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>product/add_product_quick" method="post" name="frmProd"> <!-- onsubmit="return frmValidate()" --> <div id="errorBox"></div> <div class="col-md-12 tableadd1"> <!--<tr> <td><label>Serial No</label></td><td><input type="text" name="serial_no" id="serial_no" class=""></td> </tr>--> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Product Name <span class="star">*</span></label> <input type="text" name="product_name" id="product_name" class="prod-name form-control" maxlength="80"> <div id="proderror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category <span class="star">*</span></label> <select name="category" id="category" class='form-control'> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ ?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } ?> </select> <div id="caterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category <span class="star">*</span></label> <select name="subcategory" id="subcategory" class='form-control'> <option value="">---Select---</option> </select> <div id="subcaterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Brand Name <span class="star">*</span></label> <select name="brand" id="brand" class='form-control'> <option value="">---Select---</option> <?php foreach($brandlists as $brkey){ ?> <option value="<?php echo $brkey->id; ?>"><?php echo $brkey->brand_name; ?></option> <?php } ?> </select> <div id="branderror"></div> </div> </div> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Model <span class="star">*</span></label> <input type="text" name="model" id="model" class="prod-model form-control" maxlength="80"> <div id="modelerror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Additional Information </label> <select name="addlinfo[]" class="limitedNumbChosen form-control" multiple="true"> <option value="">---Select---</option> <?php foreach($accessories_list as $acckey1){ ?> <option value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } ?> </select> <div id="infoerror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Description</label> <textarea type="text" name="description" id="description" class="materialize-textarea form-control" maxlength="150"></textarea> </div> </div> <div class="col-md-12 tableadd1"> <div class="col-md-12 col-sm-12 col-xs-12"> <button class="btn cyan waves-effect waves-light " type="submit" >Submit</button> </div> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!--<script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> <script> $(document).ready(function(){ //Chosen $(".limitedNumbChosen").chosen({ placeholder_text_multiple: "---Select---" }) .bind("chosen:maxselected", function (){ window.alert("You reached your limited number of selections which is 2 selections!"); }); $(".prod-name").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9. ]/g,'') ); }); $(".prod-model").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9-.\/+*() ]/g,'') ); }); $("textarea").removeClass("materialize-textarea"); $("textarea").css({ 'height':'100px', 'overflow-y':'auto', 'overflow-x':'hidden' }) }); </script> </body> </html><file_sep>/application/views/add_service_charge.php <head> <style> body{background-color:#fff;} .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color:#5f3282; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { border: 1px solid #522276; text-align: center; } .tableadd1 tr { height: 50px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td.plus { padding-top: 14px; } .tableadd1 tr td.plus input { width:100px; border:1px solid gray; } .tableadd1 tr td input{ background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { /* border: 1px solid #055E87 !important; */ background: rgb(112, 66, 139) none repeat scroll 0% -1%; padding: 4px; border-radius: 5px; color: #ffffff; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { width:50%; margin-top:20px; } #addtable tr td { border:none; text-align:left; } .tableadd1 tr td label { line-height: 0; color: #ffffff; font-weight: bold; } #errorBox{ color: #f00; margin-left: 293px; position: relative; right: 281px; top: 5px; font-size:11px; } #modelerror{ color:#ff0000; font-size:11px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } .btn, .btn-large, .btn-flat { text-transform: none; } .star{ color:#ff0000; font-size:12px; } a{ color: #522276; } a:hover{ color: #522276; cursor:pointer; } a:focus{ color: #522276; } a:active{ color: #522276; } </style> <script> $(function() { $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }) </script> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var category=$('#service_cat-0').val(); // var datastring='countid='+vl1; var datastring='countid='+vl1+'&category='+category; //disable_select_options(); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Servicecategory/addrow2", data: datastring, cache: false, success: function(result) { //alert(result); $('.tableadd1').append(result); disable_select_options(); } }); }); }); </script> <script> $(function(){ $('html body').on('change','select[name="model[]"]',function(){ //alert('sdfl'); disable_select_options(); }); }); function disable_select_options(){ var sra_selected = []; $('select[name="model[]"]').each(function(){ if($(this).val() !== ''){ sra_selected.push($(this).val()); } }); console.log(sra_selected); $('select[name="model[]"]').each(function(){ $(this).find('option:not(:selected)').each(function(){ var value = $(this).attr('value'); var pos = $.inArray(value,sra_selected); if(pos >= 0 ){ $(this).attr('disabled','disabled'); } }); }); //console.log(sra_selected); } </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('minus-0').value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus-0').value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); function UpdateStatus1(id){ //alert(id);alert($("#enggdate_"+id).val()); var eng_name = $("#eng_name-"+id).val(); var eng_spare_name = $("#eng_spare_name-"+id).val(); var engg_date = $("#enggdate_"+id).val(); if(eng_name==""){ alert("Enter the Engineer Name"); }else if(eng_spare_name==""){ alert("Enter the Spare Name"); }else if(engg_date==""){ alert("Enter the Date"); }else{ var plus = $("#plus-"+id).val(); var minus = $("#minus-"+id).val(); //alert(engg_date); var engg_reason = $("#engg_reason-"+id).val(); var spare_qty = $("#spare_qty-"+id).val(); var used_spare = $("#used_spare-"+id).val(); var eng_spare = $("#eng_spare-"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/add_spare_engg', data: {'eng_name' : eng_name, 'eng_spare_name' : eng_spare_name, 'plus' : plus, 'minus' : minus, 'engg_date' : engg_date, 'engg_reason' : engg_reason, 'spare_qty' : spare_qty, 'used_spare' : used_spare, 'eng_spare' : eng_spare}, dataType: "text", cache:false, success: function(data){ alert("Spares For Engineers Added"); } }); }); } } </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var service_cat = document.frm_servicecharge.service_cat.value; if( service_cat == "" ) { document.frm_servicecharge.service_cat.focus() ; document.getElementById("errorBox").innerHTML = "Select the Service Category"; return false; } if( document.getElementById("model-0").value == "") { document.getElementById("modelerror").innerHTML = "Select the Model"; return false; } } </script> </head> <section id="content"> <div class="container"> <div class="section"> <h2>Add Service Charge</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <form name="frm_servicecharge" action="<?php echo base_url(); ?>Servicecategory/add_service_charge" method="post" onsubmit="return frmValidate()"> <div class="col-md-12"> <div class="tableadd" id="addtable"> <div class="col-md-12"> <div class="col-md-3"><label>Service Category<span class="mandatory" style="color:red;">*</span></label></div> <div class="col-md-3"><select name="service_cat" id="service_cat-0"> <option value="">---Select---</option> <?php if(!empty($service_charge_ByGrp)){ foreach($service_charge_ByGrp as $serv_grp){ $service_cat_id[] = $serv_grp->service_cat_id; } } foreach($list as $listkey){ if(!in_array($listkey->id,$service_cat_id)){ ?> <option value="<?php echo $listkey->id; ?>"><?php echo $listkey->service_category; ?></option> <?php } } ?> </select> </div> <div id="errorBox" class="col-md-6"></div> </div> </div> <div id="table1" class="col-md-12" style="margin: 30px 20px;"> <table class="tableadd1" style="width:70%;"> <tr class="rowadd"> <td><label>Model <span class="star">*</span></label></td> <td><label>Charge</label></td><!--<td><label>Action</label></td>--> </tr> <tr> <td> <select name="model[]" id="model-0" class="eng_spare_name" onchange='service_model-0'> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="modelerror"></div> </td> <td class="plus"> <input type="text" name="service_charge[]" id="service_charge-0" class=""> <a class="link" id="addMoreRows" class="rowadd" ><i class="fa fa-plus-square" aria-hidden="true"></i></a> </td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(0)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0" > </div> <div class="col-md-3"><button class="btn cyan waves-effect waves-light" class="submitcategory" type="submit" name="action" style="margin-left:30px;">Submit</button></div> </div> </div> </form> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function(){ $("#service_cat-0").change(function(){ //alert("test"); if($(this).val()=="") { $("#errorBox").show(); } else{ $("#errorBox").fadeOut('slow'); } }); $("#model-0").change(function(){ //alert("modle"); if($(this).val()=="") { $("#modelerror").show(); } else{ $("#modelerror").fadeOut('slow'); } }); }); </script> </body> </html><file_sep>/application/views_bkMarch_0817/add_prod_cat.php <style> .tableadd tr td input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 3px; /* padding-left: 10px; */ margin-left: 13px; } .tableadd tr td input { height: 21px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script> $(document).on("keyup","#UserName1", function(){ var name=$(this).val(); //alert(name); if(name) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name, }, success: function (data) { if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Category Name Already Exist').show().delay(1000).fadeOut(); $('#UserName1').val(''); return false; } } }); } }); </script> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($(".firstname").val()==""){ $("#lname1").text("Enter Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $(".firstname").keyup(function(){ if($(this).val()==""){ $("#lname1").show(); } else{ $("#lname1").fadeOut('slow'); } }) }); </script> <style> body{background-color:#fff;} .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .delRowBtn { display: inline-block; padding: 0px 5px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Product Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Productcategory/add_prod_category" method="post" > <div id="myTable" class="tableadd" > <div class="col-md-12" style="padding: 0px"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category Name</label> <input type="text" name="cat_name[]" id="UserName1" class="firstname"> <div class="fname" id="lname1" style="color:red"></div> </div> </div> <!--<tr> <td><label style="font-weight:bold;">Category Name</label></td> </tr> <tr> <td><input type="text" name="cat_name[]" id="UserName1" class="firstname"><div class="fname" id="lname1" style="color:red"></div></td> </tr>--> </div> <a class="link" id="addRowBtn1">Add Category</a><button class="btn cyan waves-effect waves-light registersubmit" type="submit">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script type='text/javascript'>//<![CDATA[ $(function(){ var tb2 = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ i++; $('<div class="col-md-12" style="padding: 0px"><div class="col-md-3 col-sm-6 col-xs-12"><input type="text" name="cat_name[]" id="UserName'+i+'" class="firstname"><div class="fname" id="lname'+i+'" style="color:red"></div></div><div class="col-md-1 col-sm-6 col-xs-12" style="padding:0px"><a class="delRowBtn btn btn-primary fa fa-trash" style="height:30px;"></a></div></div>').appendTo(tb2); $("#UserName"+i).keyup(function(){ var name1=document.getElementById( "UserName"+i ).value; //alert(name1); if(name1) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name1, }, success: function (data) { // alert(data); if(data == 0){ $('#lname'+i).html(''); } else{ //alert("else called"); $('#lname'+i).text('Category Name Already Exist').show().delay(1000).fadeOut(); $('#UserName'+i).val(''); return false; } } }); } }); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName"+i).val()==""){ $("#lname"+i).text("Enter Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','left':'14px'}); event.preventDefault(); } }); $("#UserName"+i).keyup(function(){ if($(this).val()==""){ $("#lname"+i).show(); } else{ $("#lname"+i).fadeOut('slow'); } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> </body> </html><file_sep>/application/views/add_service_charge_row.php <!--<tr> <td> <select id="spare_name_<?php echo $count; ?>" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> </select> </td> <td><input type="text" name="qty[]"><input type="hidden" name="spare_qty1[]" id="spare_qty1_<?php echo $count; ?>"><input type="hidden" name="used_spare1[]" id="used_spare1_<?php echo $count; ?>"><input type="hidden" name="purchase_price1[]" id="purchase_price1_<?php echo $count; ?>"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_<?php echo $count; ?>"></td> <td><input type="text" name="purchase_date[]"></td> <td><input type="text" name="purchase_price[]"></td> <td><input type="text" name="invoice_no[]"></td> <td><input type="text" name="reason[]"></td> <td style="border:none;"><button class="delRowBtn" >Delete</button></td> </tr>--> <div class="container"> <div class="section"> <tr> <td> <select name="model[]" class="category1" id="model_<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="modelerror-<?php echo $count; ?>"></div> <input type="hidden" id="service_cat" value="<?php echo $cat_id; ?>"> </td> <td class="plus"> <input type="text" name="service_charge[]" id="service_charge-<?php echo $count; ?>" class="plus1"><input type="hidden" name="service_charge_id[]" class="" value=""> </td> <td style="text-align:left;border:none;"><a class="delRowBtn" onClick="$(this).closest('tr').remove();"><i class="fa fa-trash"></i></a></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(<?php echo $count; ?>)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ //alert("gdfgdf"); $('.category1').change(function(){ //alert("gdfgdf"); var model=$(this).val(); var category=$('#service_cat').val(); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; //alert(arr); var datastring='model1='+model+'&category1='+category; //alert(datastring); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>Servicecategory/check_charge", data:datastring, cache:false, success:function(data){ //alert(data); if(data == 0){ } else{ alert("Model Already Exit"); $('#model_'+ctid+"> option").remove(); $('#model_'+ctid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#model_'+ctid).append("<option value='"+data.id+"'>"+data.model+"</option>"); }); return false; } } }); }); }); </script> <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>--> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('minus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('plus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <!--<script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script>--> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var service_cat = document.frm_servicecharge.service_cat.value; if( service_cat == "" ) { document.frm_servicecharge.service_cat.focus() ; document.getElementById("errorBox").innerHTML = "select the service category"; return false; } if( document.getElementById("model-0").value == "") { document.getElementById("modelerror").innerHTML = "select the model"; return false; } } </script> <script> </script> <style> .delRowBtn{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color:#522276 !important; margin-left: 10px; } .delRowBtn:hover{ background: transparent !important; border: transparent !important; color: #522276 !important; } .delRowBtn:focus{ background-color: transparent !important; border-color: transparent !important; color: #522276 !important; } .z-depth-1-half, .btn:hover, .btn-large:hover, .btn-floating:hover { box-shadow: none !important; } .plus1{ position: relative; right: 9px; } </style> <file_sep>/application/views/add_accessories.php <script> $(document).ready(function(){ $('#addRowBtn').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>accessories/add_accsrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <!--<script type='text/javascript'>//<![CDATA[ $(function(){ var tbl = $("#myTable"); $("#addRowBtn").click(function(){ //var inc=1; // var v1=$('#countid').val(); //alert(v1); $('<tr><td width="25.35%"><input type="text" name="acc_name[]" id="acc1"><div id="dname1"></div></td><td><a class="delRowBtn btn btn-primary fa fa-trash" style="height:36px; margin-left: 15px"></a></td> </tr>').appendTo(tbl); }); /* $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#acc1"+i).val()==""){ $("#dname1"+i).text("Enter Accessories Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $("#acc1").keyup(function(){ if($(this).val()==""){ $("#dname1").show(); } else{ $("#dname1").fadeOut('slow'); } }); */ $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script>--> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#acc1").val()==""){ $("#dname1").text("Enter Accessories Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $("#acc1").keyup(function(){ if($(this).val()==""){ $("#dname1").show(); } else{ $("#dname1").fadeOut('slow'); } }); $("#acc1").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); }); </script> <style> .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; cursor:pointer; font-size:13px; font-weight:bold !important; } .link:hover{ color: white; font-size:13px; font-weight:bold !important; text-decoration:none; } input[type=text]{ border: 1px solid #ccc; } .divider { background-color: #522276 !important; } h5{ color: #dbd0e1; } .btn, .btn-large { letter-spacing: 0; text-transform:capitalize; } .star{ color:#ff0000; font-size:15px; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">New Accessories</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>accessories/add_accessories" method="post"> <table id="myTable" class="tableadd"> <tr> <td><label style="width:180px;font-weight:bold;">Accessories Name <span class="star">*</span></label></td> </tr> <tr> <td><input type="text" name="acc_name[]" id="acc1" maxlength="80"><input type="hidden" value="1" id="countid"><div id="dname1" style="color:red; font-size: 11px;"></div> </td> </tr> </table> <input type="hidden" id="countid" value="1"> <a class="link" id="addRowBtn">Add</a><button class="btn cyan waves-effect waves-light registersubmit" type="submit">Submit <!--<i class="fa fa-arrow-right"></i>--> </button> <!--<a class="link" href='' onclick='$("<tr><td><input type=\"text\" name=\"acc_name[]\" /></td></tr>").appendTo($("#myTable")); return false;'>Add</a><button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button>--> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $(document).on("keyup","#acc1", function(){ var name=$(this).val(); //alert(name); if(name) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>accessories/acc_validation', data: { p_id:name, }, success: function (data) { if(data == 0){ $('#dname1').html(''); } else{ $('#dname1').html('Accessories Name Already Exist').show(); $('#acc1').val(''); return false; } } }); } }); </script> </body> </html><file_sep>/application/models/old_Service_model.php <?php class Service_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function get_zons($id){ $this->db->select("id, serv_loc_code, service_loc",FALSE); $this->db->from('service_location'); $this->db->like('service_loc', $id, 'after'); $this->db->order_by('service_loc', 'asc'); $query = $this->db->get(); return $query->result(); } public function add_services($data){ $this->db->insert('service_request',$data); return $this->db->insert_id(); } public function add_stamping_info($data){ $this->db->insert('stamping_details',$data); } public function stamping_details($id){ $this->db->select("*",FALSE); $this->db->from('stamping_details'); $this->db->where('req_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_service_details($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('service_request_details', $data1, $where); $this->db->query($qry); /* echo $this->db->last_query(); exit; */ //exit; } public function add_service_details($data1){ $this->db->insert('service_request_details',$data1); } public function get_customerdetails($id){ $this->db->select("customers.id, customers.mobile, customers.company_name, customers.email_id, customer_service_location.service_zone_loc, service_location.service_loc",FALSE); $this->db->from('customers'); $this->db->join('customer_service_location', 'customer_service_location.customer_id = customers.id'); $this->db->join('service_location', 'service_location.id = customer_service_location.service_zone_loc'); $this->db->where('customers.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function warranty_pending_claims(){ $this->db->select("quote_review_spare_details.id, quote_review_spare_details.request_id as quote_req_id, service_request.request_id, products.model, customers.company_name,quote_review.status,quote_review.warranty_mode,quote_review.code_no,quote_review.code_date",FALSE); $this->db->from('quote_review_spare_details'); $this->db->join('service_request', 'service_request.id=quote_review_spare_details.request_id'); $this->db->join('service_request_details', 'service_request_details.request_id=service_request.id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('customers', 'customers.id = service_request.cust_name'); $this->db->join('customer_service_location', 'customer_service_location.id = service_request.br_name'); $this->db->join('quote_review', 'quote_review.req_id = service_request.request_id'); $this->db->group_by('quote_review_spare_details.request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function updatestsid($id) { $this->db->select('code_no,code_date,warranty_mode'); $this->db->from('quote_review'); $this->db->where('req_id',$id); $query = $this->db->get(); return $query->result(); } public function view_claim($id){ $this->db->select("quote_review_spare_details.id, quote_review_spare_details.request_id as quote_req_id, quote_review_spare_details.warranty_claim_status, quote_review_spare_details.desc_failure, quote_review_spare_details.why_failure, quote_review_spare_details.correct_action, quote_review_spare_details.spare_qty, quote_review_spare_details.spare_qty, service_request.request_id, service_request.request_date, service_request_details.serial_no, products.model, customers.company_name, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, customer_service_location.pincode, customer_service_location.contact_name, customer_service_location.mobile, GROUP_CONCAT(spares.id,'-',spares.spare_name,'-',spares.part_no) as spare_details, order_details.purchase_date",FALSE); $this->db->from('quote_review_spare_details'); $this->db->join('service_request', 'service_request.id=quote_review_spare_details.request_id'); $this->db->join('service_request_details', 'service_request_details.request_id=service_request.id'); $this->db->join('order_details', 'order_details.serial_no=service_request_details.serial_no'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('customers', 'customers.id = service_request.cust_name'); $this->db->join('customer_service_location', 'customer_service_location.id = service_request.br_name'); $this->db->join('spares', 'spares.id = quote_review_spare_details.spare_id'); $this->db->where('quote_review_spare_details.request_id', $id); $this->db->group_by('quote_review_spare_details.request_id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_modelById($id){ $this->db->select("*",FALSE); $this->db->from('products'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function updateclaim($data,$id) { $this->db->where('req_id',$id); return $this->db->update('quote_review',$data); } public function preventive_req_list1($prev_date){ $this->db->select("orders.id, customers.customer_name, service_location.service_loc, products.model ,( CASE WHEN order_details.warranty_date!='' THEN 'Warranty' WHEN order_details.prev_main!='' THEN 'Preventive' WHEN order_details.paid!='' THEN 'Paid' ELSE 1 END) AS machine_status, order_details.prenos, order_details.prev_main, order_details.prev_main_updated, order_details.prenos_cnt",FALSE); $this->db->from('orders'); $this->db->join('order_details', 'order_details.order_id=orders.id'); $this->db->join('customers', 'customers.id=orders.customer_id'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); //$this->db->order_by('service_request.id', 'asc'); $this->db->where_in('order_details.prev_main_updated', $prev_date); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_custo(){ $this->db->select("customers.id, customers.mobile, customers.email_id, customers.company_name",FALSE); $this->db->from('customers'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function customerlist(){ $this->db->select("id, customer_id, customer_name, customer_type, mobile, email_id, company_name",FALSE); $this->db->from('customers'); $query = $this->db->get(); return $query->result(); } public function service_typelist(){ $this->db->select("id, prod_service_status",FALSE); $this->db->from('service_status'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function list_serialnos(){ $this->db->select("serial_no",FALSE); $this->db->from('order_details'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_cnt(){ $this->db->select("request_id",FALSE); $this->db->from('service_request'); $this->db->not_like('request_id', 'P-'); $this->db->order_by('request_id', 'desc'); $this->db->limit(1); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_mods(){ $this->db->select("products.id, products.model",FALSE); $this->db->from('products'); $this->db->order_by('products.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function preventive_req_list(){ $this->db->select("orders.id, orders.customer_id, orders.customer_service_loc_id, order_details.order_id, order_details.serial_no, order_details.cat_id, order_details.subcat_id, order_details.brand_id, order_details.model_id, order_details.service_loc_id, order_details.warranty_date, customers.customer_name, customers.mobile, customers.email_id, service_location.service_loc, products.model ,( CASE WHEN order_details.warranty_date!='' THEN 'Warranty' WHEN order_details.prev_main!='' THEN 'Preventive' WHEN order_details.paid!='' THEN 'Paid' ELSE 1 END) AS machine_status, order_details.prenos, order_details.prev_main, order_details.prev_main_updated, order_details.prenos_cnt, order_details.purchase_date, order_details.amc_start_date, order_details.amc_type, order_details.amc_end_date",FALSE); $this->db->from('orders'); $this->db->join('order_details', 'order_details.order_id=orders.id'); $this->db->join('customers', 'customers.id=orders.customer_id'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); //$this->db->order_by('service_request.id', 'asc'); $this->db->where('order_details.prenos!=', '0'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_preventive($data,$order_id){ $this->db->where('order_id',$order_id); $this->db->update('order_details',$data); } public function service_p_cnt(){ $this->db->select("request_id",FALSE); $this->db->from('service_request'); $this->db->like('request_id', 'P-', 'after'); $this->db->order_by('request_id', 'desc'); $this->db->limit(1); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_orderdetails($id){ $this->db->select("prod_category.id As catid, prod_subcategory.id As subcatid, brands.id As brandid, products.id As modelid, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model, order_details.warranty_date, order_details.prev_main, order_details.paid,( CASE WHEN order_details.warranty_date!='' THEN 'Warranty' WHEN order_details.prev_main!='' THEN 'Preventive' WHEN order_details.rent_date!='' THEN 'Rental' WHEN order_details.paid!='' THEN 'Chargeable' ELSE 1 END) AS machine_status, order_details.amc_start_date, order_details.amc_type, order_details.amc_end_date, order_details.batch_no, service_location.service_loc, service_location.id As locid",FALSE); $this->db->from('order_details'); $this->db->join('prod_category', 'prod_category.id = order_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = order_details.subcat_id'); $this->db->join('brands', 'brands.id = order_details.brand_id'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); //$this->db->join('service_category', 'service_category.model = products.id'); $this->db->order_by('order_details.order_id', 'asc'); $this->db->where('order_details.serial_no', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_servicecatdetails($id){ $this->db->select("products.id As modelid, products.model, service_category.service_category As service_category, service_category.id As sercat_id",FALSE); $this->db->from('order_details'); // $this->db->join('prod_category', 'prod_category.id = order_details.cat_id'); //$this->db->join('prod_subcategory', 'prod_subcategory.id = order_details.subcat_id'); //$this->db->join('brands', 'brands.id = order_details.brand_id'); $this->db->join('products', 'products.id = order_details.model_id'); //$this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); //$this->db->join('service_category', 'service_category.model = products.id'); $this->db->join('service_charge', 'service_charge.model = products.id'); $this->db->join('service_category', 'service_category.id = service_charge.service_cat_id'); $this->db->order_by('order_details.order_id', 'asc'); $this->db->where('order_details.serial_no', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_probcatdetails($id){ $this->db->select("problem_category.prob_category As prob_category, problem_category.id As prob_catid",FALSE); $this->db->from('order_details'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->join('problem_category', 'problem_category.model = products.id'); $this->db->order_by('order_details.order_id', 'asc'); $this->db->where('order_details.serial_no', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_serialdetails($id){ $this->db->select("order_details.serial_no, order_details.model_id, order_details.cat_id, order_details.subcat_id, order_details.brand_id, order_details.warranty_date, order_details.prev_main, order_details.paid,( CASE WHEN order_details.warranty_date!='' THEN 'Warranty' WHEN order_details.prev_main!='' THEN 'Preventive' WHEN order_details.paid!='' THEN 'Chargeable' ELSE 1 END) AS machine_status, order_details.amc_start_date, order_details.amc_type, order_details.amc_end_date, order_details.batch_no",FALSE); $this->db->from('orders'); $this->db->join('order_details', 'order_details.order_id = orders.id'); $this->db->where('orders.customer_service_loc_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_servicenodetails($id,$cust_id){ $this->db->select("order_details.serial_no, order_details.warranty_date, order_details.prev_main, order_details.paid,( CASE WHEN order_details.warranty_date!='' THEN 'Warranty' WHEN order_details.prev_main!='' THEN 'Preventive' WHEN order_details.paid!='' THEN 'Chargeable' ELSE 1 END) AS machine_status, order_details.amc_start_date, order_details.amc_type, order_details.amc_end_date, order_details.batch_no, service_location.service_loc, service_location.id As locid",FALSE); $this->db->from('orders'); $this->db->join('order_details', 'order_details.order_id = orders.id'); $this->db->join('service_location', 'service_location.id = order_details.service_loc_id'); $this->db->where('orders.customer_id', $cust_id); $this->db->where('order_details.model_id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_modelnos($id){ $this->db->distinct(); $this->db->select("order_details.serial_no, products.id, products.model",FALSE); $this->db->from('orders'); $this->db->join('order_details', 'order_details.order_id = orders.id'); $this->db->join('products', 'products.id = order_details.model_id'); $this->db->where('orders.customer_service_loc_id', $id); $this->db->group_by('products.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_orderdetails1($id){ $this->db->select("products.id, products.category, products.subcategory, products.brand, products.model, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name",FALSE); $this->db->from('products'); $this->db->join('prod_category', 'prod_category.id = products.category'); $this->db->join('prod_subcategory', 'prod_subcategory.id = products.subcategory'); $this->db->join('brands', 'brands.id = products.brand'); $this->db->where('products.id', $id); $query = $this->db->get(); return $query->result(); } public function get_servicecatdetails1($id){ $this->db->select("products.id As modelid, products.model, service_category.service_category As service_category, service_category.id As sercat_id",FALSE); $this->db->from('products'); $this->db->join('service_charge', 'service_charge.model = products.id'); $this->db->join('service_category', 'service_category.id = service_charge.service_cat_id'); $this->db->where('service_charge.model', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function check_req($req){ $this->db->select("*",FALSE); $this->db->from('service_request'); $this->db->where('request_id', $req); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_probcatdetails1($id){ $this->db->select("problem_category.prob_category As prob_category, problem_category.id As prob_catid",FALSE); $this->db->from('products'); $this->db->join('problem_category', 'problem_category.model = products.id'); $this->db->where('products.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_req_list($user_access,$user_type){ if($user_type=="1"){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.status, customers.customer_name, customers.company_name",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); }else{ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.status, customers.customer_name, customers.company_name",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } public function service_req_list1($user_access,$user_type){ if($user_type=="1"){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); }else{ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.machine_status, products.model, service_location.service_loc",FALSE); $this->db->from('service_request_details'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } public function service_req_listforEmp(){ $this->db->select("service_request_details.request_id, employee.emp_name",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); //$this->db->order_by('order_details.order_id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function status_list(){ $this->db->select("id, status",FALSE); $this->db->from('status'); $query = $this->db->get(); return $query->result(); } public function combine_status_list(){ $this->db->select("service_request.id, service_request.status",FALSE); $this->db->from('service_request'); //$this->db->join('quote_review', 'quote_review.req_id=service_request.id'); //$this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_searchByStatus($id){ $query=$this->db->query("select service_request.id, service_request.request_id, service_request.request_date, service_request.status, customers.customer_name, customers.company_name from service_request As service_request inner join service_request_details As service_request_details ON service_request_details.request_id = service_request.id inner join customers As customers ON customers.id=service_request.cust_name WHERE service_request.status = $id",FALSE); //echo $this->db->last_query();exit; return $query->result(); } public function getservicereqbyid($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.mobile, service_request.email_id, service_request.address As cust_addr, service_request.address1, customers.customer_name, customers.mobile, customers.address, customers.address1, customers.company_name, customers.id As cust_id, customers.land_ln, customers.pincode, customers.email_id, customer_service_location.landline, customer_service_location.address as br_address, customer_service_location.address1 as br_address1, customer_service_location.pincode as br_pincode, customer_service_location.area as area, customer_service_location.mobile as br_mobile, customer_service_location.email_id as br_email_id",FALSE); $this->db->from('service_request'); $this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('customer_service_location', 'customer_service_location.id=service_request.br_name'); $this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function zone_pincodes(){ $query=$this->db->query("select * from service_location",FALSE); //echo $this->db->last_query();exit; return $query->result(); } public function customer_list($search,$drop) { $query=$this->db->query("select service_request.id,cust.customer_name,pro.product_name,det. machine_status,emp.emp_name,det.site,loc.service_loc ,service_request.created_on,service_request.status from service_request left join service_request_details as det on det.request_id=service_request.id left join customers as cust on cust.id=service_request.cust_name left join products as pro on pro.id=det.model_id left join service_location as loc on loc.id=det.zone left join status as stat on stat.id=service_request.status left join employee as emp on emp.id=det.assign_to where service_request.status='$drop' AND (pro.product_name='$search' OR cust.customer_name='$search' OR det.machine_status='$search' OR det.site='$search' OR emp.emp_name='$search' OR loc.service_loc='$search')"); // echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getallreq_list($search) { $query=$this->db->query("select service_request.id,cust.customer_name,pro.product_name,det. machine_status,emp.emp_name,det.site,loc.service_loc,service_request.status,service_request.created_on from service_request left join service_request_details as det on det.request_id=service_request.id left join customers as cust on cust.id=service_request.cust_name left join products as pro on pro.id=det.model_id left join service_location as loc on loc.id=det.zone left join status as stat on stat.id=service_request.status left join employee as emp on emp.id=det.assign_to where det.site='$search' OR det.machine_status='$search' OR cust.customer_name='$search' OR pro.product_name='$search' OR emp.emp_name='$search' OR service_loc='$search' OR service_request.created_on='$search 23:59:59.993'"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqDetailsbyid($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.serial_no, service_request_details.warranty_date, service_request_details.service_type, service_request_details.service_cat, service_request_details.zone, service_request_details.problem, service_request_details.assign_to, service_request_details.received, service_request_details.machine_status, service_request_details.service_priority,service_request_details.blank_app,service_request_details.notes,service_request_details.service_loc_coverage,service_request_details.batch_no, prod_category.id As catid, prod_subcategory.id As subcatid, brands.id As brandid, products.id As modelid, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model, service_location.service_loc, service_location.id As locid, service_request.status",FALSE); $this->db->from('service_request_details'); $this->db->join('service_request', 'service_request.id = service_request_details.request_id'); $this->db->join('prod_category', 'prod_category.id = service_request_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = service_request_details.subcat_id'); $this->db->join('brands', 'brands.id = service_request_details.brand_id'); $this->db->join('products', 'products.id = service_request_details.model_id'); $this->db->join('service_location', 'service_location.id = service_request_details.zone'); //$this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicereqDetailsbyid1($id){ $this->db->select("service_request_details.id, service_request_details.request_id, service_request_details.site, service_request_details.service_type",FALSE); $this->db->from('service_request_details'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_cancel_reason($id){ $this->db->select("quote_review.notes",FALSE); $this->db->from('service_request'); //$this->db->join('service_request_details', 'service_request_details.request_id = service_request.id'); $this->db->join('quote_review', 'quote_review.req_id = service_request.id'); $this->db->where('service_request.id', $id); $this->db->where('service_request.status', '10'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getserviceEmpbyid($id){ $this->db->select("service_request_details.assign_to, employee.id As emp_id, employee.emp_name ",FALSE); $this->db->from('service_request_details'); $this->db->join('employee', 'employee.id = service_request_details.assign_to'); $this->db->where('service_request_details.request_id', $id); $this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function accessories_list(){ $this->db->select("id, accessory",FALSE); $this->db->from('accessories'); $this->db->order_by('accessory', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function servicecat_list(){ $this->db->select("id,service_category",FALSE); $this->db->from('service_category'); $query = $this->db->get(); return $query->result(); } public function print_servicecat_list($id){ $this->db->select("service_category.service_category",FALSE); $this->db->from('service_request_details'); $this->db->join('service_category', 'service_category.id = service_request_details.service_cat'); $this->db->where('service_request_details.request_id', $id); //$this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function print_problemlist($id){ $this->db->select("problem_category.prob_category",FALSE); $this->db->from('service_request_details'); $this->db->join('problem_category', 'problem_category.id = service_request_details.problem'); $this->db->where('service_request_details.request_id', $id); //$this->db->order_by('service_request_details.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function sms_problemlist($id){ $this->db->select("prob_category",FALSE); $this->db->from('problem_category'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_emp_email($id){ $this->db->select("emp_email",FALSE); $this->db->from('employee'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function problemlist(){ $this->db->select("id,prob_category",FALSE); $this->db->from('problem_category'); $query = $this->db->get(); return $query->result(); } public function getProbByModel($model_id){ $this->db->select("id,prob_category",FALSE); $this->db->from('problem_category'); $this->db->where('model', $model_id); $query = $this->db->get(); return $query->result(); } public function employee_list(){ $this->db->select("employee.id, employee.emp_id, employee.emp_name, employee. emp_mobile",FALSE); $this->db->from('employee'); //$this->db->join('employee_service_skill', 'employee_service_skill.empid=employee.id'); $this->db->order_by('employee.emp_name', 'asc'); //$this->db->group_by('employee_service_skill.empid'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function employee_list1(){ $this->db->select("employee_service_skill.empid, GROUP_CONCAT(employee_service_skill.service_category) as service_category",FALSE); $this->db->from('employee_service_skill'); //$this->db->join('employee_service_skill', 'employee_service_skill.empid = employee.id'); $this->db->group_by('employee_service_skill.empid'); $this->db->order_by('employee_service_skill.empid', 'asc'); $query = $this->db->get(); //echo $this->db->last-query(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function stamping_list(){ $this->db->select("employee.id, GROUP_CONCAT(employee_service_skill.service_category) As serv_category",FALSE); $this->db->from('employee'); $this->db->join('employee_service_skill', 'employee_service_skill.empid=employee.id'); $this->db->group_by('employee_service_skill.empid'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function prod_cat_dropdownlist(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $query = $this->db->get(); return $query->result(); } public function prod_sub_cat_dropdownlist(){ $this->db->select("id,prod_category_id,subcat_name",FALSE); $this->db->from('prod_subcategory'); $query = $this->db->get(); return $query->result(); } public function brandlist(){ $this->db->select("id, cat_id, subcat_id, brand_name",FALSE); $this->db->from('brands'); $query = $this->db->get(); return $query->result(); } public function serviceLocList(){ $this->db->select("id, service_loc",FALSE); $this->db->from('service_location'); $query = $this->db->get(); return $query->result(); } public function get_branch($id){ $query = $this->db->get_where('customer_service_location', array('customer_id' => $id)); return $query->result(); } public function getBranchservicereqbyid($id){ $this->db->select("service_request.id, service_request.request_id, service_request.request_date, service_request.mobile, service_request.email_id, customer_service_location.id As cslid, customer_service_location.branch_name",FALSE); $this->db->from('service_request'); //$this->db->join('customers', 'customers.id=service_request.cust_name'); $this->db->join('customer_service_location', 'customer_service_location.id=service_request.br_name'); $this->db->where('service_request.id', $id); $this->db->order_by('service_request.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_branchdetails($id){ $query = $this->db->get_where('customer_service_location', array('id' => $id)); return $query->result(); } public function get_servicezone($id){ $this->db->select("customer_service_location.service_zone_loc, service_location.service_loc, service_location.zone_coverage",FALSE); $this->db->from('customer_service_location'); $this->db->join('service_location', 'service_location.id = customer_service_location.service_zone_loc'); $this->db->where('customer_service_location.id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsub_cat($id){ $query = $this->db->get_where('prod_subcategory', array('prod_category_id' => $id)); return $query->result(); //$this->db->where('prod_category_id',$id); //return $this->db->get('prod_subcategory')->row(); } public function get_brands($categoryid,$subcatid){ $query = $this->db->get_where('brands', array('cat_id' => $categoryid, 'subcat_id' => $subcatid)); return $query->result(); } public function get_models($categoryid,$subcatid,$brandid){ $query = $this->db->get_where('products', array('category' => $categoryid, 'subcategory' => $subcatid, 'brand' => $brandid)); return $query->result(); } public function orderlist1(){ $this->db->select("orders.id, customers.customer_name,customers.customer_type",FALSE); $this->db->from('orders'); $this->db->join('customers', 'customers.id=orders.customer_id'); $this->db->order_by('orders.id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_service_request($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function update_stamping_details($data,$id){ $this->db->where('req_id',$id); $this->db->update('stamping_details',$data); } public function update_service_status($data,$id){ $this->db->where('id',$id); $this->db->update('service_request',$data); } public function delete_serv_req_details($id){ $this->db->where('request_id',$id); $this->db->delete('service_request_details'); } public function delete_orders($id){ $this->db->where('id',$id); $this->db->delete('orders'); } }<file_sep>/application/views/add_row_subcat.php <div class="col-md-12"> <div class="col-md-4 col-sm-3 col-xs-12"> <select id="pro_cat<?php echo $count; ?>" name="pro_cat[]"> <option value="">---Select---</option> <?php foreach($droplist as $dkey){ ?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } ?> </select> <div id="ghname<?php echo $count; ?>"></div> </div> <div class="col-md-3 col-sm-3 col-xs-12"> <input type="text" name="sub_catname[]" class="model" id="sub_category-<?php echo $count; ?>" maxlength="50"> <div id="kname<?php echo $count; ?>" style="color:red"></div> </div> <div class="col-md-1"><span><a class="delRowBtn btn btn-primary"><i class="fa fa-trash"></i></a></span></div></div> <script> $(document).ready(function(){ $('#sub_category-<?php echo $count; ?>').change(function(){ //var a=$(this).attr('id').split('-').pop(); //alert(a); var sub_category = $(this).val(); var category=$('#pro_cat<?php echo $count; ?>').val(); var datastring='category='+category+'&sub_category='+sub_category; //alert(datastring); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>subcategory/subcategory_validation', data: datastring, success: function(data) { // alert(data); if(data == 0){ $('#kname<?php echo $count; ?>').html(''); } else{ $('#kname<?php echo $count; ?>').text('Sub-Category Name Already Exist').show().css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); $('#sub_category-<?php echo $count; ?>').val(''); } } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); $(".registersubmit").click(function(event){ if($('#pro_cat<?php echo $count; ?>').val()==""){ $('#ghname<?php echo $count; ?>').text("Select Category Name").css({'color':'#ff0000','font-size':'10px'}); } if($('#sub_category-<?php echo $count; ?>').val()==""){ $('#kname<?php echo $count; ?>').text("Enter Sub-Category Name").css({'color':'#ff0000','font-size':'10px'}); } }); $('#sub_category-<?php echo $count; ?>').bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $('#sub_category-<?php echo $count; ?>').keyup(function(){ if($(this).val()==""){ $('#kname<?php echo $count; ?>').show(); } else{ $('#kname<?php echo $count; ?>').fadeOut('slow'); } }); $('#pro_cat<?php echo $count; ?>').change(function(){ if($('#pro_cat<?php echo $count; ?>').val()==""){ $('#ghname<?php echo $count; ?>').show(); } else{ $('#ghname<?php echo $count; ?>').fadeOut('slow'); } }); }); </script><file_sep>/application/views/engineer_stockin.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; border: 1px solid gray; height: 27px; } .dropdown-content { display:none; } #table1 { margin-top:10px; width:100%; border-collapse: collapse; } #table1 tr { height:40px; } #table1 tr td { border:1px solid gray; text-align:center; } span { float: right; margin-top: -44px; margin-right: 20px; } #table1 tr td input { width:120px; border: 1px solid gray; height: 27px; } #table1 tr td select { width:120px; border: 1px solid gray; height: 27px; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 114px; margin: auto auto 35px; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } .color { background: rgb(5, 94, 135) none repeat scroll 0% 0%; color: white; height: 30px !important; } </style> <script type="text/javascript"> $(document).ready(function() { $("#pro_cat").change(function() { var vl=$('#countid').val(); //alert(vl); $('#spare_name_'+vl+ "> option").remove(); //$("#spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_spares", data: dataString, cache: false, success: function(data) { $('#spare_name_'+vl).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#spare_name_'+vl).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#pro_subcat").change(function() { var vl=$('#countid').val(); //alert(vl); $('#spare_name_'+vl+ "> option").remove(); //$("#spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbysubcat", data: dataString, cache: false, success: function(data) { $('#spare_name_'+vl).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#spare_name_'+vl).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#brand").change(function() { var vl=$('#countid').val(); //alert(vl); $('#spare_name_'+vl+ "> option").remove(); //$("#spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbybrand", data: dataString, cache: false, success: function(data) { $('#spare_name_'+vl).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#spare_name_'+vl).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#model").change(function() { var vl=$('#countid').val(); //alert(vl); $('#spare_name_'+vl+ "> option").remove(); //$("#spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbymodel", data: dataString, cache: false, success: function(data) { $('#spare_name_'+vl).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#spare_name_'+vl).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var vl=$('#countid').val(); //alert(vl); // alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1_'+vl).val(data.spare_qty), $('#used_spare1_'+vl).val(data.used_spare), $('#purchase_price1_'+vl).val(data.purchase_price), $('#purchase_qty1_'+vl).val(data.purchase_qty) }); } }); }); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow1", data: datastring, cache: false, success: function(result) { //alert(result); $('#table1').append(result); } }); }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Engineer Stock In</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Spare/update_spare_stock" method="post"> <table id="table1"> <tr class="color"><td><label>Qty</label></td><td><label>Date</label></td></tr> <tr> <td><input type="text" name="qty"></td> <td><input type="text" name="purchase_price"></td> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0" > <button class="btn cyan waves-effect waves-light rowadd" type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr><td> <select id="spare_name" class="spare_name" name="spare_name[]"><option value="">---Select---</option> </select></td><td><input type="text" name="qty[]"></td><td><input type="text" name="purchase_date[]"></td><td><input type="text" name="purchase_price[]"></td><td><input type="text" name="invoice_no[]"></td><td style="border:none;"><button class="delRowBtn" >Delete</button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> </body> </html><file_sep>/application/views_bkMarch_0817/add_zone_pin_row.php <!--<tr> <td> <select id="spare_name_<?php echo $count; ?>" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> </select> </td> <td><input type="text" name="qty[]"><input type="hidden" name="spare_qty1[]" id="spare_qty1_<?php echo $count; ?>"><input type="hidden" name="used_spare1[]" id="used_spare1_<?php echo $count; ?>"><input type="hidden" name="purchase_price1[]" id="purchase_price1_<?php echo $count; ?>"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_<?php echo $count; ?>"></td> <td><input type="text" name="purchase_date[]"></td> <td><input type="text" name="purchase_price[]"></td> <td><input type="text" name="invoice_no[]"></td> <td><input type="text" name="reason[]"></td> <td style="border:none;"><button class="delRowBtn" >Delete</button></td> </tr>--> <tr> <td style="padding:10px 0;"><input type="text" name="area_name[]" id="area_name-0"></td> <td style="padding:10px 0;"><input type="text" name="pincode[]" id="pincode-0"></td> </tr> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('minus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('plus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <file_sep>/application/models/Accessories_model.php <?php class Accessories_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_accessory($data){ $this->db->insert('accessories',$data); return true; } public function getaccessbyid($id){ $this->db->select("id As ac_id, accessory",FALSE); $this->db->from('accessories'); //$this->db->join('prod_category', 'prod_category.id=brands.cat_id'); //$this->db->join('prod_subcategory', 'prod_subcategory.id=brands.subcat_id'); $this->db->where('id', $id); $this->db->order_by('id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function checkaccessname($user) { $this->db->select('accessory'); $this->db->from('accessories'); $this->db->where_in('accessory',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function accessories_list(){ $this->db->select("id,accessory",FALSE); $this->db->from('accessories'); $query = $this->db->get(); return $query->result(); } public function update_accessory($data,$id){ $this->db->where('id',$id); $this->db->update('accessories',$data); } public function del_accessory($id){ $this->db->where('id',$id); $this->db->delete('accessories'); } public function acc_validation($product_id) { $query = $this->db->get_where('accessories', array('accessory' => $product_id)); return $numrow = $query->num_rows(); } }<file_sep>/application/views_bkMarch_0817/delivered_view.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $(' <tr><td> <select> <option>---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <style> .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td select { width: 210px !important; } .tableadd2 tr td select { width: 165px; } .tableadd tr td label{ width: 180px !important; font-weight: bold; font-size: 13px; } .box{ padding: 20px; margin-top: 20px; box-shadow:none !important; } .spare_table tr td label { width: 100%; } .spare_charge { margin-left:20%; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Delivered View</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>delivery/edit_quotereview" method="post" name="frmServiceStatus"> <?php foreach($getQuoteByReqId as $key){ if(isset($key->problem)){ $problem_data = explode(",",$key->problem); } ?> <table class="tableadd"> <tr> <td><label>Request ID</label>:</td><td><input type="text" name="reque_id" class="" value="<?php echo $key->request_id; ?>" readonly></td> <td><label>Customer Name</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->customer_name; ?>" readonly></td> </tr> <tr> <td><label>Branch Name</label>:</td><td><input type="text" name="br_name" class="" value="<?php echo $key->branch_name; ?>" readonly></td> <td><label>Address</label>:</td><td><?php echo $key->address.' '.$key->address1; ?></td> </tr> <tr> <td><label>Product Name</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->model; ?>" readonly><input type="hidden" name="req_id" id="req_id" class="" value="<?php echo $req_id; ?>"></td> <td><label>Date Of Purchase</label>:</td><td><input type="text" name="" value="<?php echo $key->purchase_date; ?>" readonly></td> </tr> <tr> <td><label>Warranty End Date</label>:</td><td><input type="text" name="" value="<?php echo $key->warranty_date; ?>" readonly></td> <td><label>Date Of Request</label>:</td><td><input type="text" name="" value="<?php echo $key->request_date; ?>" readonly></td> </tr> <tr> <td><label>Site</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->site; ?>" readonly></td><td><label>Location</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->service_loc; ?>" readonly></td> </tr> <tr> <td><label>Problem</label>:</td><td><?php if(!empty($problemlist1)){ foreach($problemlist1 as $problemlistkey1){ if (in_array($problemlistkey1->id, $problem_data)){ echo '<br/>'.$prob_category = $problemlistkey1->prob_category; }} }else{ echo $prob_category =""; } ?></td><td><label>Machine Status</label>:</td><td><input type="text" name="" class="" value="<?php echo $key->machine_status; ?>" readonly></td> </tr> </table> <?php } ?> <?php if($key->site != "Stamping"){ ?> <table id="table1" class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>Spare Name</td> <td>Quantity</td> <td>Amount</td> </tr> <?php if(!empty($spareIds)){ foreach($spareIds as $key3){ foreach($key3 as $key4){ $usedspare[] = $key4->used_spare; $stockspare[] = $key4->spare_qty; $salesprice[] = $key4->sales_price; } } }//exit; $tot_spare_amt = 0; if(!empty($spare_amtt)){ //print_r($spare_amtt); foreach($spare_amtt as $spareAmt_key){ $tot_spare_amt += $spareAmt_key; } } $i = 0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ $tax_amt11 = $i;}else{foreach($getTaxDefaultInfo as $taxKey){ $tax_amt11 = ($tot_spare_amt * $taxKey->tax_percentage) / 100; }} } foreach($getServiceCatbyID as $ServiceKey){ if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ $labor_chrg = $i;}else{ $labor_chrg = $ServiceKey->service_charge;}} if(isset($getservicecharge)){ $labor_chrg = $getservicecharge;} if($WarranKey->machine_status=="Chargeable" && $WarranKey->site == 'Customer Site'){ $conchrg = $key->concharge;}else{$conchrg = $i;} if(isset($tot_spare_amt) || isset($tax_amt11) || isset($labor_chrg) || isset($conchrg) ){ $tottt = $tot_spare_amt+$tax_amt11+$labor_chrg+$conchrg; } $count='0'; foreach($getQuoteReviewSpareDetByID as $ReviewDetKey2){ ?> <tr> <td><input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="<?php if(!empty($usedspare[$count])){echo $usedspare[$count];}?>"><input type="hidden" name="spare_tbl_id[]" id="spare_tbl_id<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->id;?>"> <?php foreach($spareListByModelId1 as $sparekey1){ if($sparekey1->id==$ReviewDetKey2->spare_id){ echo $sparekey1->spare_name; } } ?> </td> <td><?php echo $ReviewDetKey2->spare_qty; ?></td> <td><?php echo $ReviewDetKey2->amt; ?></td> </tr> <?php $count++; } ?> </table> <?php foreach($getQuoteReviewDetByID1 as $ReviewDetKey1){ ?> <table class="tableadd"> <tr> <td><label>Spare Tax Amount</label>:</td><td> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Preventive'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?><?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Chargeable'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <input type="text" name="spare_tax" id="spare_tax" class="" value="<?php $i = 0; if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{foreach($getTaxDefaultInfo as $taxKey){ echo $tax_amt = ($tot_spare_amt * $taxKey->tax_percentage) / 100; }}?>" readonly><input type="hidden" name="tax_type" id="tax_type" class="" value="<?php foreach($getTaxDefaultInfo as $taxKey){ echo $taxKey->tax_percentage; }?>" ></td><td><label>Spare Total Charges</label>:</td><td><input type="text" name="spare_tot" id="spare_tot" class="" value="<?php if(isset($tot_spare_amt)){echo $tot_spare_amt;} ?>" readonly></td> </tr> <tr> <td><label>Labour Charges</label>:</td><td><input type="text" name="labourcharge" id="labourcharge" class="" value="<?php foreach($getServiceCatbyID as $ServiceKey){if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $i;}else{echo $ServiceKey->service_charge;}} if(isset($getservicecharge)){echo $getservicecharge;} ?>" readonly></td><td><label>Conveyance Charges</label>:</td><td><input type="text" name="concharge" id="concharge" class="" value="<?php if($WarranKey->machine_status=="Chargeable" && $WarranKey->site == 'Customer Site'){echo $key->concharge;}else{echo $i;} ?>" readonly></td> </tr> <tr> <td><label>Total Amount</label>:</td><td><input type="text" name="total_amt" id="total_amt" class="" value="<?php if((isset($ReviewDetKey1->pending_amt) && $ReviewDetKey1->pending_amt!="0") || (isset($ReviewDetKey1->disc_amt) && $ReviewDetKey1->disc_amt!="0") || (isset($ReviewDetKey1->plus_amt) && $ReviewDetKey1->plus_amt!="0")){echo $ReviewDetKey1->total_amt; }else{echo $tottt;}?>" readonly><input type="hidden" name="total_amt1" id="total_amt1" class="" value="<?php if((isset($ReviewDetKey1->pending_amt) && $ReviewDetKey1->pending_amt!="0") || (isset($ReviewDetKey1->disc_amt) && $ReviewDetKey1->disc_amt!="0") || (isset($ReviewDetKey1->plus_amt) && $ReviewDetKey1->plus_amt!="0")){echo $ReviewDetKey1->total_amt; }else{echo $tottt;}?>" ></td> <td><label>Discount Amount</label>:</td><td><input type="text" name="disc_amt" value="" readonly><input type="hidden" name="disc_amt1" id="disc_amt1" class="" value="<?php echo $ReviewDetKey1->disc_amt; ?>" ></td> </tr> <tr> <td><label>Add Amount</label>:</td><td><input type="text" name="plus_amt" value="" readonly><input type="hidden" name="plus_amt1" id="plus_amt1" class="" value="<?php echo $ReviewDetKey1->plus_amt; ?>" ></td> <td><label><b>Payment mode: </b></label></td> <td> <select name="payment_mode"> <option value="">---Select---</option> <option value="Cash" <?php if(isset($ReviewDetKey1->payment_mode) && $ReviewDetKey1->payment_mode=="Cash"){?> selected="selected" <?php } ?>>Cash</option> <option value="Cheque" <?php if(isset($ReviewDetKey1->payment_mode) && $ReviewDetKey1->payment_mode=="Cheque"){?> selected="selected" <?php } ?>>Cheque</option> </select> </td> </tr> <tr> <td><label><b>CMR Paid</b></label></td> <td><input type="text" name="service_cmr_paid" id="service_cmr_paid" value="" ><input type="hidden" name="service_cmr_paid1" id="service_cmr_paid1" class="" value="<?php if(isset($ReviewDetKey1->cmr_paid)){echo $st = $ReviewDetKey1->cmr_paid;}else{ echo $st = '0'; } ?>"></td> <td><label><b>Pending Amount</b></label></td> <td><input type="text" name="service_pending_amt" id="service_pending_amt" value="<?php if(isset($ReviewDetKey1->pending_amt)){echo $ReviewDetKey1->pending_amt;} ?>" readonly><input type="hidden" name="service_pending_amt1" id="service_pending_amt1" class="" value="<?php if(isset($ReviewDetKey1->pending_amt)){echo $ReviewDetKey1->pending_amt;} ?>"></td> </tr> <tr class="ready "> <td><label>Date Of Delivery</label>:</td><td><input type="text" name="" value="<?php echo $ReviewDetKey1->delivery_date; ?>" readonly></td> <td><label>Comments</label>:</td><td><input type="text" name="" class="" value="<?php echo $ReviewDetKey1->comments; ?>" readonly></td> </tr> <tr class="ready"> <td><label>Emp Pts</label>:</td><td><input type="text" name="emp_pts" value="<?php if(isset($ReviewDetKey1->emp_pts) && $ReviewDetKey1->emp_pts!="0"){echo $ReviewDetKey1->emp_pts; }else{echo "0";}?>" readonly></td> </tr> </table> <table class="tableadd"> <tr> <td><label>Notes</label>:</td><td><textarea type="text" name="notes" id="notes" class="materialize-textarea" readonly><?php if($ReviewDetKey1->notes!=""){echo $ReviewDetKey1->notes;}else{foreach($getQuoteByReqId as $notekey){echo $notekey->notes;}} ?></textarea></td> </tr> </table> <table class="tableadd"> <tr> <td><label>Customer Feedback</label>:</td><td><textarea type="text" name="cust_feed" id="cust_feed" class="materialize-textarea"><?php if($ReviewDetKey1->cust_feed!=""){echo $ReviewDetKey1->cust_feed;} ?></textarea></td> </tr> </table> <?php } ?> <?php } ?> <?php if($key->site == "Stamping"){ if(!empty($stamping_details)){ foreach($stamping_details as $stamp_det){ if(isset($stamp_det->stamping_received)){ $stamping_received = explode(",",$stamp_det->stamping_received); } ?> <p><b>Stamping Details:</b> </p> <table class="tableadd"> <tr> <td><label><b>Year</b></label></td> <td><input type="text" name="year" id="year" class="" value="<?php if(isset($stamp_det->year)){echo $stamp_det->year;} ?>" readonly></td> <td><label><b>Quarter</b></label></td> <td><input type="text" name="qtr" id="qtr" class="" value="<?php if(isset($stamp_det->quarter)){echo $stamp_det->quarter;} ?>" readonly></td> </tr> <tr> <td><label><b>Kg</b></label></td> <td><input type="text" name="kg" id="kg" class="" value="<?php if(isset($stamp_det->kg)){echo $stamp_det->kg;} ?>" readonly></td> <td><label><b>Received</b></label></td> <td> <select name="stamping_received[]" multiple style="height:60px; background-image:none;border: 1px solid #055E87; border-radius: 5px;"> <option value="">---Select---</option> <option value="vcplate" <?php if (in_array('vcplate', $stamping_received)){?> selected="selected" <?php } ?> >VC Plate</option> <option value="vcpaper" <?php if (in_array('vcpaper', $stamping_received)){?> selected="selected" <?php } ?>>VC Paper</option> <option value="bothplatepaper" <?php if (in_array('bothplatepaper', $stamping_received)){?> selected="selected" <?php } ?>>Both VC Plate &amp; VC Paper</option> </select> </td> </tr> <tr> <td><label><b>Stamping Charge</b></label></td> <td><input type="text" name="stamping_charge" id="stamping_charge" class="" value="<?php if(isset($stamp_det->stamping_charge)){echo $stamp_det->stamping_charge;} ?>" readonly></td> <td><label><b>Agent Charge</b></label></td> <td><input type="text" name="agn_charge" id="agn_charge" class="" value="<?php if(isset($stamp_det->agn_charge)){echo $stamp_det->agn_charge;} ?>" readonly></td> </tr> <tr> <td><label><b>Penalty</b></label></td> <td><input type="text" name="penalty" id="penalty" class="" value="<?php if(isset($stamp_det->penalty)){echo $stamp_det->penalty;} ?>" readonly></td> <td><label><b>Conveyance Charge</b></label></td> <td><input type="text" name="conveyance_charge" id="conveyance_charge" class="" value="<?php if(isset($stamp_det->conveyance)){echo $stamp_det->conveyance;} ?>" readonly></td> </tr> <tr> <td><label><b>Total Charge</b></label></td> <td><input type="text" name="tot_charge" id="tot_charge" class="" value="<?php if(isset($stamp_det->tot_charge)){echo $stamp_det->tot_charge;} ?>" readonly></td> <td><label><b>CMR Paid</b></label></td> <td><input type="text" name="cmr_paid" id="cmr_paid" class="" value="<?php if(isset($stamp_det-> cmr_paid)){echo $stamp_det->cmr_paid;} ?>" readonly></td> </tr> <tr> <td><label><b>Pending Amount</b></label></td> <td><input type="text" name="pending_amt" id="pending_amt" class="" value="<?php if(isset($stamp_det->pending_amt)){echo $stamp_det->pending_amt;} ?>" readonly></td> <td><label>Date Of Delivery</label>:</td> <td><input type="text" name="delivery_date" value="<?php foreach($getQuoteReviewDetByID1 as $ReviewDetKey1){ if(isset($ReviewDetKey1->delivery_date)){echo $ReviewDetKey1->delivery_date; }else{echo $del_date;} } ?>" readonly></td> </tr> <tr> <td><label>Assign To</label>:</td><td><input type="text" name="assign_to" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->emp_name; }?>" readonly><input type="hidden" name="assign_to_id" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->id; }?>" readonly></td> </tr> <?php if(!empty($log_stamping_details)){ foreach($log_stamping_details as $log_stampingKey){?> <tr> <td><label>Date of On-Hold</label>:</td><td><input type="text" name="on_hold" value="<?php if(isset($log_stampingKey->on_hold_date)){echo $log_stampingKey->on_hold_date; }else{echo $req_date;} ?>" readonly> <input type="hidden" name="assign_to_stamp_id" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->id; }?>" readonly></td> <td><label>Reason</label>:</td><td><textarea type="text" name="on_hold_reason" id="on_hold_reason" class="materialize-textarea" readonly><?php if(isset($log_stampingKey->on_hold_reason)){echo $log_stampingKey->on_hold_reason; } ?></textarea></td> </tr> <?php } }?> </table> <table class="tableadd"> <tr> <td><label>Customer Feedback</label>:</td><td><textarea type="text" name="cust_feed" id="cust_feed" class="materialize-textarea"><?php if($ReviewDetKey1->cust_feed!=""){echo $ReviewDetKey1->cust_feed;} ?></textarea></td> </tr> </table> <?php } } } ?> <?php //if($key->site!='Stamping'){?> <!--<table class="spare_table" style="margin-top: 20px;width: 60%;"> <label style="color:red;">Check any button to print invoice </label> <tr><td><label><input type="radio" id="print_invoice" class="print_invoice" name="print_invoice" value="with_spare"><span class="spare_charge">With Spare charges</span></label> </td> <td><label><input type="radio" id="print_invoice" class="print_invoice" name="print_invoice" value="without_spare"><span class="spare_charge">Without Spare charges</span></label></td> </tr> </table>--> <?php //} ?> <table class="tableadd" style="margin-top: 25px;"> <tr> <td> <button class="btn cyan waves-effect waves-light " type="submit" name="Save" value="save">Submit <i class="fa fa-arrow-right"></i> </button> <?php if($key->site!='Stamping'){?> <!--<a class="delivery box" href="<?php echo base_url(); ?>ready_delivery/print_request/<?php echo $req_id; ?>" style="background: rgb(5, 94, 135) none repeat scroll 0% 0% !important; padding: 10.4px !important; color: #FFF !important; border-radius: 5px !important; margin-left: 20px !important;" id="print_box" target="_blank">Print Invoice</a>--> <!--<button href="<?php echo base_url(); ?>ready_delivery/print_request/<?php echo $req_id; ?>" style=" padding: 10.4px !important; color: #FFF !important; border-radius: 5px !important; margin-left: 20px !important;" id="print_box" type="submit" name="Save" value="print">Print Invoice</button> --> <?php } ?> &nbsp;<a class="btn cyan waves-effect waves-light " onclick="history.go(-1);">Exit </a> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script> /* $(document).ready(function(){ $('#print_box').click(function(){ if(document.getElementById('print_invoice').checked){ var with_spare = '1'; } if(document.getElementById('print_invoice1').checked){ var without_spare = '0'; } alert(without_spare); //var dataString = 'id='+id; }); }); */ </script> <script > $(window).load(function(){ $(document).ready(function(){ $("#print_box").attr("disabled","disabled"); $("#print_box").css("background", "#999"); $(".print_invoice").click(function(){ $("#print_box").removeAttr("disabled").css("background","#055E87"); }) $("#print_box").click(function(e){ if($("#print_box").attr("disabled")=="disabled") { e.preventDefault(); } }); }); }); </script> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }); }); }//]]> </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $('#plus_amt').keyup(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; } else{ var disc_amt = $( this ).val(); //alert(disc_amt); if(disc_amt){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) + parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); }else{ var total_amt = $('#total_amt1').val(); //alert(total_amt); $('#total_amt').val(total_amt); $('#service_pending_amt').val(total_amt); $('#service_pending_amt1').val(total_amt); } } }); $('#disc_amt').keyup(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; } else{ var disc_amt = $( this ).val(); //alert(disc_amt); if(disc_amt){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) - parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); }else{ var total_amt = $('#total_amt1').val(); //alert(total_amt); $('#total_amt').val(total_amt); $('#service_pending_amt').val(total_amt); $('#service_pending_amt1').val(total_amt); } } }); $('#service_cmr_paid').keyup(function(e) { //alert("hello boss"); if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message alert("Numbers Only"); return false; }else{ var service_pending_amt_val = $('#service_pending_amt1').val(); //alert(service_pending_amt_val); var service_cmr_paid = $(this).val(); //alert(service_cmr_paid); if(service_cmr_paid){ var service_pending_amt = parseInt(service_pending_amt_val) - parseInt(service_cmr_paid); //alert(service_pending_amt); $('#service_pending_amt').val(service_pending_amt); }else{ $('#service_pending_amt').val(service_pending_amt_val); } } }); $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('disc_amt').value!=""){ alert("enter discount or addition amt"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus_amt').value!=""){ alert("enter discount or addition amt"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); </script> </body> </html><file_sep>/application/controllers/Sparereport.php <?php class sparereport extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Sparereport_model'); } function get_engineer_name() { $from_date=$this->input->post('from'); $to_date=$this->input->post('to'); $engg_name=$this->input->post('engineer'); $spare_name=$this->input->post('spare'); $m_data['enggname_list']=$this->Sparereport_model->engnamelist(); $m_data['sparename_list']=$this->Sparereport_model->sparenamelist(); $m_data['sparereport'] = $this->Sparereport_model->get_sparereport($spare_name,$from_date,$to_date); $data['user_dat'] = $this->session->userdata('login_data'); //print_r($data['report']);exit; $this->load->view('templates/header',$data); $this->load->view('sparereport_engg_list',$m_data); } } <file_sep>/application/views_bkMarch_0817/view_amclist.php <style> .link{ padding: 8px; border: 1px solid rgb(5, 94, 135); background: rgb(5, 94, 135) none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } #myTable tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:400px !important; } #myTable tr td select { width: 210px !important; } .tableadd tr td input { width: 210px !important; } #errorBox{ color:#F00; } .box{ box-shadow:none !important; } .box1{ display: none; box-shadow:none !important; } .amc tr td input{ width: 400px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 5px; padding-left: 10px; } .select-wrapper { width: 130px; } .tableadd .select-wrapper { width: 130px; /* margin-top: -55px; */ position: relative; top: -36px; } .amc tr td{ width:150px; margin-right: 20px; } .amc tr td select { height: 33px; border-radius: 5px; width: 81px; border: none; border-bottom: 1px solid #055E87; background-color: transparent; background-image: linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; /*padding: 0.5em 3.5em 0.5em 1em;*/ margin: 0px; box-sizing: border-box; -moz-appearance: none; } .col-md-3,.col-md-12 { padding: 0px; } .col-md-2{ padding: 0px; line-height: 30px; } .card-panel,.col-md-6 { padding: 0px; } .box { margin-bottom: 0px; } label { position: relative; left: 30px; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">View Sales</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url();?>pages/amc_list" method="post"> <?php foreach($list as $key){?> <div id="errorBox"></div> <div class="tableadd" > <div class="col-md-12"> <div class="col-md-2"><label>Invoice No:</label></div> <div class="col-md-2"><?php echo $key->order_id; ?></div> <div class="col-md-2"><label>Customer Name:</label></div> <div class="col-md-2"><?php echo $key->customer_name;?></div> <div class="col-md-2"><label>Branch Name:</label></div> <div class="col-md-2"><?php if($key->cslid){ ?> <?php echo $key->branch_name; ?> <?php } ?> </div> </div> <div class="col-md-12"> <div class="col-md-2"><label>Contact Name:</label></div> <div class="col-md-2"><?php echo $key->contact_name; ?></div> <div class="col-md-2"><label>Mobile:</label></div> <div class="col-md-2"><?php echo $key->mobile; ?></div> <div class="col-md-2"><label>Email:</label></div> <div class="col-md-2"><?php echo $key->email_id; ?></div> </div> <div class="col-md-12"> <div class="col-md-2"><label>Address:</label></div> <div class="col-md-2"><?php echo $key->address; ?></div> <div class="col-md-2"><label>City:</label></div> <div class="col-md-2"><?php echo $key->city; ?></div> <div class="col-md-2"><label>State:</label></div> <div class="col-md-2"><?php echo $key->state; ?></div> </div> <div class="col-md-12"> <div class="col-md-2"><label>Pincode:</label></div> <div class="col-md-2"><?php echo $key->pincode; ?><?php echo $key->zone_coverage; ?></div> </div> </div> <?php } ?> <?php foreach($list1 as $key1){?> <div id="table1" class="tableadd" style="margin-bottom: 20px;"> <label style="color: black;font-size: 15px;font-weight: bold;margin-right: 10px">Add Product</label> <div class="col-md-12"> <div class="col-md-2"><label>Serial No:</label></div> <div class="col-md-2"><?php echo $key1->serial_no; ?><?php echo $key1->id; ?></div> <div class="col-md-2"><label>Batch No:</label></div> <div class="col-md-2"><?php echo $key1->batch_no; ?></div> <div class="col-md-2"><label>Model:</label></div> <div class="col-md-2"><?php echo $key1->model;?></div> </div> <div class="col-md-12"> <div class="col-md-2"><label>Category:</label></div> <div class="col-md-2"><?php echo $key1->cat_name; ?><input type="hidden" name="category" id="category" value="<?php echo $key1->cat_id; ?>"></div> <div class="col-md-2"><label>SubCategory:</label></div> <div class="col-md-2"><?php echo $key1->subcat_name; ?><input type="hidden" name="subcategory" id="subcategory" value="<?php echo $key1->subcat_id; ?>"></div> <div class="col-md-2"><label>Brand Name:</label></div> <div class="col-md-2"><?php echo $key1->brand_name; ?><input type="hidden" name="brandname" id="brandname" value="<?php echo $key1->brand_id; ?>"></div> </div> <div class="col-md-12"> <div class="col-md-2"><label >Service Zone:</label></div> <div class="col-md-2"><?php echo $key1->service_zone; ?><input type="hidden" name="service_loc" id="service_loc" value="<?php echo $key1->service_loc_id; ?>"></div> <div class="col-md-2"><label>Sale Date:</label></div> <div class="col-md-2"><?php echo $key1->purchase_date; ?><input type="hidden" name="warranty_date_hide" id="warranty_date_hide" value="<?php echo $key1->warranty_date; ?>" readonly><input type="hidden" name="prev_main_hide" id="prev_main_hide" value="<?php echo $key1->prev_main; ?>" readonly><input type="hidden" name="paid_hide" id="paid_hide" value="<?php echo $key1->paid; ?>" readonly></div> </div> <div id="table1" class="tableadd"> <div><label> <?php if($key1->paid){ echo "chargeable";?><?php }?></label></div> <div><?php if($key1->warranty_date){?></div> <div class="col-md-12 warranty box"> <div class="col-md-2"><label>Warranty Date:</label></div> <div class="col-md-2"><?php echo $key1->warranty_date; ?></div> </div> <?php }?> <?php if($key1->prev_main){?> <div class="col-md-12 prevent box"> <div class="col-md-2"><label>End Date:</label></div> <div class="col-md-2"><?php echo $key1->prev_main; ?></div> <div class="col-md-2"><label>Nos:</label></div> <div class="col-md-2"><?php if($key1->prenos=='1'){ echo "1";?> <?php } ?> <?php if($key1->prenos=='3'){ echo "3";?> <?php } ?> <?php if($key1->prenos=='6'){echo "6";?> <?php } ?> <?php if($key1->prenos=='12'){ echo "12";?> <?php } ?> </div> </div> <?php } ?> <?php if($key1->amc_type){?> <div class="col-md-12 amc box"> <div class="col-md-2"><label>AMC Type:</label></div> <div class="col-md-2"><?php if($key1->amc_type=='Comprehensive'){ echo "Comprehensive";?> <?php } ?> <?php if($key1->amc_type=='serviceonly'){ echo "serviceonly";?> <?php } ?> </div> <div class="col-md-2"><label>Start Date:</label></div> <div class="col-md-2"><?php echo $key1->amc_start_date; ?></div> <div class="col-md-2"><label>End Date:</label></div> <div class="col-md-2"><?php echo $key1->amc_end_date; ?></div> </div> <div class="col-md-12 amc box"> <div class="col-md-2"><label class="nos">Nos:</label></div> <div class="col-md-2"><?php if($key1->prenos=='1'){ echo "1";?> <?php } ?> <?php if($key1->prenos=='3'){ echo "3";?> <?php } ?> <?php if($key1->prenos=='6'){ echo "6";?> <?php } ?> <?php if($key1->prenos=='12'){ echo "12";?> <?php } ?> </div> </div> <?php } ?> </div> <div class="tableadd"> <div class="col-md-12"> <div class="col-md-2"><label>Notes:</label></div> <div class="col-md-6"><?php echo $key1->notes;?></div> </div> </div> <?php } ?> <!--<table id="tabletest" class="tableadd" style="margin-bottom: 20px;"></table> <input type="hidden" id="countid" value="<?php echo $count; ?>">--> <!--<a id="addMoreRows" style="background: rgb(5, 94, 135) none repeat scroll 0% 0%; padding: 11px; color: #FFF; border-radius: 5px; margin-right: 20px;">Add Product</a>--> <button class="btn cyan waves-effect waves-light " type="submit">Close<i class="fa fa-arrow-right"></i></button> </div> </div> <div class="col-md-1"> </div> </form> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 999-9999'); $('#mobile').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode1').mask('999999'); }); });//]]> </script> <link href="<?php echo base_url(); ?>assets/css/jquery.datepick.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/jquery.plugin.js"></script> <script src="<?php echo base_url(); ?>assets/js/jquery.datepick.js"></script> <script> $(function() { $('#popupDatepicker').datepick(); $('#popupDatepicker1').datepick(); }); function showDate(date) { alert('The date chosen is ' + date); } </script> <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="paid"){ $(".box").not(".paid").hide(); $(".box1").not(".paid").hide(); $(".paid").show(); } if($(this).attr("value")=="warranty"){ $(".box").not(".warranty").hide(); $(".box1").not(".warranty").hide(); $(".warranty").show(); $(".warranty1").show(); } if($(this).attr("value")=="prevent"){ $(".box").not(".prevent").hide(); $(".box1").not(".prevent").hide(); $(".prevent").show(); $(".prevent1").show(); } if($(this).attr("value")=="amc"){ $(".box").not(".amc").hide(); $(".box1").not(".amc").hide(); $(".amc").show(); $(".amc1").show(); } }); }); </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("input[name='datepickerpurchase']").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("input[name='datepickerwarranty']").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }//]]> </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/view_sales.php <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 4px; border: 1px solid #ccc; } table.dataTable.no-footer tr td { border: 1px solid #ccc !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border: 1px solid #ccc; color: #303f9f; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } #data-table-simple_length { display: block; } .dataTables_wrapper { position: relative; clear: both; zoom: 1; } .dataTables_wrapper .dataTables_length { float: left; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ table.dataTable.no-footer { border-bottom: none !important; } table.dataTable, table.dataTable th, table.dataTable td { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } table.dataTable { width: 100%; margin: 0 auto; clear: both; border-collapse: collapse !important; border-spacing: 0; } table { width: 100%; display: table; } label { display: inline-block; max-width: 100%; margin-bottom: 5px; font-weight: 700; } select { background-color: rgba(255, 255, 255, 0.9); width: 100%; padding: 5px; border: 1px solid #bbb; border-radius: 2px; height: 2rem; /* display: none; */ } #data-table-simple_filter label { font-size: 15px !important; } .dataTables_wrapper .dataTables_filter input { margin-left: 0.5em; } input[type=search] { background-color: transparent; border: 1px solid #bbb; border-radius: 7; width: 55%; font-size: 1.1rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .dataTables_wrapper .dataTables_info { clear: both; float: left; padding-top: 0.755em; } .dataTables_wrapper .dataTables_paginate { float: right; text-align: right; padding-top: 0.25em; } ul{ display:none; } .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate { color: #bbb; } table.dataTable thead th, table.dataTable thead td { padding: 10px 18px; border-bottom: 1px solid #bbb !important; } </style> <script> function frmValidate(){ if((document.getElementById("print_invoice").checked == false) && (document.getElementById("print_invoice1").checked == false)) { document.getElementById("print_invoice").focus(); document.getElementById("errorBox").innerHTML = "Check any button to print invoice"; return false; } } </script> <section id="content"> <div class="container"> <div class="section"> <h2>Sales Details</h2> <div class="divider"></div> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th style="width:100 !important">Serial No</th> <th style="width:200 !important">Model Name</th> <th>Installation Date</th> <th>Status</th> </tr> </thead> <tbody> <?php foreach($list as $key){?> <tr> <td><?php echo $key->serial_no;?></td> <td><?php echo $key->model;?></td> <td><?php echo $key->purchase_date;?></td> <td><?php $a = $key->amc_start_date; $b = $key->cmc_start_date; $c = $key->warranty_date; $d = $key->rent_type; if($a!='' && $b=='' && $c=='' && $d=='') { echo "AMC"; } if($a=='' && $b!='' && $c=='' && $d=='') { echo "CMC"; } if($a=='' && $b=='' && $c!='' && $d=='') { echo "Warranty"; } if($a=='' && $b=='' && $c=='' && $d!='') { echo "Rent"; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> </body> </html><file_sep>/application/views_bkMarch_0817/add_service_req_row.php <table class="tableadd" > <label style="color: black; font-size: 15px; font-weight: bold; margin-bottom:20px;">Add Product</label> <tr> <td><label>Serial No</label></td> <td> <select name="serial_no[]" id="serialno_<?php echo $count; ?>" class="serialno"> <option value="">---Select---</option> <?php foreach($list_serialnos as $serialkey){ ?> <option value="<?php echo $serialkey->serial_no; ?>"><?php echo $serialkey->serial_no; ?></option> <?php } ?> </select> </td> <td><label>Category</label></td><td > <input type="text" name="category[]" id="category<?php echo $count; ?>" class=""><input name="countids[]" type="hidden" value="<?php echo $count; ?>"/><input type="hidden" name="categoryid[]" id="categoryid<?php echo $count; ?>" class=""> </td> </tr> <tr> <td><label>SubCategory</label></td> <td > <input type="text" name="subcategory[]" id="subcategory<?php echo $count; ?>" class=""><input type="hidden" name="subcategoryid[]" id="subcategoryid<?php echo $count; ?>" class=""> </td> <td ><label>Brand Name</label></td><td style="width:200px;"> <input type="text" name="brandname[]" id="brandname<?php echo $count; ?>" class=""><input type="hidden" name="brandid[]" id="brandid<?php echo $count; ?>" class=""> </td> </tr> <tr> <td><label>Model</label></td> <td > <input type="text" name="model[]" id="model<?php echo $count; ?>" class=""><input type="hidden" name="modelid[]" id="modelid<?php echo $count; ?>" class=""> </td> <td><label>Warranty Date</label></td><td><input id="warranty_date<?php echo $count; ?>" type="text" name="warranty_date[]"></td> </tr> <tr> <td><label>Machine Status</label></td> <td> <select name="machine_status[]"> <option value="">---Select---</option> <option value="AMC">AMC</option> <option value="Warranty">Warranty</option> <option value="Out Of Warranty">Out Of Warranty</option> </select> </td> <td><label>Site</label></td> <td> <select name="site[]"> <option value="">---Select---</option> <option value="OnSite">OnSite</option> <option value="OffSite">OffSite</option> </select> </td> </tr> <tr> <td><label>Service Type</label></td> <td> <select name="service_type[]"> <option value="">---Select---</option> <option value="AMC">AMC</option> <option value="Warranty">Warranty</option> <option value="Out Of Warranty">Out Of Warranty</option> <option value="Stampings">Stampings</option> </select> </td> <td><label>Service Category</label></td> <td> <select name="service_cat[]"> <option value="">---Select---</option> <?php foreach($servicecat_list as $servicecatkey){ ?> <option value="<?php echo $servicecatkey->id; ?>"><?php echo $servicecatkey->service_category; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><label>Zone</label></td> <td> <input type="text" name="zone[]" id="zone<?php echo $count; ?>" class=""><input type="hidden" name="locid[]" id="locid<?php echo $count; ?>" class=""> </td> <td><label>Problem</label></td> <td> <select name="prob[]"> <option value="">---Select---</option> <?php foreach($problemlist as $probkey){ ?> <option value="<?php echo $probkey->id; ?>"><?php echo $probkey->prob_category; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><label>Assign To</label></td> <td> <select name="assign_to[]"> <option value="">---Select---</option> <?php foreach($employee_list as $empkey){ ?> <option value="<?php echo $empkey->id; ?>"><?php echo $empkey->emp_name.'- ('.$empkey->emp_id.')'; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><label style="font-weight:bold;">Received</label></td> </tr> </table> <table style="margin-bottom: 40px;"><tr><td> <ul class="recei"> <li><label>Charger</label></li><li><label>Data Cable</label></li><li><label>Battery</label></li><li><label>Headset</label></li><li><label>Cover</label></li> </ul></td> </tr><tr><td> <ul class="recei"> <li><input type="checkbox" class="" name="received<?php echo $count; ?>[]" value="Charger"></li><li><input type="checkbox" class="" name="received<?php echo $count; ?>[]" value="DataCable"></li><li><input type="checkbox" class="" name="received<?php echo $count; ?>[]" value="Battery"></li><li><input type="checkbox" class="" name="received<?php echo $count; ?>[]" value="Headset"></li><li><input type="checkbox" class="" name="received<?php echo $count; ?>[]" value="Cover"></li> </ul></td> </tr> </table> <script> $(document).ready(function(){ $('.serialno').change(function(){ var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(catid); var id = $(this).val(); //alert(id); var dataString = 'serialno='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>service/get_orderbyid", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#category'+ctid).val(data.product_category), $('#categoryid'+ctid).val(data.catid), $('#subcategory'+ctid).val(data.subcat_name), $('#subcategoryid'+ctid).val(data.subcatid), $('#brandname'+ctid).val(data.brand_name), $('#brandid'+ctid).val(data.brandid), $('#model'+ctid).val(data.model), $('#modelid'+ctid).val(data.modelid), $('#warranty_date'+ctid).val(data.warranty_date), $('#zone'+ctid).val(data.service_loc), $('#locid'+ctid).val(data.locid) }); } }); }); }); </script> <script type="text/javascript"> jQuery.noConflict(); $(document).ready(function() { $(".category").change(function(){ //alert("ggg"); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var catid = arr['1']; //alert(catid); $('#subcategory_'+catid+ "> option").remove(); var id=$(this).val(); //alert("catttt: "+catid); //alert("iddddd: "+id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory_'+catid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory_'+catid).append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); $(".subcategory").change(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id=$(this).val(); var subcatid=$(this).val(); categoryid = $('#category_'+ctid).val(); //alert("Subcat: "+subcatid+"Cat:" +categoryid); //$('#subcategory_'+catid+ "> option").remove(); $('#brandname_'+ctid+"> option").remove(); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_brand", data: dataString, cache: false, success: function(data) { $('#brandname_'+ctid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.brand_name); $('#brandname_'+ctid).append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); $(".brandname").change(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); $('#model_'+ctid+"> option").remove(); var brandid=$(this).val(); categoryid = $('#category_'+ctid).val(); subcategoryid = $('#subcategory_'+ctid).val(); //alert("Subcat: "+subcategoryid+"Cat:" +categoryid+"brandid:" +brandid); var dataString = 'subcatid='+ subcategoryid+'&categoryid='+ categoryid+'&brandid='+ brandid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_model", data: dataString, cache: false, success: function(data) { $('#model_'+ctid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.model); $('#model_'+ctid).append("<option value='"+data.id+"'>"+data.model+"</option>"); }); } }); }); }); </script><file_sep>/application/views/dash -updated on 10-02-2017.php <style> /*.btn { position: relative; padding: 0px 2px; border: 0; margin: 0px 1px; cursor: pointer; border-radius: 2px; text-transform: uppercase; text-decoration: none; color: rgba(255,255,255,.84); transition: box-shadow .28s cubic-bezier(.4,0,.2,1); outline: none!important; }*/ .btn-sm { padding: 8px 10px !important; font-size: 12px; line-height: 1.5; border-radius: 3px; font-weight: bold !important; } .table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th, .table>thead>tr>td, .table>tbody>tr>td, .table>tfoot>tr>td { padding: 1px 5px !important; line-height: 1.42857143; vertical-align: top; border-top: 1px solid #ddd !important; font-size: 11px; font-weight: bold; } .label { display: inline; padding: .2em .6em .3em; font-size: 81%; font-weight: 700; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; } .fa { font-size: 20px !important; } .fa-globe{ font-size: 30px !important; position:relative; top:7px; } .fa-desktop{ font-size: 30px !important; position:relative; top:7px; } .fa-list-alt{ font-size: 30px !important; position:relative; top:7px; } .fa-cog{ font-size: 30px !important; position:relative; top:7px; } .fa-bell-o{ font-size: 30px !important; position:relative; top:7px; } .fa-truck{ font-size: 30px !important; position:relative; top:7px; } .info-box-icon { border-top-left-radius: 2px; border-top-right-radius: 0; border-bottom-right-radius: 0; border-bottom-left-radius: 2px; display: block; float: left; height: 45px; width: 36px; text-align: center; font-size: 45px; line-height: 20px; background: rgba(0,0,0,0.2); position: relative; top: 6px; } .info-box-text { display: block; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; } .tableft{ padding-left: 10px !important; } .breadcrumbs-title { font-size: 2.2rem; line-height: 0rem; margin: 0 0 0; } .row { margin-left: auto; margin-right: auto; margin-bottom: 0px; } .content { min-height: 250px; padding: 0; margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px; } .section { padding: 0 !important; } .box { position: relative; border-radius: 3px; background: #ffffff; border-top: 3px solid #d2d6de; margin-bottom: 7px !important; width: 100%; box-shadow: 0 1px 1px rgba(0,0,0,0.1); } .nav-tabs-custom>.tab-content { background: #fff; padding: 0px !important; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .nav-tabs-custom { margin-bottom: 0px !important; background: #fff; box-shadow: 0 1px 1px rgba(0,0,0,0.1); border-radius: 3px; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2 class="breadcrumbs-title">Dashboard</h2> <hr> <div class="content-wrapper" style="padding-top:0px;"> <section class="content"> <div class="row"> <!--<div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-globe fa-fw"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/onsite_list">Service Center</a></span> <span class="info-box-number">10</span> </div> </div> </div>--> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-desktop"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/offsite_list" >Customer Site</a></span> <span class="info-box-number" > 9</span> </div> </div> </div> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-list-alt"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/amc_list">AMC List</a></span> <span class="info-box-number" > <?php foreach($amc_cnt As $amckey){ echo $amckey->site; }?></span> </div> </div> </div> <!--<div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-cog"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/stamping_list" >Stampings</a></span> <span class="info-box-number" >10</span> </div> </div> </div>--> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="fa fa-bell-o"></i></span> <div class="info-box-content"> <span class="info-box-text">Request Alert</span> <span class="info-box-number"><?php foreach($req_alert_cnt As $reqkey){ echo $reqkey->status; }?></span> </div> </div> </div> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-green"> <i class="fa fa-truck"></i> </span> <div class="info-box-content"> <span class="info-box-text">Ready For Delivery</span> <span class="info-box-number"><?php foreach($readyfordelivery_cnt As $readykey){ echo $readykey->status; }?></span> </div> </div> </div> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-yellow"><i class="fa fa-exclamation-triangle"></i></span> <div class="info-box-content"> <span class="info-box-text">Expiring Contracts</span> <?php error_reporting(0); /* $servername = "localhost"; $username = "sellejyp_serv"; $password = "<PASSWORD>"; $dbname = "sellejyp_serviceEff"; */ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "srs"; $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT count(ord.id) As expiring_cnt,cust.customer_name,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ser_loc.service_loc FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE (unix_timestamp(ordt.warranty_date) < unix_timestamp(CURDATE()) and ordt.warranty_date!='') or (unix_timestamp(ordt.prev_main) < unix_timestamp(CURDATE()) and ordt.prev_main!='')"); while($res = mysql_fetch_array($qry)) { ?> <span class="info-box-number"> <?php if($res['expiring_cnt']!=''){ echo $res['expiring_cnt']; } ?> </span> <?php }?> </div> </div> </div> </div> <div class="row"> <!-- Left col --> <section class="col-lg-9 connectedSortable"> <!-- Custom tabs (Charts with tabs)--> <div class="nav-tabs-custom"> <!-- Tabs within a box --> <div class="tab-content no-padding"> <!-- Morris chart - Sales --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Open Request</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse" ><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table class="table no-margin"> <thead> <tr> <th>Request ID</th> <th>Customer</th> <th>Model</th> <th>Service</th> <th>Fault</th> <th>Due Date</th> <th>Status</th> </tr> </thead> <tbody> <?php foreach($request_list As $request_key){?> <tr> <td><a href="<?php echo base_url(); ?>service/update_service_req/<?php echo $request_key->request_id; ?>"><?php echo $request_key->request_id; ?></a></td> <td><?php echo $request_key->customer_name; ?></td> <td><?php echo $request_key->model; ?></td> <td><?php echo $request_key->service_type; ?></td> <td><?php echo $request_key->prob_category; ?></td> <td><?php echo $request_key->delivery_date; ?></td> <td> <?php if($request_key->statusid == '1') { ?> <span class="label label-danger"><?php echo $request_key->status; ?></span> <?php } ?> <?php if($request_key->statusid == '3') { ?> <span class="label label-warning"><?php echo $request_key->status; ?></span> <?php } ?> <?php if($request_key->statusid == '4') { ?> <span class="label label-success"><?php echo $request_key->status; ?></span> <?php } ?> <?php if($request_key->statusid == '2' || $request_key->statusid == '5' || $request_key->statusid == '6' || $request_key->statusid == '7' || $request_key->statusid == '8') { ?> <span class="label label-success"><?php echo $request_key->status; ?></span> <?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div><!-- /.table-responsive --> </div><!-- /.box-body --> <div class="box-footer clearfix"> <a href="<?php echo base_url(); ?>pages/add_service_req" class="btn btn-sm btn-primary pull-left">New Request</a> <a href="<?php echo base_url(); ?>pages/service_req_list" class="btn btn-sm btn-primary pull-right">All Request</a> </div><!-- /.box-footer --> </div> </div> </div><!-- /.nav-tabs-custom --> <div class="tab-content no-padding col-md-8"> <!-- Morris chart - Sales --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Engineer Status</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table class="table no-margin"> <thead> <tr> <th>Engineer Name</th> <th>Total Open Request</th> <th style="width:15.2%">On Hold</th> <th>Awaiting Approval</th> <th>Awaitig Delivery</th> </tr> </thead> <tbody> <?php foreach($engineer_status As $engg_key){?> <tr> <td> <a href="<?php echo base_url(); ?>pages/engg_individual_list/<?php echo $engg_key->assign_to; ?>"><?php echo $engg_key->emp_name; ?></a> </td> <td> <a href="<?php echo base_url(); ?>pages/engg_individual_workinpro_list/<?php echo $engg_key->assign_to; ?>"><?php foreach($engineer_work_inpro as $workinprokey){ if($workinprokey->assign_to==$engg_key->assign_to){ echo $workinprokey->total_reqs;}} ?> </a> </td> <td> <a href="<?php echo base_url(); ?>pages/engg_individual_onhold_list/<?php echo $engg_key->assign_to; ?>"><?php foreach($engineer_on_hold as $holdkey){ if($holdkey->assign_to==$engg_key->assign_to){ echo $holdkey->total_reqs;} } ?> </a> </td> <td> <a href="<?php echo base_url(); ?>pages/engg_individual_awaiting_list/<?php echo $engg_key->assign_to; ?>"><?php foreach($engineer_quote_awaiting_approval as $awaitingkey){ if($awaitingkey->assign_to==$engg_key->assign_to){ echo $awaitingkey->total_reqs;} } ?> </a> </td> <td> <a href="<?php echo base_url(); ?>pages/engg_individual_ready_list/<?php echo $engg_key->assign_to; ?>"><?php foreach($engineer_ready_delivery as $readykey){ if($readykey->assign_to==$engg_key->assign_to){ echo $readykey->total_reqs;}} ?> </a> </td> </tr> <?php } ?> </tbody> </table> </div><!-- /.table-responsive --> </div><!-- /.box-body --> <div class="box-footer clearfix"> <a href="<?php echo base_url(); ?>pages/add_order" class="btn btn-sm btn-primary pull-left">New Order</a> <a href="<?php echo base_url(); ?>pages/order_list" class="btn btn-sm btn-primary pull-right">All Order</a> </div><!-- /.box-footer --> </div> </div> <div class="tab-content no-padding tableft col-md-4"> <div class="tab-content no-padding"> <!-- Morris chart - Sales --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Spare Stock</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table class="table no-margin"> <thead> <tr> <th>Spare Name</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> <tr> <td>Induction 2kg Filament</td> <td>1000</td> </tr> </tbody> </table> </div> </div> <div class="box-footer clearfix" style="padding: 7px;"> <a href="<?php echo base_url(); ?>pages/add_spare" class="btn btn-sm btn-primary pull-right">View All</a> </div> </div> </div> </div> </section> <section class="col-lg-3 connectedSortable"> <div class="tab-content no-padding"> <!-- Morris chart - Sales --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Area Wise Open Request</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table class="table no-margin"> <thead> <tr> <th>Area</th> <th>No Of Request</th> </tr> </thead> <tbody> <?php foreach($list As $key){?> <tr> <td> <a href="<?php echo base_url(); ?>pages/Areawise_list/<?php echo $key->id; ?>"><?php echo $key->service_loc; ?></a> </td> <td><?php echo $key->req_id; ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> <div class="box-footer clearfix"> <a href="" class="btn btn-sm btn-primary pull-right">View All</a> </div> </div> </div> <div class="tab-content no-padding"> <!-- Morris chart - Sales --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Minimum Spare Alerts</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table class="table no-margin"> <thead> <tr> <th style="width: 63.2%;">Spare Name</th> <th>Stock In hand</th> <th>Min Qty</th> </tr> </thead> <tbody> <?php foreach($spare_min_alerts As $spareminkey){?> <tr> <td><?php echo $spareminkey->spare_name; ?></td> <td><?php echo $spareminkey->spare_qty; ?></td> <td><?php echo $spareminkey->min_qty; ?></td> </tr> <?php } ?> <tr> <td>Induction 2 kg muz</td> <td>0</td> <td>0</td> </tr> <tr> <td>Turbo 3D Main Board</td> <td>0</td> <td>0</td> </tr> <!--<tr> <td>lock & key</td> <td>0</td> <td>0</td> </tr>--> </tbody> </table> </div> </div> <div class="box-footer clearfix"> <a href="<?php echo base_url(); ?>pages/min_spare_alerts" class="btn btn-primary btn-sm pull-right">View All</a> </div> </div> </div> </section> </div> </section> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/dash/app.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/dash/dashboard.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/models/Servicelocation_model.php <?php class Servicelocation_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_service_location($data){ $this->db->insert('service_location',$data); return $this->db->insert_id(); } public function checkzoonname($user) { $this->db->select('service_loc'); $this->db->from('service_location'); $this->db->where_in('service_loc',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function add_zone_pincode($data){ $this->db->insert_batch('zone_pincodes',$data); } public function add_zone_pincode1($data){ $this->db->insert('zone_pincodes',$data); } public function update_zone_pincodes($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('zone_pincodes', $data1, $where); $this->db->query($qry); } public function service_location_list(){ $this->db->select("id,serv_loc_code,service_loc,concharge",FALSE); $this->db->from('service_location'); $query = $this->db->get(); return $query->result(); } public function update_serv_loc($data,$id){ $this->db->where('id',$id); $this->db->update('service_location',$data); } public function del_serv_loc($id){ $this->db->where('id',$id); $this->db->delete('service_location'); } public function getserviceLocbyid($id){ $this->db->select("*",FALSE); $this->db->from('service_location'); $this->db->where('id', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getZonePincodebyid($id){ $this->db->select("*",FALSE); $this->db->from('zone_pincodes'); $this->db->where('zone_code', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function del_zone_pincode($id){ $this->db->where('id',$id); $this->db->delete('zone_pincodes'); } public function checkpin($idd,$zone) { $this->db->select('id'); $this->db->from('service_location'); $this->db->where('service_loc',$zone); $query=$this->db->get(); $res=$query->result(); $slocid=$res[0]->id; $this->db->where('pincode',$idd); $this->db->where('zone_code',$slocid); $this->db->from('zone_pincodes'); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $numrow = $query->num_rows(); } public function checkname($idd) { $this->db->from('service_location'); $this->db->where('service_loc',$idd); $query=$this->db->get(); return $numrow = $query->num_rows(); } public function checkcode($idd) { //echo $idd;exit; $this->db->from('service_location'); $this->db->where('serv_loc_code',$idd); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $numrow = $query->num_rows(); } }<file_sep>/application/models/Monthreport_model.php <?php class Monthreport_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } function getstampingmonth_report($from_date,$to_date) { $query=$this->db->query("select serdet.request_id,stamp.stamping_charge, stamp.agn_charge, stamp.penalty, stamp.conveyance,stamp.pending_amt, service.created_on, serdet.site , cust.customer_name , pro.model , stamp.cmr_paid , stat.status from stamping_details as stamp left join service_request_details as serdet on serdet.request_id=stamp.req_id left join service_request as service on service.id=serdet.request_id left join customers as cust on cust.id=service.cust_name left join products as pro on pro.id=serdet.model_id left join status as stat on stat.id=service.status where serdet.site='Stamping' AND service.created_on BETWEEN '$from_date' AND '$to_date 23:59:59.993' "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } } ?><file_sep>/application/views/user_cate_list.php <style> .ui-state-default { background:#6c477d; color:#fff; border: 3px solid #fff !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } /*select { position: relative; margin: -5px 6px; }*/ #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=text]{ background-color: transparent; border:none; border-radius: 7; width: 55% !important; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .h1, .h2, .h3, h1, h2, h3 { margin-top: 20px; margin-bottom: 0px; } hr { margin-top: 0px; } a{ color: #522276; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } body{ background-color: #fff;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); acc_name = $("#acc_name_"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/update_accessories', data: {'id' : id, 'acc_name' : acc_name}, dataType: "text", cache:false, success: function(data){ alert("Accessories updated"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>customer/del_cust_type', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/cust_type_list"; alert("Customer Type deleted"); } } }); }); } function InactiveStatus(id){ //alert(id); //$(function() //{ $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Users/update_status', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("User made Inactive"); window.location = "<?php echo base_url(); ?>pages/user_cate_list"; } }); //}); } function activeStatus(id){ //alert(id); //$(function() // { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Users/update_status1', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("User made Active"); window.location = "<?php echo base_url(); ?>pages/user_cate_list"; } }); //}); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Users List</h2> <a href="<?php echo base_url(); ?>pages/add_user_cate" style="position: relative; bottom: 27px; left: 88%;"><i class="fa fa-plus-square" aria-hidden="true" title="Add New User"></i></a> <hr> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr> <th class="hidden">Id</th> <th>S.No.</th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Name</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>User Name</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>User Type</b></th> <!--<th style="text-align:center;font-size:13px;color:##303f9f;"><b>User Access</b></th>--> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Action</b></th> </tr> </thead> <tbody> <?php $i=1;foreach($get_users As $user_key){ /* if(isset($user_key->categories_assigned)){ $categories_assigned = explode(",",$user_key->categories_assigned); } */ ?> <tr> <td class="hidden"><?php echo $user_key->id;?></td> <td><?php echo $i;?></td> <td><?php echo $user_key->name; ?></td> <td><?php echo $user_key->user_name; ?></td> <td><?php if(isset($user_key->user_type) && $user_key->user_type=='1'){echo "Administrator"; } if(isset($user_key->user_type) && $user_key->user_type=='2'){echo "Service Co-ordinator"; }if(isset($user_key->user_type) && $user_key->user_type=='3'){echo "Accounts"; } if(isset($user_key->user_type) && $user_key->user_type=='4'){echo "Spares"; } if(isset($user_key->user_type) && $user_key->user_type=='5'){echo "Sales"; }if(isset($user_key->user_type) && $user_key->user_type=='6'){echo "Stamping"; }if(isset($user_key->user_type) && $user_key->user_type=='7'){echo "Engineer"; }?></td> <!-- <td><?php if($user_key->user_access=="stamping_user"){ echo "Stamping";} if($user_key->user_access=="nonstamping_user"){ echo "Non - Stamping";} ?></td>--> <td class="options-width" style="text-align:center;"> <a href="#" style="padding-right:10px;" onclick='brinfo(<?php echo $user_key->id; ?>)' ><i class="fa fa-pencil-square-o"></i></a> <?php if($user_key->status!='1') { ?> <a href="#" onclick="InactiveStatus('<?php echo $user_key->id; ?>')" >Inactive</a><?php } ?><?php if($user_key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $user_key->id; ?>')" >Active</a><?php } ?> </td> </tr> <?php $i++;} ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>Users/edit_user_cate/'+id, type : 'iframe', padding : 5, afterClose: function () { // USE THIS IT IS YOUR ANSWER THE KEY WORD IS "afterClose" parent.location.reload(true); alert('User Update Successfully!!!'); } }); } </script> </body> </html><file_sep>/application/views/add_service_loc.php <head> <style> .delRowBtn{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } body{background-color:#fff;} .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { border: 1px solid #522276; text-align: center; } .tableadd1 tr { height: 40px; } .tableadd1 tr:first-child { height: 40px; background: rgb(112, 66, 139) none repeat scroll 0% 0%; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:#fff; font-weight:bold; } .tableadd1 tr td.plus { padding-top: 14px; } .tableadd1 tr td.plus input { width:70px; border:1px solid #522276; } .tableadd1 tr td input { height: 25px; border-radius: 5px; padding-left: 10px; margin-bottom: 0px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 0px 4px 4px 4px; height: 30px; border-radius: 5px; color: #70428b; } #addtable { margin-top:20px; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:black; } .tableadd tr td input { width: 210px; border-radius: 5px; padding-left: 10px; } .tableadd1 tr td input { width: 210px; border-radius: 5px; padding-left: 10px; } #errorBox1,#zonecode_error{ color:#F00; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } .btn{text-transform:none !important;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Servicelocation/addrow2", data: datastring, cache: false, success: function(result) { //alert(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('minus-0').value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus-0').value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); function UpdateStatus1(id){ //alert(id);alert($("#enggdate_"+id).val()); var eng_name = $("#eng_name-"+id).val(); var eng_spare_name = $("#eng_spare_name-"+id).val(); var engg_date = $("#enggdate_"+id).val(); if(eng_name==""){ alert("Enter the Engineer Name"); }else if(eng_spare_name==""){ alert("Enter the Spare Name"); }else if(engg_date==""){ alert("Enter the Date"); }else{ var plus = $("#plus-"+id).val(); var minus = $("#minus-"+id).val(); //alert(engg_date); var engg_reason = $("#engg_reason-"+id).val(); var spare_qty = $("#spare_qty-"+id).val(); var used_spare = $("#used_spare-"+id).val(); var eng_spare = $("#eng_spare-"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/add_spare_engg', data: {'eng_name' : eng_name, 'eng_spare_name' : eng_spare_name, 'plus' : plus, 'minus' : minus, 'engg_date' : engg_date, 'engg_reason' : engg_reason, 'spare_qty' : spare_qty, 'used_spare' : used_spare, 'eng_spare' : eng_spare}, dataType: "text", cache:false, success: function(data){ alert("Spares For Engineers Added"); } }); }); } } </script> <!--<script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var serv_loc_code = document.frmZone.serv_loc_code.value; var serv_loc_name = document.frmZone.serv_loc_name.value; var serv_loc_area = document.frmZone.area_name.value; var serv_loc_pincode = document.frmZone.pincode.value; alert(serv_loc_area); if( serv_loc_code == "" ) { //alert("Hi"); document.frmZone.serv_loc_code.focus() ; document.getElementById("zonecode_error").innerHTML = "Enter the Zone Code"; return false; } if( serv_loc_name == "" ) { document.frmZone.serv_loc_name.focus() ; document.getElementById("errorBox1").innerHTML = "Enter the Zone Name"; return false; } if( serv_loc_area == "") { document.frmZone.area_name.focus() ; document.getElementById("errorBox2").innerHTML = "Enter the Area Name"; return false; } if( serv_loc_pincode == "") { document.frmZone.pincode.focus() ; document.getElementById("errorBox3").innerHTML = "Enter the Pincode Name"; return false; } } </script>--> <script> $(function(){ $('input:text[id="area_name-0"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z0-9]/g,'') ); }); $('input:text[id="zonename"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('input:text[id="conveyance"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $( "form" ).submit(function( event ) { if ( $( "#zonename" ).val() === "" ) { $( "#errorBox1" ).text( "Enter the Zone Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#zonecode" ).val() === "" ) { $( "#zonecode_error" ).text( "Enter the Zone Code" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#area_name-0" ).val() === "" ) { $( "#errorBox2" ).text( "Enter the Area Name" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ( $( "#pincode-0_0" ).val() === "" ) { $( "#errorBox3" ).text( "Enter the Pincode" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(function() { $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!--<script> $(document).ready(function(){alert('sdaks'); //$("#UserName<?php echo $count; ?>").keyup(function(){ $(document).on("keyup","#zonecode", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var name=$('#zonecode').val(); //alert(name); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Servicelocation/checkcode', data: { p_id:name, }, success: function (data) { //alert(data); if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Zone Code Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '12px'}); $('#zonecode').val(''); return false; } } }); } }); </script>--> <script> $(document).ready(function(){ //$('#prob_cat_name').change(function(){ //alert("check"); $(document).on("keyup","#zonename", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var name=$("#zonename").val(); //alert(name); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Servicelocation/checkname', data: { p_id:name, }, success: function (data) { //alert(data); if(data == 0){ $('#lname2').html(''); } else{ $('#lname2').html('Zone Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); $('#zonename').val(''); return false; } } }); } }); </script> <script> $(document).ready(function(){//alert('jsjdf'); //$('#prob_cat_name').change(function(){ //alert("check"); $(document).on("change","#zonecode", function(){//alert('fsdakf'); var timerr; clearTimeout(timerr); timerr = setTimeout(mobilee, 3000); }); //alert(brand); function mobilee(){ var namee=$("#zonecode").val(); //alert(namee); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Servicelocation/checkcode', data: { p_id:namee, }, success: function (data) { alert(data); if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Zone Code Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); $('#zonecode').val(''); return false; } } }); } }); </script> <script> $(document).ready(function(){ $('#zonename').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z ]/g,'') ); }); $('#conveyance').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9 ]/g,'') ); }); $('#pincode-0_0').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9 ]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $("#zonename").keyup(function(){ if($(this).val()==""){ $("#errorBox1").show(); } else{ $("#errorBox1").hide(); } }); $("#zonecode").keyup(function(){ if($(this).val()==""){ $("#zonecode_error").show(); } else{ $("#zonecode_error").hide(); } }); $("#area_name-0").keyup(function(){ if($(this).val()==""){ $("#errorBox2").show(); } else{ $("#errorBox2").hide(); } }); $("#pincode-0_0").keyup(function(){ if($(this).val()==""){ $("#errorBox3").show(); } else{ $("#errorBox3").hide(); } }); }); </script> <!--<script> $(document).ready(function(){ $('.pincode').change(function(){ var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('_'); var vl = arr['1']; var pin=$('#pincode-0_'+vl).val(); var zone=$('#zonename').val(); var datastring='id='+pin+'&zone='+zone; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Servicelocation/checkpin", data: datastring, cache: false, success: function(result) { if(result!='0') { alert('Already Exists'); } } }); }); }); </script>--> <script> $(function(){ $('.pincode').change(function(){ //alert('sdalkjfl'); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('_'); var vl = arr['1']; var pin=$('#pincode-0_'+vl).val(); var i; for(i=0;i<=vl;i++){ if(vl!=i){ var check=$('#pincode-0_'+i).val(); if(pin==check){ $('#pincode-0_'+vl).val(''); alert('Already Exists'); } } } }); }); </script> </head> <section id="content"> <div class="container"> <div class="section"> <h2>Add Service Zone</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <form name="frmZone" action="<?php echo base_url(); ?>Servicelocation/add_service_location" method="post" onsubmit="return frmValidate()"> <div id="errorBox"></div> <div class="col-md-1"> </div> <div class="col-md-10"> <div class="col-md-12 tableadd" id="addtable"> <div class="col-md-3"> <label>Zone Code&nbsp;<span style="color:red;">*</span></label> <input type="text" name="serv_loc_code" class="corporate" id="zonecode" maxlength="2"> <span id="zonecode_error"></span> <div id='lname1'></div> </div> <div class="col-md-3"> <label>Zone Name&nbsp;<span style="color:red;">*</span></label> <input type="text" name="serv_loc_name" class="corporate" id="zonename" maxlength="50"> <div id="errorBox1"></div> <div id='lname2'></div> </div> <div class="col-md-3"> <label>Conveyance charge</label> <input type="text" name="concharge" class="corporate" id="conveyance" maxlength="6"> </div> <div class="col-md-3"> <label>Zone Coverage</label> <select name="zone_coverage"> <option value="">---Select---</option> <option value="on_site">Onsite</option> <option value="outstation">Out Station</option> </select> </div> </div> <div style="margin: 10px 15px;" class="col-md-12"> <table id="table1" class="tableadd1" style="width:70%;"> <tr> <td><label>Area&nbsp;<span style="color:red;">*</span></label></td> <td><label>Pincode&nbsp;<span style="color:red;">*</span></label></td><!--<td><label>Action</label></td>--> </tr> <tr> <td style="padding:10px 0;"><input type="text" name="area_name[]" id="area_name-0"><div id="errorBox2"></div></td> <td style="padding:10px 0;"><input type="text" name="pincode[]" id="pincode-0_0" maxlength="6" class='pincode'><div id="errorBox3"></div></td> <td style="border:none;"><a id="addMoreRows" class="btn cyan rowadd"><i class="fa fa-plus-square" aria-hidden="true"></i></a></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(0)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0" > </div> <div class="col-md-12"> <div class="col-md-2"> <button class="btn cyan waves-effect waves-light" type="submit" name="action">Submit</button> </div> </div> </div> <div class="col-md-1"> </div> </form> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <script> $(document).ready(function(){ $('input:text[id="zonecode"]').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^a-zA-z0-9]/g,'') ); }); $('input:text[id="zonecode"]').change(function(){ if($(this).val().length <2){ alert("Zone code must have 2 digits"); $( "#zonecode" ).val(''); $(this).focus(); return false; } }); }); </script> <script> $(function(){ $('input[name^="pincode"]').change(function() { var $current = $(this); $('input[name^="pincode"]').each(function() { if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id')) { $( "#errorBox3" ).text( "Already Exists" ).show().css({'color':'#ff0000','font-size':'10px'}); } }); }); }); </script> </body> </html><file_sep>/application/views/add_prod.php <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"> <style> hr { border-style: solid; border-width: 1px; color: #303F9F; } body{background-color:#fff;} #errorBox { color:#F00; } .tableadd1 select { border: 1px solid #000; background-image:none; border-radius: 5px; width: 100%; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .limitedNumbChosen { width: 100%; } .chosen-container { width: 100% !important; } .chosen-container-multi .chosen-choices { border: 1px solid #ccc; } textarea.materialize-textarea { overflow: auto; padding: 3px; resize: none; min-height: 10rem; } .chosen-container-multi .chosen-choices li.search-field input[type=text] { color: #333; } select { border: 1px solid #ccc !important; } .star{ color:#ff0000; font-size:15px; } .btn{text-transform:none !important;} </style> <script> $(function(){ $("button").click(function(event){ //alert("clcl"); if($("#product_name").val()==""){ $("#proderror").text("Enter the Product Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } if($("#category").val()==""){ $("#caterror").text("Please select the Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#subcategory").val()==""){ $("#subcaterror").text("Please select the Sub-Category").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#brand").val()==""){ $("#branderror").text("Please select the Brand Name").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } if($("#model").val()==""){ $("#modelerror").text("Enter the product Name").show().css({ 'font-size':'12px', 'color':'#ff0000', 'position':'relative', 'bottom':'10px' }); event.preventDefault(); } /*if($(".limitedNumbChosen").find("option:selected").length < 1){ $("#infoerror").text("Please select the Addtional Information").show().css({ 'font-size':'12px', 'color':'#ff0000' }); }*/ }); $("#product_name").keyup(function(){ if($(this).val()==""){ $("#proderror").show(); } else{ $("#proderror").fadeOut('slow'); } }); $("#category").change(function(){ if($(this).val()==""){ $("#caterror").show(); } else{ $("#caterror").fadeOut('slow'); } }); $("#subcategory").change(function(){ if($(this).val()==""){ $("#subcaterror").show(); } else{ $("#subcaterror").fadeOut('slow'); } }); $("#brand").change(function(){ if($(this).val()==""){ $("#branderror").show(); } else{ $("#branderror").fadeOut('slow'); } }); $("#model").keyup(function(){ if($(this).val()==""){ $("#modelerror").show(); } else{ $("#modelerror").fadeOut('slow'); } }); $(".limitedNumbChosen").change(function(){ if($(this).val()==""){ $("#infoerror").show(); } else{ $("#infoerror").fadeOut('slow'); } }); }); /*function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var product_name = document.frmProd.product_name.value, category = document.frmProd.category.value, subcategory = document.frmProd.subcategory.value, brand = document.frmProd.brand.value, model = document.frmProd.model.value; if( product_name == "" ) { document.frmProd.product_name.focus() ; document.getElementById("proderror").innerHTML = "Please Enter the Product Name"; return false; } if( category == "" ) { document.frmProd.category.focus() ; document.getElementById("caterror").innerHTML = "Please select the Category Name"; return false; } if( subcategory == "" ) { document.frmProd.subcategory.focus() ; document.getElementById("subcaterror").innerHTML = "Please select the Sub-Category Name"; return false; } if( brand == "" ) { document.frmProd.brand.focus() ; document.getElementById("branderror").innerHTML = "Please select the Brand Name"; return false; } if( model == "" ) { document.frmProd.model.focus() ; document.getElementById("modelerror").innerHTML = "Please Enter the Model"; return false; } }*/ </script> <script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> /* $(document).ready(function() { $("#subcategory").change(function() { $("#brand > option").remove(); var subcatid=$(this).val(); categoryid = $("#category").val(); //alert("Subcat: "+id+"Cat:" +category); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/get_brand", data: dataString, cache: false, success: function(data) { $('#brand').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data); $('#brand').append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); }); */ </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Product Details</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>product/add_product" method="post" name="frmProd"> <!-- onsubmit="return frmValidate()" --> <div id="errorBox"></div> <div class="col-md-12 tableadd1"> <!--<tr> <td><label>Serial No</label></td><td><input type="text" name="serial_no" id="serial_no" class=""></td> </tr>--> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Product Name <span class="star">*</span></label> <input type="text" name="model" id="model" class="prod-model" maxlength="80"> <div id="modelerror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category <span class="star">*</span></label> <select name="category" id="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ ?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } ?> </select> <div id="caterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category <span class="star">*</span></label> <select name="subcategory" id="subcategory"> <option value="">---Select---</option> </select> <div id="subcaterror"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Stock</label> <input type="text" name="stock_qty" id="stock_qty" class="prod-name" maxlength="80"> </div> </div> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Description</label> <textarea type="text" name="description" id="description" class="materialize-textarea" maxlength="150"></textarea> </div> </div> <div class="col-md-12 tableadd1"> <!--<div> <td><input type="checkbox" class="" name="addlinfo[]" value="charger"></td><td><input type="checkbox" class="" name="addlinfo[]" value="DataCable"></td><td><input type="checkbox" class="" name="addlinfo[]" value="Battery"></td><td><input type="checkbox" class="" name="addlinfo[]" value="Headset"></td><td><input type="checkbox" class="" name="addlinfo[]" value="Cover"></td> </div>--> <div class="col-md-12 col-sm-12 col-xs-12"> <button class="btn cyan waves-effect waves-light " type="submit" >Submit</button> </div> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!--<script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> <script> $(document).ready(function(){ //Chosen $(".limitedNumbChosen").chosen({ placeholder_text_multiple: "---Select---" }) .bind("chosen:maxselected", function (){ window.alert("You reached your limited number of selections which is 2 selections!"); }); $(".prod-name").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9. ]/g,'') ); }); $(".prod-model").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9-.\/+*() ]/g,'') ); }); $("textarea").removeClass("materialize-textarea"); $("textarea").css({ 'height':'100px', 'overflow-y':'auto', 'overflow-x':'hidden' }) }); </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/edit_prod_sub_cat.php <style> .tableadd input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 3px; /* padding-left: 10px; */ margin-left: 13px; } .tableadd input { height: 21px !important; margin-top: 11px; margin-right: -242px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width:103%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; } .star{ color:#ff0000; font-size:12px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2rem; width: 103%; font-size: 12px; margin: 0 0 0px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .btn{text-transform:none !important;} </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Sub-Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>subcategory/edit_sub_category" method="post"> <table id="myTable" class="tableadd"> <?php foreach($list as $key){ ?> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category Name <span class="star">*</span></label> <select id="pro_cat" name="pro_cat" class="prodcat" > <option value="">---Select---</option> <?php foreach($droplists as $dkey){ if($dkey->id==$key->pro_catid){ ?> <option selected="selected" value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } } ?> </select> <div class="form-group"> <div class="prodcaterror"></div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category Name <span class="star">*</span></label> <input type="text" name="sub_catname" class="model subcat" value="<?php echo $key->subcat_name; ?>" maxlength="50" id="sub_category-1"><input type="hidden" name="subcatid" class="model" value="<?php echo $key->prosubcat_id; ?>"> <div class="form-group"> <div class="subcaterror"></div> </div> </div> <!--<tr><td><label>Category Name</label></td><td><label>Sub-Category Name</label></td></tr> <tr> <td> <select id= "pro_cat" name="pro_cat"> <option value="">---Select---</option> <?php foreach($droplists as $dkey){ if($dkey->id==$key->pro_catid){ ?> <option selected="selected" value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } } ?> </select> </td> <td><input type="text" name="sub_catname" class="model" value="<?php echo $key->subcat_name; ?>"><input type="hidden" name="subcatid" class="model" value="<?php echo $key->prosubcat_id; ?>"></td> </tr>--> <?php } ?> </table> <button class="btn cyan waves-effect waves-light editcategory" type="submit" name="action" style="margin-left:20px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function(){ $(".editcategory").click(function(event){ if($("#pro_cat").val()=="") { $(".prodcaterror").text("Select Category Name").show().css({ 'color':'#ff0000','font-size':'10px' }); event.preventDefault(); } if($(".subcat").val()=="") { $(".subcaterror").text("Enter Sub-Category Name").show().css({ 'color':'#ff0000','font-size':'10px' }); event.preventDefault(); } }); $("#pro_cat").change(function(){ if($(this).val()=="") { $(".prodcaterror").show(); } else{ $(".prodcaterror").hide(); } }); $(".subcat").keyup(function(){ if($(this).val()=="") { $(".subcaterror").show(); } else{ $(".subcaterror").hide(); } }); $(".subcat").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9- ]/g,"")); }); }); </script> <!-- <script> $(document).ready(function(){ $(".subcat").keyup(function(){ if($(this).val()==""){ $(".subcaterror").show(); } else{ $(".subcaterror").hide(); } }); $(".pno").keyup(function(){ if($(this).val()==""){ $("#errorBox1").show(); } else{ $("#errorBox1").hide(); } }); }); </script>--> <script> $(document).ready(function(){ //alert("hiii"); $('#sub_category-1').change(function(){ var category=$("#pro_cat").val(); var sub_category=$(this).val(); var datastring='category='+category+'&sub_category='+sub_category; //alert(datastring); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>subcategory/subcategory_validation', data: datastring, success: function(data) { //alert(data); if(data == 0){ $('.subcaterror').html(''); } else{ $('.subcaterror').html('Sub-Category Name Already Exist').show().css({'color':'#ff0000','font-size':'10px'}); $('#sub_category-1').val(''); return false; } } }); }); }); </script> </body> </html><file_sep>/application/views/add_user_cate.php <style> .box { position: relative; border-radius: 3px; background: #ffffff; border-top:1px solid #ccc !important; margin-bottom: 9px; width: 100%; box-shadow: 0 1px 1px rgba(0,0,0,0.1); } select { border: 1px solid #ccc; margin: 0 0 15px 0; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .btn{text-transform:none !important;} </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <style> body{background-color:#fff;} select[multiple] { height: 200px !important; } #errorBox{ color:#F00; font-size:12px; } </style> <!--<script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var first_name = document.frmUsers.first_name.value, user_name = document.frmUsers.user_name.value, pass = document.frmUsers.pass.value, user_type = document.frmUsers.user_type.value; //branch_name = document.frmCust.branch_name.value if( first_name == "" ) { document.frmUsers.first_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the name"; return false; } if( user_name == "" ) { document.frmUsers.user_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the user name"; return false; } if( pass == "" ) { document.frmUsers.pass.focus() ; document.getElementById("errorBox").innerHTML = "enter the password"; return false; } if( user_type == "" ) { document.frmUsers.user_type.focus() ; document.getElementById("errorBox").innerHTML = "enter the user type"; return false; } } </script>--> <script> $(function(){ $( "form" ).submit(function( event ) { if ( $( "#text-input" ).val() === "" ) { $( "#first_name_error" ).text( "Enter the Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( ".user_name" ).val() === "" ) { $( "#user_name_error" ).text( "Enter the User Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( ".pass" ).val() === "" ) { $( "#pass_error" ).text( "Enter the Password" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( ".cpass" ).val() === "" ) { $( "#cpass_error" ).text( "Enter the Confirm Password" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#user_type" ).val() === "" ) { $( "#user_type_error" ).text( "Please select the User Type" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( ".cpass" ).val() === $( ".pass" ).val() ) { return true; //$( "#cpass_error" ).text( "" ).show(); //event.preventDefault(); }else{ $( "#cpass_error" ).text( "Confirm Password does not match with the Password" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('.cpass').val(''); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#text-input").keyup(function(){ if($(this).val()==""){ $("#first_name_error").show(); } else{ $("#first_name_error").hide(); } }); $(".user_name").keyup(function(){ if($(this).val()==""){ $("#user_name_error").show(); } else{ $("#user_name_error").hide(); } }); $(".pass").keyup(function(){ if($(this).val()==""){ $("#pass_error").show(); } else{ $("#pass_error").hide(); } }); $(".cpass").keyup(function(){ if($(this).val()==""){ $("#cpass_error").show(); } else{ $("#cpass_error").hide(); } }); $("#user_type").change(function(){ if($(this).val()==""){ $("#user_type_error").show(); } else{ $("#user_type_error").hide(); } }); }); </script> <script type="text/javascript"> //var $= jQuery.noConflict(); $(document).ready(function() { $("#user_type").change(function() { var id=$(this).val(); if(id=='7'){ //alert("sdsadsdsd"); $("#engg_name > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Users/get_employees", data: dataString, cache: false, success: function(data) { $('#engg_name').append("<option value='0'>---Select---</option>"); $.each(data, function(index, data){//alert(data.branch_name); $('#engg_name').append("<option value='"+data.id+"'>"+data.emp_name+"</option>"); }); } }); } else{ $("#engg_name > option").remove(); $('#engg_name').append("<option value='0'>---Select---</option>"); } }); }); </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>New Users</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <form action="<?php echo base_url(); ?>Users/add_users" method="post" onsubmit="return frmValidate()" autocomplete="off" name="frmUsers"> <div id="errorBox"></div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>Name&nbsp;<span style="color:red;">*</span></label> <input type="text" class="first_name" id="text-input" name="first_name"> <div id="first_name_error" style="color:red; font-size:11px;"></div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>User Name&nbsp;<span style="color:red;">*</span></label> <input type="text" class="form-control user_name" id="text-input" name="user_name"> <div id="user_name_error" style="color:red; font-size:11px;"></div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>Password&nbsp;<span style="color:red;">*</span></label> <input type="<PASSWORD>" class="form-control pass" id="text-input" name="pass"> <div id="pass_error" style="color:red; font-size:11px;"></div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>Confirm Password&nbsp;<span style="color:red;">*</span></label> <input type="<PASSWORD>" class="form-control cpass" id="text-input" name="cpass"> <div id="cpass_error" style="color:red; font-size:11px;"></div> </div> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label >User Type&nbsp;<span style="color:red;">*</span></label> <select name="user_type" id="user_type" class="user_type_list"> <option value="">---Select---</option> <option value="1">Administrator</option> <option value="2">Service Co-ordinator</option> <option value="3">Accounts</option> <option value="4">Spares</option> <option value="5">Sales</option> <option value="6">Stamping</option> <option value="7">Engineers</option> </select> <div id="user_type_error" style="color:red; font-size:11px;"></div> </div> </div> <!--<div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>User Access</label> <select name="user_access" id="user_access" class="user_type_list"> <option value="">---Select---</option> <option value="stamping_user">Stamping</option> <option value="nonstamping_user">Non-Stamping</option> <!--<option value="3">Engineers</option> </select> </div> </div>--> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label>Engineers</label> <select name="engg_name" id="engg_name"> <option value="0">---Select---</option> </select> </div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <button style="margin-left: 6%;margin-top: 5%;"class="btn cyan waves-effect waves-light " type="submit" name="action">Submit</button> </div></div> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).on("keyup",".user_name", function(){ var timer; clearTimeout(timer); timer = setTimeout(user, 3000); }); //alert(brand); function user(){ var id=$(".user_name").val(); var datastring = 'id='+id; //alert(datastring); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Users/checkname", data: datastring, cache: false, success: function(data) { //alert(data); if(data == 0){ $('#user_name_error').html(''); } else{ $('#user_name_error').html('User Name Already Exist!').show(); $('.user_name').val(''); return false; } } }); } }); </script> <script type="text/javascript"> $(document).ready(function() { $('#add').click(function() { $('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { $('#select2 option:selected').remove().appendTo('#select1'); }); }); </script> </body> </html><file_sep>/application/views/add_quick.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td> <select> <option>Motorola</option> <option><NAME></option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td><td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(document).ready(function(){ $('#billingtoo').click(function(){//alert("haiiii"); //$addr = $('#address').val(); var id = $(this).val(); //alert(id); //var stateid = $('#state').val(); $('#re_address').val($('#address').val()); $('#re_address1').val($('#address1').val()); $('#re_city').val($('#search-box').val()); //$('#re_state').val($('#state').val()); $('#re-pincode').val($('#pincode').val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_state", data:'stateid='+$('#state').val(), success: function(data) { $.each(data, function(index, data){//alert(data.branch_name); $('#re_state').val(data.state); }); } }); }); }); </script> <script type='text/javascript'>//<![CDATA[ function FillBilling(f) { if(f.billingtoo.checked == true) { alert(f.search-box.value); f.re_address.value = f.address.value; f.re_address1.value = f.address1.value; f.re_city.value = f.search-box.value; f.re_state.value = f.state.value; f.re_pincode.value = f.pincode.value; } } </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var customer_id = document.frmCust.customer_id.value, customer_name = document.frmCust.customer_name.value, cust_type = document.frmCust.cust_type.value, service_zone = document.frmCust.service_zone.value, pincode = document.frmCust.pincode.value, land_ln = document.frmCust.land_ln.value, mobile = document.frmCust.mobile.value; //email = document.frmCust.email.value; /*if( customer_id == "" ) { document.frmCust.customer_id.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer id."; return false; } if( customer_name == "" ) { document.frmCust.customer_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer name"; return false; } if( pincode == "" ) { document.frmCust.pincode.focus() ; document.getElementById("errorBox").innerHTML = "enter the pincode"; return false; } if( cust_type == "" ) { document.frmCust.cust_type.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer type"; return false; } if( service_zone == "" ) { document.frmCust.service_zone.focus() ; document.getElementById("errorBox").innerHTML = "enter the service zone"; return false; } if( mobile == "" && land_ln == "") { document.frmCust.mobile.focus() ; document.getElementById("errorBox").innerHTML = "enter the mobile / landline"; return false; }*/ /* if( email == "" ) { document.frmCust.email.focus() ; document.getElementById("errorBox").innerHTML = "enter the email"; return false; } */ if(service_zone != "") { //alert("Hi1"); var mob = $('#mobile').val(); var customer_name = $('#customer_name').val(); var cust_idd = $('#cust_idd').val(); var cust_idd = $('#cust_idd').val(); var email = $('#email').val(); var cust_loc = $('#cust_loc').val(); var address = $('#address').val(); var address1 = $('#address1').val(); var pincode=$('#pincode').val(); var area_name=$('#area_name').val(); var service_zone=$('#service_zone').val(); var service_loc=$('#service_loc_coverage').val(); var type='<?php echo $type; ?>'; if(type=='service'){ parent.setSelectedUser(mob,customer_name,cust_idd,email,cust_loc,address,address1); }else{ //alert('hii s'); parent.setSelectedUser1(mob,customer_name,cust_idd,email,cust_loc,address,address1,pincode,area_name,service_zone,service_loc); } //parent.$.fancybox.close(); } } </script> <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-right:20px; } .link:hover { color:black; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } </style> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} .dropdown-content { display: none; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 230px; margin: auto auto 35px; } .tableadd tr td select { border: 1px solid #808080; height: 27px; width: 210px; } .tableadd tr td input { width: 120px; border: 1px solid #808080; height: 27px; } .tableadd tr td { padding:10px 10px 10px 0px; } .rowadd { border: 1px solid #8868a0 !important; background: #8868a0 none repeat scroll 0% 0% !important; padding: 6px; border-radius: 5px; color: #FFF; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } .box{ display: none; box-shadow:none !important; } .del { display:block; } .rowadd{ cursor:pointer; } </style> <script> $(document).ready(function(){ $('.del').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); }); $('.ready').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkland_ln", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Add Customer Details</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/add_customer_quick" method="post" name="frmCust" onsubmit="return frmValidate()" autocomplete="off"> <div id="errorBox"></div> <table class="tableadd"> <tr> <td><label>Type Of Customer<span style="color:red;">*</span></label></td> <td> <select name="cust_type" id="cust_type"> <option value="">---Select---</option> <?php foreach($customer_type as $custtypekey){ ?> <option value="<?php echo $custtypekey->id.'-'.$custtypekey->type; ?>"><?php echo $custtypekey->type; ?></option> <?php } ?> </select> <div id="type_error" style="color:red;"></div> </td> <td><label>Customer ID<span style="color:red;">*</span></label></td><td><input type="text" name="customer_id" id="customer_id" class="customer"value="<?php echo $cnt; ?>" readonly><input type="hidden" name="cust_idd" id="cust_idd" class="customer"value="<?php echo $cnt; ?>" readonly><input type="hidden" name="cust_loc" id="cust_loc" class="customer" value="<?php echo $cust_loc_cnt; ?>" readonly> <div id="cid_error" style="color:red;"></div></td> </tr> <tr> <td><label>Customer Name<span style="color:red;">*</span></label></td><td><input type="text" name="customer_name" id="customer_name" class="" autocomplete="off" ><div id="name_error" style="color:red;"></div></td> <td><label>Pincode<span style="color:red;">*</span></label></td><td><input type="text" name="pincode" id="pincode" class="pincode"> <div id="pincode_error" style="color:red;"></div></td> </tr> <tr> <td><label>Area</label></td><td><input type="text" name="area_name" class="" id="area_name"><input type="hidden" name="area_id" class="" id="area_id"></td> <td><label>Service Zone<span style="color:red;">*</span></label></td> <td> <select name="service_zone" id="service_zone"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ ?> <option value="<?php echo $zonekey->id.'-'.$zonekey->serv_loc_code.'-'.$zonekey->zone_coverage; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } ?> </select> <div id="zone_error" style="color:red;"></div> </td> <input type="hidden" name="service_loc_coverage" id="service_loc_coverage" class="contact_name"> <!--<td><label>Mobile No<span style="color:red;">*</span></label></td><td><input type="text" name="mobile" id="mobile" class="mobile"></td>--> </tr> <tr> <td ><label class="del box">Mobile No<span style="color:red;">*</span></label> <label class="ready box">Landline No<span style="color:red;">*</span></label> </td> <td ><input type="text" name="mobile" id="mobile" class="del box"> <input type="text" name="land_ln" id="land_ln" class="ready box"> <div id="number_error" style="color:red;"></div></td> <td><label>Email Id</label></td><td><input type="text" name="email" id="email" class="email"></td> </tr> <tr> <td><label>Address</label></td><td><input type="text" name="address" id="address" class="adress"></td> <td><label>Address 1</label></td><td><input type="text" name="address1" id="address1" class="adress1"></td> </tr> </table> <button class="btn cyan waves-effect waves-light rowadd" type="submit" >Add Customer <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $('#pincode').change(function() { var id=$(this).val(); //alert(id); $("#service_zone > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#service_zone').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ if(data.service_loc.length > 0){ $('#service_zone').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#area_name').val(data.area_name); $('#area_id').val(data.area_id); }); } }); }); }); </script> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#mobiles').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $(document).ready(function(){ $('#cust_type').change(function(){ //alert("hii"); var cust_type_id = $(this).val(); var land = cust_type_id.split('-'); var id = land['0']; var corp = land['1']; //alert(id+"_"+corp); if(corp=='CORPORATE' || corp=='corporate' || corp=='Corporate' || corp=='corporate'){ $(".box").not(".ready").hide(); $(".ready").show(); }else{ $(".box").not(".del").hide(); $(".del").show(); } var cust_id = $('#customer_id').val(); if(cust_id.length == '5'){ var customerid = id+cust_id; $('#customer_id').val(customerid); }else{ var cust_id2 = cust_id.substring(2, cust_id.length); var customerid = id+cust_id2; $('#customer_id').val(customerid); //var zoneid = cust_id1+zone_id; //$('#customer_id').val(zoneid); } }); $('#service_zone').change(function(){ if(document.getElementById('cust_type').selectedIndex == 0){ alert("Kindly Select Customer Type first"); }else{ var z_id = $(this).val(); var arr = z_id.split('-'); var zone_id = arr['1']; var zone_coverage = arr['2']; $('#service_loc_coverage').val(zone_coverage); //alert(zone_id); var cust_type_id = $('#customer_id').val(); //alert(cust_type_id); if(cust_type_id.length == '7'){ // var cust_id = cust_type_id+zone_id; var position = 2; var output = [cust_type_id.slice(0, position), zone_id, cust_type_id.slice(position)].join(''); //alert(output) $('#customer_id').val(output); }else{ //var cust_id1 = cust_type_id.substring(0, cust_type_id.length 2); //alert(str.replaceAt(2, zone_id)); String.prototype.replaceAt=function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); } strss = cust_type_id.replaceAt(2, zone_id); $('#customer_id').val(strss); } } }); }); </script> <script> $(document).ready(function() { $('#custttt').click(function() { var mob = $('#mobile').val(); var customer_name = $('#customer_name').val(); var cust_idd = $('#cust_idd').val(); var cust_idd = $('#cust_idd').val(); var email = $('#email').val(); parent.setSelectedUser(mob,customer_name,cust_idd,email); parent.$.fancybox.close(); }); }); </script> <script> $(function(){ $( "form" ).submit(function( event ) { if ( $( "#cust_type" ).val() == "" ) { $( "#type_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( "#customer_name" ).val() == "" ) { $( "#name_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( "#customer_id" ).val() == "" ) { $( "#cid_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( "#pincode" ).val() == "" ) { $( "#pincode_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( "#service_zone" ).val() == "" ) { $( "#zone_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } if ( $( "#mobile" ).val() == "" ) { $( "#number_error" ).text( "Field cannot be empty" ).show(); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#cust_type").change(function(){ if($(this).val()==""){ $("#type_error").show(); } else{ $("#type_error").hide(); } }); $("#customer_name").keyup(function(){ if($(this).val()==""){ $("#name_error").show(); } else{ $("#name_error").fadeOut(); } }); $("#mobile").keyup(function(){ if($(this).val()==""){ $("#number_error").show(); } else{ $("#number_error").hide(); } }); $("#pincode").keyup(function(){ if($(this).val()==""){ $("#pincode_error").show(); } else{ $("#pincode_error").hide(); } }); $("#service_type").change(function(){ if($(this).val()==""){ $("#service_type_error").show(); } else{ $("#service_type_error").hide(); } }); $("#service_zone").change(function(){ if($(this).val()==""){ $("#zone_error").show(); } else{ $("#zone_error").hide(); } }); $("#model").change(function(){ if($(this).val()==""){ $("#model_error").show(); } else{ $("#model_error").hide(); } }); }); </script> </body> </html><file_sep>/application/models/Tax_model.php <?php class Tax_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_tax($data){ $this->db->insert('tax_details',$data); return true; } public function checktaxname($data) { //echo $data; exit; $query = $this->db->get_where('tax_details', array('tax_name' => $data)); return $numrow = $query->num_rows(); } public function tax_list(){ $this->db->select("id, tax_name, tax_percentage, tax_default, status",FALSE); $this->db->from('tax_details'); $this->db->order_by("id","desc"); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_tax_info($data,$id){ $this->db->where('id',$id); $this->db->update('tax_details',$data); } public function update_tax_default($data,$id){ $this->db->where('id',$id); $this->db->update('tax_details',$data); } public function del_tax_info($id){ $this->db->where('id',$id); $this->db->delete('tax_details'); } public function update_tax_list($data,$id){ print_r($data); print_r($id); $this->db->where('id',$id); $this->db->update('tax_details',$data); } public function update_status_customer1($data,$id){ $this->db->where('id',$id); $this->db->update('tax_details',$data); } }<file_sep>/application/views/add_qc_master_row.php <tr> <td style="padding:10px 0;"><input type="text" name="qc_param[]" id="qc_param-<?php echo $count; ?>" class="qcparam" maxlength="20"></td> <td style="padding:10px 0;"><input type="text" name="qc_value[]" id="qc_value-<?php echo $count; ?>" class="qcvalue" maxlength="6"></td> <td style="border:none;text-align:center;"><a id="delbtn" class="delrow" onClick="$(this).closest('tr').remove();"><i class="fa fa-trash" style="color:#5f3282;"></i></a></td> </tr> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function(){ $(".qcparam").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9.]/g,"")); }); $(".qcvalue").bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^0-9.]/g,"")); }); }); </script> <file_sep>/application/views_bkMarch_0817/quote_review.php <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Quote Review</h4> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Request Id</th> <th>Customer Name</th> <th>Product Name</th> <th>Machine Status</th> <th>Requested Date</th> <th>Assign To</th> <th>Site</th> <th>Location</th> <th>Problem</th> </tr> </thead> <!-- <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot>--> <tbody> <?php foreach($quote_review_req_list as $key){?> <tr> <td><a href="<?php echo base_url(); ?>quote_review_view/quote_review_display/<?php echo $key->id; ?>"><?php echo $key->request_id; ?></a></td> <td><?php echo $key->customer_name; ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->model;} } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?></td> <td><?php echo $key->request_date; ?></td> <td><?php foreach($service_req_listforEmp as $key2){ if($key2->request_id==$key->id){ echo $key2->emp_name; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->site; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->service_loc; } } ?></td> <td><?php foreach($service_req_listforProb as $servprobkey2){ if($servprobkey2->request_id==$key->id){ echo $servprobkey2->prob_category; } } ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/controllers/Quotereview.php <?php class quotereview extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Quotereview_model'); $this->load->model('workin_prog_model'); } public function service_status(){ $id=$this->uri->segment(3); $data1['req_id'] = $id; $data1['get_status']=$this->Quotereview_model->get_status($id); $data1['getQuoteReviewDetByID1']=$this->Quotereview_model->getQuoteReviewDetByID1($id); //echo "<pre>"; //print_r($data1['getQuoteReviewDetByID1']); //exit; if(!empty($data1['getQuoteReviewDetByID1'])){ $modelid = $data1['getQuoteReviewDetByID1'][0]->model_id; $data1['spareListByModelId1']= $this->Quotereview_model->spareListByModelId($modelid); }else{ $data1['spareListByModelId1']= $this->Quotereview_model->spareList(); } $data1['getQuoteReviewSpareDetByID']=$this->Quotereview_model->getQuoteReviewSpareDetByID($id); if(!empty($data1['getQuoteReviewSpareDetByID'])){ foreach($data1['getQuoteReviewSpareDetByID'] as $ReviewDetKey3){ $spare_id = $ReviewDetKey3->spare_id; $data1['spareIds'][]= $this->Quotereview_model->getsparedetForEditbyid($spare_id); $data1['spare_amtt'][] = $ReviewDetKey3->amt; } }//echo "<pre>";print_r($data1['spareIds']);exit; $get_request_details = $this->Quotereview_model->get_request_details($id); $sr_no = $get_request_details[0]->serial_no; //exit; if($sr_no!=""){//echo "<br/>dsssssssss"; $data1['getQuoteByReqId']=$this->Quotereview_model->getQuoteByReqId($id); }else{ $data1['getQuoteByReqId']=$this->Quotereview_model->getQuoteByReqId1($id); } if(!empty($data1['getQuoteByReqId'])){ if($data1['getQuoteByReqId'][0]->modelid!=""){ $service_modelid = $data1['getQuoteByReqId'][0]->modelid; }else{ $service_modelid = ""; } if($data1['getQuoteByReqId'][0]->service_cat!=""){ $service_service_cat = $data1['getQuoteByReqId'][0]->service_cat; }else{ $service_service_cat = ""; } } $data1['getProbforQuoteByReqId']=$this->Quotereview_model->getProbforQuoteByReqId($id); $data1['getServiceCatbyID']=$this->Quotereview_model->getServiceCatbyID($service_service_cat, $service_modelid); if(empty($data1['getServiceCatbyID'])){ $data1['getservicecharge'] = '0'; } $data1['status_list']=$this->Quotereview_model->status_list(); $data1['status_listForquoteInpro']=$this->Quotereview_model->status_listForquoteInpro(); $data1['status_listForoffsiteworkInpro']=$this->Quotereview_model->status_listForoffsiteworkInpro(); $data1['status_listForEmpLogin']=$this->Quotereview_model->status_listForEmpLogin(); $data1['service_req_listforaddlEmp1']=$this->Quotereview_model->service_req_listforaddlEmp1($id); $data1['getTaxDefaultInfo']=$this->Quotereview_model->getTaxDefaultInfo(); $data1['problemlist1']=$this->Quotereview_model->problemlist(); $data1['getWarrantyInfo']=$this->Quotereview_model->getWarrantyInfo($id); date_default_timezone_set('Asia/Calcutta'); $data1['del_date'] = date("Y-m-d H:i:s"); $data1['service_req_listforEmp1']=$this->Quotereview_model->service_req_listforEmp1($id); $data1['get_qc_parameters_details']=$this->Quotereview_model->get_qc_parameters_details($id); //$data1['offsite_flag'] = "working"; //$data1['getQuoteReviewDetByID']=$this->Quotereview_model->getQuoteReviewDetByID($id); if(!empty($data1['getQuoteReviewDetByID1'])){ $data111['user_dat'] = $this->session->userdata('login_data'); $data1['user_type'] = $data111['user_dat'][0]->user_type; $data1['emp_id'] = $data111['user_dat'][0]->emp_id; $this->load->view('templates/header',$data111); $this->load->view('service_status',$data1); }else{ $data111['user_dat'] = $this->session->userdata('login_data'); $data1['user_type'] = $data111['user_dat'][0]->user_type; $data1['emp_id'] = $data111['user_dat'][0]->emp_id; $this->load->view('templates/header',$data111); $this->load->view('service_status_new',$data1); } } public function addrow(){ $data['count']=$this->input->post('countid'); $modelid=$this->input->post('modelid'); $data['engidd']=$this->input->post('engidd'); //print_r($data['engidd']);exit; $data['spareListByModelId']=$this->Quotereview_model->spareListByModelId($modelid); $this->load->view('add_spares_row',$data); } public function getsparedet(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Quotereview_model->getsparedetbyid($id))); } public function add_quotereview(){ //echo "<pre>";print_r($_POST);exit; ini_set('max_execution_time', 900); $reqid = $this->input->post('req_id'); date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $stats=$this->input->post('status'); $data['req_id']=$this->input->post('req_id'); $data['model_id']=$this->input->post('modelid'); //$stats=$this->input->post('status'); /* $sms_mob=$this->input->post('sms_mobile'); if($stats=='1' && isset($sms_mob)){ $sms_mobs=$this->input->post('sms_mobile'); $cust_name = $this->input->post('cust_name'); $modell = $this->input->post('p_name'); $brand_name = $this->input->post('brand_name'); $sms= "Req ID: ".$reqid; $sms.= " Cust Name: ".$cust_name; if ($this->input->post('cust_mobile')!=""){ $sms.= " Phone: ".$this->input->post('cust_mobile'); } //$sms.= " Brand: ".$brand_name; $sms.= " Model: ".$modell; if ($this->input->post('probs')!=""){ $sms.= " Problem: ".$this->input->post('probs'); } if ($this->input->post('blanket_app')!=""){ $sms.= " Blanket Appr: ".$this->input->post('blanket_app'); } $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=srscales&pass=<PASSWORD>&sender=SRSCAL&phone=$sms_mobs&text=$messages&priority=sdnd&stype=normal"); } */ $spare_taxx = $this->input->post('spare_tax'); if($spare_taxx!=""){ $data['spare_tax']=$this->input->post('spare_tax'); }else{ $data['spare_tax']='0'; } $spare_tott = $this->input->post('spare_tot'); if($spare_tott!=""){ $data['spare_tot']=$this->input->post('spare_tot'); }else{ $data['spare_tot']='0'; } $labourchargee = $this->input->post('labourcharge'); if($labourchargee!=""){ $data['labourcharge']=$this->input->post('labourcharge'); }else{ $data['labourcharge']='0'; } $conchargee = $this->input->post('concharge'); if($conchargee!=""){ $data['concharge']=$this->input->post('concharge'); }else{ $data['concharge']='0'; } $total_amtt = $this->input->post('total_amt'); if($total_amtt!=""){ $data['total_amt']=$this->input->post('total_amt'); }else{ $data['total_amt']='0'; } $total_amt = $this->input->post('total_amt'); //$data['pending_amt']=$this->input->post('total_amt'); $data['delivery_date']=$this->input->post('delivery_date1'); $data['comments']=$this->input->post('comment_deliver'); /* if($this->input->post('eng_notes')!=""){ $data5['eng_notes']=$this->input->post('eng_notes'); $data5['created_on'] = date("Y-m-d H:i:s"); $data5['engg_id'] = $this->input->post('eng_name'); $data5['req_id'] = $this->input->post('reque_id'); $this->Quotereview_model->history_ins($data5); } */ $ratings = $this->input->post('rating'); if(isset($ratings) && $ratings!=''){ $data['rating']=$this->input->post('rating'); } $userty =$this->input->post('usrtyp'); $assignn_to = $this->input->post('assign_to_id'); $notes_all = $this->input->post('notes_all'); /*$data['notes_all']=$this->input->post('notes_all'); if($notes_all!=''){ if($notes_all=='eng_notes'){ if($this->input->post('eng_notes')!=""){ $data5['eng_notes']=$this->input->post('eng_notes'); $data5['created_on'] = date("Y-m-d H:i:s"); $data5['engg_id'] = $this->input->post('eng_name'); $data5['req_id'] = $this->input->post('req_id'); $this->Quotereview_model->history_ins($data5); } $data['eng_notes']=$this->input->post('eng_notes'); } if($notes_all=='cust_remark'){ if($this->input->post('cust_remark')!=""){ $data51['cust_remark']=$this->input->post('cust_remark'); $data51['created_on'] = date("Y-m-d H:i:s"); $data51['emp_id'] = $this->input->post('eng_name'); $data51['given_by'] = $userty; $data51['req_id'] = $this->input->post('req_id'); $this->Quotereview_model->history_cust_remark($data51); } $data['cust_remark']=$this->input->post('cust_remark'); } } */ //$total_amt=$this->input->post('total_amt'); //$service_cmr_paid = $this->input->post('service_cmr_paid'); //$service_cmr_paid1 = $this->input->post('service_cmr_paid1'); //$tot_service_cmr_paid = $service_cmr_paid + $service_cmr_paid1; //$data['cmr_paid'] = $tot_service_cmr_paid; //$data['pending_amt']=$this->input->post('service_pending_amt'); //$data['payment_mode']=$this->input->post('payment_mode'); $coord_notes=$this->input->post('notes'); if($coord_notes!="") { $data['notes']=$this->input->post('notes'); $data5q1['co_notess']=$this->input->post('notes'); $data5q1['created_on'] = date("Y-m-d H:i:s"); $data5q1['usrr_id'] = $assignn_to; $data5q1['req_id'] = $this->input->post('req_id'); $this->workin_prog_model->history_notess($data5q1); } else{ $data['notes']=''; } //$maijnn = $this->input->post('reporttyt'); //if($this->input->post('reporttyt')!=''){ //if($maijnn=="eng_notess"){ if($this->input->post('eng_notess')!=""){ $data52['eng_notess']=$this->input->post('eng_notess'); $data52['created_on'] = date("Y-m-d H:i:s"); $data52['engg_id'] = $assignn_to; $data52['req_id'] = $this->input->post('req_id'); $this->workin_prog_model->history_inss($data52); $data['eng_notess']=$this->input->post('eng_notess'); } //} //if($maijnn=="cust_solution"){ if($this->input->post('cust_solution')!=""){ $data5e1['cust_solution']=$this->input->post('cust_solution'); $data5e1['created_on'] = date("Y-m-d H:i:s"); $data5e1['engg_id'] = $assignn_to; $data5e1['given_by'] = $userty; $data5e1['req_id'] = $this->input->post('req_id'); $this->workin_prog_model->history_cust_solution($data5e1); $data['cust_solution']=$this->input->post('cust_solution'); } //} //} if($this->input->post('cust_remarkk')!=null){ $data51['cust_remark']=$this->input->post('cust_remarkk'); $data51['created_on'] = date("Y-m-d H:i:s"); $data51['engg_id'] = $assignn_to; $data51['given_by'] = $userty; $data51['req_id'] = $this->input->post('req_id'); $this->workin_prog_model->history_cust_remark($data51); $data['cust_remark']=$this->input->post('cust_remarkk'); } $cust_mobi = $this->input->post('cust_mobile'); if($stats=='7' && isset($cust_mobi)){ $modell = $this->input->post('p_name'); $brand_name = $this->input->post('brand_name'); $sms= "Req ID: ".$this->input->post('reque_id');; $sms.= " Brand: ".str_replace('&',' and ',$brand_name); $sms.= ", Model: ".$modell; if ($total_amt!=""){ $sms.= ", Quotation: ".$total_amt; } $sms.= " We need confirmation, send msg to 9841443300 (OK/Not OK). Thank You"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_mobi&text=$messages&priority=ndnd&stype=normal"); } if($stats=='5'){ $cust_site_mobile = '9962135225'; $reque_id=$this->input->post('reque_id'); //$cust_site_mobile = '9841443300'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $sms= "Hi. Please prepare quotation and get customer approval for request ID: ".$reque_id; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($stats=='16'){ $cust_site_mobile = '9962135225'; $reque_id=$this->input->post('reque_id'); //$cust_site_mobile = '7200669999'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $sms= "Hi. request ID: ".$reque_id." has been done"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($stats=='9'){ $cust_site_mobile = '9962135225'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $reque_id=$this->input->post('reque_id'); $onhold_date = $this->input->post('on_hold'); $onhold_reason = $this->input->post('onhold_reason'); $sms= "Hi. Request ID: ".$reque_id." is on-hold. Date: ".$onhold_date." Reason: ".$onhold_reason; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($stats=='9'){ $data['onhold_date']=$this->input->post('on_hold'); $data['onhold_reason']=$this->input->post('onhold_reason'); $data7['on_hold'] = $this->input->post('on_hold'); $data7['onhold_reason']=$this->input->post('onhold_reason'); $data7['req_id'] = $this->input->post('req_id'); $data7['emp_id']=$this->input->post('assign_to_id'); $this->Quotereview_model->log_onhold($data7); } $eng_ack = $this->input->post('eng_ack'); if($eng_ack!=""){ $data_ackupdate['eng_ack']=$this->input->post('eng_ack'); $data_ackupdate['accepted_engg_id']=$this->input->post('empiid'); }else{ $data_ackupdate['eng_ack']=''; } $this->Quotereview_model->update_eng_ack($data_ackupdate,$reqid); if($eng_ack!='' && isset($eng_ack)){ $cust_site_mobile1 = '9962135225'; $reque_id=$this->input->post('reque_id'); if($eng_ack=='accept'){ $eng_ack_msg = 'accepted'; $sms= "Hi. Request Id: ".$reque_id." is ".$eng_ack_msg; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } if($eng_ack=='reject'){ $eng_ack_msg = 'rejected'; $sms= "Hi. Request Id: ".$reque_id." is ".$eng_ack_msg; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } if($eng_ack=='later'){ $sms= "Hi. Request Id: ".$reque_id." will be serviced later"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } } /* if($service_cmr_paid!='0' && $service_cmr_paid!=''){ $log_payment_data=array( 'req_id'=>$reqid, 'cmr_paid'=>$this->input->post('service_cmr_paid'), 'payment_mode'=>$this->input->post('payment_mode'), 'pending_amt'=>$this->input->post('service_pending_amt'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $this->Quotereview_model->log_service_payment_details($log_payment_data); } */ /* $disc_amt=$this->input->post('disc_amt'); $disc_amt1=$this->input->post('disc_amt1'); $disc_amt2 = $disc_amt + $disc_amt1; if($disc_amt!=""){ $data['disc_amt']= $disc_amt2; $data['total_amt']=$this->input->post('total_amt'); $data['pending_amt'] = $this->input->post('service_pending_amt'); }else{ $data['total_amt']=$this->input->post('total_amt'); $data['pending_amt'] = $this->input->post('total_amt'); $data['total_charge']=$this->input->post('total_amt'); } */ //print_r($data); $result=$this->Quotereview_model->add_quotereview($data); $order_row_id=$this->input->post('order_row_id'); $batch_no = $this->input->post('batch_no'); $serial_no = $this->input->post('serial_no'); if(isset($serial_no) && $serial_no!="" && $serial_no!='update sr no'){ $data_order_det['batch_no']=$this->input->post('batch_no'); $data_order_det['serial_no']=$this->input->post('serial_no'); $this->Quotereview_model->update_order_srno($data_order_det,$order_row_id); $data_service_det['batch_no']=$this->input->post('batch_no'); $data_service_det['serial_no']=$this->input->post('serial_no'); $this->Quotereview_model->update_service_srno($data_service_det,$reqid); } $data4=array( 'status'=>$this->input->post('status'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $this->Quotereview_model->update_stats($data4,$reqid); $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $warranty_claim_status=$data1['warranty_claim_status']=$this->input->post('warranty_claim_status'); $desc_failure=$data1['desc_failure']=$this->input->post('desc_failure'); $why_failure=$data1['why_failure']=$this->input->post('why_failure'); $correct_action=$data1['correct_action']=$this->input->post('correct_action'); /* echo "<pre>"; print_r($warranty_claim_status); echo "<pre>"; print_r($desc_failure); echo "<pre>"; print_r($why_failure); echo "<pre>"; print_r($correct_action); exit; */ $amt=$data1['amt']=$this->input->post('amt'); $c=$spare_name; $count=count($c); if($reqid){ $data1 =array(); for($i=0; $i<$count; $i++) { if($spare_name[$i]!="" && $spare_qty[$i]!=""){ if($warranty_claim_status[$i]=='to_claim'){ $desc_failure1 = $desc_failure[$i]; $why_failure1 = $why_failure[$i]; $correct_action1 = $correct_action[$i]; }else{ $desc_failure1 = ''; $why_failure1 = ''; $correct_action1 = ''; } $data1= array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i], 'warranty_claim_status' => $warranty_claim_status[$i], 'desc_failure' => $desc_failure1, 'why_failure' => $why_failure1, 'correct_action' => $correct_action1 ); } if(!empty($data1)){ $this->Quotereview_model->add_quotereview_spares($data1); } } } $res_qc_value = $this->input->post('res_qc_value'); $qc_param_id = $this->input->post('qc_param_id'); $this->Quotereview_model->delete_qc_param_details($reqid); if(!empty($res_qc_value)){ $qc_data = array(); for($i=0; $i<count($res_qc_value); $i++) { $qc_data = array( 'request_id' => $reqid, 'qc_master_id' => $qc_param_id[$i], 'result_qc_value' => $res_qc_value[$i] ); $this->Quotereview_model->add_qc_param_details($qc_data); } } $eemail = $this->input->post('email'); if($eemail!=""){ //email $config = Array( 'mailtype' => 'html' ); $this->load->library('email', $config); $this->email->from('<EMAIL>', 'Admin'); // $text = $this->input->post('eng_notes'); //echo $text;exit; $this->email->to($eemail); $this->email->subject('Subject'); $data_email['sub'] = $this->input->post('eng_notes'); // print_r($data['sub']); exit; $message="<table> <tr><td>". $data_email['sub']."</td></tr> <tr><td colspan='2' style='text-align:center;font-size:15px;font-weight:bolder'> Thank you for Contact Us ..! </td></tr> </table>"; // echo $message; exit; $this->email->message($message); $this->email->send(); } echo "<script>alert('Work In-progress Updated');window.location.href='".base_url()."pages/workin_prog_list';</script>"; } public function edit_quotereview(){ //echo "<pre>";print_r($_POST);exit; $reqid = $this->input->post('req_id'); date_default_timezone_set('Asia/Calcutta'); $data['updated_on'] = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $data['user_id'] = $data111['user_dat'][0]->id; $user_id = $data111['user_dat'][0]->id; //$data['req_id']=$this->input->post('req_id'); $stats=$this->input->post('status'); $sms_mob=$this->input->post('sms_mobile'); if($stats=='1' && isset($sms_mob)){ $sms_mobs=$this->input->post('sms_mobile'); $cust_name = $this->input->post('cust_name'); $modell = $this->input->post('p_name'); $brand_name = $this->input->post('brand_name'); $sms= "Req ID: ".$reqid; $sms.= " Cust Name: ".$cust_name; if ($this->input->post('cust_mobile')!=""){ $sms.= " Phone: ".$this->input->post('cust_mobile'); } //$sms.= " Brand: ".$brand_name; $sms.= " Model: ".$modell; if ($this->input->post('probs')!=""){ $sms.= " Problem: ".$this->input->post('probs'); } if ($this->input->post('blanket_app')!=""){ $sms.= " Blanket Appr: ".$this->input->post('blanket_app'); } $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$sms_mobs&text=$messages&priority=ndnd&stype=normal"); } $data['spare_tax']=$this->input->post('spare_tax'); //$data['tax_type']=$this->input->post('tax_type'); $data['spare_tot']=$this->input->post('spare_tot'); $data['labourcharge']=$this->input->post('labourcharge'); $data['concharge']=$this->input->post('concharge'); $data['total_charge']=$this->input->post('total_amt'); $data['total_amt']=$this->input->post('total_amt'); $total_amt = $this->input->post('total_amt'); $data['pending_amt']=$this->input->post('total_amt'); $data['delivery_date']=$this->input->post('delivery_date'); $data['notes']=$this->input->post('notes'); $this->Quotereview_model->update_quotereview($data,$reqid); $cust_mobi = $this->input->post('cust_mobile'); if($stats=='7' && isset($cust_mobi)){ $modell = $this->input->post('p_name'); $brand_name = $this->input->post('brand_name'); $sms= "Req ID: ".$this->input->post('reque_id');; $sms.= " Brand: ".str_replace('&',' and ',$brand_name); $sms.= ", Model: ".$modell; if ($total_amt!=""){ $sms.= ", Quotation: ".$total_amt; } $sms.= " We need confirmation, send msg to 9841443300 (OK/Not OK). Thank You"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_mobi&text=$messages&priority=ndnd&stype=normal"); } $data4=array( 'status'=>$this->input->post('status'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); foreach ($data4 as $datakey => $datavalue) { //echo $datakey.'-'.$datavalue; if (!empty($datavalue)){ $this->Quotereview_model->update_stats($data4,$reqid); } } $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $amt=$data1['amt']=$this->input->post('amt'); //$this->Quotereview_model->delete_quote_review($reqid); //$used_spares=$data1['spare_tbl_id']=$this->input->post('spare_tbl_id'); $c=$spare_name; $count=count($c); /* if($reqid){ $data1 = array(); for($i=0; $i<$count; $i++) { if($stats=='2'){ $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; $used_spare = $spare_qty[$i] + $used_spares[$i]; $data2[] = array( 'id' => $spare_name[$i], 'spare_qty' => $bal_spare, 'used_spare' => $used_spare ); } $data1[] = array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i] ); } if(!empty($data2)){ $this->Quotereview_model->update_spare_balance($data2); } if(!empty($data1)){ $this->Quotereview_model->add_quotereview_spares($data1); } } */ echo "<script>alert('Quote Review Updated');window.location.href='".base_url()."pages/quote_in_progress_list';</script>"; } public function add_service_req(){ //echo "<pre>";print_r($_POST);exit; $data['request_id']=$this->input->post('req_id'); $data['cust_name']=$this->input->post('cust_name'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['request_date']=$this->input->post('datepicker'); $result=$this->Service_model->add_services($data); if($result){ $data1['request_id']=$result; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); $result1=$this->Service_model->add_service_details($data1); } if($result){ echo "<script>alert('Service Request Added');window.location.href='".base_url()."pages/service_req_list';</script>"; } } public function get_custbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function update_service_req(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_req',$data); } public function edit_service_req(){ $data=array( 'request_id'=>$this->input->post('req_id'), 'cust_name'=>$this->input->post('cust_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email_id'), 'request_date'=>$this->input->post('datepicker') ); $id=$this->input->post('servicereqid'); $this->Service_model->update_service_request($data,$id); if($id){ $data1['request_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); //echo "<pre>"; //print_r($data1); $this->Service_model->delete_serv_req_details($id); $result1=$this->Service_model->add_service_details($data1); } echo "<script>alert('Service Request Updated');window.location.href='".base_url()."pages/service_req_list';</script>"; } public function get_branchname(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_branch($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_order(){ $id=$this->input->post('id'); $this->Order_model->delete_order_details($id); $result = $this->Order_model->delete_orders($id); } }<file_sep>/application/views/edit_password.php <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#brand-1").val()==""){ $("#fname1").text("Enter your Old password").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'11px'}); event.preventDefault(); } if($("#brand-2").val()==""){ $("#fname2").text("Enter your New password").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'11px'}); event.preventDefault(); } if($("#brand-3").val()==""){ $("#fname3").text("ReEnter your New password").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'11px'}); event.preventDefault(); } }); $("#brand1").keyup(function(){ if($(this).val()==""){ $("#fname1").show(); } else{ $("#fname1").fadeOut('slow'); } }) $("#brand2").keyup(function(){ if($(this).val()==""){ $("#fname2").show(); } else{ $("#fname2").fadeOut('slow'); } }) $("#brand3").keyup(function(){ if($(this).val()==""){ $("#fname3").show(); } else{ $("#fname3").fadeOut('slow'); } }) }); </script> <script> $(document).ready(function(){ //alert("sdfdasf"); $('#addMoreRows').click(function(){ //alert("ddssss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Brand/addrow", data: datastring, cache: false, success: function(result) { // alert(result); $('#myTable').append(result); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <style> .tableadd tr td input { width: 237px; /* height: 22px !important; */ /* border: 1px solid #B3B3B3; */ border-radius: 2px; /* padding-left: 10px; */ margin-left: 14px; } .tableadd tr td input { height: 22px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <!--<script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td style="width:27.2%;"><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script>--> <script> $(document).ready(function(){ $('[id^="pro_cat_"]').change(function(){alert("hii"); var id = $(this).val(); var arr = id.split(','); var procatid = arr['0']; var subid = arr['1']; var data_String; data_String = 'id='+subid+'&procatid='+procatid; $.post('<?php echo base_url(); ?>subcategory/update_sub_category',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Category changed"); //$('#actaddress').val(data.Address1), }); }); }); </script> <!--<script type="text/javascript"> $(document).ready(function() { var rowCount = 1; $('#addMoreRowsc').click(function() { alert("xs"); rowCount ++; var recRow = '<tr><td><select name="category[]" id="category'+rowCount+'" class="category"><option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ ?><option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option><?php } ?></select></td><td><select name="subcategory[]" id="subcategory"><option value="">---Select---</option></select></td> <td><input type="text" value="" name=""></td></tr>'; $("#myTable").append(recRow); }); }); </script>--> <script type="text/javascript"> $(document).ready(function() { $(".category").change(function(){ alert("vijayyy"); }); }); </script> <!--<script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { //alert("ffff"); $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Brand/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script>--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <!--<script type="text/javascript"> function removeRow(removeNum) { jQuery('#rowCount'+removeNum).remove(); } </script>--> <link rel="stylesheet" href="css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> body{background-color:#fff;} .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; cursor:pointer; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } a:hover, a:active, a:focus { outline: none; text-decoration: none; color: #fff; } .delRowBtn{ padding:0px 12px; height:30px; } .tableadd tr td select { border-radius:5px; /* margin-bottom: 25px !important;*/ } .tableadd tr td input { width: 215px; } .tableadd { margin-bottom:5px; } .tableadd tr td label { font-weight:bold; } label { font-size: 1.3rem; color: #522276; } .btn{ text-transform:capitalize; } .link{ font-size: 13px; font-weight: bold !important; } .star{ font-size:15px; color:#ff0000; } </style> <script> function checkOld() { // var getpold = $("#brand-1").val(); // var getuser = $("#changepas").val(); var aaaa = document.getElementById('brand-1').value; var bbbb = document.getElementById('changepas').value; if(aaaa!=bbbb) { alert("Mismatched Old Passward!") $("#brand-1").val(''); $("#brand-1").focus(); } } </script> <script> function checkNew() { var aaaa = document.getElementById('brand-2').value; var bbbb = document.getElementById('brand-3').value; if(aaaa!=bbbb) { alert("Incorrect Re-entered Passward!") $("#brand-3").val(''); $("#brand-3").focus(); } } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Change Password</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <?php //print_r($user_dat); ?> <form action="<?php echo base_url(); ?>login/update_password" method="post" autocomplete="off"> <div id="myTable" class="tableadd"> <!--<tr><td><label>Brand Name</label></td></tr> <tr> <td><input type="text" value="" name="brand_name[]" id="brand1" class="firstname"><div class="fname"></div><div id="dpt_error1" style="color: #ff0000;position: relative; top: 0px;left: 0px;"></div></td> </tr> <input type="hidden" id="countid" value="1">--> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Old Password<span class="star">*</span></label> <input type="text" value="" name="brand_name1" id="brand-1" onchange="checkOld();" maxlength="80"><div id="fname1"></div> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>New Password <span class="star">*</span></label> <input type="text" value="" name="brand_name2" id="brand-2" maxlength="80"><div id="fname2"></div> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Re Enter New Password<span class="star">*</span></label> <input type="text" value="" name="brand_name3" onchange="checkNew();" id="brand-3" maxlength="80"><div id="fname3"></div> </div> </div> <?php foreach($user_dat as $usd) { $pasdsad[] = $usd->password; $idd[] = $usd->id; } ?> <input type="hidden" name="changepas" id="changepas" value="<?php echo $pasdsad[0];?>"> <input type="hidden" name="changeid" id="changeid" value="<?php echo $idd[0];?>"> </div> <div class="col-md-12"> <div class="col-md-6"> <!--<a class="link" id="addMoreRows">Add Brand</a>--> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" >Submit <i class="fa fa-arrow-right"></i></button> </div> </div> <div class="tableadd"> <div> <div></div> <div style="padding-top: 25px;"></div> </div> </div> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> /* $(document).on("keyup","#brand1", function(){ //alert("dfg"); //alert($(this').val()); var brand=$(this).val(); //alert(brand); if(brand) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Brand/brand_validation', data: { brand:brand, }, success: function (data) { if(data == 0){ $('#dpt_error1').fadeOut('slow'); } else{ $('#dpt_error1').text('Brand Name Already Exist').show().delay(1000).fadeOut(); $('#brand1').val(''); return false; } } }); } }); */ $("#brand-1").keyup(function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); </script> </body> </html><file_sep>/application/views/add_prod_cat.php <!--<script type='text/javascript'>//<![CDATA[ $(function(){ var tb2 = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ ++i; $('<div class="col-md-12" style="padding: 0px"><div class="col-md-3 col-sm-6 col-xs-12"><input type="text" name="cat_name[]" id="UserName'+i+'" class="firstname"><div class="fname" id="lname'+i+'" style="color:red"></div></div><div class="col-md-1 col-sm-6 col-xs-12" style="padding:0px"><a class="delRowBtn btn btn-primary fa fa-trash" style="height:30px;"></a></div></div>').appendTo(tb2); $("#UserName"+i).keyup(function(){ var name1=document.getElementById( "UserName"+i ).value; //alert(name1); if(name1) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name1, }, success: function (data) { // alert(data); if(data == 0){ $('#lname'+i).html(''); } else{ //alert("else called"); $('#lname'+i).text('Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '12px'}); $('#UserName'+i).val(''); return false; } } }); } }); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName"+i).val()==""){ $("#lname"+i).text("Enter Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '12px'}); event.preventDefault(); } }); $("#UserName"+i).keyup(function(){ if($(this).val()==""){ $("#lname"+i).show(); } else{ $("#lname"+i).fadeOut('slow'); } }); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script>--> <script> $(document).ready(function(){ $('#addRowBtn1').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Productcategory/add_prodrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .btn, .btn-large, .btn-flat{text-transform:none;} .tableadd tr td input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 3px; /* padding-left: 10px; */ margin-left: 13px; } .tableadd tr td input { height: 21px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script> $(document).ready(function(){ //$('#prob_cat_name').change(function(){ //alert("check"); $(document).on("keyup","#UserName1", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ //$(document).on("keyup","#UserName1", function(){ var name=$("#UserName1").val(); //alert(name); if(name !=''){ $.ajax({ type: 'post', url: '<?php echo base_url(); ?>Productcategory/category_validation', data: { p_id:name, }, success: function (data) { //alert(data); if(data == 0){ $('#lname12').html(''); } else{ $('#lname12').text('Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); $('.firstname').val(''); return false; } } }); } } }); </script> <script> $(function(){ $("#submit").click(function(event){ //alert("xcfg"); if($(".firstname").val()==""){ $("#lname1").text("Enter Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '10px'}); event.preventDefault(); } }); $("#UserName1").keyup(function(){ if($(this).val()==""){ $("#lname1").show(); } else{ $("#lname1").fadeOut('slow'); } }); }); </script> <style> body{background-color:#fff;} .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; } .delRowBtn { display: inline-block; padding: 0px 5px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } .star{ color:#ff0000; font-size:15px; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Add Product Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Productcategory/add_prod_category" method="post" > <div id="myTable" class="tableadd" > <div class="col-md-12" style="padding: 0px"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category Name <span class="star">*</span></label> <input type="text" name="cat_name[]" id="UserName1" class="firstname" maxlength="80"> <div class="fname" id="lname1" style="color:red"></div> <span id="lname12" style="color:red"></span> <input type="hidden" id="countid" value="1"> </div> <a class="link" id="addRowBtn1"><i class="fa fa-plus-square" aria-hidden="true"style="margin-top:30px;color:#5f3282;"></i> </a> </div> </div> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" id="submit" style="margin-left:20px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> </body> </html><file_sep>/application/views/purchase_spare.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; border: 1px solid gray; height: 27px; } .dropdown-content { display:none; } #table1 { margin-top:10px; width:100%; border-collapse: collapse; } #table1 tr { height:40px; } #table1 tr td { border:1px solid #522276; text-align:center; } span { float: right; /* margin-top: -44px; */ margin-right: 0px; } #table1 tr td input { width:120px; border: 1px solid gray; height: 27px; } #table1 tr td select { width:120px; border: 1px solid gray; height: 27px; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 114px; margin: auto auto 35px; } .rowadd { border: 1px solid #8868a0 !important; background: #8868a0 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; cursor: pointer; } .color { background: #6c477d; color: white; height: 30px !important; } #or{float: right; margin-top: 7px; font-size: 11px; margin-right: 4px;} </style> <script type="text/javascript"> $(document).ready(function() { $("#pro_cat").change(function() { var vl=$('#countid').val(); //alert(vl); //$('#spare_name_'+vl+ "> option").remove(); $(".spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_spares", data: dataString, cache: false, success: function(data) { $('.spare_name').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('.spare_name').append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#pro_subcat").change(function() { var vl=$('#countid').val(); //alert(vl); //$('#spare_name_'+vl+ "> option").remove(); $(".spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbysubcat", data: dataString, cache: false, success: function(data) { $('.spare_name').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('.spare_name').append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#brand").change(function() { var vl=$('#countid').val(); //alert(vl); //$('#spare_name_'+vl+ "> option").remove(); $(".spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbybrand", data: dataString, cache: false, success: function(data) { $('.spare_name').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('.spare_name').append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $("#model").change(function() { var vl=$('#countid').val(); //alert(vl); //$('#spare_name_'+vl+ "> option").remove(); $(".spare_name > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_sparesbymodel", data: dataString, cache: false, success: function(data) { $('.spare_name').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('.spare_name').append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); }); } }); }); }); </script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var vl=$('#countid').val(); //alert(vl); // alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1_'+vl).val(data.spare_qty), $('#used_spare1_'+vl).val(data.used_spare), $('#purchase_price1_'+vl).val(data.purchase_price), $('#purchase_qty1_'+vl).val(data.purchase_qty) }); } }); }); }); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var catt=$('#pro_cat').val(); //alert(catt); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1+'&prod_cat='+catt; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow1", data: datastring, cache: false, success: function(result) { //alert(result); $('#table1').append(result); } }); }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Stock-In</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Spare/update_spare_stock" method="post"> <table id="myTable" class="tableadd" style="width:100%;"> <tr><td><label>Category</label></td><td><label>Sub-Category</label></td><td><label>Brand</label></td><td><label>Model</label></td></tr> <tr> <td> <select id= "pro_cat" name="pro_cat" style="width: 170px;"> <option value="">---Select---</option> <?php foreach($prodcatlist as $prodcatkey){ ?> <option value="<?php echo $prodcatkey->id; ?>"><?php echo $prodcatkey->product_category; ?></option> <?php } ?> </select> <span id="or">OR</span> </td> <td> <select id= "pro_subcat" name="pro_subcat" style="width: 170px;"> <option value="">---Select---</option> <?php foreach($subcatlist as $subcatkey){ if($subcatkey->subcat_name !=null){?> <option value="<?php echo $subcatkey->id; ?>"><?php echo $subcatkey->subcat_name; ?></option> <?php }} ?> </select><span id="or">OR</span> </td> <td> <select id="brand" name="brand" style="width: 170px;"> <option value="">---Select---</option> <?php foreach($getbrands as $brandkey){ ?> <option value="<?php echo $brandkey->id; ?>"><?php echo $brandkey->brand_name; ?></option> <?php } ?> </select><span id="or">OR</span> </td> <td> <select id="model" name="model" style="width: 170px;"> <option value="">---Select---</option> <?php foreach($getmodels as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> </td> </tr> </table> <table id="table1"> <tr class="color"><td><label>Spare Name</label><span style="color:red;position: relative; left: -17px; top: 0px;">*</span></td> <td><label>Qty<span style="color:red;color: red;position: relative;left: -42px; top: -1px;">*</span></label></td> <td><label>Date of Purchase</label></td> <td><label>Price</label></td> <td><label>Invoice Ref</label></td> <td><label>Reason</label></td> </tr> <tr> <td> <select id="spare_name_0" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> </select> <div id="name_error_0" style="color:red"></div> </td> <td><input type="text" name="qty[]" id="qty_0" maxlength="10"> <div id="qty_error_0" style="color:red"></div><input type="hidden" name="spare_qty1[]" id="spare_qty1_0"><input type="hidden" name="used_spare1[]" id="used_spare1_0"><input type="hidden" name="purchase_price1[]" id="purchase_price1_0"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_0"></td> <td><input type="text" name="purchase_date[]" id="datetimepicker7" class="datetimepicker7"></td> <td><input type="text" name="purchase_price[]" id="price" maxlength="10"></td> <td><input type="text" name="invoice_no[]" id="ino" maxlength="50"></td> <td><input type="text" name="reason[]" id="reason" maxlength="100"></td> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0" > <a id="addMoreRows" class="rowadd">Add Row</a> <button class="btn cyan waves-effect waves-light rowadd" type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr><td> <select id="spare_name" class="spare_name" name="spare_name[]"><option value="">---Select---</option> </select></td><td><input type="text" name="qty[]"></td><td><input type="text" name="purchase_date[]"></td><td><input type="text" name="purchase_price[]"></td><td><input type="text" name="invoice_no[]"></td><td style="border:none;"><button class="delRowBtn" >Delete</button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js"></script> <script> $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999/19/39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('.datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); </script> <script> $(document).ready(function(){ /* $('#reason').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z .\/-_,]+$/,'') ); }); */ $('#qty_0,#price').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $('#ino').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z. ]+$/,'') ); }); $( "form" ).submit(function( event ) { if ( $( "#spare_name_0" ).val() === "" ) { $( "#name_error_0" ).text( " Please Select the Spare Name" ).show().css({'color':'#ff0000','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#qty_0" ).val() === "" ) { $( "#qty_error_0" ).text( "Please Enter the Quantity" ).show().css({'color':'#ff0000','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#spare_name_0").change(function(){ if($(this).val()==""){ $("#name_error_0").show(); } else{ $("#name_error_0").hide(); } }); $("#qty_0").keyup(function(){ if($(this).val()==""){ $("#qty_error_0").show(); } else{ $("#qty_error_0").hide(); } }); }); </script> </body> </html><file_sep>/application/models/Customer_model.php <?php class Customer_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_customer($data){ $this->db->insert('customers',$data); return $this->db->insert_id(); } public function add_city($data){ $this->db->insert('city',$data); return true; } public function add_labtech1($data8){ $this->db->insert_batch('customer_labtech',$data8); } public function add_labtech($data8){ $this->db->insert('customer_labtech',$data8); } public function add_service_location($data1){ $this->db->insert_batch('customer_service_location',$data1); } public function add_service_location1($data1){ $this->db->insert('customer_service_location',$data1); } public function add_quick_service_location($data1){ $this->db->insert('customer_service_location',$data1); } public function update_service_location($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('customer_service_location', $data1, $where); $this->db->query($qry); /* echo $this->db->last_query(); exit; */ //exit; } public function updaterelationship($e_id,$p_data) { $this->db->update('customer_labtech',$p_data,array('id'=>$e_id)); } public function customer_list(){ $this->db->select("customers.id,customers.customer_name,customers.mobile,customers.city",FALSE); $this->db->from('customers'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function check_cust($id){ $this->db->select('mobile'); $this->db->from('customers'); $this->db->where_in('mobile',$id); //$this->db->order_by('id','desc'); $query=$this->db->get(); return $query->result(); } public function get_zonearea($id){ $this->db->select("service_location.id, service_location.serv_loc_code, service_location.service_loc, service_location.concharge, service_location.zone_coverage, zone_pincodes.area_name, zone_pincodes.id as area_id",FALSE); $this->db->from('zone_pincodes'); $this->db->join('service_location', 'service_location.id = zone_pincodes.zone_code'); $this->db->where('zone_pincodes.pincode', $id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function check_custbylandln($land_ln){ $this->db->select("*",FALSE); $this->db->from('customers'); $this->db->where('land_ln', $land_ln); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function add_cust_type($data){ $this->db->insert('customer_type',$data); return true; } public function checktypename($user) { $this->db->select('type'); $this->db->from('customer_type'); $this->db->where_in('type',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function cust_type_list(){ $this->db->select("id,type,status",FALSE); $this->db->from('customer_type'); $this->db->order_by('id', 'DESC'); $query = $this->db->get(); return $query->result(); } public function service_zone_list(){ $this->db->select("id,serv_loc_code,service_loc,concharge,zone_coverage",FALSE); $this->db->from('service_location'); $this->db->order_by('service_loc', 'asc'); $query = $this->db->get(); return $query->result(); } public function pincode_list(){ $this->db->select("id,zone_code,area_name,pincode",FALSE); $this->db->from('zone_pincodes'); $this->db->order_by('zone_code', 'asc'); $query = $this->db->get(); return $query->result(); } public function cust_cnt(){ $this->db->select("id",FALSE); $this->db->from('customers'); $this->db->order_by('id', 'desc'); $this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function cust_service_loc_cnt(){ $this->db->select("id",FALSE); $this->db->from('customer_service_location'); $this->db->order_by('id', 'desc'); $this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function state_list(){ $this->db->select("id,state",FALSE); $this->db->from('state'); $this->db->order_by('state', 'asc'); //$this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function get_cities($id){ $this->db->distinct(); $this->db->select("city",FALSE); $this->db->from('city'); $this->db->like('city', $id, 'after'); //$this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function getcustomerbyid($id){ $query=$this->db->get_where('customers',array('id'=>$id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_states($id){ $query=$this->db->get_where('state',array('id'=>$id)); return $query->result(); } public function getcustomertypebyid($id){ $query=$this->db->get_where('customer_type',array('id'=>$id)); return $query->result(); } public function getcustomertypebyid1($id) { $query=$this->db->get_where('tax_details',array('id'=>$id)); return $query->result(); } /*public function getlablistbyid($id){ $this->db->select('lab_tech.lab_name,lab_tech.id,customer_labtech.customer_id,customer_labtech.lab_value,customer_labtech.id as cutslab,customer_labtech.lab_name as custlabname'); $this->db->from('customer_labtech'); $this->db->join('lab_tech','lab_tech.id=customer_labtech.lab_name'); $query=$this->db->get(); return $query->result(); }*/ public function getlablistbyid($id){ $this->db->select('lab_tech.lab_name,lab_tech.id,customer_labtech.customer_id,customer_labtech.lab_value,customer_labtech.id as cutslab'); $this->db->from('customer_labtech'); $this->db->join('lab_tech','lab_tech.id=customer_labtech.lab_name'); $this->db->where('customer_labtech.customer_id',$id); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getlabbyid($id){ //echo $id; //$this->db->select('lab_tech.lab_name,lab_tech.id,customer_labtech.customer_id,customer_labtech.lab_value as lvalue,customer_labtech.id as cutslab,customer_labtech.lab_name as custlabname'); $this->db->select('*'); $this->db->from('customer_labtech'); $this->db->where('customer_id',$id); //$this->db->join('lab_tech','lab_tech.id=customer_labtech.lab_name'); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } function delete_brand_status($currentElemID) { $this->db->where_in('id',$currentElemID); return $this->db->delete('customer_labtech'); } public function labss_list() { $this->db->select('*'); $this->db->from('lab_tech'); $this->db->order_by('id','desc'); $query=$this->db->get(); return $query->result(); } public function getcustservicelocationbyid($id){ $query1=$this->db->get_where('customer_service_location',array('customer_id'=>$id)); return $query1->result(); } public function update_customer($data,$id){ $this->db->where('id',$id); $this->db->update('customers',$data); } public function update_customer_service_loc($data,$id,$ser_loc_id){ //echo $ids;echo "<pre>";print_r($data);exit; $this->db->where('id',$ser_loc_id); $this->db->where('customer_id',$id); $this->db->update('customer_service_location',$data); } public function update_customer_type($data,$id){ $this->db->where('id',$id); $this->db->update('customer_type',$data); } public function delete_customer_service_loc($id,$data){ $this->db->where('customer_id',$id); //$this->db->delete('customer_service_location'); $this->db->update('customer_service_location',$data); } public function del_customers($id,$data){ $this->db->where('id',$id); //$this->db->delete('customers'); $this->db->update('customers',$data); } public function del_customer_type($id){ $this->db->where('id',$id); $this->db->delete('customer_type'); } public function custtype_validation($product_id) { //echo $product_id; echo("aaaaaaaa"); exit; $query = $this->db->get_where('customer_type', array('type' => $product_id)); return $numrow = $query->num_rows(); } public function custtype_validation1($product_id) { //echo $product_id; echo("aaaaaaaa"); exit; $query = $this->db->get_where('customer_type', array('type' => $product_id)); return $numrow = $query->num_rows(); } public function update_status_customer($data,$id){ print_r($data); print_r($id); $this->db->where('id',$id); $this->db->update('customer_type',$data); } public function update_status_customer1($data,$id){ //print_r($data); $this->db->where('id',$id); $this->db->update('customer_type',$data); } public function getcustomersalesbyid($idd) { $this->db->select('orders.order_id,orders.customer_id,order_details.order_id as cutsorder ,order_details.amc_start_date,order_details.cmc_start_date,order_details.rent_type,order_details.warranty_date,order_details.serial_no,order_details.model_id,order_details.purchase_date,products .model'); $this->db->from('orders'); $this->db->join('order_details','order_details.order_id =orders.id'); $this->db->join('products','products.id =order_details.model_id'); $this->db->where('orders.customer_id',$idd); $query=$this->db->get(); //echo $this->db->last_query(); //exit; return $query->result(); } public function category_validation1($prob_cat_name,$model) { $query = $this->db->get_where('customer_type', array('type' => $product_id)); return $numrow = $query->num_rows(); //echo "<pre>";print_r($query->result());exit;1 } public function delete_custlocation_details($result){ $this->db->where_in('id',$result); $this->db->delete('customer_service_location'); } public function add_noperday_history($datas){ $this->db->insert('customer_noperday_history',$datas); return true; } }<file_sep>/application/views_bkMarch_0817/view_claim.php <?php tcpdf(); $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $obj_pdf->SetCreator(PDF_CREATOR); $title = "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 aaaa"; $obj_pdf->SetTitle($title); $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING); $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $obj_pdf->SetDefaultMonospacedFont('helvetica'); $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $obj_pdf->SetFont('helvetica', '', 9); $obj_pdf->setFontSubsetting(false); $obj_pdf->AddPage(); $content= '<style> table { border-collapse: collapse; } table, th, td { border: 1px solid black; } table,td{ height:30px; } </style> <html> <body> <section id="content"> <div class="container"> <div class="col-md-12"> <table align="center" style="background: #fff; border-radius: 5px 5px 5px 5px; border: 1px solid #ccc;"> <tr> <td> <TABLE class="tp01" cellpadding="0" cellspacing="0" border="0"> <TR> <TD colspan="1"><img src="<?php echo base_url(); ?>assets/images/stagologo.png" alt="materialize logo" ></td> <TD colspan="1" style="text-align:center;"><h2>WARRANTY CLAIM</h2><p>Demande de Garantie</p></td> <TD colspan="1"><p>SUBMIT TO / renvoyer a :</p> <p ><b style="color:red;">DIAGNOSTICA STAGO - SAVE</b> - B.P.226</p> <p>92602 ASNIERES CEDEX - FRANCE</p> <p>FAX : (33)(0) 1 46 88 22 400px</p> <p>@: <EMAIL></p> </td> </tr> <TR> <TD colspan="1"><p><b>TYPE OF INSTRUMENT:</b>'.$model.'</p> <p>Type dinstrument</p> </td> <TD colspan="1"><p><b>SERIAL No:</b> '.$serial_no.'</p> <p>&#8457;N de serie</p> </td> <TD colspan="1"><p><b>DATE OF INSTALLATION (YY MM DD):</b></p> <p>Date dinstallation (AA MM JJ)'.$purchase_date.'</p></td> </tr> </table> </table> </div> </div> </section> </body> </html>'; ob_end_clean(); $obj_pdf->writeHTML($content, true, false, true, false, ''); //$obj_pdf->Output('ssss.pdf', 'I'); $obj_pdf->Output('service/assets/'.$serial_no.'.pdf', 'F'); ?><file_sep>/application/views/problemaddrow.php <?php $count=$_POST['countid']; ?> <tr> </tr> <tr> <td> <input type="text" name="prob_code[]" id="prob_code<?php echo $count;?>" onchange="" class="prob_cate" maxlength="50"> <div id="prob_code_error<?php echo $count;?>" style="color:red"></div> <div id="name_error<?php echo $count; ?>" style="color:red"></div> </td> <td> <select name="model[]" id="model<?php echo $count;?>"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="model_error<?php echo $count;?>" style="color:red;" ></div> </td> <td> <input type="text" name="prob_cat_name[]" id="prob_cat_name<?php echo $count;?>" maxlength="50"> <div id="prob_cat_name_error<?php echo $count;?>" style="color:red"></div> </td> <td> <textarea name="p_description[]" id="p_description<?php echo $count;?>" value=""/></textarea> </td> <td> <a class="delRowBtn btn btn-primary"><i class="fa fa-trash"></i></a> </td> </tr> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <style> .delRowBtn{ position: relative; top: 0px; } </style> <script> $(document).ready(function(){ //alert("hiii"); //$('#prob_cat_name<?php echo $count;?>').change(function(){ $(document).on("keyup","#prob_cat_name<?php echo $count;?>", function(){ var timer; clearTimeout(timer); timer = setTimeout(mobile, 3000); }); //alert(brand); function mobile(){ var prob_code=$('#prob_cat_name<?php echo $count;?>').val(); var model=$('#model<?php echo $count;?>').val(); //alert(prob_code); var datastring='code='+model+'&problem='+prob_code; //alert(datastring); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkproblem", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ //alert("hiii"); $('#prob_cat_name_error<?php echo $count;?>').html('Problem Category Name Already Exist!').show().css({'color':'#ff0000','font-size':'10px'}); $('#prob_cat_name<?php echo $count;?>').val(''); } else { $('#prob_cat_name_error<?php echo $count;?>').hide(); } } }); } }); </script> <script> $(function(){ $("#product").click(function(event) { //alert('dfgdfgdf'); var aaa = $("#prob_cat_name<?php echo $count; ?>").val(); if ( $("#prob_cat_name<?php echo $count; ?>").val() === "" ) { $("#prob_cat_name_error<?php echo $count; ?>").text( "Enter the Problem Category Name" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ($("#model<?php echo $count; ?>").val() === "" ) { $("#model_error<?php echo $count; ?>").text( "Please choose the model" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ($("#prob_code<?php echo $count; ?>").val() === "" ) { $("#prob_code_error<?php echo $count; ?>").text( "Enter the Problem Category Code" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(function(){ $("#prob_cat_name<?php echo $count; ?>").change(function(){ if($(this).val()==""){ $("#prob_cat_name_error<?php echo $count; ?>").show(); } else{ $("#prob_cat_name_error<?php echo $count; ?>").hide(); } }); $("#model<?php echo $count; ?>").change(function(){ var aaa = $(this).val(); if($(this).val()==""){ $("#model_error<?php echo $count; ?>").show(); } else{ $("#model_error<?php echo $count; ?>").hide(); } }); $("#prob_code<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#prob_code_error<?php echo $count; ?>").show(); } else{ $("#prob_code_error<?php echo $count; ?>").hide(); } }); $("#prob_code<?php echo $count; ?>,#prob_cat_name<?php echo $count; ?>").bind("keyup blur", function(){ $(this).val( $(this).val().replace(/[^A-Za-z0-9 ]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $('#prob_code<?php echo $count; ?>').change(function(){ var prob_code=$(this).val(); var datastring='code='+prob_code; $.ajax({ type:"POST", url:"<?php echo base_url(); ?>problemcategory/checkCode", data:datastring, cache:false, success:function(data){ //alert(data); if(data >0){ $('#name_error<?php echo $count; ?>').html('Problem Code already Exist!').show().css({'color':'#ff0000','font-size':'10px'}); $('#prob_code<?php echo $count; ?>').val(''); } else if(data==0) { $('#name_error<?php echo $count; ?>').hide(); } } }); }); }); </script> <!--<div class="col-md-12"> <div class="col-md-3"> <input type="text" name="prob_code[]" id="prob_code<?php echo $count;?>" onchange="" class="prob_cate form-control" > <div id="prob_code_error<?php echo $count;?>" style="color:red"></div> <div id="name_error<?php echo $count; ?>" style="color:red"></div> </div> <div class="col-md-3"> <input type="text" name="prob_cat_name[]" id="prob_cat_name<?php echo $count;?>" class="form-control"> <div id="prob_cat_name_error<?php echo $count;?>" style="color:red"></div> </div> <div class="col-md-3"> <select name="model[]" id="model<?php echo $count;?>" class="form-control"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="model_error<?php echo $count;?>" style="color:red;" ></div> </div> <div class="col-md-3"> <textarea name="p_description[]" id="p_description<?php echo $count;?>" value=""/></textarea> </div> <a class="delRowBtn btn btn-primary" style="float: right; top: -46px; left: 30px;"><i class="fa fa-trash"></i></a> </div>--> <!--<div class="col-md-12" style="padding:0px"> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Code</label> <input type="text" name="prob_code[]" id="prob_code<?php echo $count;?>" class="prob_cate"> <div id="prob_code_error<?php echo $count;?>" style="color:red"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Category Name</label> <input type="text" name="prob_cat_name[]" id="prob_cat_name<?php echo $count;?>"> <div id="prob_cat_name_error<?php echo $count;?>" style="color:red"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Model</label> <select name="model[]" id="model<?php echo $count;?>"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> <div id="model_error<?php echo $count;?>" style="color:red;"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Description</label> <textarea name="p_description[]" id="p_description<?php echo $count;?>" value="" /></textarea> </div> <div class="col-md-3"> <a class="delRowBtn btn btn-primary"><i class="fa fa-trash"></i></a> </div> </div>--> <file_sep>/application/views_bkMarch_0817/templates/header - renew on 25-01-2017.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo base_url(); ?>assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link href="<?php echo base_url(); ?>assets/js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/AdminLTE.min.css"> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addrow.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addtable.js'></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <link href="<?php echo base_url(); ?>assets/css/print.css" type="text/css" rel="stylesheet" media="print" /> <style> .btn-box-tool:active { background-color: rgb(5, 94, 135); } .side-nav.fixed a { display: block; padding: 0px 2px 0px 1px !important; color: #055E87; } .side-nav li ul li a { margin: 0px 1rem 0px 0rem !important; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready( function() { // initialize accordion $('.Accordion ul').each( function() { var currentURI = window.location.href; var links = $('a', this); var collapse = true; for (var i = 0; i < links.size(); i++) { var elem = links.eq(i); var href = elem.attr('href'); var hrefLength = href.length; var compareTo = currentURI.substr(-1*hrefLength); if (href == compareTo) { collapse = false; break; } }; if (collapse) { $(this).hide(); } }); $(".Accordion").delegate('span', 'click', function() { var ul = $(this).next('ul'); if (ul.is(':visible')) { ul.slideUp(500); } else { $('.Accordion ul').not(ul).slideUp(500); ul.slideDown(500); } }); }); </script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $('.Accordion').on('click', 'li a', function(){ $('.Accordion li a').removeClass('active'); $(this).addClass('active'); }); });//]]> </script> </head> <body> <!--<div id="loader-wrapper"> <!-- <div id="loader"></div> --> <!-- <div class="loader-section section-left"></div> <div class="loader-section section-right"></div> </div>--> <header id="header" class="page-topbar"> <div class="navbar-fixed"> <nav class="cyan"> <div class="nav-wrapper"> <ul class="left"> <li><h1 class="logo-wrapper"><?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type!='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <img src="<?php echo base_url(); ?>assets/images/srs.png" alt="materialize logo" style="width:230px;height:50px"> </a> <?php } }?> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type=='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <!--<img src="<?php echo base_url(); ?>assets/images/logoservice1.png" alt="materialize logo"><img src="<?php echo base_url(); ?>assets/images/maxsell-logo1.png" alt="materialize logo">--> <img src="<?php echo base_url(); ?>assets/images/srs.png" alt="materialize logo" style="width:230px;height:50px"> </a> <?php } }?> </h1></li> </ul> <ul class="right hide-on-med-and-down"> <li><a href="javascript:void(0);" class="waves-effect waves-block waves-light toggle-fullscreen"> <i class="fa fa-arrows-alt"></i> </a> </li> <li><a href="<?php echo base_url(); ?>login/logout" class="waves-effect waves-block waves-light"><?php //foreach($user_dat As $Ses_key){echo "Welcome: ".$Ses_key->name; } ?> Logout</a> </li> </ul> </div> </nav> </div> </header> <div id="main"> <div class="wrapper"> <style> .fa { font-size:21px !important; } .fa-user { font-size: 2.4rem !important; padding-left: 3px; } #slide-out li a i { padding-left: 7px; } .fa-arrow-right { font-size:14px !important; } .toggle-fullscreen:hover { color:white !important; } .toggle-fullscreen:focus { color:white !important; } .Accordion li.active a { color:black; } @media only screen and (max-width: 992px){ .hide-on-med-and-down { display: block !important; } header .brand-logo img { width: 172px !important; position: relative; right: 75px; bottom: 8px; } .waves-effect { position: relative; left: 0px; } .sidebar-collapse { position: absolute; left: -170px; top: -70px; } } @media only screen and (min-width: 301px){ nav, nav .nav-wrapper i, nav a.button-collapse, nav a.button-collapse i { height: 64px !important; line-height: 64px !important; } } </style> <script type="text/javascript"> $(function(){ $('.Accordion a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active') // $('.hhhh a').click(function(){ // $(this).parent().addClass('active').siblings().removeClass('active') //}) }) </script> <aside id="left-sidebar-nav"> <br/> <ul id="slide-out" class="side-nav fixed leftside-navigation Accordion"> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type!='7'){ ?> <li ><a href="<?php echo base_url(); ?>pages/dash" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">dashboard</i> Dashboard</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='3' || $Ses_key1->user_type=='6'){ ?> <li><span><i class="fa fa-user"></i> Customers <i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer List</a></li> <li><a href="<?php echo base_url(); ?>pages/add_cust"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add Customer</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li ><span><i class="material-icons">shopping_basket</i> Product<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Product List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add Product</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li ><span><i class="material-icons">supervisor_account</i>Employee<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/emp_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Employee List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_emp"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Employee</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url(); ?>pages/comp_list" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">store</i> Company Details</a> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='3' || $Ses_key1->user_type=='5'){ ?> <li ><span><i class="material-icons">shopping_basket</i> Sales Details <i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/order_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i> Sales List</a> </li> <li><a href="<?php echo base_url(); ?>pages/amc_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i> AMC List</a> </li> <li><a href="<?php echo base_url(); ?>pages/expiry_closed"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Chargeables</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Sales</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='6'){ ?> <li ><span><i class="material-icons">assignment</i>Service<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/add_service_req"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Request</a> </li> <li><a href="<?php echo base_url(); ?>pages/service_req_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>All Request</a> </li> <li><a href="<?php echo base_url(); ?>pages/quote_in_progress_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Quote In-progress</a> </li> <!--<li><a href="<?php echo base_url(); ?>pages/quote_review"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Quote Review</a> </li>--> <li><a href="<?php echo base_url(); ?>pages/quote_approved"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Awaiting Approvals</a> </li> <li><a href="<?php echo base_url(); ?>pages/workin_prog_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Work InProgress</a> </li> <li><a href="<?php echo base_url(); ?>pages/comp_engg_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Completed by Engg</a> </li> <li><a href="<?php echo base_url(); ?>pages/quality_check_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>QC</a> </li> <li><a href="<?php echo base_url(); ?>pages/ready_delivery_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Ready - Delivery</a> </li> <li><a href="<?php echo base_url(); ?>pages/delivered_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Delivered / Invoices</a> </li> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url(); ?>pages/add_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Sales</a> </li> <?php }}?> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li ><span><i class="material-icons">new_releases</i>Spares<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/add_spare"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Master</a> </li> <li><a href="<?php echo base_url(); ?>pages/spare_stock"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Stock</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_new_stock"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Spare</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_spare_engineers"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare to Engrs</a> </li> <li><a href="<?php echo base_url(); ?>pages/sparereceipt"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Receipt List</a> </li> <li><a href="<?php echo base_url(); ?>pages/spare_purchase_order"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Create purchase order</a> </li> <li><a href="<?php echo base_url(); ?>pages/purchase_orders"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Purchase orders</a> </li> <li><a href="<?php echo base_url(); ?>pages/min_spare_alerts"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Min spare alerts</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li ><span><i class="material-icons">new_releases</i> Expiring Product<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Expiring Contracts</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <!--<li><span><i class="fa fa-cogs"></i> Product Service Status<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_service_stat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Status List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_service_stat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Status</a> </li> </ul> </li>--> <li><span><i class="fa fa-folder-open"></i> Product Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Category List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Category</a> </li> </ul> </li> <li><span><i class="fa fa-indent"></i> Sub-Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_subcat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SubCategory List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prod_subcat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New SubCategory</a> </li> </ul> </li> <li ><span><i class="fa fa-chrome"></i> Product Brand<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/brandList"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Brand List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_brand"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Brand</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Service Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/service_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service category List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Service category</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_charge"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Service Charge</a> </li> <li><a href="<?php echo base_url(); ?>pages/service_charge_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service charge List</a> </li> </ul> </li> <li ><span><i class="fa fa-map"></i>Service Zone<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/service_loc_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Zone List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_service_loc"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Zone</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Problem Category<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/prob_cat_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Problem List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_prob_cat"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Problem</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Tax<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/tax_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Tax List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_tax"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Tax</a> </li> </ul> </li> <li ><span><i class="fa fa-cog"></i> Customer Type<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_type_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer Type List</a> </li> <li><a href="<?php echo base_url(); ?>pages/cust_type"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>New Customer Type</a> </li> </ul> </li> <li ><a href="<?php echo base_url(); ?>pages/accessories_list" class="waves-effect waves-cyan"><i class="material-icons" style="margin-right: 1rem;">store</i> Accessories</a> </li> <li><span><i class="material-icons">people</i> Users<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <li><a href="<?php echo base_url(); ?>pages/user_cate_list"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>User List</a> </li> <li><a href="<?php echo base_url(); ?>pages/add_user_cate"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Add User</a> </li> </ul> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2' || $Ses_key1->user_type=='5' || $Ses_key1->user_type=='6' || $Ses_key1->user_type=='4'){ ?> <li><span><i class="fa fa-cog"></i> Reports<i class="fa fa-angle-down"style="float: right; width: 5px;font-size: 19px;"></i></span> <ul> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/revenuereport" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url();?>pages/report_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Revenue Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/engineer_servicereport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Engineers Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/customerreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Customer Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/service_mach_report" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Service Machines Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='2'){ ?> <li><a href="<?php echo base_url(); ?>pages/expiry_list1"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Warranty Expired Reports</a> </li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1'){ ?> <li><a href="<?php echo base_url();?>pages/agingreport" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Aging Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparereport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/engineerreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Spare to Engineer Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparepurchase_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SparePurchase Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='4'){ ?> <li><a href="<?php echo base_url();?>pages/sparecharge_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>SpareCharge Report</a></li> <?php }}?> <?php foreach($user_dat As $Ses_key1){ if($Ses_key1->user_type=='1' || $Ses_key1->user_type=='6'){ ?> <li><a href="<?php echo base_url();?>pages/stampingreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>StampingReport1</a></li> <li><a href="<?php echo base_url();?>pages/monthlyreport_list" class="waves-effect waves-cyan"><i class="fa fa-arrow-right" style="font-size: 14px;"></i>Stamping Monthly</a></li> <?php }}?> </ul> </li> <?php }}?> </ul> <a href="#" data-activates="slide-out" class="sidebar-collapse btn-floating btn-medium waves-effect waves-light hide-on-large-only cyan"><i class="fa fa-bars"></i></a> </aside><file_sep>/application/models/Cron_model.php <?php class Cron_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function get_report($y,$m) { $query = $this->db->query("select customers.customer_name, customers.company_name,customer_service_location.address, customer_service_location.address1, customer_service_location.city,customer_service_location.mobile, customer_service_location.email_id, customer_type.type as customertype,loc.service_loc from customers as customers left join customer_type as customer_type on customer_type.id=customers.customer_type left join customer_service_location as customer_service_location on customer_service_location.customer_id=customers.id left join service_location as loc on loc.id=customers.service_zone WHERE YEAR(customers.created_on) = $y AND MONTH(customers.created_on) = $m"); return $query->result_array(); } public function get_servicereport($y1,$m1) { $query= $this->db->query("select service_request.request_id, service_request.request_date,products.model,customers.company_name,customer_service_location.branch_name,customer_service_location.address, customer_service_location.mobile, quote_review.labourcharge,quote_review.concharge,employee.emp_name,status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = service_request_details.zone left join employee as employee on employee.id = service_request_details.assign_to left join status as status on status.id = service_request.status left join quote_review as quote_review on quote_review.req_id = service_request.id WHERE YEAR(service_request.request_date) = $y1 AND MONTH(service_request.request_date) = $m1"); //echo "<pre>";print_r($query->result());exit; return $query->result_array(); } public function get_revenuereport($y,$m) { $query= $this->db->query("select service_request.request_id,service_request.request_date,products.model,customers.company_name, customer_service_location.branch_name,customer_service_location.address, customer_service_location.mobile, quote_review.labourcharge, quote_review.concharge,employee.emp_name,status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage,quote_review.spare_tax, quote_review.spare_tot from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = service_request_details.zone left join employee as employee on employee.id = service_request_details.assign_to left join status as status on status.id = service_request.status left join quote_review as quote_review on quote_review.req_id = service_request.id WHERE YEAR(service_request.request_date) = $y AND MONTH(service_request.request_date) = $m"); //echo "<pre>";print_r($query->result());exit; return $query->result_array(); } public function get_serialreport($y,$m) { $query = $this->db->query("select group_concat(distinct(det.request_id),'//',service_request.request_date) as ser,order_details.purchase_date,products.model,customers.customer_name,det.serial_no from order_details left join service_request_details as det on det.serial_no = order_details.serial_no left join service_request on service_request.id = det.request_id left join products on products.id = det.model_id left join brands on brands.id = det.brand_id left join customers on customers.id = service_request.cust_name left join service_location on serv_loc_code = det.zone left join service_category on service_category.id = det.service_cat left join problem_category on problem_category.id = det.problem WHERE YEAR(order_details.purchase_date) = $y AND MONTH(order_details.purchase_date) = $m group by order_details.serial_no"); //echo "<pre>";print_r($query->result());exit; return $query->result_array(); } public function get_sparereport($y,$m) { $query=$this->db->query("select spares.spare_name,group_concat(distinct(emp.emp_name),'//',customers.customer_name,'//',products.model,'//', service_request.id) as serv_request,qurew.desc_failure from spares left join quote_review_spare_details as qurew on qurew.spare_id = spares.id left join service_request_details as det on det.request_id = qurew.request_id left join service_request on service_request.id=det.request_id left join employee as emp on emp.id=det.assign_to left join customers on customers.id = service_request.cust_name left join products on products.id = det.model_id WHERE YEAR(service_request.request_date) = $y AND MONTH(service_request.request_date) = $m group by spares.id"); // echo "<pre>";print_r($query->result());exit; return $query->result_array(); } } ?><file_sep>/application/views_bkMarch_0817/brands_list.php <ul id="country-list"> <?php foreach($brands_list as $key) { ?> <li onClick="selectCountry2('<?php echo $key->brand_name; ?>','<?php echo $key->id; ?>');"><?php echo $key->brand_name; ?></li> <?php } ?> </ul> <file_sep>/application/views_bkMarch_0817/add_prod_service_stat.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Add Service Status</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>prodservicestat/add_prod_service_status" method="post"> <table id="myTable" class="tableadd"> <tr> <td><label style="font-weight:bold;">Service Status Name</label></td> </tr> <tr> <td><input type="text" name="status_name[]" class="corporate"></td> </tr> </table> <a class="link" href='' onclick='$("<tr><td><input type=\"text\" name=\"status_name[]\" /></td></tr>").appendTo($("#myTable")); return false;'>Add Service</a><button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/templates/header.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo base_url(); ?>assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/font-awesome/css/ionicons.min.css"> <link href="<?php echo base_url(); ?>assets/js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/AdminLTE.min.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery-ui.css"> <link href="<?php echo base_url(); ?>assets/css/print.css" type="text/css" rel="stylesheet" media="print" /> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addrow.js'></script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addtable.js'></script> <script src="<?php echo base_url(); ?>assets/js/jquery-ui.js"></script> <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script> <style> .btn-box-tool:active { background-color: rgb(5, 94, 135); } .side-nav.fixed a { display: block; padding: 0px 2px 0px 1px !important; color: #055E87; } .side-nav li ul li a { margin: 0px 1rem 0px 0rem !important; } /*.saturate { -webkit-filter: saturate(50); filter: saturate(50); }*/ @media only screen and (min-width:240px) and (max-width:768px){ .nav{ display:none; } .navbar-toggle{ display:none; } .right{ float: none !important; position: relative !important; bottom: 0px !important; width: 134px !important; left: 60px; background: #303f9f; } .img-welcome { width: 25px; height: 25px; float: right !important; position: relative; right: 0px !important; top: 2px; /* border: 1px solid #ccc; */ } ol, ul { margin-top: 0; margin-bottom: -24px !important; } } .bg-aqua, .callout.callout-info, .alert-info, .label-info, .modal-info .modal-body { background-color: #3e0963 !important; } .box-title{ color:#6C217E; } /*header, footer { color: white; background: #DBD0E1 !important; background-image: url(background.png); box-shadow: 0 0 10px rgba(0, 0, 0, 0.51); } */ /* Mega Menu New */ .nav, .nav a, .nav ul, .nav li, .nav div, .nav form, .nav input { margin: 0; padding: 0; border: none; outline: none; } .nav a { text-decoration: none; } .nav li { list-style: none; } .nav { display: inline-block; position: relative; cursor: default; z-index: 500; left:80px; background: transparent; } .nav > li { display: block; float: left; } .nav > li > a { position: relative; display: block; z-index: 510; height: 54px; padding: 0 20px !important; line-height: 54px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; font-stretch: ultra-expanded; color: #ffffff;/*#522276*/ text-shadow: 0 0 1px rgba(0,0,0,.35); /*background: #303f9f; border-left: 1px solid #303f9f; border-right: 1px solid #303f9f;*/ -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li:hover > a { /*background: #303f9f;*/ } .nav > li:first-child > a { border-radius: 3px 0 0 3px; border-left: none; } .nav > li.nav-search > form { position: relative; width: inherit; height: 54px; z-index: 510; border-left: 1px solid #4b4441; } .nav > li.nav-search input[type="text"] { display: block; float: left; width: 1px; height: 24px; padding: 15px 0; line-height: 24px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #999999; text-shadow: 0 0 1px rgba(0,0,0,.35); background: #372f2b; -webkit-transition: all .3s ease 1s; -moz-transition: all .3s ease 1s; -o-transition: all .3s ease 1s; -ms-transition: all .3s ease 1s; transition: all .3s ease 1s; } .nav > li.nav-search input[type="text"]:focus { color: #fcfcfc; } .nav > li.nav-search input[type="text"]:focus, .nav > li.nav-search:hover input[type="text"] { width: 110px; padding: 15px 20px; -webkit-transition: all .3s ease .1s; -moz-transition: all .3s ease .1s; -o-transition: all .3s ease .1s; -ms-transition: all .3s ease .1s; transition: all .3s ease .1s; } .nav > li.nav-search input[type="submit"] { display: block; float: left; width: 20px; height: 54px; padding: 0 25px; cursor: pointer; background: #372f2b url(../img/search-icon.png) no-repeat center center; border-radius: 0 3px 3px 0; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li.nav-search input[type="submit"]:hover { background-color: #4b4441; } .nav > li > div#sales { position: fixed; display: block; width: auto; top: 54px; left: 270px; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div#sales { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div#sales:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div#sales:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav > li > div#service { position: fixed; display: block; width: auto; top: 54px; left: 365px; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div#service { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div#service:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div#service:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav > li > div#spare { position: fixed; display: block; width: auto; top: 54px; left: 465px; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div#spare { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div#spare:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li:hover > div#spare:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div#spare:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav > li:hover > div#spare:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav > li > div#master { position: fixed; display: block; width: auto; top: 54px; left: 560px; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div#master { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div#master:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div#master:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav > li > div#reports { position: fixed; display: block; width: auto; top: 54px; left: 650px; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div#reports { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div#reports:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div#reports:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav .nav-column { float: left; width: auto; padding: 0px 5px; } .nav .nav-column h3 { margin: 20px 0 10px 0; line-height: 18px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #6C217E; text-transform: uppercase; } .nav .nav-column h3.orange { color: #ff722b; } .nav .nav-column li a { display: block; line-height: 26px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 12px; color: #888888; text-decoration:none; } .nav .nav-column li a:hover { color: #666666; } .nav>li>a:hover, .nav>li>a:visited .nav>li>a:active, .nav>li>a:focus { color: #522276; background: #DBD0E1; z-index:1; } .divider{ background-color: #967d58 !important; } .right { float: right !important; position: relative !important; right: 0px !important; top: -50px; background: transparent; } .right li > div a{ color:#522276; font-size:1em; } .waves-block { display: block; color: #522276; } .waves-light{ font-size:13px; font-weight:bold; } .right li > a i.fa-sign-out{ font-size:16px !important; } .fa-arrows-alt{ margin-right:10px; } a.waves-light:hover, a.waves-light:active, a.waves-light:focus { color: #fff !important; } header{ padding:0 !important; height:55px; } .navbar-header { float: left; width: 223px !important; } .navbar-nav>li>a { padding-top: 10px; padding-bottom: 10px; line-height: 54px !important; } .btn-primary { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } .btn-primary:hover { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } .btn-primary:focus { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } /* Responsive Menu Style */ .navbar-toggle { position: relative; float: right; padding: 9px 10px; /* margin-top: 8px; */ margin-right: 15px; margin-bottom: 8px; background-color: transparent; background-image: none; border: 1px solid transparent; border-radius: 4px; position: relative; bottom: 40px; } .navbar-toggle .icon-bar { display: block; width: 22px; height: 2px; border-radius: 1px; border:solid #fff; } .in .nav{ left: 0px; position: relative; width: 415px; } .in .nav li{ float: none; position: inherit; border-bottom: 1px solid #ccc; } .collapse.in { display: block; position: relative; z-index: 11; bottom: 50px; background: #fff; padding-left: 0px; height:auto; } .in .nav > li > div{ z-index: 1111; width: 250px; } .in .nav .nav-column{ float: none; width: 70%; padding: 0px 1.5%; } .in .nav .nav-column > ul{ width: 244px; } .in .nav .nav-column > ul >li{ border-bottom:none; } .in .nav .nav-column .divider{ width:244px; } .in ul.right{ float: none !important; position: relative !important; bottom: 0px !important; width: 413px; left: 0px; background: #303f9f; } .img-welcome{ width:20px; height:20px; float:right; position:relative; left:22px; /*border:1px solid #ccc;*/ } .in .right .img-welcome{ width:25px; height:25px; position:relative; left: -260px; bottom: 0px; /*border:1px solid #ccc;*/ } .fa { font-size:21px !important; } .fa-user { font-size: 2.4rem !important; padding-left: 3px; } #slide-out li a i { padding-left: 7px; } .fa-arrow-right { font-size:14px !important; } .coloricon{ background-image:url("<?php echo base_url(); ?>assets/images/icon.png"); height:25px; width:25px; background-repeat: no-repeat; background-size: cover; background-color: transparent; /*position:relative; left:1298px;*/ position: relative; top: 20px; } .theme { height:25px; width:25px; background-repeat: no-repeat; background-size: cover; background-color: transparent; /*position:relative; left:1298px;*/ position: relative; top: 20px; } .coloricon:hover { background-color: transparent !important; box-shadow: none !important; } /*.coloricon:active { background-color: transparent !important; box-shadow: none !important; }*/ .coloricon:focus { background-color: transparent !important; box-shadow: none !important; } .color-picker { background: rgba(255, 255, 255, 0.75); /* padding: 10px; */ border: 1px solid rgba(203, 203, 203, 0.6); border-radius: 2px; position: absolute; width: 160px; right: 95px; top: 50px; /*bottom: 510px;*/ } .picker-wrapper { padding: 0px !important; } .color-picker > div { width: 15px !important; display: inline-block; height: 15px !important; margin: 2px !important; border-radius: inherit !important; opacity: 0.7; } .color-picker > div:before { content: ""; border-left: 17px solid #fff; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -13px; z-index: 1001; } .wrapper { min-height: 100%; position: static; overflow: inherit; } .color-picker > div:after { content: ""; border-left: 17px solid #ccc; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -15px; z-index: 800; } .btn-box-tool { padding: 5px; font-size: 12px; background: transparent; color: #000 !important; font-weight:bold; } .toggle-fullscreen:hover { color:white !important; text-decoration:none; } .toggle-fullscreen:focus { color:white !important; text-decoration:none; } .Accordion li.active a { color:black; } @media only screen and (max-width: 992px){ .hide-on-med-and-down { display: block !important; } /*header .brand-logo img { width: 172px !important; position: relative; right: 75px; bottom: 8px; }*/ .waves-effect { position: relative; left: 0px; } .sidebar-collapse { position: absolute; left: -170px; top: -70px; } } @media only screen and (min-width: 301px){ nav, nav .nav-wrapper i, nav a.button-collapse, nav a.button-collapse i { height: 64px !important; line-height: 64px !important; } } .hide-on-med-and-down li { display: -webkit-inline-box; } .dropdown-menu>li>a { color: #111;/*#522276*/ background: #ffffff;/*#f8efff*/ margin: 2px 0px; padding: 5px 20px; } .dropdown-menu>li>a:hover { /*background-color: #dbd0e1;*/ color: #336499 !important; } .btn-primary.active, .btn-primary.focus, .btn-primary:active, .btn-primary:focus, .btn-primary:hover, .open>.dropdown-toggle.btn-primary { color: #ffffff;/*#522276*/ background-color: #111;/*#dbd0e1*/ border-color: #333;/*#522276*/ } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 168px; padding: 0px 0; margin: 2px 0 0; font-size: 14px; text-align: left; list-style: none; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid #333;/*#522276*/ /*border: 1px solid rgba(0,0,0,.15);*/ border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); box-shadow: 0 6px 12px rgba(0,0,0,.175); } </style> <style> #header, thead { /*background: #336499;#dbd0e1*/ background: #4971d6;/*#dbd0e1*/ box-shadow: 0 0 10px #444; } h2 { color: #dbd0e1; } </style> </head> <body> <header id="header" class="page-topbar"> <div class="navbar-header"> <a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1" style="color:#FFFFFF">Fish Bills <!--<img src="<?php echo base_url(); ?>assets/images/logo.png" alt="materialize logo" style="height: 45px;color:#fff;float:left;position:relative;left:30px;margin: 5px;" class="saturate">--> </a> </div> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".js-navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse js-navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="<?php echo base_url(); ?>pages/dash">Home</a></li> <li><a href="<?php echo base_url(); ?>pages/bills">Bills</a></li> <li><a href="<?php echo base_url(); ?>pages/cust_list">Customers</a></li> <li><a href="<?php echo base_url(); ?>pages/prod_list">Products</a></li> <li><a href="<?php echo base_url(); ?>pages/prod_cat_list">Category</a></li> <li><a href="<?php echo base_url(); ?>pages/prod_subcat_list">Sub-Category</a></li> </ul> </div> <div class="navbar-header right"> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Welcome<span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="<?php echo base_url(); ?>login/logout" class="waves-effect waves-block waves-light"><i class="fa fa-sign-out"></i> Logout</a></li> <!--<li><a href="#">JavaScript</a></li>--> </ul> </div> </div> </header> <script> $(document).ready(function() { $("#bg").change(function() { $("#header,thead").css("background",$("#bg").val()); $("h2").css("color",$("#bg").val()); }); }); </script><file_sep>/application/models/User_model.php <?php class User_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_user($data){ $this->db->insert('users',$data); return true; } public function check_username($user_name){ $this->db->select("*",FALSE); $this->db->from('users'); $this->db->where('user_name', $user_name); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_users(){ $this->db->select("*",FALSE); $this->db->from('users'); $this->db->order_by('id', 'desc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_categories(){ $this->db->select("id,product_category",FALSE); $this->db->from('prod_category'); $this->db->where('status', '0'); $this->db->order_by('product_category', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_categoriesbyid($categories_assigned){ $query = $this->db->query("select id,product_category from prod_category WHERE status='0' and id NOT IN ($categories_assigned)"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_assigned_categories($categories_assigned){ $query = $this->db->query("select id,product_category from prod_category WHERE status='0' and id IN ($categories_assigned)"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_usersbyid($id){ $this->db->select("*",FALSE); $this->db->from('users'); $this->db->where('id', $id); $this->db->order_by('id', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_employeeDetails(){ $this->db->select("*",FALSE); $this->db->from('employee'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_user($data,$user_id){ $this->db->where('id',$user_id); $this->db->update('users',$data); } public function update_user_status($data,$id){ $this->db->where('id',$id); $this->db->update('users',$data); } public function update_user_status1($data,$id){ $this->db->where('id',$id); $this->db->update('users',$data); } public function name_validation($name1) {//echo $name1;exit; $this->db->where('user_name',$name1); $this->db->from('users'); $query=$this->db->get(); //echo "<pre>";print_r($query->result());exit; return $numrow = $query->num_rows(); } }<file_sep>/application/views/zone_list.php <ul id="country-list"> <?php foreach($zone_list as $key) { ?> <li onClick="selectCountry4('<?php echo $key->service_loc; ?>','<?php echo $key->id; ?>');"><?php echo $key->service_loc; ?></li> <?php } ?> </ul> <file_sep>/application/views_bkMarch_0817/add_cust_row.php <style> input[type=text] { background-color:#fff; } </style> <div class="col-md-12" style="border:1px solid #ccc;background-color:whitesmoke;margin-bottom:8px;"> <h4><strong>Add Service Location</strong></h4><br/> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Branch Name</label> <input type="text" name="branch_name[]" class="branch_name"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Landline No</label> <input type="text" name="phone[]" id="phone" class="phone"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address</label> <input type="text" name="re_address[]" id="re_address" class="re_address"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Address 1</label> <input type="text" name="re_address1[]" id="re_address1" class="re_address1"> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>City </label> <input type="text" name="re_city[]" id="re_city" class="city"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>State</label> <input type="text" name="re_state[]" id="re_state" class="re_state"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Pincode</label> <input type="text" name="re_pincode[]" id="pin" class="re_pincode" value=""> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Service Zone</label> <select name="service_zone_loc[]" id="zone_loc"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $zoneid){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } }?> </select> </div> </div> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Area</label> <input type="text" name="area_name" class="" id="place_name"><input type="hidden" name="area_idd[]" class="" id="areacode_id"> </div> </div> <h4><strong>Add Contact</strong></h4><br> <div class="col-md-12"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Contact Name</label> <input type="text" name="contact_name[]" class="contact_name"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Designation</label> <input type="text" name="designation[]" class="designation"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Mobile</label> <input type="text" name="mobiles[]" id="mobiles" class="mobile"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Email Id</label> <input type="text" name="emails[]" class="email"> </div> </div> </div> <!--<tr> <td><label style="font-weight: bold;font-size: 14px;color: #000;line-height: 4;">Add Service Location</label></td> </tr> <tr> <td><label>Branch Name</label></td><td><input type="text" name="branch_name[]" class="branch_name"></td> <td><label>Landline No</label></td><td><input type="text" name="phone[]" id="phone" class="phone"></td> </tr> <tr> <td><label>Address</label></td><td><input type="text" name="re_address[]" id="re_address" class="re_address"></td> <td><label>Address 1</label></td><td><input type="text" name="re_address1[]" id="re_address1" class="re_address1"></td> </tr> <tr> <td><label>City </label></td><td><input type="text" name="re_city[]" id="re_city" class="city"></td><td><label>State</label></td><td><input type="text" name="re_state[]" id="re_state" class="re_state"></td> </tr> <tr> <td><label>Pincode</label></td><td><input type="text" name="re_pincode[]" id="pin" class="re_pincode" value=""></td> <td><label>Service Zone</label></td> <td> <select name="service_zone_loc[]" id="zone_loc"> <option value="">---Select---</option> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $zoneid){ ?> <option selected="selected" value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } else{?> <option value="<?php echo $zonekey->id; ?>"><?php echo $zonekey->service_loc; ?></option> <?php } }?> </select> <input type="hidden" name="service_loc_coverage[]" id="service_loc_coverage" class="contact_name" value="<?php if(isset($zone_coverage) && $zone_coverage!=""){echo $zone_coverage;} ?>"> </td> <tr> <td><label>Area</label></td><td><input type="text" name="area_name" class="" id="place_name"><input type="hidden" name="area_idd[]" class="" id="areacode_id"></td></tr> </tr> <tr><td><label style="font-weight: bold;">Add Contact</label></td><td></td></tr> <tr> <td><label>Contact Name</label></td><td><input type="text" name="contact_name[]" class="contact_name"></td><td><label>Designation</label></td><td><input type="text" name="designation[]" class="designation"></td> </tr> <tr> <td><label>Mobile</label></td><td><input type="text" name="mobiles[]" id="mobiles" class="mobile"></td> <td><label>Email Id</label></td><td><input type="text" name="emails[]" class="email"></td> </tr>--> <script> $(document).ready(function(){ $('#pin').keyup(function() { //alert("ghdg"); var id=$(this).val(); //alert(id); $("#zone_loc > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/get_zonearea", data: dataString, cache: false, success: function(data) { $('#zone_loc').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data); if(data.service_loc.length > 0){ $('#zone_loc').append("<option value='"+data.id+'-'+data.serv_loc_code+'-'+data.zone_coverage+"'>"+data.service_loc+"</option>"); } $('#place_name').val(data.area_name); $('#areacode_id').val(data.area_id); }); } }); }); }); </script> <file_sep>/application/controllers/Accessories.php <?php class accessories extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Accessories_model'); } public function add_accessories(){ $acc_name=$this->input->post('acc_name'); $c=$acc_name; $count=count($c); for($i=0; $i<$count; $i++) { if($acc_name[$i]!=""){ $data1 = array('accessory' => $acc_name[$i]); $result=$this->Accessories_model->add_accessory($data1); } } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/accessories_list';alert('Accessories Added Successfully!!!');</script>"; } } public function update_accessories_name(){ $id=$this->uri->segment(3); $data['list']=$this->Accessories_model->getaccessbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_accessories',$data); } public function update_accessories(){ $id=$this->input->post('accid'); //echo $id; $data=array( 'accessory'=>$this->input->post('acc_name') ); //print_r ($data); $s = $this->Accessories_model->update_accessory($data,$id); echo "<script>alert('Accessories Updated Successfully!!!');window.location.href='".base_url()."pages/accessories_list';</script>"; } public function del_accessories(){ $id=$this->input->post('id'); $s = $this->Accessories_model->del_accessory($id); } public function acc_validation() { $product_id = $this->input->post('p_id'); $this->output->set_content_type("application/json")->set_output(json_encode($this->Accessories_model->acc_validation($product_id))); } public function add_accsrow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_accs',$data); } }<file_sep>/application/views/edit_lab_list.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(function(){ $("#submit").click(function(event){ //alert("xcfg"); if($("#lname").val()==""){ $("#lname1").text("Enter Lab Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size': '12px'}); event.preventDefault(); } }); $("#lname").keyup(function(){ if($(this).val()==""){ $("#lname1").show(); } else{ $("#lname1").fadeOut('slow'); } }) }); </script> <script> $(document).ready(function(){ $('#lname').bind('keyup blur', function(){ //$(this).val( $(this).val().replace(/[^0-9]/g,'') ); $(this).val( $(this).val().replace(/[^0-9a-zA-Z ./-_,]+$/,'') ); }); }); </script> <script> $(document).ready(function(){ $('#lname').keyup(function(){ var name=$(this).val(); //alert(name); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>Labcategory/category_validation", data:{ id:name, }, cache:false, success:function(data){ //alert(data); if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Lab Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#lname').val(''); return false; //exit; } } }); }); }); </script> <style> input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .btn{text-transform:none !important;} </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Lab</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Labcategory/edit_lab_category" method="post"> <table id="myTable" class="tableadd"> <div class="col-md-12" style="padding: 0px"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Lab Name<span style="color:red;">*</span></label> <input type="text" name="lab_name" class="corporate" value="<?php foreach($list As $key){ echo $key->lab_name; } ?>" id="lname" maxlength="100"> <input type="hidden" name="lab_name1" class="corporate1" value="<?php foreach($list As $key){ echo $key->lab_name; } ?>" id="lname" maxlength="100"> <input type="hidden" name="labid" class="corporate" value="<?php foreach($list As $key){ echo $key->id; }?>"> <div class="fname" id="lname1" style="color:red"></div> </div> </div> <!--<tr> <td><label style="font-weight:bold;">Category Name</label></td> </tr> <tr> <td><input type="text" name="cat_name" class="corporate" value="<?php echo $key->product_category; ?>"> <input type="hidden" name="catid" class="corporate" value="<?php echo $key->id; ?>"></td> </tr>--> </table> <button class="btn cyan waves-effect waves-light " type="submit" name="action" id="submit">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/pdfreport.php <?php tcpdf(); $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $obj_pdf->SetCreator(PDF_CREATOR); $title = "AMC Quotation"; $obj_pdf->SetTitle($title); $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING); $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $obj_pdf->SetDefaultMonospacedFont('helvetica'); $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $obj_pdf->SetFont('helvetica', '', 9); $obj_pdf->setFontSubsetting(false); $obj_pdf->AddPage(); ob_start(); // we can have any view part here like HTML, PHP etc $servername = "localhost"; $username = "srscales_srscalesuser"; $password = "<PASSWORD>"; $dbname = "srscales_serviceEff"; $con = mysql_connect($servername,$username,$password); mysql_select_db($dbname,$con); $date1 = date('Y-m-d'); //echo "SELECT unix_timestamp(warranty_date) from order_details where id='52'"; $qry = mysql_query("SELECT ord.id,cust.customer_name,cust.customer_id,pro.product_name,pro.model, ordt.purchase_date,ordt.warranty_date,ordt.prev_main,ser_loc.service_loc, ( CASE WHEN ordt.warranty_date!='' THEN 'Warranty' WHEN ordt.prev_main!='' THEN 'Preventive' WHEN ordt.paid!='' THEN 'Paid' ELSE 1 END) AS machine_status FROM `order_details` As ordt inner join orders As ord ON ord.id = ordt.order_id inner join customers As cust ON cust.id = ord.customer_id inner join products As pro ON pro.id = ordt.model_id inner join service_location As ser_loc ON ser_loc.id = ordt.service_loc_id WHERE ord.id ='$orderid'"); while($res = mysql_fetch_array($qry)){ $customer_id = $res['customer_id']; $customer_name = $res['customer_name']; $model = $res['model']; $purchase_date = $res['purchase_date']; $warranty_date = $res['warranty_date']; $service_loc = $res['service_loc']; $machine_status = $res['machine_status']; } //exit; $content = '<html> <head> <title>AMC Quotation</title> </head> <body> <table> <tr> <td><b>Customer ID: </b>'.$customer_id.'</td> <td><b>Customer Name:</b>'.$customer_name.'</td> </tr> <tr> <td><b>Model:</b>'.$model.'</td> <td><b>Purchase Date:</b>'.$purchase_date.'</td> </tr> <tr> <td><b>Warranty Date:</b>'.$warranty_date.'</td> <td><b>Service Zone:</b>'.$service_loc.'</td> </tr> <tr> <td><b>Machine Status:</b>'.$machine_status.'</td> <td><b>Charge:</b>'.$charge.'</td> </tr> <tr> <td><b>AMC From Date:</b>'.$amc_frmdate.'</td> <td><b>AMC To Date:</b>'.$amc_todate.'</td> </tr> </table> </body> </html>'; ob_end_clean(); $obj_pdf->writeHTML($content, true, false, true, false, ''); $obj_pdf->Output('AMC_Quotation.pdf', 'I'); ?><file_sep>/application/views/cust_type_list.php <style> .ui-state-default { background:#6c477d; color:#fff; border: 3px solid #fff !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; } thead { border-bottom: 1px solid #d0d0d0; border: 1px solid #522276; background:#6c477d; color:#fff; font-weight:bold; font-size:12px; } /*thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; }*/ .dataTables_wrapper .dataTables_filter { float: right; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=text]{ background-color: transparent; border:none; border-radius: 7; width: 55% !important; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } input[type=text]{ background-color: transparent; border: 0px solid #522276; border-radius: 7; width: 55% !important; font-size: 12px; margin: 0 0 -2px 0; padding: 3px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height:17px; } input[type=search]{ width:55%; border:1px solid #522276; padding:0px 8px; } a { color: #522276; } a:hover { color: #9678ab; } a:focus { color: #522276; } a:active { color: #522276; } .dataTables_wrapper .dataTables_info { clear: both; float: left; padding-top: 0.755em; padding-left: 7em; } .dataTables_wrapper .dataTables_paginate { float: right; text-align: right; padding-top: 0.25em; padding-right: 6em; } body{ background-color: #fff;} </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); acc_name = $("#acc_name_"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/update_accessories', data: {'id' : id, 'acc_name' : acc_name}, dataType: "text", cache:false, success: function(data){ alert("Accessories updated"); } }); }); } function DelStatus(id){ $.ajax({ type: "POST", url: '<?php echo base_url(); ?>customer/del_cust_type', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/cust_type_list"; alert("Customer Type deleted"); } } }); } </script> <script> function InactiveStatus(id){ //alert(id); //$(function() //{ $.ajax({ type: "POST", url: '<?php echo base_url(); ?>customer/Inactive_cust_type', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("customer Inactive"); window.location = "<?php echo base_url(); ?>pages/cust_type_list"; } }); // }); } function activeStatus(id){ //alert("hiii"); //alert(id); //$(function() // { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>customer/active_cust_type', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("Customer Active"); window.location = "<?php echo base_url(); ?>pages/cust_type_list"; } }); //}); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Customer Type List</h2> <a href="<?php echo base_url(); ?>pages/cust_type"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Customer Type" style="position: relative; bottom: 27px;left: 88%;"></i></a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr> <th>S.No.</td> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Code</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><b>Customer Type</b></th> <th style="text-align:center;font-size:13px;color:##303f9f;"><B>Action</b></th> </tr> </thead> <tbody> <?php $i=1;foreach($cust_type_list as $key){ ?> <tr> <td><?php echo $i;?></td> <td><input type="text" value="<?php echo $key->id; ?>" ></td> <td><?php echo $key->type; ?><input type="hidden" value="<?php echo $key->type; ?>" class="" name="customer_type" id="customer_type_<?php echo $key->id; ?>"></td> <td class="options-width"> <a href="<?php echo base_url(); ?>customer/update_cust_list/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o" aria-hidden="true"></i> </a> <?php if($key->status!='1') { ?><a href="#" onclick="InactiveStatus('<?php echo $key->id; ?>')">Inactive</a><?php } ?><?php if($key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $key->id; ?>')">Active</a><?php } ?> </td> </tr> <?php $i++;} ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/edit_user_cate.php <style> select { border: 1px solid #ccc; margin: 0 0 15px 0; } select[multiple] { height: 200px !important; width:200px !important; } select { width:100% !important; } #errorBox{ color:#F00; } .user_type { height: 35px; border-radius: 5px; border: none; border-bottom: 1px solid #055E87; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; border-radius: 0px; margin: 0px; box-sizing: border-box; -moz-appearance: none; } .btn{text-transform:none !important;} </style> <script type="text/javascript"> //var $= jQuery.noConflict(); $(document).ready(function() { $("#user_type").change(function() { var id=$(this).val(); if(id=='3'){ //alert("sdsadsdsd"); $("#engg_name > option").remove(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Users/get_employees", data: dataString, cache: false, success: function(data) { $('#engg_name').append("<option value='0'>---Select---</option>"); $.each(data, function(index, data){//alert(data.branch_name); $('#engg_name').append("<option value='"+data.id+"'>"+data.emp_name+"</option>"); }); } }); } }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Users</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Users/update_users" method="post" onsubmit="return frmValidate()" autocomplete="off" name="frmUsers"> <!--<div id="errorBox"></div>--> <?php foreach($get_usersbyid As $user_key){ /* if(isset($user_key->categories_assigned)){ $categories_assigned = explode(",",$user_key->categories_assigned); } */ ?> <div class="col-md-12 col-sm-12"> <div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">Name&nbsp;<span style="color:red;">*</span></label> <div class="col-md-7"> <input type="text" class="form-control frstname" id="text-input" name="first_name" value="<?php echo $user_key->name; ?>" style="border: 1px solid #ccc;margin-bottom:0px;"><input type="hidden" class="form-control" id="text-input" name="user_id" value="<?php echo $user_key->id; ?>"> <div id="nameerror"></div> </div> </div> </div> <div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">User Name&nbsp;<span style="color:red;">*</span></label> <div class="col-md-7"> <input type="text" class="form-control user_name" id="text-input" name="user_name" value="<?php echo $user_key->user_name; ?>" style="border: 1px solid #ccc;margin-bottom:0px;" > <div id="usernameerror"></div> </div> </div> </div> <div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">Confirm Password&nbsp;<span style="color:red;">*</span></label> <div class="col-md-7"> <input type="password" class="form-control password" id="text-input" name="pass" value="<?php echo $user_key->password; ?>" style="border: 1px solid #ccc;margin-bottom:0px;" > <div id="passerror"></div> </div> </div> </div> </div> <div class="col-md-12 col-sm-12"> <div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">User Type&nbsp;<span style="color:red;">*</span></label> <div class="col-md-7"> <select name="user_type" class="user_type" style="border: 1px solid #ccc;" onchange="document.getElementById('usertypeerror').style.display='none'"> <option value="" >---Select---</option> <option value="1" <?php if(isset($user_key->user_type) && $user_key->user_type=='1') {?> selected="selected" <?php } ?>>Administrator</option> <option value="2" <?php if(isset($user_key->user_type) && $user_key->user_type=='2') {?> selected="selected" <?php } ?>>Service Co-ordinator</option> <option value="3" <?php if(isset($user_key->user_type) && $user_key->user_type=='3') {?> selected="selected" <?php } ?>>Accounts</option> <option value="4" <?php if(isset($user_key->user_type) && $user_key->user_type=='4') {?> selected="selected" <?php } ?>>Spares</option> <option value="5" <?php if(isset($user_key->user_type) && $user_key->user_type=='5') {?> selected="selected" <?php } ?>>Sales</option> <option value="6" <?php if(isset($user_key->user_type) && $user_key->user_type=='6') {?> selected="selected" <?php } ?>>Stamping</option> <option value="7" <?php if(isset($user_key->user_type) && $user_key->user_type=='7') {?> selected="selected" <?php } ?>>Engineers</option> </select> <div id="usertypeerror"></div> </div> </div> </div> <!--<div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">User Access</label> <div class="col-md-7"> <select name="user_access" id="user_access" class="user_type" style="border: 1px solid #ccc; " onchange="document.getElementById('useraccesserror').style.display='none'"> <option value="">---Select---</option> <option value="stamping_user" <?php if(isset($user_key->user_access) && $user_key->user_access=='stamping_user') {?> selected="selected" <?php } ?>>Stamping</option> <option value="nonstamping_user" <?php if(isset($user_key->user_access) && $user_key->user_access=='nonstamping_user') {?> selected="selected" <?php } ?>>Non-Stamping</option> <!--<option value="3">Engineers</option> </select> <div id="useraccesserror"></div> </div> </div> </div>--> <?php if(isset($user_key->user_type) && $user_key->user_type=='7') {?> <div class="col-md-6 col-sm-4"> <div class="form-group"> <label for="form-control" class="col-md-5">Engineers</label> <div class="col-md-7"> <select name="engg_name" id="engg_name" style="border: 1px solid #ccc;" onchange="document.getElementById('engineerserror').style.display='none'"> <option value="0">---Select---</option> <?php foreach($get_employees as $empkey){ if($empkey->id == $user_key->emp_id){ ?> <option value="<?php echo $empkey->id; ?>" selected="selected"><?php echo $empkey->emp_name; ?></option> <?php } else{?> <option value="<?php echo $empkey->id; ?>"><?php echo $empkey->emp_name; ?></option> <?php } }?> </select> <div id="engineerserror"></div> </div> </div> </div> <?php } ?> </div> <?php } ?> <button style="margin-left: 6%; "class="btn cyan waves-effect waves-light " type="submit" name="action" id="submit">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).on("keyup",".user_name", function(){ var timer; clearTimeout(timer); timer = setTimeout(user, 3000); }); //alert(brand); function user(){ var id=$(".user_name").val(); var datastring = 'id='+id; //alert(datastring); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Users/checkname", data: datastring, cache: false, success: function(data) { //alert(data); if(data == 0){ $('#usernameerror').html(''); } else{ $('#usernameerror').html('User Name Already Exist!').show().css({'color':'#ff0000','font-size':'10px'}); $('.user_name').val(''); return false; } } }); } }); </script> <script> $(document).ready(function(){ //alert("hii"); $( "#submit" ).click(function( event ) {// alert("1"); if ( $( ".frstname" ).val() === "" ) { $( "#nameerror" ).text( "Enter the Name" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ( $( ".user_name" ).val() === "" ) { $( "#usernameerror" ).text( "Enter the User Name" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ( $( ".user_type" ).val() === "" ) { $( "#usertypeerror" ).text( "Please Select the User Type" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } if ( $( ".password" ).val() === "" ) { $( "#passerror" ).text( "Enter the Confirm Password" ).show().css({'color':'#ff0000','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(function(){ $(".frstname").keyup(function(){ if($(this).val()==""){ $("#nameerror").show(); } else{ $("#nameerror").hide(); } }); $(".user_name").keyup(function(){ if($(this).val()==""){ $("#usernameerror").show(); } else{ $("#usernameerror").hide(); } }); $("#user_type").change(function(){ if($(this).val()==""){ $("#usertypeerror").show(); } else{ $("#usertypeerror").hide(); } }); $(".password").keyup(function(){ if($(this).val()==""){ $("#passerror").show(); } else{ $("#passerror").hide(); } }); }); </script> <link href="<?php echo base_url(); ?>assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //alert("ghdsg"); $('#add').click(function() { $('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { $('#select2 option:selected').remove().appendTo('#select1'); }); }); </script> </body> </html><file_sep>/application/views_bkMarch_0817/addrow_sales.php <tr> <td> <table> <tr> <td><label>Serial No</label></td><td ><input type="text" name="serial_no[]" id="serial_no-<?php echo $count;?>" value="<?php echo "DUM".$cnt; ?>" class="serial_no"></td> <td><label>Model&nbsp;<span style="color:red;">*</span></label></td><td><select name="model[]" id="model-<?php echo $count;?>" class="modelss"><option value="">---Select---</option><?php foreach($modellist as $modelkey){ ?><option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?></select></td> </tr> <tr> <td><label>Category</label></td><td ><input type="text" name="category_name[]" id="category_name-<?php echo $count;?>" readonly><input type="hidden" name="category[]" id="category-<?php echo $count;?>"><input type="hidden" name="mod_id[]" id="mod_id-<?php echo $count;?>"><input type="hidden" name="model_name[]" id="model_name-<?php echo $count;?>"></td> <td><label>SubCategory</label></td> <td><input type="text" name="subcategory_name[]" id="subcategory_name-<?php echo $count;?>" readonly><input type="hidden" name="subcategory[]" id="subcategory-<?php echo $count;?>"></td> </tr> <tr> <td><label>Brand Name</label></td> <td ><input type="text" name="brand_name[]" id="brand_name-<?php echo $count;?>" readonly><input type="hidden" name="brandname[]" id="brandname-<?php echo $count;?>"></td> <td><label >Service Zone</label></td><td> <input type="text" name="service_loc_name[]" id="service_loc_name-<?php echo $count;?>" value="<?php echo $service_loc_name; ?>" class="service_loc_name" readonly><input type="hidden" name="service_loc[]" id="service_loc-<?php echo $count;?>" value="<?php echo $service_loc; ?>" class="service_loc"></td> </tr> <tr> <td><label>Sale Date</label></td><td><input class="date" type="text" name="purchase[]" id="purchase-<?php echo $count;?>" value=""></td> <td><select name="service_cat-<?php echo $count;?>[]" id="service_cat-<?php echo $count;?>" multiple hidden> </select></td> <td> <select name="probi-<?php echo $count;?>[]" id="probi-<?php echo $count;?>" multiple hidden> </select> </td> </tr> </table> </td> <td><a id="delrow"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr> <script> $(document).ready(function(){ $('.modelss').change(function(){//alert("ddddd"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('-'); var rowid = arr['1']; //alert(rowid); var id = $(this).val(); //alert(id); $('#service_cat-'+rowid+ "> option").remove(); $('#probi-'+rowid+ "> option").remove(); /* $("#service_cat-0 > option").remove(); $("#probi-0 > option").remove(); */ var dataString = 'modelno='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/get_productinfobyid", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#category_name-'+rowid).val(data.product_category), $('#category-'+rowid).val(data.category), $('#subcategory_name-'+rowid).val(data.subcat_name), $('#subcategory-'+rowid).val(data.subcategory), $('#brand_name-'+rowid).val(data.brand_name), $('#brandname-'+rowid).val(data.brand), $('#mod_id-'+rowid).val(data.id), $('#model_name-'+rowid).val(data.model) }); } }); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/get_servicecatbyid1", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#service_cat-'+rowid).append("<option selected='selected' value='"+data.sercat_id+"-"+data.service_category+"'>"+data.service_category+"</option>"); }); } }); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/get_probcatbyid1", data: dataString, cache: false, success: function(data) { $('#probi-'+rowid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ //alert(data.prob_category); $('#probi-'+rowid).append("<option selected='selected' value='"+data.prob_catid+"-"+data.prob_category+"'>"+data.prob_category+"</option>"); }); } }); }); }); </script> <file_sep>/application/controllers/Servicebk.php <?php class service extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Service_model'); } public function get_zone_list(){ $id=$this->input->post('keyword');//echo $id; exit; $data['zone_list']=$this->Service_model->get_zons($id); $this->load->view('zone_list',$data); } public function add_service_req(){ //echo "<pre>";print_r($_POST);exit; $req=$this->input->post('req_id'); $check_req=$this->Service_model->check_req($req); if(empty($check_req)){ $data['request_id']=$this->input->post('req_id'); $data['cust_name']=$this->input->post('customer_id'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['request_date']=$this->input->post('datepicker'); $data['status']=$this->input->post('status'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $data['user_id'] = $data111['user_dat'][0]->id; $req_autoid=$this->input->post('req_id'); $customer_mobile=$this->input->post('mobile'); $result=$this->Service_model->add_services($data); $res = sprintf("%05d", $result); if($result){ /* if(isset($customer_mobile) && $customer_mobile!=""){ $sms= "Your service request ID ".$req." created. Pls contact 9841443300 for Quote/status/delivery of your machine. <br>SRScales<br> 64606666"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=srscales&pass=<PASSWORD>&sender=SRSCAL&phone=$customer_mobile&text=$messages&priority=sdnd&stype=normal"); } */ $data1['request_id']=$res; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); if($this->input->post('warranty_date')!=""){ $data1['warranty_date'] = $this->input->post('warranty_date'); }else{ $data1['warranty_date'] = ""; } $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $sitee = $this->input->post('site'); if($sitee == 'Stamping'){ $stamp_data['req_id'] = $res; $stamp_data['year'] = $this->input->post('year'); $stamp_data['quarter'] = $this->input->post('qtr'); $stamp_data['kg'] = $this->input->post('kg'); $stamp_data['stamping_charge'] = $this->input->post('stamping_charge'); $stamp_data['agn_charge'] = $this->input->post('agn_charge'); $stamp_data['penalty'] = $this->input->post('penalty'); $stamp_data['conveyance'] = $this->input->post('conveyance_charge'); $stamp_data['tot_charge'] = $this->input->post('tot_charge'); $stamp_data['stamping_received']=$this->input->post('stamping_received'); date_default_timezone_set('Asia/Calcutta'); $stamp_data['created_on'] = date("Y-m-d H:i:s"); $stamp_data['updated_on'] = date("Y-m-d H:i:s"); if (is_array($stamp_data['stamping_received'])){ $stamp_data['stamping_received']= implode(",",$stamp_data['stamping_received']); }else{ $stamp_data['stamping_received']=""; } $this->Service_model->add_stamping_info($stamp_data); } $data1['service_type']=$this->input->post('service_type'); //$data1['service_cat']=$this->input->post('service_cat'); $ser_det = $this->input->post('service_cat'); $ser = explode("-",$ser_det); $data1['service_cat'] = $ser['0']; $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('probi'); if (is_array($data1['problem'])){ $data1['problem']= implode(",",$data1['problem']); }else{ $data1['problem']=""; } //$data1['problem']=$this->input->post('prob'); //$data1['assign_to']=$this->input->post('assign_to'); $data1['service_priority']=$this->input->post('service_priority'); $data1['blank_app']=$this->input->post('blank_app'); $emp_det = $this->input->post('assign_to'); $emp = explode(",",$emp_det); $data1['assign_to'] = $emp['0']; $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } $data1['notes']=$this->input->post('notes'); //$countids=$this->input->post('countids'); $result1=$this->Service_model->add_service_details($data1); } if($result){ if($sitee != 'Stamping'){ echo "<script>alert('Service Request Added. Your Request ID is: '+'".$req_autoid."');window.location.href='".base_url()."pages/service_req_list';window.open('".base_url()."service/print_service/".$res."')</script>"; }else{ echo "<script>alert('Service Request Added. Your Request ID is: '+'".$req_autoid."');window.location.href='".base_url()."pages/service_req_list';window.open('".base_url()."service/stamping_print_service/".$res."')</script>"; } } }else{ echo "<script>alert('Service Request ID already exists');window.location.href='".base_url()."pages/add_service_req';</script>"; } } public function print_service(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->print_servicecat_list($id); $data['problemlist']=$this->Service_model->print_problemlist($id); $data['problemlist1']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('print_request',$data); } public function stamping_print_service(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->print_servicecat_list($id); $data['problemlist']=$this->Service_model->print_problemlist($id); $data['stamping_details']=$this->Service_model->stamping_details($id); $data['problemlist1']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('stamping_print_service',$data); } public function get_custbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_cus(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_custo())); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid1(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_servicecatbyid1(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicecatdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_probcatbyid1(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_probcatdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_servicecatbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicecatdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_probcatbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_probcatdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function addrow(){ $data['count']=$this->input->post('countid'); //echo "Count: ".$data['count']; $data['customerlist']=$this->Service_model->customerlist(); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $this->load->view('add_service_req_row',$data); } public function update_service_req(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['get_mods']=$this->Service_model->get_mods(); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['service_typelist']=$this->Service_model->service_typelist(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data['stamping_details']=$this->Service_model->stamping_details($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_req',$data); } public function update_service_status(){ $reqid=$this->input->post('reqid'); //$this->input->post('procatid'); $data=array( 'status'=>$this->input->post('statusid') ); $s = $this->Service_model->update_service_status($data,$reqid); } public function get_serials(){ $id=$this->input->post('id');//echo $id; exit; //$cust_id=$this->input->post('cust_id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_serialdetails($id))); } public function get_serialnos(){ $id=$this->input->post('id');//echo $id; exit; $cust_id=$this->input->post('cust_id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicenodetails($id,$cust_id))); } public function get_modelnos(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_modelnos($id))); } public function edit_service_req(){ date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $data=array( 'request_id'=>$this->input->post('req_id'), 'cust_name'=>$this->input->post('cust_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email_id'), 'request_date'=>$this->input->post('datepicker'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $id=$this->input->post('servicereqid'); $rowid=$this->input->post('servicereqdetailid'); $this->Service_model->update_service_request($data,$id); if($id){ $data1['request_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); //$data1['warranty_date']=$this->input->post('warranty_date'); if($this->input->post('warranty_date')!=""){ $data1['warranty_date'] = $this->input->post('warranty_date'); }else{ $data1['warranty_date'] = ""; } $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $sitee = $this->input->post('site'); if($sitee == 'Stamping'){ //$stamp_data['req_id'] = $res; $stamp_data['year'] = $this->input->post('year'); $stamp_data['quarter'] = $this->input->post('qtr'); $stamp_data['kg'] = $this->input->post('kg'); $stamp_data['stamping_charge'] = $this->input->post('stamping_charge'); $stamp_data['agn_charge'] = $this->input->post('agn_charge'); $stamp_data['penalty'] = $this->input->post('penalty'); $stamp_data['conveyance'] = $this->input->post('conveyance_charge'); $stamp_data['tot_charge'] = $this->input->post('tot_charge'); $stamp_data['stamping_received']=$this->input->post('stamping_received'); if (is_array($stamp_data['stamping_received'])){ $stamping_received= implode(",",$stamp_data['stamping_received']); }else{ $stamping_received=""; } $data8=array( 'year'=>$this->input->post('year'), 'quarter'=>$this->input->post('qtr'), 'kg'=>$this->input->post('kg'), 'stamping_charge'=>$this->input->post('stamping_charge'), 'agn_charge'=>$this->input->post('agn_charge'), 'penalty'=>$this->input->post('penalty'), 'conveyance'=>$this->input->post('conveyance_charge'), 'tot_charge'=>$this->input->post('tot_charge'), 'stamping_received'=>$stamping_received, 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $this->Service_model->update_stamping_details($data8,$id); } $data1['service_type']=$this->input->post('service_type'); //$data1['service_cat']=$this->input->post('service_cat'); $ser_det = $this->input->post('service_cat'); $ser = explode("-",$ser_det); $data1['service_cat'] = $ser['0']; $data1['zone']=$this->input->post('locid'); $proble=$this->input->post('probi'); /* echo "<pre>"; print_r($data1['problem']); exit; */ if (is_array($proble)){ $data1['problem']= implode(",",$proble); }else{ $data1['problem']=""; } //$data1['problem']=$this->input->post('prob'); //$data1['assign_to']=$this->input->post('assign_to'); $data1['service_priority']=$this->input->post('service_priority'); $data1['blank_app']=$this->input->post('blank_app'); $emp_det = $this->input->post('assign_to'); $emp = explode(",",$emp_det); $data1['assign_to'] = $emp['0']; $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } $data1['notes']=$this->input->post('notes'); //$countids=$this->input->post('countids'); /* echo "<pre>"; print_r($data1); exit; */ //$this->Service_model->delete_serv_req_details($id); //$result1=$this->Service_model->add_service_details($data1); $where = "id=".$rowid." AND request_id=".$id; $result1=$this->Service_model->update_service_details($data1,$where); } echo "<script>alert('Service Request Updated');window.location.href='".base_url()."pages/service_req_list';</script>"; } public function get_branchname(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_branch($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_order(){ $id=$this->input->post('id'); $this->Order_model->delete_order_details($id); $result = $this->Order_model->delete_orders($id); } }<file_sep>/application/views_bkMarch_0817/edit_prod_list.php <style> body{background-color:#fff;} #errorBox { color:#F00; } .tableadd1 select { border: 1px solid #000; background-image:none; border-radius: 2px; width: 100%; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .limitedNumbChosen { width: 100%; } .chosen-container { width: 100% !important; } .chosen-container-multi .chosen-choices { border: 1px solid #ccc; } textarea.materialize-textarea { overflow-y: hidden; padding: 3px; resize: none; min-height: 10rem; } .chosen-container-multi .chosen-choices li.search-field input[type=text] { color: #333; } select { border: 1px solid #ccc !important; } </style> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var product_name = document.frmProd.product_name.value, category = document.frmProd.category.value, subcategory = document.frmProd.subcategory.value, model = document.frmProd.model.value; if( product_name == "" ) { document.frmProd.product_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the product name"; return false; } if( category == "" ) { document.frmProd.category.focus() ; document.getElementById("errorBox").innerHTML = "enter the category name"; return false; } if( subcategory == "" ) { document.frmProd.subcategory.focus() ; document.getElementById("errorBox").innerHTML = "enter the sub category name"; return false; } if( model == "" ) { document.frmProd.model.focus() ; document.getElementById("errorBox").innerHTML = "enter the model"; return false; } } </script> <script type="text/javascript"> $(document).ready(function() { $("#category").change(function() { //alert("hi"); $("#subcategory > option").remove(); var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory').append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); }); </script> <script type="text/javascript"> /* $(document).ready(function() { $("#subcategory").change(function() { $("#brand > option").remove(); var subcatid=$(this).val(); categoryid = $("#category").val(); //alert("Subcat: "+id+"Cat:" +category); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/get_brand", data: dataString, cache: false, success: function(data) { $('#brand').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data); $('#brand').append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); }); */ </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Product Details</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Product/edit_product" method="post" name="frmProd" onsubmit="return frmValidate()" > <?php foreach($list as $key){ $addl = explode(",",$key->addlinfo); ?> <div id="errorBox"></div> <table class="tableadd" style="width: 75%;"> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Product Name</label> <input type="text" name="product_name" id="product_name" class="" value="<?php echo $key->product_name; ?>"><input name="product_id" value="<?php echo $key->id; ?>" type="hidden"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Category</label> <select name="category" id="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ if($pcatkey->id==$key->category){ ?> <option selected="selected" value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } } ?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category</label> <select name="subcategory" id="subcategory"> <option value="">---Select---</option> <?php foreach($subcatlist as $psubcatkey){ if($psubcatkey->id==$key->subcategory){ ?> <option selected="selected" value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } else {?> <option value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } } ?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Brand Name</label> <select name="brand" id="brand"> <option value="">---Select---</option> <?php foreach($brandlist as $brandskey){ if($brandskey->id==$key->brand){ ?> <option selected="selected" value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } else {?> <option value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } } ?> </select> </div> </div> <div class="col-md-12 tableadd1"> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Model</label> <input type="text" name="model" id="model" class="" value="<?php echo $key->model; ?>"> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Additional Information</label> <select name="addlinfo[]" multiple> <option value="">---Select---</option> <?php foreach($accessories_list as $acckey1){ if (in_array($acckey1->accessory, $addl)){ ?> <option selected="selected" value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } else{?> <option value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } }?> </select> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Description</label> <textarea type="text" name="description" id="description" class="materialize-textarea" ><?php echo $key->description; ?></textarea> </div> </div> <!--<tr> <td><label>Product Name</label></td><td><input type="text" name="product_name" id="product_name" class="" value="<?php echo $key->product_name; ?>"><input name="product_id" value="<?php echo $key->id; ?>" type="hidden"></td> </tr> <tr> <td ><label>Category</label></td><td style="width:200px;"> <select name="category" id="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ if($pcatkey->id==$key->category){ ?> <option selected="selected" value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } else {?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td ><label>Sub-Category</label></td><td style="width:200px;"> <select name="subcategory" id="subcategory"> <option value="">---Select---</option> <?php foreach($subcatlist as $psubcatkey){ if($psubcatkey->id==$key->subcategory){ ?> <option selected="selected" value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } else {?> <option value="<?php echo $psubcatkey->id; ?>"><?php echo $psubcatkey->subcat_name; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td ><label>Brand Name</label></td><td style="width:200px;"> <select name="brand" id="brand"> <option value="">---Select---</option> <?php foreach($brandlist as $brandskey){ if($brandskey->id==$key->brand){ ?> <option selected="selected" value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } else {?> <option value="<?php echo $brandskey->id; ?>"><?php echo $brandskey->brand_name; ?></option> <?php } } ?> </select> </td> </tr> <tr> <td><label>Model</label></td><td><input type="text" name="model" id="model" class="" value="<?php echo $key->model; ?>"></td> </tr> <tr> <td><label>Description</label></td><td><textarea type="text" name="description" id="description" class="materialize-textarea" ><?php echo $key->description; ?></textarea></td> </tr>--> </table> <table class="tableadd1 tableadd" style="width: 75%;"> <!--<tr> <td><label >Additional Information</label></td> <td> <select name="addlinfo[]" multiple> <option value="">---Select---</option> <?php foreach($accessories_list as $acckey1){ if (in_array($acckey1->accessory, $addl)){ ?> <option selected="selected" value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } else{?> <option value="<?php echo $acckey1->accessory; ?>"><?php echo $acckey1->accessory; ?></option> <?php } }?> </select> </td> </tr>--> <!--<tr> <td><input type="checkbox" class="" name="addlinfo[]" value="charger" <?php if (in_array("charger", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="DataCable" <?php if (in_array("DataCable", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Battery" <?php if (in_array("Battery", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Headset" <?php if (in_array("Headset", $addl)){ ?> checked='checked'<?php } ?>></td><td><input type="checkbox" class="" name="addlinfo[]" value="Cover" <?php if (in_array("Cover", $addl)){ ?> checked='checked'<?php } ?>></td> </tr>--> <tr> <td style="padding-top: 25px;"> <button class="btn cyan waves-effect waves-light " type="submit" >Submit <i class="fa fa-arrow-right"></i> </button> </td> </tr> </table> </div> <?php } ?> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/models/Report_model.php <?php class Report_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } //service report public function modellist() { $this->db->select("id, model",FALSE); $this->db->from('products'); $this->db->order_by('model','asc'); $query = $this->db->get(); return $query->result(); } public function procatlist() { $this->db->select("id, product_category",FALSE); $this->db->from('prod_category'); $this->db->order_by('product_category','asc'); $query = $this->db->get(); return $query->result(); } public function custlist() { $this->db->select("*",FALSE); $this->db->from('customers'); $this->db->order_by('customer_name','asc'); $query = $this->db->get(); return $query->result(); } public function zonelist() { $this->db->select("*",FALSE); $this->db->from('service_location'); $this->db->order_by('service_loc','asc'); $query = $this->db->get(); return $query->result(); } public function problemlist() { $this->db->select("*",FALSE); $this->db->from('problem_category'); //$this->db->where('model', $datat); $this->db->order_by('id','asc'); $query = $this->db->get(); //print_r($query); return $query->result(); } function get_report($wh) { $query=$this->db->query("select service_request.created_on,service_request.request_id,rew.notes,req.site,pro.model,pro.id,cate.prob_category as problem,customers.customer_name, rew.total_amt,service.service_category,emp.emp_name,service_request.request_date ,loc.service_loc,service_request.mobile,stat.status,brand.brand_name,rew.labourcharge,rew.spare_tax,rew.spare_tot,rew.cmr_paid,rew.pending_amt,rew.disc_amt,rew.emp_pts,customers.address1 from service_request left join customers on customers.id=service_request.cust_name left join service_request_details as req on req.request_id=service_request.id left join products as pro on pro.id=req.model_id left join problem_category as cate on cate.id=req.problem left join quote_review as rew on rew.req_id=req.request_id left join service_category as service on service.id=req.service_cat left join employee as emp on emp.id=req.assign_to left join service_location as loc on loc.id=req.zone left join status as stat on stat.id=service_request.status left join brands as brand on brand.id=req.brand_id $wh"); return $query->result(); } //spare report public function engnamelist(){ $this->db->select('*'); $this->db->from('employee'); $this->db->order_by('emp_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function sparenamelist() { $this->db->select('*'); $this->db->from('spares'); $this->db->where('spare_name <> ', ''); $this->db->order_by('spare_name', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sparereport($wh) { $query=$this->db->query("select spares.id,spares.spare_name,group_concat(distinct(emp.emp_name),'//',customers.customer_name,'//',products.model,'//',service_request.id,service_request.active_req) as serv_request,qurew.desc_failure,det.serial_no from spares left join quote_review_spare_details as qurew on qurew.spare_id = spares.id left join service_request_details as det on det.request_id = qurew.request_id left join service_request on service_request.id=det.request_id left join employee as emp on emp.id=det.assign_to left join customers on customers.id = service_request.cust_name left join products on products.id = det.model_id $wh group by spares.id"); // echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getsparecharge_list($whxg) { $query = $this->db->query("select req.request_id,cust.customer_name,spa.spare_name,det.spare_qty,det.amt,req.request_date,service.machine_status,spa.purchase_price from service_request as req left join quote_review_spare_details as det on det.request_id = req.id left join spares as spa on spa.id = det.spare_id left join customers as cust on cust.id = req.cust_name left join service_request_details as service on service.request_id = req.id $whxg"); return $query->result(); } //purchase public function get_purchase($wh) { //$whereee = "engg.spare_id=$sname"; $query=$this->db->query("select spares.spare_name,engg.purchase_qty,engg.purchase_date,engg.invoice_no,engg.return_qty,engg.purchase_price,engg.reason,engg.spare_id from spare_purchase_details as engg inner join spares on spares.id = engg.spare_id $wh"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_engineerreport($whxg) { //echo "<pre>";print_r($whxg);exit; $query = $this->db->query("select emp.emp_name,engg.engineer_date,engg.qty_out,spa.spare_name,req.active_req,req.request_id,cust.customer_name,engg.qty_in,engg.reason from spare_to_engineers as engg left join employee as emp on emp.id=engg.emp_id left join spares as spa on spa.id=engg.spare_id left join service_request as req on req.id=engg.req_id left join customers as cust on cust.id=engg.cust_name $whxg"); /*$query=$this->db->query("select emp.emp_name,engg.engineer_date,engg.qty_out,spa.spare_name,req.id,cust.customer_name,SUM(engg.qty_in)as qty_in,engg.reason from spare_to_engineers as engg left join employee as emp on emp.id=engg.emp_id left join spares as spa on spa.id=engg.spare_id left join service_request as req on req.id=engg.req_id left join customers as cust on cust.id=engg.cust_name $whxg group by engg.emp_id"); */ //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_engineerreport1($whxg) { //echo "<pre>";print_r($whxg);exit; $query= $this->db->query("select group_concat(history_cust_solution.cust_solution) as cs, service_request.request_id, service_request.cust_name, service_request.request_date, products.model, prod_category.product_category, customers.company_name, customers.customer_name, customer_service_location.branch_name, customer_service_location.mobile, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, service_request_details.machine_status, service_request_details.problem, quote_review.labourcharge, quote_review.concharge, quote_review.spare_tax, quote_review.spare_tot, quote_review.emp_pts, status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage, employee.emp_name,service_request_details.serial_no,problem_category.prob_category from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = service_request_details.zone left join employee as employee on employee.id = service_request_details.assign_to left join status as status on status.id = service_request.status left join problem_category as problem_category on problem_category.id = service_request_details.problem left join history_cust_solution as history_cust_solution on history_cust_solution.req_id = service_request.id left join quote_review as quote_review on quote_review.req_id = service_request.id $whxg group by service_request_details.request_id"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } //stamping report public function emp_list() { $this->db->select("id, emp_name",FALSE); $this->db->from('employee'); $this->db->order_by('emp_name','asc'); $query = $this->db->get(); return $query->result(); } function getstamping_report($from_date,$to_date) { $query=$this->db->query("select stamp.req_id,cust.customer_name,cust.mobile,cust.land_ln,cust.state,cust.city,service.created_on,stamp.agn_charge,stamp.conveyance,stamp.cmr_paid,det.site,stat.state from stamping_details as stamp left join service_request as service on service.id=stamp.req_id left join service_request_details as det on det.request_id=service.id left join customers as cust on cust.id=service.cust_name left join state as stat on stat.id=cust.state where det.site='Stamping' AND service.created_on BETWEEN '$from_date' AND '$to_date 23:59:59.993' "); return $query->result(); } //stamping Monthly Report_model function getstampingmonth_report($from_date,$to_date) { $query=$this->db->query("select serdet.request_id,stamp.stamping_charge, stamp.agn_charge, stamp.penalty, stamp.conveyance,stamp.pending_amt, service.created_on, serdet.site , cust.customer_name , pro.model , stamp.cmr_paid , stat.status from stamping_details as stamp left join service_request_details as serdet on serdet.request_id=stamp.req_id left join service_request as service on service.id=serdet.request_id left join customers as cust on cust.id=service.cust_name left join products as pro on pro.id=serdet.model_id left join status as stat on stat.id=service.status where serdet.site='Stamping' AND service.created_on BETWEEN '$from_date' AND '$to_date 23:59:59.993'"); return $query->result(); } //customer Report public function service_zone_list() { $this->db->select("id,serv_loc_code,service_loc,concharge",FALSE); $this->db->from('service_location'); $this->db->order_by('service_loc', 'asc'); $query = $this->db->get(); return $query->result(); } public function cust_type_list() { $this->db->select("id,type",FALSE); $this->db->from('customer_type'); $this->db->order_by('type', 'asc'); $query = $this->db->get(); return $query->result(); } public function product_list() { $this->db->select("id,model",FALSE); $this->db->from('products'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); return $query->result(); } public function status_list() { $this->db->select("id,status",FALSE); $this->db->from('status'); $this->db->order_by('status', 'asc'); $query = $this->db->get(); return $query->result(); } public function engg_status_list() { $query = $this->db->query("Select * from status where id IN (1,9,3,4,2)"); return $query->result(); } public function area_list() { $this->db->select("*",FALSE); $this->db->from('zone_pincodes'); $this->db->order_by('area_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function brand_list() { $this->db->select("*",FALSE); $this->db->from('brands'); $this->db->order_by('brand_name', 'asc'); $query = $this->db->get(); return $query->result(); } public function getcustomer_report($whxg) { /*$query = $this->db->query("select customers.id, customers.customer_name, customers.company_name, customers.cal_ref, customer_service_location.branch_name, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, customer_service_location.pincode, customer_service_location.mobile, customer_service_location.email_id, customer_type.type as customertype, loc.service_loc,customers.created_on from customers as customers left join customer_type as customer_type on customer_type.id=customers.customer_type left join customer_service_location as customer_service_location on customer_service_location.customer_id=customers.id left join service_location as loc on loc.id=customers.service_zone $whxg");*/ //echo "<pre>";print_r($query->result());exit; $query = $this->db->query("select customers.id, customers.customer_name, customers.company_name, customers.cal_ref, customer_service_location.branch_name, customers.address, customers.address1, customers.city, customer_service_location.state, customer_service_location.pincode, customers.mobile, customers.email_id, customer_type.type as customertype, loc.service_loc,customers.created_on from customers as customers left join customer_type as customer_type on customer_type.id=customers.customer_type left join customer_service_location as customer_service_location on customer_service_location.customer_id=customers.id left join service_location as loc on loc.id=customers.service_zone $whxg"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } //aging report public function getaging_report($from,$r1,$r2,$model,$customer,$category,$emp,$zone) { $strquery=""; $strquery="select group_concat(custsolution.cust_solution)as cs, DATEDIFF(NOW(),req.request_date) AS DaysDiff ,req.request_id,req.request_date,pro.model,cust.customer_name,cust.address, service.machine_status,service.problem,stat.status,req.active_req,service.serial_no from service_request as req left join service_request_details as service on service.request_id = req.request_id left join products as pro on pro.id= service.model_id left join employee as emp on emp.id = service.assign_to left join service_location as zone on zone.id = service.zone left join prod_category as cate on cate.id = service.cat_id left join customers as cust on cust.id = req.cust_name left join problem_category as problem on problem.id = service.problem left join history_cust_solution as custsolution on custsolution.req_id = service.request_id left join status as stat on stat.id = req.status "; if ($r2<91) { $strquery=$strquery." where DATEDIFF(NOW(),req.request_date) between $r1 and $r2"; //$whxg= 'where service_request.active_req = '.'0' . ' AND ' .substr(implode('',$b),0,-5); } else if($r2>90) { $strquery=$strquery." where DATEDIFF(NOW(),req.request_date) > 90 "; } $strquery=$strquery." and req.request_date >= '$from' and req.status!=4 and req.active_req=0 "; //echo $strquery; /* if ($sersite!="") { $strquery=$strquery." and service.site = '$sersite'"; } */ if($model!="") { $strquery=$strquery." and pro.id = '$model'"; } if($customer!="") { $strquery=$strquery." and cust.id = '$customer'"; } if($category!="") { $strquery=$strquery." and problem.id = '$category'"; } if($emp!="") { $strquery=$strquery." and emp.id = '$emp'"; } if($zone!="") { $strquery=$strquery." and zone.id = '$zone'"; } $query=$this->db->query($strquery); /*$query=$this->db->query("select DATEDIFF(NOW(),req.request_date) AS DaysDiff ,req.request_id,req.cust_name,req.request_date,pro.model,cust.customer_name, cust.address, service.machine_status,service.problem,stat.status,service.site from service_request as req left join service_request_details as service on service.request_id = req.request_id left join products as pro on pro.id= service.model_id left join employee as emp on emp.id = service.assign_to left join service_location as zone on zone.id = service.zone left join prod_category as cate on cate.id = service.cat_id left join customers as cust on cust.id = req.cust_name left join problem_category as problem on problem.id = service.problem $whxg ");*/ //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getprob_category() { $this->db->select("id, prob_category",FALSE); $this->db->from('problem_category'); $this->db->order_by('prob_category','asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } //revenue report public function getrevenue_report($whxg) { $query= $this->db->query("select group_concat(DISTINCT history_cust_solution.cust_solution) as cs, service_request.request_id, service_request.cust_name, service_request.request_date, products.model, prod_category.product_category, customers.company_name, customers.customer_name, customer_service_location.branch_name, customer_service_location.mobile, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, service_request_details.machine_status, service_request_details.problem, quote_review.labourcharge, quote_review.concharge, quote_review.spare_tax, quote_review.spare_tot, status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage, employee.emp_name, brands.brand_name,service_request_details.serial_no,problem_category.prob_category from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = customer_service_location.service_zone_loc left join employee as employee on employee.id = service_request_details.accepted_engg_id left join status as status on status.id = service_request.status left join brands as brands on brands.id = service_request_details.brand_id left join problem_category as problem_category on problem_category.id = service_request_details.problem left join history_cust_solution as history_cust_solution on history_cust_solution.req_id = service_request_details.request_id left join quote_review as quote_review on quote_review.req_id = service_request.id $whxg group by request_id"); //echo $this->db->last_query(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } //preventive report public function getpreventive_report($whxg) { $query =$this->db->query("select group_concat(history_cust_solution.cust_solution) as cs, service_request.request_id, service_request.cust_name, service_request.request_date, products.model, prod_category.product_category, customers.company_name, customers.customer_name, customer_service_location.branch_name, customer_service_location.mobile, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, service_request_details.machine_status, service_request_details.problem, quote_review.labourcharge, quote_review.concharge, quote_review.spare_tax, quote_review.spare_tot, status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage, employee.emp_name, brands.brand_name,service_request_details.serial_no,problem_category.prob_category,service_request_details.service_type,service_request_details.accepted_engg_id from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = customer_service_location.service_zone_loc left join employee as employee on employee.id = service_request_details.accepted_engg_id left join status as status on status.id = service_request.status left join brands as brands on brands.id = products.id left join problem_category as problem_category on problem_category.id = service_request_details.problem left join history_cust_solution as history_cust_solution on history_cust_solution.req_id = service_request_details.id left join quote_review as quote_review on quote_review.req_id = service_request.id $whxg AND service_request.request_id LIKE '%P-%' AND (service_request_details.service_type='Preventive' || service_request_details.service_type='Warranty') group by request_id"); //$this->db->like('service_request.request_id', 'P-'); //$query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; //echo $this->db->last_query(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getrevenue1_report($whxg) { $query= $this->db->query("select group_concat(history_cust_solution.cust_solution ) as cs, service_request.request_id, service_request.cust_name, service_request.request_date, products.model, prod_category.product_category, customers.company_name, customers.customer_name, customer_service_location.branch_name, customer_service_location.mobile, customer_service_location.address, customer_service_location.address1, customer_service_location.city, customer_service_location.state, service_request_details.machine_status, service_request_details.problem, quote_review.labourcharge, quote_review.concharge, quote_review.spare_tax, quote_review.spare_tot, status.status, zone_pincodes.area_name, service_location.service_loc, service_location.zone_coverage, employee.emp_name,brands.brand_name,service_request_details.serial_no,problem_category.prob_category,quote_review_spare_details.spare_id from service_request as service_request left join service_request_details as service_request_details on service_request_details.request_id = service_request.id left join products as products on products.id= service_request_details.model_id left join prod_category as prod_category on prod_category.id = service_request_details.cat_id left join customers as customers on customers.id = service_request.cust_name left join customer_service_location as customer_service_location on customer_service_location.customer_id = customers.id left join zone_pincodes as zone_pincodes on zone_pincodes.id = customer_service_location.area left join service_location as service_location on service_location.id = service_request_details.zone left join employee as employee on employee.id = service_request_details.assign_to left join status as status on status.id = service_request.status left join brands as brands on brands.id = products.id left join problem_category as problem_category on problem_category.id = service_request_details.problem left join history_cust_solution as history_cust_solution on history_cust_solution.req_id = service_request_details.id left join quote_review_spare_details as quote_review_spare_details on quote_review_spare_details.request_id = service_request.id left join quote_review as quote_review on quote_review.req_id = service_request.id $whxg group by request_id "); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function get_sermachine_report($from,$to,$model,$prod_category,$machine_status,$cust_type,$cust_name,$service_zone) { //echo $cust_name;exit; /* echo $from; echo "<br>".$to; echo "<br>".$model; echo "<br>".$prod_category; echo "<br>".$machine_status; echo "<br>".$cust_type; */ $strquery=""; if($from =='' && $to ==''){ $strquery_wh="order_details.model_id = $model"; }else{ $strquery_wh="order_details.purchase_date between '$from' and '$to'"; } $strquery="select orders.id, order_details.serial_no, products.model, customers.company_name, customers.customer_name, order_details.warranty_date, order_details.amc_end_date, order_details.purchase_date, order_details.paid, orders.order_id, order_details.notes, order_details.rent_type, order_details.amc_start_date, customer_service_location.branch_name, customer_service_location.address, customer_service_location.address1, customer_service_location.mobile,state.state, prod_category.product_category, customer_type.type as cust_type,order_details.cmc_start_date,order_details.cmc_end_date, service_location.service_loc from orders as orders left join order_details as order_details on order_details.order_id = orders.id left join customers as customers on customers.id = orders.customer_id left join customer_service_location as customer_service_location on customer_service_location.customer_id = orders.customer_service_loc_id left join customer_type as customer_type on customer_type.id = customers.customer_type left join products as products on products.id = order_details.model_id left join prod_category as prod_category on prod_category.id = order_details.cat_id inner join state as state on state.id = customers.state inner join service_location as service_location on service_location.id = order_details.service_loc_id where "; $strquery=$strquery.$strquery_wh; if($machine_status=='all') { $strquery=$strquery; } if($machine_status=='paid') { $strquery=$strquery." and order_details.paid ='paid'"; } if($machine_status=='Warranty') { $strquery=$strquery." and order_details.warranty_date!='' and order_details.amc_start_date='' and unix_timestamp(order_details.warranty_date) > unix_timestamp(CURDATE())"; } /*if($machine_status=='Preventive') { $strquery=$strquery." and order_details.prev_main!='' and order_details.amc_start_date='' and unix_timestamp(order_details.prev_main) > unix_timestamp(CURDATE())"; }*/ if($machine_status=='amc') { $strquery=$strquery." and order_details.amc_start_date!='' and unix_timestamp(order_details.amc_end_date) > unix_timestamp(CURDATE())"; } if($machine_status=='cmc') { $strquery=$strquery." and order_details.cmc_start_date!='' and unix_timestamp(order_details.cmc_end_date) > unix_timestamp(CURDATE())"; } if($machine_status=='syndicate') { $strquery=$strquery." and order_details.rent_type ='syndicate'"; } if($machine_status=='distributor') { $strquery=$strquery." and order_details.rent_type ='distributor'"; } if ($cust_type!="") { $strquery=$strquery." and customers.customer_type = $cust_type"; } if($cust_name!="") { $strquery=$strquery." and customers.customer_name = '$cust_name'"; } if ($model!="" &&$from!=''&&$to!='') { $strquery=$strquery." and order_details.model_id = $model"; } if ($prod_category!="") { $strquery=$strquery." and order_details.cat_id = $prod_category"; } if ($service_zone!="") { $strquery=$strquery." and customers.service_zone = $service_zone"; } $query=$this->db->query($strquery); //echo $this->db->last_query();exit; //echo "<pre>";print_r($query->result());exit; return $query->result(); } //serial list public function get_serial() { $this->db->select('order_details.serial_no,order_details.order_id'); $this->db->from('orders'); $this->db->join('order_details','order_details.order_id=orders.id'); $query=$this->db->get(); return $query->result(); } public function getserial_report($whxg) { $query = $this->db->query("select group_concat(distinct(det.request_id),'//',service_request.request_date) as ser,service_request.request_date,products.model,brands.brand_name,service_location.service_loc,customers.customer_name,service_category.service_category as categoryname,det.machine_status,det.service_type,det.problem ,det.serial_no,order_details.purchase_date,problem_category.prob_category,group_concat(history_cust_solution.cust_solution) as cs from order_details left join service_request_details as det on det.serial_no = order_details.serial_no left join service_request on service_request.id = det.request_id left join products on products.id = det.model_id left join brands on brands.id = det.brand_id left join customers on customers.id = service_request.cust_name left join service_location on serv_loc_code = det.zone left join service_category on service_category.id = det.service_cat left join history_cust_solution as history_cust_solution on history_cust_solution.req_id = det.id left join problem_category on problem_category.id = det.problem $whxg group by order_details.serial_no"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getpopup_list($id) { $query = $this->db->query("select brands.brand_name,service_location.service_loc,service_category.service_category as categoryname,det.machine_status,det.service_type,det.problem,det.serial_no from service_request left join service_request_details as det on det.request_id = service_request.id left join products on products.id = det.model_id left join brands on brands.id = det.brand_id left join customers on customers.id = service_request.cust_name left join service_location on serv_loc_code = det.zone left join service_category on service_category.id = det.service_cat left join problem_category on problem_category.id = det.problem where det.request_id='".$id."' group by det.request_id"); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function sparelist(){ $this->db->select("spare_details.spare_id, prod_category.product_category, prod_subcategory.subcat_name, brands.brand_name, products.model",FALSE); $this->db->from('spare_details'); $this->db->join('prod_category', 'prod_category.id = spare_details.cat_id'); $this->db->join('prod_subcategory', 'prod_subcategory.id = spare_details.subcat_id'); $this->db->join('brands', 'brands.id = spare_details.brand_id'); $this->db->join('products', 'products.id = spare_details.model_id'); $query = $this->db->get(); return $query->result(); } public function sparelist1($from,$to){ $query=$this->db->query("select id, spare_name, spare_qty, used_spare, eng_spare, purchase_price, purchase_qty, purchase_date, sales_price, effective_date, dashboard_show, min_qty, part_no from spares where created_on BETWEEN '$from' AND '$to 23:59:59.993'"); return $query->result(); /* $this->db->select("id, spare_name, spare_qty, used_spare, eng_spare, purchase_price, purchase_qty, purchase_date, sales_price, effective_date, dashboard_show, min_qty, part_no",FALSE); $this->db->from('spares'); $this->db->order_by('id', 'DESC'); $query = $this->db->get(); return $query->result(); */ } public function engspareqty(){ $this->db->select("spares.id,petty_spare.spare_id",FALSE); $this->db->select_sum('petty_spare.qty_plus'); $this->db->from('spares'); $this->db->join('petty_spare', 'petty_spare.spare_id = spares.id','left'); $this->db->group_by('petty_spare.spare_id'); $query = $this->db->get(); return $query->result(); } }<file_sep>/application/views/spare_purchaseview.php <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 4px; border: 1px solid #ccc; } table.dataTable.no-footer tr td { border: 1px solid #ccc !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border: 1px solid #ccc; color: #303f9f; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } #data-table-simple_length { display: block; } .dataTables_wrapper { position: relative; clear: both; zoom: 1; } .dataTables_wrapper .dataTables_length { float: left; } table.dataTable.no-footer { border-bottom: none !important; } table.dataTable, table.dataTable th, table.dataTable td { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } table.dataTable { width: 100%; margin: 0 auto; clear: both; border-collapse: collapse !important; border-spacing: 0; } table { width: 100%; display: table; } label { display: inline-block; max-width: 100%; margin-bottom: 5px; font-weight: 700; } select { background-color: rgba(255, 255, 255, 0.9); width: 100%; padding: 5px; border: 1px solid #bbb; border-radius: 2px; height: 2rem; /* display: none; */ } #data-table-simple_filter label { font-size: 15px !important; } .dataTables_wrapper .dataTables_filter input { margin-left: 0.5em; } input[type=search] { background-color: transparent; border: 1px solid #bbb; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .dataTables_wrapper .dataTables_info { clear: both; float: left; padding-top: 0.755em; } .dataTables_wrapper .dataTables_paginate { float: right; text-align: right; padding-top: 0.25em; } ul{ display:none; } .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate { color: #bbb; } table.dataTable thead th, table.dataTable thead td { padding: 10px 18px; border-bottom: 1px solid #bbb !important; } </style> <script> function frmValidate(){ if((document.getElementById("print_invoice").checked == false) && (document.getElementById("print_invoice1").checked == false)) { document.getElementById("print_invoice").focus(); document.getElementById("errorBox").innerHTML = "Check any button to print invoice"; return false; } } </script> <section id="content"> <div class="container"> <div class="section"> <h2>Spare Purchase Details</h2> <div class="divider"></div> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <!--<th style="width:100 !important">Spare Id</th>--> <th style="width:200 !important">Quantity</th> <th>Purchase Date</th> <th>Reason</th> </tr> </thead> <tbody> <?php foreach($spare_view as $key){?> <tr> <!--<td><?php echo $key->spare_id;?></td>--> <td><?php if($key->purchase_qty !=0){ echo $key->purchase_qty;}?></td> <td><?php echo $key->purchase_date;?></td> <td><?php echo $key->reason; ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> </body> </html><file_sep>/application/views/dash.php <style> /*.btn { position: relative; padding: 0px 2px; border: 0; margin: 0px 1px; cursor: pointer; border-radius: 2px; text-transform: uppercase; text-decoration: none; color: rgba(255,255,255,.84); transition: box-shadow .28s cubic-bezier(.4,0,.2,1); outline: none!important; }*/ .btn-sm { padding: 8px 10px !important; font-size: 12px; line-height: 1.5; border-radius: 3px; font-weight: bold !important; } .table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th, .table>thead>tr>td, .table>tbody>tr>td, .table>tfoot>tr>td { padding: 1px 5px !important; line-height: 1.42857143; vertical-align: top; border-top: 1px solid #ddd !important; font-size: 11px; font-weight: bold; } .label { display: inline; padding: .2em .6em .3em; font-size: 81%; font-weight: 700; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; } .fa { font-size: 20px !important; } .fa-globe{ font-size: 30px !important; position:relative; top:7px; } .fa-desktop{ font-size: 30px !important; position:relative; top:7px; } .fa-list-alt{ font-size: 30px !important; position:relative; top:7px; } .fa-cog{ font-size: 30px !important; position:relative; top:7px; } .fa-bell-o{ font-size: 30px !important; position:relative; top:7px; } .fa-truck{ font-size: 30px !important; position:relative; top:7px; } .info-box-icon { border-top-left-radius: 2px; border-top-right-radius: 0; border-bottom-right-radius: 0; border-bottom-left-radius: 2px; display: block; float: left; height: 45px; width: 36px; text-align: center; font-size: 45px; line-height: 20px; background: rgba(0,0,0,0.2); position: relative; top: 6px; } .info-box-text { display: block; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; } .tableft{ padding-left: 10px !important; } .breadcrumbs-title { font-size: 2.2rem; line-height: 0rem; color:#6C217E; font-weight:bold; } .info-box-text a { text-transform: capitalize; color: #6C217E; } .info-box-text { text-transform: capitalize; color: #6C217E; } .info-box-number { display: block; font-weight: bold; font-size: 15px; color: #73538a; } .no-margin tbody tr td > a{ color: #82609c; } .row { margin-left: auto; margin-right: auto; margin-bottom: 0px; } .content { min-height: 250px; padding: 0; margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px; } .section { padding: 0 !important; } .box { position: relative; border-radius: 3px; background: #ffffff; border-top: 3px solid #d2d6de; margin-bottom: 7px !important; width: 100%; box-shadow: 0 1px 1px rgba(0,0,0,0.1); } .nav-tabs-custom>.tab-content { background: #fff; padding: 0px !important; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .nav-tabs-custom { margin-bottom: 0px !important; background: #fff; box-shadow: 0 1px 1px rgba(0,0,0,0.1); border-radius: 3px; } thead { border-bottom: 1px solid #111;/*#d0d0d0*/ background-color: #f2f2f2;/*#dbd0e1*/ border: 3px solid #777;/*#dbd0e1*/ color: #111;/*#3e0963*/ } table th {background-color: #f2f2f2 !important;} </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2 class="breadcrumbs-title">Dashboard</h2> <hr> <div class="content-wrapper" style="padding-top:0px;"> <section class="content"> <div class="row"> <!--<div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-globe fa-fw"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/onsite_list">Service Center</a></span> <span class="info-box-number">10</span> </div> </div> </div>--> <!--<div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-desktop"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/offsite_list" >Customer Site</a></span> <span class="info-box-number" > 9</span> </div> </div> </div>--> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-list-alt"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url();?>pages/ready_delivery_list">Stocks</a></span> <span class="info-box-number">10 / 20</span> </div> </div> </div> <!--<div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-aqua"><i class="fa fa-cog"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url(); ?>pages/stamping_list" >Stampings</a></span> <span class="info-box-number" >10</span> </div> </div> </div>--> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="fa fa-bell-o"></i></span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url();?>pages/req_alert_list">Request Alert</a></span> <span class="info-box-number">12/20</span> </div> </div> </div> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-green"> <i class="fa fa-truck"></i> </span> <div class="info-box-content"> <span class="info-box-text"><a href="<?php echo base_url();?>pages/ready_delivery_list">Customers</a></span> <span class="info-box-number">15/20</span> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/dash/app.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/dash/dashboard.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/controllers/Order.php <?php class order extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Order_model'); $this->load->model('Customer_model'); $this->load->model('Product_model'); } public function add_bills(){ $this->load->library('email'); $data['order_id']=$this->input->post('bill_no'); $data['customer_id']=$this->input->post('cust_name'); $data['mobile']=$this->input->post('mobile'); $data['address']=$this->input->post('address'); $data['city']=$this->input->post('city_name'); $data['state']=$this->input->post('state_name'); $data['pincode']=$this->input->post('pincode'); $data['purchase_date']=$this->input->post('puchase_date'); $data['email_id']=$this->input->post('email_id'); $data['sub_total']=$this->input->post('sub_total1'); $data['disc']=$this->input->post('disc_amt'); $data['grand_total']=$this->input->post('grand_total'); $data['amt_pending']=$this->input->post('grand_total'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $result=$this->Order_model->add_orders($data); //$res = sprintf("%05d", $result); $ep_name = $this->input->post('p_name'); $email_idd = $this->input->post('email_id'); $content = '<html lang="en"> <head> <title>Parshva Creations</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="x-apple-disable-message-reformatting"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { mso-line-height-rule:exactly; -ms-text-size-adjust:100%; -webkit-text-size-adjust:100%; margin: 1.6cm;} table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt} table { border-collapse: collapse; border-spacing: 0;margin: 0 auto;} img, a img { border:0 none; height: auto; line-height: 100%; outline: none; -ms-interpolation-mode: bicubic} a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; font-size: inherit !important; font-family: inherit !important; font-weight: inherit !important; line-height: inherit !important} .x-gmail-data-detectors, .x-gmail-data-detectors *, .aBn { border-bottom: 0 !important; cursor: default !important} .a6S { display:none !important; opacity:0.01 !important} img.g-img + div { display:none !important} .button-link { text-decoration: none !important} #printArea { padding: 20px;} #printArea .print-area-cnt { border: 1px solid #999; } #printArea .print-tab-top { border-bottom: 1px solid #ccc; background-color: #336499; } #printArea .print-tab { margin:0;width:100%;line-height:100%; border: 1px solid #ccc; } #printArea .print-tab-head .print-tab-logo { width: 20%; border-top: 0 !important; } #printArea .print-tab-head .print-tab-logo img { height:70px;color:#fff;float:left;position:relative;margin-top: 25px; } #printArea .print-tab-head .print-tab-title { width: 80%; padding-top: 20px; border-top: 0 !important; } #printArea .print-tab-head .print-tab-title h4 { font-size: 18px; color: #ffffff; font-weight: bold; text-align: center;font-size: 24px; } #printArea .print-tab-head .print-tab-title p { font-size: 18px; color: #ffffff; text-align: center; } #printArea .body-part { padding: 10px;} #printArea .body-part table { margin:0;width:100%;line-height:100%; border: 1px solid #ccc; } #printArea .body-part h4 { padding: 10px; text-align: left; } #printArea .body-part hr { border-bottom: 1px solid #ccc; width: 15%; margin-left: 0px; margin-top: -10px; } #printArea .body-part .print-area-personal tr td { padding: 10px; } #printArea .body-part .print-area-product thead tr { color: #444;background-color: #f2f2f2; } #printArea .body-part .print-area-product th,#printArea .body-part .print-area-product td { text-align: center;border: 1px solid #ccc; } #printArea .btn-print { border-radius: 0;border: 2px solid #ffffff; outline: 1px solid #ccc;} #printArea .body-part table tr, #printArea .body-part table th, #printArea .body-part table td {} } @media print { .btn-print { display: none;} } @page { margin: 0; } @media only screen and (min-width: 375px) and (max-width: 413px) { .ios-gm-fix { min-width: 375px !important;} } </style> </head> <body> <div class="container"> <div class="row" id="printArea" style=" padding: 20px;"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 print-area-cnt" style="border: 1px solid #999;"> <div class="row"> <table role="presentation" class="table ios-gm-fix print-tab-top" style="border-bottom: 1px solid #ccc; background-color: #336499;"> <tbody class="print-tab-head"> <tr> <td class="print-tab-logo" style="width: 20%; border-top: 0 !important;"> <img src="'.base_url().'assets/images/logo.png" alt="materialize logo" style="height:70px;color:#fff;float:left;position:relative;margin-top: 25px;" class="saturate"> </td> <td class="print-tab-title" style="width: 80%; padding-top: 20px; border-top: 0 !important;"> <h4 style="font-size: 18px; color: #ffffff; font-weight: bold; text-align: center;font-size: 24px;">Parshva Creations</h4> <p style="font-size: 18px; color: #ffffff; text-align: center;">7, Balaji Complex, Elephant Gate Street, (Near Jain Temple Mint Street), Sowcarpet</p> <p style="font-size: 18px; color: #ffffff; text-align: center;">Tamil Nadu, Chennai - 600079</p> </td> </tr> </tbody> </table> </div> <div class="row body-part" style="padding: 10px;"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h4 style=" padding: 10px; text-align: left;">Billing Details</h4> <hr style="border-bottom: 1px solid #ccc; width: 15%; margin-left: 0px; margin-top: -10px;"> <div class="table-responsive"> <table role="presentation" class="table ios-gm-fix print-tab" style="margin:0;width:100%;line-height:100%; border: 1px solid #ccc;"> <tbody> <tr> <td> <table role="presentation" style=" width: 100%; border: 1px solid #ccc;" align="left" class="table print-area-personal"> <tbody> <tr><td style="padding: 10px;">Bill No</td><td>:</td><td>'.$this->input->post('bill_no').'</td></tr> <tr><td style="padding: 10px;">Customer Name</td><td>:</td><td>'.$this->input->post('cust_name').'</td></tr> <tr><td style="padding: 10px;">Mobile</td><td>:</td><td>'.$this->input->post('mobile').'</td></tr> <tr><td style="padding: 10px;">Address</td><td>:</td><td>'.$this->input->post('address').'</td></tr> </tbody> </table> </td> <td> <table role="presentation" style=" width: 100%; border: 1px solid #ccc;" align="right" class="table print-area-personal"> <tbody> <tr><td style="padding: 10px;">City</td><td>:</td><td>'.$this->input->post('city_name').'</td></tr> <tr><td style="padding: 10px;">State</td><td>:</td><td>'.$this->input->post('state_name').'</td></tr> <tr><td style="padding: 10px;">Pincode</td><td>:</td><td>'.$this->input->post('pincode').'</td></tr> <tr><td style="padding: 10px;">Purchase Date</td><td>:</td><td>'.$this->input->post('puchase_date').'</td></tr> </tbody> </table> </td> </tr> </tbody> </table> </div> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style=" text-align: left;"> <h4 style="border: 0; padding: 10px;">Product Details</h4> <hr style="border-bottom: 1px solid #ccc; width: 13%; margin-left: 0px; margin-top: -10px;"> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="table-responsive"> <table role="presentation" class="table ios-gm-fix print-tab print-area-product" style=" width: 100%; border: 1px solid #ccc;"> <thead> <tr style=" color: #444;background-color: #f2f2f2;"> <th style=" text-align: center;border: 1px solid #ccc;">S.No.</th> <th style=" text-align: center;border: 1px solid #ccc;">Product Name</th> <th style=" text-align: center;border: 1px solid #ccc;">Unit Price</th> <th style=" text-align: center;border: 1px solid #ccc;">Qty</th> <th style=" text-align: center;border: 1px solid #ccc;">Total Amount</th> </tr> </thead> <tbody>'; $j=1; for($i=0;$i<count($ep_name);$i++){ $content.='<tr style=" text-align: center;"> <td style="border: 1px solid #ccc;">'.$j.'</td> <td style="border: 1px solid #ccc;">'.$this->input->post('p_name')[$i].'</td> <td style="border: 1px solid #ccc;">'.$this->input->post('qty')[$i].'</td> <td style="border: 1px solid #ccc;">'.$this->input->post('price')[$i].'</td> <td style="border: 1px solid #ccc;">'.$this->input->post('sub_total')[$i].'</td> </tr>'; $j++;} $content.='<tr style=" text-align: center;"> <td colspan="2" style="border: 1px solid #fff;border-right:1px solid #ccc;"></td> <td style="border: 1px solid #ccc;">Sub total</td> <td style="border: 1px solid #ccc;">'.$this->input->post('sub_total1').'</td> </tr> <tr style=" text-align: center;"> <td colspan="2" style="border: 1px solid #fff;border-right:1px solid #ccc;"></td> <td style="border: 1px solid #ccc;">Discount</td> <td style="border: 1px solid #ccc;">'.$this->input->post('disc_amt').'</td> </tr> <tr style=" text-align: center;"> <td colspan="2" style="border: 1px solid #fff;border-right:1px solid #ccc;"></td> <td style="border: 1px solid #ccc;">Grand total</td> <td style="border: 1px solid #ccc;">'.$this->input->post('grand_total').'</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </body> </html>'; $this->email->set_mailtype("html"); $this->email->from('<EMAIL>', 'vijayakumar'); $this->email->to($email_idd); $this->email->subject('Bill - Parshva Creations'); $this->email->message($content); $this->email->send(); if($result){ $p_name = $this->input->post('p_name'); for($i=0;$i<count($p_name);$i++){ $data1['order_id']=$result; $data1['p_name']=$this->input->post('p_name')[$i]; $data1['qty']=$this->input->post('qty')[$i]; $data1['price']=$this->input->post('price')[$i]; $data1['sub_total']=$this->input->post('sub_total')[$i]; $result1=$this->Order_model->add_order_details($data1); $this->Order_model->update_stock_in_hand($this->input->post('qty')[$i], $this->input->post('p_name')[$i]); $this->Order_model->update_used_qty($this->input->post('qty')[$i], $this->input->post('p_name')[$i]); } echo "<script>alert('Bill Added Successfully!!!');window.location.href='".base_url()."pages/dash';</script>"; } } public function update_bills(){ $id=$this->uri->segment(3); $data['customer_list']=$this->Customer_model->customer_list(); $data['getorderbyid']=$this->Order_model->getorderbyid($id); $data['getorderDetailsbyid']=$this->Order_model->getorderDetailsbyid($id); $data['prod_list']=$this->Product_model->product_list(); $this->load->view('templates/header'); $this->load->view('edit_bills',$data); } public function print_bills(){ $id=$this->uri->segment(3); $data['getorderbyid']=$this->Order_model->getorderbyid($id); $data['getCustDetails'] = $this->Order_model->getCustDetails($data['getorderbyid'][0]->customer_id); $data['getorderDetailsbyid']=$this->Order_model->getorderDetailsbyid($id); $this->load->view('print_bills',$data); } public function edit_bills(){ $id = $this->input->post('bill_id'); $data['order_id']=$this->input->post('bill_no'); //$data['customer_id']=$this->input->post('cust_name'); $data['mobile']=$this->input->post('mobile'); $data['address']=$this->input->post('address'); $data['city']=$this->input->post('city_name'); $data['state']=$this->input->post('state_name'); $data['pincode']=$this->input->post('pincode'); $data['purchase_date']=$this->input->post('puchase_date'); $data['email_id']=$this->input->post('email_id'); $data['sub_total']=$this->input->post('sub_total1'); $data['disc']=$this->input->post('disc_amt'); $data['grand_total']=$this->input->post('grand_total'); $amt_paid = $this->input->post('amt_paid'); $amt_paid1 = $this->input->post('amt_paid1'); $data['amt_paid']= $amt_paid + $amt_paid1; $data['amt_pending']=$this->input->post('amt_pending'); date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $result = $this->Order_model->update_orders($data,$id); if($result){ $p_name = $this->input->post('p_name'); for($i=0;$i<count($p_name);$i++){ $ord_id = $this->input->post('ord_id')[$i]; if(isset($ord_id) && $ord_id!=""){ $data1['p_name']=$this->input->post('p_name')[$i]; $data1['qty']=$this->input->post('qty')[$i]; $data1['price']=$this->input->post('price')[$i]; $data1['sub_total']=$this->input->post('sub_total')[$i]; $result1=$this->Order_model->update_order_details($data1,$ord_id); }else{ $data1['order_id']=$id; $data1['p_name']=$this->input->post('p_name')[$i]; $data1['qty']=$this->input->post('qty')[$i]; $data1['price']=$this->input->post('price')[$i]; $data1['sub_total']=$this->input->post('sub_total')[$i]; $result1=$this->Order_model->add_order_details($data1); } } echo "<script>alert('Bill Updated Successfully!!!');window.location.href='".base_url()."pages/dash';</script>"; } } public function get_customerById(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_customerById($id))); } public function edit_order(){ //echo "<pre>";print_r($_POST);exit; date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $data=array( 'order_id'=>$this->input->post('order_no'), 'customer_id'=>$this->input->post('cust_name'), 'customer_service_loc_id'=>$this->input->post('br_name'), 'contact_name'=>$this->input->post('cont_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email'), 'address'=>$this->input->post('addr'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'pincode'=>$this->input->post('pincode'), 'zone_coverage'=>$this->input->post('service_loc_coverage'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $id=$this->input->post('orderid'); $this->Order_model->update_orders($data,$id); //$this->Order_model->delete_order_details($id); $rowid=$this->input->post('orderdetailid'); /* $pm_date = $this->input->post('pm_date'); $pm_sch_id = $this->input->post('pm_sch_id'); $pm_sch_status = $this->input->post('pm_sch_status'); for($k=0;$k<count($pm_date);$k++){ $data_pm['order_id']=$id; $data_pm['schedule_date']=$pm_date[$k]; if($pm_sch_status[$k]=='1'){ $data_pm['status']='1'; }else{ $data_pm['status']='0'; } if($pm_sch_id[$k]!="" && isset($pm_sch_id[$k])){ $result=$this->Order_model->update_pm_details($data_pm,$pm_sch_id[$k]); }else{ $this->Order_model->add_pm_details($data_pm); } } */ if($id){ $data1['order_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['batch_no']=$this->input->post('batch_no'); $data1['cat_id']=$this->input->post('category'); $data1['subcat_id']=$this->input->post('subcategory'); $data1['brand_id']=$this->input->post('brandname'); $data1['model_id']=$this->input->post('model'); //$data1['price']=$this->input->post('price'); $data1['service_loc_id']=$this->input->post('service_loc'); $data1['purchase_date']=$this->input->post('purchase'); $colorRadio = $this->input->post('colorRadio'); if($colorRadio=='paid'){ $data1['paid']=$this->input->post('colorRadio'); $data1['warranty_date']=""; $data1['prev_main']=""; //$data1['amc_type']=""; $data1['prev_main_updated']=""; $data1['amc_start_date']=""; $data1['cmc_start_date']=""; $data1['amc_end_date']=""; $data1['cmc_end_date']=""; $data1['rent_date']=""; $data1['rent_type']=""; if($this->input->post('amc_start_date')!="" && $this->input->post('amc_prenos')!=""){ $data1['prenos']=""; } }elseif($colorRadio=='warranty'){ $data1['warranty_date']=$this->input->post('warranty'); $data1['prenos']=$this->input->post('warrnos'); $data1['prev_main_updated']=$this->input->post('purchase'); $data1['paid']=""; $data1['prev_main']=""; $data1['rent_type']=""; $data1['amc_start_date']=""; $data1['cmc_start_date']=""; $data1['amc_end_date']=""; $data1['cmc_end_date']=""; $data1['rent_date']=""; }elseif($colorRadio=='prevent'){ $data1['prev_main']=$this->input->post('preventive_main'); $data1['prev_main_updated']=$this->input->post('purchase'); $data1['prenos']=$this->input->post('prenos'); $data1['paid']=""; $data1['warranty_date']=""; $data1['rent_type']=""; $data1['amc_start_date']=""; $data1['cmc_start_date']=""; $data1['amc_end_date']=""; $data1['cmc_end_date']=""; $data1['rent_date']=""; } elseif($colorRadio=='cmc'){ $data1['prev_main_updated']=$this->input->post('cmc_start_date'); $data1['cmc_start_date']=$this->input->post('cmc_start_date'); $data1['cmc_end_date']=$this->input->post('cmc_end_date'); $data1['prenos']=$this->input->post('cmc_prenos'); $data1['paid']=""; $data1['prev_main']=""; $data1['rent_type']=""; $data1['amc_start_date']=""; $data1['amc_end_date']=""; $data1['rent_date']=""; $data1['warranty_date']=""; } elseif($colorRadio=='rent'){ $data1['paid']=""; $data1['warranty_date']=""; $data1['amc_start_date']=""; $data1['amc_end_date']=""; $data1['prev_main']=""; $data1['cmc_end_date']=""; $data1['cmc_start_date']=""; $data1['rent_date']=$this->input->post('rent'); $data1['rent_type']=$this->input->post('rent_type'); $data1['prev_main_updated']=$this->input->post('purchase'); $data1['prenos']=$this->input->post('rent_nos'); }else{ //$data1['amc_type']=$this->input->post('amc_type'); $data1['cmc_start_date']=""; $data1['cmc_end_date']=""; $data1['prev_main_updated']=$this->input->post('amc_start_date'); $data1['amc_start_date']=$this->input->post('amc_start_date'); $data1['amc_end_date']=$this->input->post('amc_end_date'); if($this->input->post('amc_prenos')!=""){ $data1['prenos']=$this->input->post('amc_prenos'); }else{ $data1['prenos']=$this->input->post('prenos'); } if($this->input->post('warranty_date_hide')!=""){ $data1['warranty_date']=""; } if($this->input->post('prev_main_hide')!=""){ $data1['prev_main']=""; } if($this->input->post('paid_hide')!=""){ $data1['paid']=""; } } $data1['notes']=$this->input->post('notes'); $warranty=$this->input->post('warranty'); //$result1=$this->Order_model->add_order_details($data1); $salename1=$this->input->post('salename'); //echo $salename1; exit; $where = "id=".$rowid." AND order_id=".$id; $result1=$this->Order_model->Update_order_details($data1,$where); if($salename1=='amc'){ echo "<script>alert('AMC Order Updated Successfully!!!');window.location.href='".base_url()."pages/amc_list';</script>"; }else if($salename1=='warranty'){ echo "<script>alert('Warranty Order Updated Successfully!!!');window.location.href='".base_url()."pages/order_list';</script>"; } else if($salename1=='cmc'){ echo "<script>alert('CMC Order Updated Successfully!!!');window.location.href='".base_url()."pages/cmc_list';</script>"; } else if($salename1=='rent'){ echo "<script>alert('Rent Order Updated Successfully!!!');window.location.href='".base_url()."pages/rent_list';</script>"; } else echo "<script>alert('Chargeable Order Updated Successfully!!!');window.location.href='".base_url()."pages/expiry_closed';</script>"; } } }<file_sep>/application/views/add_order_row.php <tr> <td><label style="color: black; font-size: 15px; font-weight: bold; margin-bottom:20px;">Add Product</label> </td> </tr> <tr> <td><label>Serial No</label></td><td ><input type="text" name="serial_no[]" id="serial_no" class=""></td> <td><label>Category</label></td><td > <select name="category[]" id="category_<?php echo $count; ?>" class="category"> <option value="">---Select---</option> <?php foreach($prodcatlist as $pcatkey){ ?> <option value="<?php echo $pcatkey->id; ?>"><?php echo $pcatkey->product_category; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><label>SubCategory</label></td> <td > <select name="subcategory[]" id="subcategory_<?php echo $count; ?>" class="subcategory"> <option value="">---Select---</option> </select> </td> <td><label>Brand Name</label></td> <td > <select name="brandname[]" id="brandname_<?php echo $count; ?>" class="brandname"> <option value="">---Select---</option> </select> </td> </tr> <tr> <td><label>Model</label></td> <td > <select name="model[]" id="model_<?php echo $count; ?>"> <option value="">---Select---</option> </select> </td> <td><label>Price</label></td><td><input type="text" name="price[]" id="price" class=""></td> </tr> <tr> <td><label >Service Location</label></td><td> <select name="service_loc[]" id="service_loc"> <option>---Select---</option> <?php foreach($serviceLocList as $lockey){ ?> <option value="<?php echo $lockey->id; ?>"><?php echo $lockey->service_loc; ?></option> <?php } ?> </select></td> <td><label>Purchase Date</label></td><td><input id="popupDatepicker" type="text" name="purchase[]"></td> </tr> <tr> <td><label>Warranty Date</label></td><td><input id="popupDatepicker1" type="text" name="warranty[]"></td> <td><label>Preventive Maintenance</label></td><td><input type="text" name="preventive_main[]" id="preventive_main" class=""></td> </tr> <script type="text/javascript"> jQuery.noConflict(); $(document).ready(function() { $(".category").change(function(){ //alert("ggg"); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var catid = arr['1']; var id=$(this).val(); //alert("catttt: "+catid); //alert("iddddd: "+id); var dataString = 'id='+ id; $('#subcategory_'+catid+ "> option").remove(); $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/getsub_category", data: dataString, cache: false, success: function(data) { $('#subcategory_'+catid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.subcat_name); $('#subcategory_'+catid).append("<option value='"+data.id+"'>"+data.subcat_name+"</option>"); }); } }); }); $(".subcategory").change(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id=$(this).val(); var subcatid=$(this).val(); categoryid = $('#category_'+ctid).val(); //alert("Subcat: "+subcatid+"Cat:" +categoryid); //$('#subcategory_'+catid+ "> option").remove(); $('#brandname_'+ctid+"> option").remove(); var dataString = 'subcatid='+ subcatid+'&categoryid='+ categoryid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/get_brand", data: dataString, cache: false, success: function(data) { $('#brandname_'+ctid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.brand_name); $('#brandname_'+ctid).append("<option value='"+data.id+"'>"+data.brand_name+"</option>"); }); } }); }); $(".brandname").change(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; $('#model_'+ctid+"> option").remove(); var brandid=$(this).val(); categoryid = $('#category_'+ctid).val(); subcategoryid = $('#subcategory_'+ctid).val(); //alert("Subcat: "+subcategoryid+"Cat:" +categoryid+"brandid:" +brandid); var dataString = 'subcatid='+ subcategoryid+'&categoryid='+ categoryid+'&brandid='+ brandid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>order/get_model", data: dataString, cache: false, success: function(data) { $('#model_'+ctid).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){//alert(data.model); $('#model_'+ctid).append("<option value='"+data.id+"'>"+data.model+"</option>"); }); } }); }); }); </script><file_sep>/application/controllers/Pages.php <?php class Pages extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Order_model'); $this->load->model('Customer_model'); $this->load->model('Product_model'); $this->load->model('Dash_model'); $this->load->model('Productcategory_model'); $this->load->model('Subcategory_model'); } public function bills(){ $data['order_list']=$this->Order_model->order_list(); $this->load->view('templates/header'); $this->load->view('bills',$data); } public function dash(){ /*$data1['stamping_cnt']=$this->Dash_model->stamping_cnt(); $data1['readyfordelivery_cnt']=$this->Dash_model->readyfordelivery_cnt(); */ $this->load->view('templates/header'); $this->load->view('dash'); } public function add_bills(){ $data['bill_cnt']=$this->Order_model->bill_cnt(); if(empty($data['bill_cnt'])){ $data['cnt']='00001'; }else{ $cusid = $data['bill_cnt'][0]->order_id; $dat= $cusid + 1; $data['cnt']=sprintf("%06d", $dat); } $data['customer_list']=$this->Customer_model->customer_list(); $data['prod_list']=$this->Product_model->product_list(); $this->load->view('templates/header'); $this->load->view('add_bills',$data); } public function add_cust(){ $data['state_list']=$this->Order_model->state_list(); $this->load->view('templates/header'); $this->load->view('add_cust',$data); } public function cust_list(){ $data['list']=$this->Customer_model->customer_list(); $this->load->view('templates/header'); $this->load->view('cust_list',$data); } public function prod_list(){ $data1['list']=$this->Product_model->product_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_list',$data1); } public function add_prod(){ $data1['prodcatlist']=$this->Product_model->prod_cat_dropdownlist(); $data1['subcatlist']=$this->Product_model->prod_sub_cat_dropdownlist(); $data1['brandlists']=$this->Product_model->brandlists(); $data1['accessories_list']=$this->Product_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod',$data1); } public function prod_cat_list(){ $data1['list']=$this->Productcategory_model->prod_cat_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_cat_list',$data1); } public function prod_subcat_list(){ $data1['list']=$this->Subcategory_model->prod_sub_cat_list(); $data1['droplists']=$this->Subcategory_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('prod_subcat_list',$data1); } public function add_prod_cat(){ $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod_cat'); } public function add_prod_subcat(){ $data1['droplist']=$this->Subcategory_model->prod_cat_dropdownlist(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('add_prod_subcat',$data1); } }<file_sep>/application/views/add_spare.php <style> .fancybox-inner{ overflow: auto; width: 800px; height: 600px !important; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 5px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; /* background-color: #DBD0E1 !important; */ } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } a{ color:#522276; cursor:pointer; } a:hover{ color:#522276; } a:active{ color:#522276; } a:focus{ color:#522276; } body{ background-color: #fff;} input[readonly] { border:none; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addspare.png" title="Add Spare" style="width:24px;height:24px;">Add Spare</button>--> <div style="float: right; height:50px; margin-top:-45px;"> <a href="<?php echo base_url(); ?>pages/add_new_stock"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Spare" style="position: relative;right: 22px;"></i></a> <a id="fancybox-manual-b" href="javascript:;" style="margin-right: 20px;"><img src="<?php echo base_url(); ?>assets/images/spare_add1.png" alt="materialize logo"></a> <a id="fancybox-manual-bc" href="javascript:;"><img src="<?php echo base_url(); ?>assets/images/spare_delete1.png" alt="materialize logo"></a> </div> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0" style="margin-top:2%;"> <thead> <tr><th class="hidden">id</th> <th colspan='2' style="width: 110px; !important">Spare Name</th> <th style="width: 50px; !important">Part No.</th> <!--<th>Qty</th>--> <th style="width: 69px; !important">Sales Price</th> <!--<th style="width: 89px; !important">Purchase Price</th>--> <!--<th>Category</th> <th>SubCategory</th> <th>Brand</th>--> <th style="width: 50px; !important">Model</th> <th>Total Quantity</th> <th>Stock In Hand</th> <th>Spare With Engineers</th> <th>Used Spare</th> <th style="width:82px !important">Effective Date</th> <th>Action</th> </tr> </thead> <tbody><?php foreach($sparelist1 as $key1){ $sdf=$key1->id;?> <tr> <td class="hidden"><?php echo $key1->id; ?></td> <td><input type="checkbox" name="dashboard_show" id="dashboard_show<?php echo $key1->id; ?>" onclick="Updatedefault('<?php echo $key1->id; ?>')" <?php if($key1->dashboard_show){?> checked="checked" <?php }?>><a onclick="clickPopup('<?php echo $sdf;?>')"> </td><td><?php echo $key1->spare_name; ?></a></td> <td><?php if($key1->part_no !=0){ echo $key1->part_no;} ?></td> <!--<td><?php if($key1->spare_qty !=0){echo $key1->spare_qty;}?></td>--> <td><?php if($key1->sales_price !=0){echo $key1->sales_price;} ?></td> <!--<td><?php if($key1->purchase_price !=0){echo $key1->purchase_price;} ?></td>--> <td> <ul class="quantity"> <?php foreach($sparelist as $key){ if($key->spare_id==$key1->id){ ?> <li><?php echo $key->model; ?></li> <?php } } ?> </ul> </td> <td><?php echo $key1->purchase_qty;?></td> <td> <input type="text" value="<?php if($key1->spare_qty !=0){ echo $key1->spare_qty; }?>" class="" name="total_spare" id="total_spare_<?php echo $key1->id; ?>" readonly></td> <!--<td><input type="text" value="<?php if($key1->eng_spare !=0){echo $key1->eng_spare;} ?>" class="" name="engg_spare" id="engg_spare_<?php echo $key1->id; ?>" readonly></td>--> <td><input type="text" value="<?php foreach($engspareqty as $ekey){ if($ekey->spare_id==$key1->id){echo $ekey->qty_plus;} }?>" class="" name="engg_spare" id="engg_spare_<?php echo $key1->id; ?>" readonly></td> <td><input type="text" value="<?php if($key1->used_spare !=0){echo $key1->used_spare;}?>" class="" name="used_spare" id="used_spare_<?php echo $key1->id; ?>" readonly></td> <td><?php echo $key1->effective_date; ?></td> <td style="text-align:center;"><a href="<?php echo base_url(); ?>Spare/update_spare/<?php echo $key1->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery-1.10.1.min.js"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var jq= jQuery.noConflict(); jq(document).ready(function() { jq("#fancybox-manual-b").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); jq.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popup', type : 'iframe', padding : 5, 'afterClose':function () { parent.location.reload(true); //window.location.reload('<?php echo base_url(); ?>pages/add_spare'); alert('Spare Stock Added Successfully!!!'); } }); }); jq("#fancybox-manual-bc").click(function() { //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); jq.fancybox.open({ href : '<?php echo base_url(); ?>Spare/purchase_popupminus', type : 'iframe', padding : 5, 'afterClose':function () { window.location.reload('<?php echo base_url(); ?>pages/add_spare'); alert('Spare Stock Minus Successfully!!!'); } }); }); /*$("#fancybox-manual-purchase").click(function() { alert("test"); //var idd=$(this).closest(this).attr('id'); //var arr = idd.split('_'); //var rowid = arr['1']; //alert(rowid); $.fancybox.open({ href : '<?php echo base_url(); ?>Spare/view_purchase', type : 'iframe', padding : 5 }); });*/ }); </script> <script> function Updatedefault(id) { if(document.getElementById('dashboard_show'+id).checked) { var dashboard_show = '1'; alert("Checked Spare Name will display on dashboard"); } else { var dashboard_show = '0'; //alert(tax_default); alert("Unchecked Spare Name disappear from dashboard"); } $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_important', data: {'id' : id, 'dashboard_show' : dashboard_show}, dataType: "text", cache:false, success: function(data){ //alert(data); //alert("Spare Selected"); } }); } </script> <script> function clickPopup(idd) { //alert("test"); //var sitename = $("#sitename_"+idd).val(); jq.fancybox.open({ href : '<?php echo base_url(); ?>spare/view_purchase/'+idd, type : 'iframe', padding : 5 }); } </script> </body> </html><file_sep>/application/controllers/Labcategory.php <?php class labcategory extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Labcategory_model'); $this->load->helper('array'); } public function add_lab_category(){ $this->load->library('form_validation'); $user=array('username'=>$this->input->post('lab_name')); $cat_name=$this->input->post('lab_name'); $c=$cat_name; $count=count($c); for($i=0; $i<$count; $i++) { if($cat_name[$i]!="") { $data1 = array('lab_name' => $cat_name[$i]); $result=$this->Labcategory_model->add_lab_cat($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_prod_cat';alert('Please enter Product Category');</script>"; } */ } if(isset($result)) { echo "<script>window.location.href='".base_url()."pages/lab_listsss';alert('Lab Added Successfully!!!');</script>"; } } //here you can add the data savings into the db. /*public function username_check($str) { $this->form_validation->set_rules('lab_name', 'User Name', 'required'); $username = $this->input->post('lab_name'); $result = $this->Labcategory_model->checkusername($username); if ($this->form_validation->run() == FALSE) { return FALSE; } else if ($result) { $this->form_validation->set_message('username_check', 'Sorry Username already exists in the database"'); return FALSE; } else { return TRUE; } }*/ /* $cat_name=$this->input->post('lab_name'); $c=$cat_name; $count=count($c); for($i=0; $i<$count; $i++) { if($cat_name[$i]!=""){ $data1 = array('lab_name' => $cat_name[$i]); $result=$this->Labcategory_model->add_lab_cat($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_prod_cat';alert('Please enter Product Category');</script>"; } */ //} //if(isset($result)){ //echo "<script>window.location.href='".base_url()."pages/lab_listsss';alert('Lab added');</script>"; //} //} */--> public function update_lab_category(){ $id=$this->uri->segment(3); $data['list']=$this->Labcategory_model->getlabbyid($id); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_lab_list',$data); } public function edit_lab_category(){ $id=$this->input->post('labid'); $data=array('lab_name'=>$this->input->post('lab_name')); $s = $this->Labcategory_model->update_lab($data,$id); echo "<script>window.location.href='".base_url()."pages/lab_listsss';alert('Lab Category Updated Successfully!!!');</script>"; } public function update_status_prod_category(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Labcategory_model->update_status_prod_cat($data,$id); echo "<script>alert('Lab Category made Inactive');window.location.href='".base_url()."pages/lab_listsss';</script>"; } public function update_status_prod_category1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Labcategory_model->update_status_prod_cat1($data,$id); echo "<script>alert('Lab Category made active');window.location.href='".base_url()."pages/lab_listsss';</script>"; } public function category_validation() { $product_id = $this->input->post('id'); //echo $product_id;exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Labcategory_model->category_validation($product_id))); } public function add_labrow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_lab',$data); } } ?><file_sep>/application/views/add_row_lab.php <div class="col-md-12" style="padding: 0px"> <div class="col-md-3 col-sm-6 col-xs-12"> <input type="text" name="lab_name[]" id="UserName<?php echo $count; ?>" class="firstname"> <div class="fname" id="lname<?php echo $count; ?>" style="color:red"></div> </div> <div class="col-md-1 col-sm-6 col-xs-12" style="padding:0px"> <a class="delRowBtn btn btn-primary fa fa-trash" style="height:30px;"></a> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName<?php echo $count; ?>" ).val()==""){ $("#lname<?php echo $count; ?>" ).text("Enter Lab Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#UserName<?php echo $count; ?>" ).keyup(function(){ if($(this).val()==""){ $("#lname<?php echo $count; ?>" ).show(); } else{ $("#lname<?php echo $count; ?>" ).fadeOut('slow'); } }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <script> $(document).ready(function(){ $('#UserName<?php echo $count; ?>').change(function(){ var name=$(this).val(); //alert(name); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>Labcategory/category_validation", data:{ id:name, }, cache:false, success:function(data){ //alert(data); if(data == 0){ $('#lname<?php echo $count; ?>').html(''); } else{ $('#lname<?php echo $count; ?>').html('Lab Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#UserName<?php echo $count; ?>').val(''); return false; //exit; } } }); }); }); </script> <file_sep>/application/views_bkMarch_0817/edit_cust_type.php <style> input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <style> .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } </style> <section id="content"> <div class="container"> <div class="section"> <h2>Edit Customer Type</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/edit_customer_type" method="post"> <table id="myTable" class="tableadd"> <?php foreach($list as $key){ ?> <div class="col-md-3 col-sm-6 col-xs-12"> <label><font color="red">*</font>Customer Type</label> <input type="text" name="cust_type" class="corporate" value="<?php echo $key->type; ?>"><input type="hidden" name="cust_typeid" class="corporate" value="<?php echo $key->id; ?>"> </div> <!--<tr> <td><label style="width:180px;font-weight:bold;">Customer Type</label></td> </tr> <tr> <td><input type="text" name="cust_type" class="corporate" value="<?php echo $key->type; ?>"><input type="hidden" name="cust_typeid" class="corporate" value="<?php echo $key->id; ?>"></td> </tr>--> <?php } ?> </table> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views/pm_service_status.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td> <select> <option>Motorola</option> <option><NAME></option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td><td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(document).ready(function(){ $('#billingtoo').click(function(){//alert("haiiii"); //$addr = $('#address').val(); var id = $(this).val(); //alert(id); //var stateid = $('#state').val(); $('#re_address').val($('#address').val()); $('#re_address1').val($('#address1').val()); $('#re_city').val($('#search-box').val()); //$('#re_state').val($('#state').val()); $('#re-pincode').val($('#pincode').val()); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_state", data:'stateid='+$('#state').val(), success: function(data) { $.each(data, function(index, data){//alert(data.branch_name); $('#re_state').val(data.state); }); } }); }); }); </script> <script type='text/javascript'>//<![CDATA[ function FillBilling(f) { if(f.billingtoo.checked == true) { alert(f.search-box.value); f.re_address.value = f.address.value; f.re_address1.value = f.address1.value; f.re_city.value = f.search-box.value; f.re_state.value = f.state.value; f.re_pincode.value = f.pincode.value; } } </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var customer_id = document.frmCust.customer_id.value, customer_name = document.frmCust.customer_name.value, cust_type = document.frmCust.cust_type.value, service_zone = document.frmCust.service_zone.value, pincode = document.frmCust.pincode.value, land_ln = document.frmCust.land_ln.value, mobile = document.frmCust.mobile.value; //email = document.frmCust.email.value; /*if( customer_id == "" ) { document.frmCust.customer_id.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer id."; return false; } if( customer_name == "" ) { document.frmCust.customer_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer name"; return false; } if( pincode == "" ) { document.frmCust.pincode.focus() ; document.getElementById("errorBox").innerHTML = "enter the pincode"; return false; } if( cust_type == "" ) { document.frmCust.cust_type.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer type"; return false; } if( service_zone == "" ) { document.frmCust.service_zone.focus() ; document.getElementById("errorBox").innerHTML = "enter the service zone"; return false; } if( mobile == "" && land_ln == "") { document.frmCust.mobile.focus() ; document.getElementById("errorBox").innerHTML = "enter the mobile / landline"; return false; }*/ /* if( email == "" ) { document.frmCust.email.focus() ; document.getElementById("errorBox").innerHTML = "enter the email"; return false; } */ if(service_zone != "") { //alert("Hi1"); var mob = $('#mobile').val(); var customer_name = $('#customer_name').val(); var cust_idd = $('#cust_idd').val(); var cust_idd = $('#cust_idd').val(); var email = $('#email').val(); var cust_loc = $('#cust_loc').val(); var address = $('#address').val(); var address1 = $('#address1').val(); parent.setSelectedUser(mob,customer_name,cust_idd,email,cust_loc,address,address1); //parent.$.fancybox.close(); } } </script> <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-right:20px; } .link:hover { color:black; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } </style> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} .dropdown-content { display: none; } h5 { font-size: 22px; text-align: center; width: auto; margin: auto auto 35px; } .tableadd tr td select { border: 1px solid #808080; height: 27px; width: 210px; } .tableadd tr td input { width: 120px; border: 1px solid #808080; height: 27px; } .tableadd tr td { padding:10px 10px 10px 0px; } .rowadd { border: 1px solid #8868a0 !important; background: #8868a0 none repeat scroll 0% 0% !important; padding: 6px; border-radius: 5px; color: #FFF; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } .box{ display: none; box-shadow:none !important; } .del { display:block; } .rowadd{ cursor:pointer; } </style> <script> $(document).ready(function(){ $('.del').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkMob", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); }); $('.ready').keyup(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>customer/checkland_ln", data: dataString, cache: false, success: function(data) { document.getElementById("errorBox").innerHTML = data; } }); }); }); </script> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title" style="margin-bottom:10px;margin-top: 15px;">Preventive Maintenance Details</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <div id="errorBox"></div> <table class="tableadd table table-bordered"> <tr> <th style="background: #ccc;">Schedule Date</th> <th style="background: #ccc;">Status</th> </tr> <?php if(!empty($getPmAlerts)){ foreach($getPmAlerts as $pm_key){ if($pm_key->schedule_date!=""){?> <tr> <td><?php echo $pm_key->schedule_date; ?></td> <td><?php if($pm_key->status=='1'){echo "Alert notified";}if($pm_key->status=='0'){echo "Not notified";} ?></td> </tr> <?php } } } else{?> <td colspan="2">No Data Available</td> <?php } ?> </table> </div> </div> </div> </div> </div> </div> </div> </section> </div> </div> </body> </html><file_sep>/application/views/report_cust_list.php <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <style> table.display { margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } </style> <?php $profit=0; $stot=0; $net=0; $count=0; $cmr=0; $pending=0; $totcharge=0; $servicecharge=0; ?> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url()?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('example', 'W3C Example Table')"> <img src="<?php echo base_url()?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="example" class="responsive-table display" cellspacing="0" > <thead> <tr> <td>Date</td> <td>RequestID</td> <td>CustomerName</td> <td>Address</td> <td>EngineerName</td> <td>Model</td> <td>Brand</td> <td>ServiceCategory</td> <td>Problem</td> <td>Zone</td> <td>Mobile</td> <td>Status</td> <td>Site</td> <td>SpareCharge</td> <td>ServiceCharge</td> <td>TotalCharge</td> <td>Discounts</td> <td>Cmr_Paid</td> <td>PendingAmount</td> <td>Notes</td> <td>emp_pts</td> </tr> </thead> <tbody> <?php if($report) { $count = count($report); foreach($report as $row) { $profit=$row->spare_tax+$row->spare_tot; //$tax+=$row->spare_tax; $stot+=$profit; //$net=$tax+$stot; $cmr+=$row->cmr_paid; $pending+=$row->pending_amt; $totcharge+=$row->total_amt; $servicecharge+=$row->labourcharge; ?> <tr> <td><?php echo $row->request_date;?></td> <td><?php echo $row->request_id;?></td> <td><?php echo $row->customer_name;?></td> <td><?php echo $row->address1;?></td> <td><?php echo $row->emp_name;?></td> <td><?php echo $row->model;?></td> <td><?php echo $row->brand_name;?></td> <td><?php echo $row->service_category;?></td> <td><?php echo $row->problem;?></td> <td><?php echo $row->service_loc;?></td> <td><?php echo $row->mobile;?></td> <td><?php echo $row->status;?></td> <td><?php echo $row->site;?></td> <td><?php echo $profit;?></td> <td><?php echo $row->labourcharge;?></td> <td><?php echo $row->total_amt;?></td> <td><?php echo $row->disc_amt;?></td> <td><?php echo $row->cmr_paid;?></td> <td><?php echo $row->pending_amt;?></td> <td><?php echo $row->notes;?></td> <td><?php echo $row->emp_pts;?></td> </tr> <?php } } else { echo "<h4 align='center'>No Data Available</h4>"; } ?> </tbody> <?php if(!empty($report)) { ?> <tbody> <tr style="visibility:hidden;"><td style="border:none;" ></td></tr> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total Service Received :<?php echo $count;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;margin-top:15px;"></td> <td colspan="2"><div class="pull-right">Total Spare Charge : <?php echo $stot;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;margin-top:15px;"></td> <td colspan="2"><div class="pull-right">Total Service Charge : <?php echo $servicecharge;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total Charges :<?php echo $totcharge;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total customer Paid :<?php echo $cmr;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total OutStanding Amount :<?php echo $pending;?></div></td> </tr> <tbody> <?php } ?> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script> var $= jQuery.noConflict(); </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script><file_sep>/application/views_bkMarch_0817/add_cust_type.php <style> .tableadd tr td input { width: 230px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 2px; padding-left: 10px; margin-left: 13px; } .tableadd tr td input { height: 21px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <script type='text/javascript'>//<![CDATA[ $(function(){ var tbl = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ $('<tr> <td style="width: 29.5%";><input type="text" name="cust_type[]" class="corporate" id="UserName'+i+'"><div class="fname" id="lname'+i+'"></div></td><td><a class="delRowBtn btn btn-primary"><i class="fa fa-trash"></i></a></td></tr>').appendTo(tbl); $("#UserName"+i).keyup(function(){ var name1=document.getElementById( "UserName"+i ).value; //alert(name1); if(name1) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>customer/custtype_validation', data: { p_id:name1, }, success: function (data) { // alert(data); if(data == 0){ $('#lname'+i).html(''); } else{ //alert("else called"); $('#lname'+i).text('Customer Type Already Exist').show().delay(1000).fadeOut(); $('#UserName'+i).val(''); return false; } } }); } }); $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName"+i).val()==""){ $("#lname"+i).text("Enter Customer Type").show().css({'color':'#ff0000','position':'relative','bottom':'10px','left':'14px'}); event.preventDefault(); } }); $("#UserName"+i).keyup(function(){ if($(this).val()==""){ $("#lname"+i).show(); } else{ $("#lname"+i).fadeOut('slow'); } }); i++; }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); </script> <style> body{background-color:#fff;} .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .waves-light { text-transform:capitalize !important; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Customer Type</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>customer/add_customer_type" method="post"> <table id="myTable" class="tableadd"> <!--<tr> <td><label style="width:180px;font-weight:bold;">Customer Type</label></td> </tr> <tr> <td><input type="text" name="cust_type[]" class="corporate"></td> </tr>--> <div class="col-md-3 col-sm-6 col-xs-12"> <label><font color="red">*</font>Customer Type</label> <input type="text" name="cust_type[]" id="UserName1" class="firstname"> <div class="fname" id="lname1" style="color:red"></div> </div> </table> <a class="link" id="addRowBtn1">Add</a><button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $(document).on("keyup","#UserName1", function(){ var name=$(this).val(); //alert(name); if(name) { $.ajax({ type: 'post', url: '<?php echo base_url(); ?>customer/custtype_validation', data: { p_id:name, }, success: function (data) { if(data == 0){ $('#lname1').html(''); } else{ $('#lname1').html('Customer Type Already Exist').show().delay(1000).fadeOut(); $('#UserName1').val(''); return false; } } }); } }); </script> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($(".firstname").val()==""){ $(".fname").text("Enter Customer Type").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $(".firstname").keyup(function(){ if($(this).val()==""){ $(".fname").show(); } else{ $(".fname").fadeOut('slow'); } }) }); </script> </body> </html><file_sep>/application/controllers/Users.php <?php class Users extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('User_model'); } public function add_users(){ //echo "<pre>";print_r($_POST);exit; $user_name = $this->input->post('user_name'); $chk_user = $this->User_model->check_username($user_name); if(empty($chk_user)){ $data['name'] = $this->input->post('first_name'); $data['user_name'] = $this->input->post('user_name'); $data['password'] = $this-><PASSWORD>->post('pass'); $data['user_type'] = $this->input->post('user_type'); //$data['user_access'] = $this->input->post('user_access'); $data['emp_id'] = $this->input->post('engg_name'); $this->User_model->add_user($data); echo "<script>alert('User Added Successfully!');window.location.href='".base_url()."pages/user_cate_list';</script>"; /* Worked on 07-06-2017 */ }else{ echo "<script>alert('User already exists');window.location.href='".base_url()."pages/add_user_cate';</script>"; } } public function edit_user_cate(){ $id=$this->uri->segment(3); $data1['get_usersbyid']=$this->User_model->get_usersbyid($id); //$categories_assigned = $data1['get_usersbyid'][0]->categories_assigned; //$data1['get_categories']=$this->User_model->get_categoriesbyid($categories_assigned); //$data1['get_assigned_categories']=$this->User_model->get_assigned_categories($categories_assigned); $data1['get_employees']=$this->User_model->get_employeeDetails(); $data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('edit_user_cate',$data1); } public function update_users(){ //echo "<pre>";print_r($_POST);exit; //$categories_assigned = $this->input->post('select2'); //echo "<pre>";print_r($categories_assigned);exit; $user_id = $this->input->post('user_id'); $data['name'] = $this->input->post('first_name'); $data['user_name'] = $this->input->post('user_name'); $data['password'] = $this->input->post('pass'); $data['user_type'] = $this->input->post('user_type'); //$data['user_access'] = $this->input->post('user_access'); $data['emp_id'] = $this->input->post('engg_name'); /* if(!empty($categories_assigned )){ $data['categories_assigned'] = implode(',',$categories_assigned); }else{ $data['categories_assigned'] = '0'; } */ $this->User_model->update_user($data,$user_id); echo"<script>parent.$.fancybox.close();</script>"; } public function update_status(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->User_model->update_user_status($data,$id); } public function update_status1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->User_model->update_user_status1($data,$id); } public function get_employees(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->User_model->get_employeeDetails())); } public function add_customer_quick(){ $mob=$this->input->post('mobile'); $chk_cust=$this->Customer_model->check_cust($mob); if(empty($chk_cust)){ $data['customer_id']=$this->input->post('customer_id'); $data['customer_name']=$this->input->post('customer_name'); $data['customer_type']=$this->input->post('cust_type'); $zone=$this->input->post('service_zone'); $zone_id = explode("-",$zone); $data['service_zone'] = $zone_id['0']; $data['company_name']=$this->input->post('company_name'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email'); $data['address']=$this->input->post('address'); $data['address1']=$this->input->post('address1'); $data['city']=$this->input->post('city'); $data['state']=$this->input->post('state'); $data['pincode']=$this->input->post('pincode'); $data2['city']=$this->input->post('city'); $brname=$data1['branch_name']=$this->input->post('branch_name'); $ser_loc_phone=$data1['landline']=$this->input->post('phone'); $ser_loc_re_address=$data1['address']=$this->input->post('re_address'); $ser_loc_re_address1=$data1['address1']=$this->input->post('re_address1'); $ser_loc_re_city=$data1['city']=$this->input->post('re_city'); $ser_loc_re_state=$data1['state']=$this->input->post('re_state'); $ser_loc_re_pincode=$data1['pincode']=$this->input->post('re_pincode'); $service_zone_loc=$data1['service_zone_loc']=$this->input->post('service_zone_loc'); $ser_loc_contact_name=$data1['contact_name']=$this->input->post('contact_name'); $ser_loc_designation=$data1['designation']=$this->input->post('designation'); $ser_loc_mobiles=$data1['mobile']=$this->input->post('mobiles'); $ser_loc_emails=$data1['email_id']=$this->input->post('emails'); //$count=count($data1['company_name']); //$data1=""; $c=$brname; $count=count($c); $this->Customer_model->add_city($data2); $result=$this->Customer_model->add_customer($data); if($result){ $data1 =array(); for($i=0; $i<$count; $i++) { $data1[] = array( 'branch_name' => $brname[$i], 'landline' => $ser_loc_phone[$i], 'address' => $ser_loc_re_address[$i], 'address1' => $ser_loc_re_address1[$i], 'city' => $ser_loc_re_city[$i], 'state' => $ser_loc_re_state[$i], 'pincode' => $ser_loc_re_pincode[$i], 'service_zone_loc' => $service_zone_loc[$i], 'contact_name' => $ser_loc_contact_name[$i], 'designation' => $ser_loc_designation[$i], 'mobile' => $ser_loc_mobiles[$i], 'email_id' => $ser_loc_emails[$i], 'customer_id'=>$result ); } $result1=$this->Customer_model->add_service_location($data1); if($result){ echo "<script>parent.$.fancybox.close();</script>"; //redirect(base_url().'pages/add_service_req/'.$result); } } }else{ echo "<script>alert('Customer already exists');window.location.href='".base_url()."pages/add_quick';</script>"; } } public function add_quick(){ $data1['customer_type']=$this->Customer_model->cust_type_list(); $data1['service_zone']=$this->Customer_model->service_zone_list(); $data1['state_list']=$this->Customer_model->state_list(); $data1['cust_cnt']=$this->Customer_model->cust_cnt(); if(empty($data1['cust_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['cust_cnt'][0]->id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $this->load->view('add_quick',$data1); } public function add_sales_quick(){ $data1['customer_type']=$this->Customer_model->cust_type_list(); $data1['service_zone']=$this->Customer_model->service_zone_list(); $data1['state_list']=$this->Customer_model->state_list(); $data1['cust_cnt']=$this->Customer_model->cust_cnt(); if(empty($data1['cust_cnt'])){ $data1['cnt']='00001'; }else{ $cusid = $data1['cust_cnt'][0]->id; $dat= $cusid + 1; $data1['cnt']=sprintf("%05d", $dat); } $this->load->view('add_sales_quick',$data1); } public function branch_quick_view(){ $id=$this->uri->segment(3); $data1['quick_branch']=$this->Customer_model->getQuickcustservicelocationbyid($id); //echo "<pre>"; //print_r($data1['customer_type']); $this->load->view('quick_branch',$data1); } public function get_city(){ $id=$this->input->post('keyword');//echo $id; exit; $data['city_list']=$this->Customer_model->get_cities($id); $this->load->view('city_list',$data); //$this->output //->set_content_type("application/json") //->set_output(json_encode($this->Customer_model->get_cities($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_state(){ $id=$this->input->post('stateid');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Customer_model->get_states($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function checkMob(){ $id=$this->input->post('id');//echo $id; exit; $chk_cust=$this->Customer_model->check_cust($id); if(!empty($chk_cust)){ echo "Customer Already Exists"; } /* $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Customer_model->get_states($id))); */ } public function checkLand(){ $id=$this->input->post('id');//echo $id; exit; $chk_cust=$this->Customer_model->check_landline($id); if(!empty($chk_cust)){ echo "Customer Already Exists"; } /* $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Customer_model->get_states($id))); */ } public function add_customer_type(){ $cust_type=$this->input->post('cust_type'); $c=$cust_type; $count=count($c); for($i=0; $i<$count; $i++) { if($cust_type[$i]!=""){ $data1 = array('type' => $cust_type[$i]); $result=$this->Customer_model->add_cust_type($data1); } else{ echo "<script>window.location.href='".base_url()."pages/cust_type';alert('Please enter Customer Type');</script>"; } } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/cust_type_list';alert('Customer Type added');</script>"; } } public function update_customer(){ $id=$this->uri->segment(3); $data['list']=$this->Customer_model->getcustomerbyid($id); $data['list1']=$this->Customer_model->getcustservicelocationbyid($id); $data['customer_type']=$this->Customer_model->cust_type_list(); $data['service_zone']=$this->Customer_model->service_zone_list(); $data['state_list']=$this->Customer_model->state_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_cust_list',$data); } public function update_cust_list(){ $id=$this->uri->segment(3); $data['list']=$this->Customer_model->getcustomertypebyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_cust_type',$data); } public function edit_customer_type(){ $cust_typeid = $this->input->post('cust_typeid'); $data=array( 'type'=>$this->input->post('cust_type') ); $this->Customer_model->update_customer_type($data,$cust_typeid); echo "<script>alert('Customer Type Updated');window.location.href='".base_url()."pages/cust_type_list';</script>"; } public function edit_customer(){ error_reporting(0); $zone=$this->input->post('service_zone'); $zone_id = explode("-",$zone); date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; if($this->input->post('mobile')!=""){ $data=array( 'customer_name'=>$this->input->post('customer_name'), 'company_name'=>$this->input->post('company_name'), 'mobile'=>$this->input->post('mobile'), 'landline'=>"", 'email_id'=>$this->input->post('email'), 'address'=>$this->input->post('address'), 'address1'=>$this->input->post('address1'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'pincode'=>$this->input->post('pincode'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); }else{ $data=array( 'customer_name'=>$this->input->post('customer_name'), 'company_name'=>$this->input->post('company_name'), 'mobile'=>"", 'landline'=>$this->input->post('landlineno'), 'email_id'=>$this->input->post('email'), 'address'=>$this->input->post('address'), 'address1'=>$this->input->post('address1'), 'city'=>$this->input->post('city'), 'state'=>$this->input->post('state'), 'pincode'=>$this->input->post('pincode'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); } $id=$this->input->post('cus_id'); $brname=$data1['branch_name']=$this->input->post('branch_name'); $ser_loc_id=$data1['id']=$this->input->post('cust_id'); $ser_loc_phone=$data1['landline']=$this->input->post('phone'); $ser_loc_re_address=$data1['address']=$this->input->post('re_address'); $ser_loc_re_address1=$data1['address1']=$this->input->post('re_address1'); $ser_loc_re_city=$data1['city']=$this->input->post('re_city'); $ser_loc_re_state=$data1['state']=$this->input->post('re_state'); $ser_loc_re_pincode=$data1['pincode']=$this->input->post('re_pincode'); $service_zone_loc=$data1['service_zone_loc']=$this->input->post('service_zone_loc'); $ser_loc_contact_name=$data1['contact_name']=$this->input->post('contact_name'); $ser_loc_designation=$data1['designation']=$this->input->post('designation'); $ser_loc_mobiles=$data1['mobile']=$this->input->post('mobiles'); $ser_loc_emails=$data1['email_id']=$this->input->post('emails'); //$count=count($data1['company_name']); //$data1=""; $c=$brname; $count=count($c); $this->Customer_model->update_customer($data,$id); $data1 =array(); for($i=0; $i<$count; $i++) { $data1 = array( 'branch_name' => $brname[$i], 'landline' => $ser_loc_phone[$i], 'address' => $ser_loc_re_address[$i], 'address1' => $ser_loc_re_address1[$i], 'city' => $ser_loc_re_city[$i], 'state' => $ser_loc_re_state[$i], 'pincode' => $ser_loc_re_pincode[$i], 'service_zone_loc' => $service_zone_loc[$i], 'contact_name' => $ser_loc_contact_name[$i], 'designation' => $ser_loc_designation[$i], 'mobile' => $ser_loc_mobiles[$i], 'email_id' => $ser_loc_emails[$i], 'customer_id' => $id, 'updated_on'=>$updated_on, 'user_id'=>$user_id ); if($ser_loc_id[$i]!="" && isset($ser_loc_id[$i])){ $where = "customer_id=".$id." AND id=".$ser_loc_id[$i]; $result=$this->Customer_model->update_service_location($data1,$where); }else{ $result=$this->Customer_model->add_service_location1($data1); } } /* if(!empty($data1)){ $this->Customer_model->delete_customer_service_loc($id); $result=$this->Customer_model->add_service_location($data1); } */ echo "<script>alert('Customer Updated');window.location.href='".base_url()."pages/cust_list';</script>"; } public function addrow(){ $data['count']=$this->input->post('countid'); $data['zoneid']=$this->input->post('zoneid'); $data['state_list']=$this->Customer_model->state_list(); $data['service_zone']=$this->Customer_model->service_zone_list(); //echo "Count: ".$data['count']; //$data['customerlist']=$this->Service_model->customerlist(); //$data['list_serialnos']=$this->Service_model->list_serialnos(); //$data['servicecat_list']=$this->Service_model->servicecat_list(); //$data['problemlist']=$this->Service_model->problemlist(); //$data['employee_list']=$this->Service_model->employee_list(); $this->load->view('add_cust_row',$data); } public function del_customer(){ $id=$this->input->post('id'); $this->Customer_model->delete_customer_service_loc($id); $result = $this->Customer_model->del_customers($id); } public function del_cust_type(){ $id=$this->input->post('id'); $this->Customer_model->del_customer_type($id); } public function checkname() { //print_r($_POST); exit; $name1= $this->input->post('id'); //echo "name:"; echo $name; exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->User_model->name_validation($name1))); } }<file_sep>/application/views_bkMarch_0817/service_status_new.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $(' <tr> <td> <select> <option>---Select---</option> <option value="spare">Spare 1</option> <option value="spare">Spare 2</option> <option value="spare">Spare 3</option> <option value="spare">Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); $(function(){ var tbl = $("#table11"); $("#addRowBtn1").click(function(){ $('<tr> <td> <select> <option>---Select---</option> <option value="spare">Spare 1</option> <option value="spare">Spare 2</option> <option value="spare">Spare 3</option> <option value="spare">Spare 4</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn1" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn1", "click", function(){ var vals = $('#spare_tot').val(); var idd=$(this).closest(this).attr('id'); // alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); //alert($('#amt'+ctid).val()); var vals = $('#spare_tot').val(); vals -= Number($('#amt'+ctid).val()); //alert(vals); $('#spare_tot').val(vals); var tax_amt = (vals * $('#tax_type').val()) / 100; var warran = $('#spare_tax1').val(); if(warran){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); $('#total_amt1').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); var tott = $('#total_amt').val(); var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(tott); //alert(Total_amount); $('#total_amt').val(Total_amount); $('#service_pending_amt').val(Total_amount); $('#service_pending_amt1').val(Total_amount); } $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1+'&modelid='+modelid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/addrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#table11').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('#totamt').click(function(){alert("ddd"); alert($('#amt').val()); }); }); </script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).val()=="6"){ $(".box").not(".ready").hide(); $(".ready").show(); } else if($(this).val()=="4"){ $(".box").not(".delivery").hide(); $(".delivery").show(); } else if($(this).val()=="9"){ $(".box").not(".onhold").hide(); $(".onhold").show(); } else if($(this).attr("value")=="blue"){ $(".box").not(".blue").hide(); $(".blue").show(); }else if($(this).val()=="eng_notes"){ $(".box").not(".eng_notes").hide(); $(".eng_notes").show(); } else if($(this).val()=="cust_remark"){ $(".box").not(".cust_remark").hide(); $(".cust_remark").show(); } else{ $(".box").hide(); } }); }).change(); }); </script> <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> <script> $(document).ready(function(){ $(".pagerefresh").click(function() { location.reload(true); }); }); </script> <style> .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td select { width: 210px !important; } .tableadd2 tr td select { width: 165px; margin-bottom: 15px; } .tableadd2 tr.back td { background: #6c477d !important; border: 1px solid #6c477d !important; color: #fff; padding: 8px; } .tableadd2 tr td input { margin: 10px; height: 30px; } .tableadd tr td label{ width: 180px !important; font-weight: bold; font-size: 13px; } .cyan { background-color: #6c477d !important; } .box{ padding: 20px; display: none; margin-top: 20px; box-shadow:none !important; } a.box{ background:gray; } [type="radio"]:not(:checked) + label, [type="radio"]:checked + label { font-size: 14px; font-weight: normal; } .rating label { font-weight: normal; padding-right: 5px; } .rating li { display: inline; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: 100%; } [type="radio"]:not(:checked), [type="radio"]:checked { position:relative; } [type="radio"] + label:before, [type="radio"] + label:after { } [type="radio"] + label:before, [type="radio"] + label:after { content: ''; position: absolute; left: 0; top: 0; margin: 4px; width: 16px; height: 16px; display:none; z-index: 0; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; } [type="radio"]:not(:checked) + label, [type="radio"]:checked + label { position: relative; padding-left: 5px; cursor: pointer; display: inline-block; height: 25px; line-height: 25px; font-size: 14px; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; } .breadcrumbs-title { font-size: 1.8rem; line-height: 5.804rem; margin: 0 0 0; color:#6C217E; font-weight:bold; } .fa { margin-right: 15px; color: #845782; } input[type=radio] { margin-left: 10px; margin-right: 2px; } .col-md-2, .col-md-1 { padding:0px; } .headerDivider { border-left:1px solid #c5c5c5; border-right:1px solid #c5c5c5; height:25px; position: absolute; top:73px; left: 280px; } @media only screen and (max-width: 350px){ .headerDivider { border-left:1px solid #c5c5c5 !important; border-right:1px solid #c5c5c5 !important; height:25px !important; position: absolute !important; top:102px !important; left: 40px !important; } .toggleaddress { display: none; } } textarea { width: 100%; height: auto !important; background-color: transparent; } .noresize{ resize: none; } .linkaddress { cursor: pointer; } @media only screen and (max-width: 380px) { td { padding: 3px !important; } a { padding: 3px !important; } select { width: 100px !important; } .tableadd2 tr td input { border-radius: 5px; height: 33px; margin-top: 17px; width: 50px; margin-left: 3px; margin-right: 3px; } .tableadd2 tr td select { padding: 0 30px 0 0; } } @media only screen and (max-width: 768px) and (min-width: 240px){ ol, ul { margin-top: 0; margin-bottom: 0 !important; } } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <div><a class="btn cyan waves-effect waves-light " onclick="history.go(-1);"><span class="fa fa-arrow-left" data-toggle="tooltip" title="Back"></span></a> <div class="headerDivider "></div><span class="fa fa-refresh pagerefresh" data-toggle="tooltip" title="Refresh"></span></div> <?php if(isset($offsite_flag)){?> <h5 class="breadcrumbs-title">Work In-progress</h5> <?php } else{?> <h5 class="breadcrumbs-title">Quote Review</h5> <?php }?> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div> <form action="<?php echo base_url(); ?>quotereview/add_quotereview" method="post" name="frmServiceStatus" > <?php foreach($getQuoteByReqId as $key){ if(isset($key->problem)){ $problem_data = explode(",",$key->problem); } ?> <div class="tableadd col-md-12 col-sm-12"> <?php if($key->status!='16'){ ?> <div class="col-md-12 col-sm-12" style="padding-left:30px;padding-bottom:10px"> <div class="col-md-2 col-sm-3"><label style="margin-bottom:0px">Acknowledgement1</label></div> <div class="col-md-1 col-sm-3"><input type="radio" name="eng_ack" value="accept">Accept</div> <div class="col-md-1 col-sm-3"><input type="radio" name="eng_ack" value="reject">Reject</div> <div class="col-md-1 col-sm-3"><input type="radio" name="eng_ack" value="later">Later</div> </div> <?php } ?> <div class="col-md-6 col-sm-12"> <div class="col-md-6 col-sm-3"> <label>Request ID:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="reque_id" class="" value="<?php echo $key->request_id; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Firm Name:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="cust_name" class="" value="<?php echo $key->company_name; ?>" readonly> <input type="hidden" name="cust_mobile" class="" value="<?php if($key->cust_mobile!=''){echo $key->cust_mobile;} ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Branch Name:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="br_name" class="" value="<?php echo $key->branch_name; ?>" readonly> </div> <div class="col-md-6 col-sm-3"><label>Contact Name:</label></div> <div class="col-md-6 col-sm-3"><input type="text" name="cont_name" class="" value="<?php echo $key->contact_name; ?>" readonly> <input type="text" value="<?php echo $key->email_id;?>" name="email"></div> <div class="col-md-6 col-sm-3"> <label>Mobile:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="cust_mobile1" class="" value="<?php echo $key->cust_mobile; ?>" readonly> </div> <div class="col-md-12 addressdiv" style="padding:0px;"> <div class="col-md-6 col-sm-3 addresslabel"><a class="linkaddress">Address</a></div> <div class="col-md-6 col-sm-3 toggleaddress"><textarea class="noresize materialize-textarea" cols="22" rows="2" readonly><?php echo $key->address.' '.$key->address1; ?></textarea></div> </div> <div class="col-md-6 col-sm-3"> <label>Landline:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="land_line" class="" value="<?php echo $key->landline; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Product Name:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="p_name" class="" value="<?php echo $key->model; ?>" readonly> <input type="hidden" name="modelid" id="modelid" class="" value="<?php echo $key->modelid; ?>"> <input type="hidden" name="req_id" id="req_id" class="" value="<?php echo $req_id; ?>"> <input type="hidden" name="brand_name" id="brand_name" class="" value="<?php echo $key->brand_name; ?>"> </div> <?php if($key->serial_no=='serial_no') {?> <div class="col-md-6 col-sm-3"> <label>Serial No.:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="serial_no" value="update sr no" readonly>&nbsp; <input type="hidden" name="order_row_id" value="<?php echo $key->order_row_id; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Batch No.:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="batch_no" value="batch no" readonly> </div> <?php } ?> <?php if($key->serial_no!='serial_no') {?> <div class="col-md-6 col-sm-3"> <label>Serial No.:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="serial_no" value="<?php echo $key->serial_no; ?>">&nbsp; <input type="hidden" name="order_row_id" value="<?php echo $key->order_row_id; ?>"> </div> <div class="col-md-6 col-sm-3"> <label>Batch No.:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="batch_no" value="<?php echo $key->batch_no; ?>"> </div> <div class="col-md-6 col-sm-3"> <label>Addl Engineer Name: </label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="addl_engg" class="" value="<?php foreach($service_req_listforaddlEmp1 as $AddlEmpkey){echo $AddlEmpkey->emp_name; }?>" readonly> <input type="text" value="<?php foreach($service_req_listforaddlEmp1 as $roww){ if($roww->id==""){ echo ""; }else {echo $roww->id;} }?>" name="eng_name"> </div> <?php } ?> </div> <div class="col-md-6"> <?php if($user_type!='7'){?> <div class="col-md-6 col-sm-3"> <label>Date Of Purchase:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="purchase_date" value="<?php echo $key->purchase_date; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Warranty End Date:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="warranty_date" value="<?php echo $key->warranty_date; ?>" readonly> </div> <?php } ?> <div class="col-md-6 col-sm-3"> <label>Date Of Request:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="request_date" value="<?php echo $key->request_date; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Problem:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" value="<?php if(!empty($problemlist1)){ foreach($problemlist1 as $problemlistkey1){ if (in_array($problemlistkey1->id, $problem_data)){ echo $prob_category = $problemlistkey1->prob_category; }} }else{ echo $prob_category =""; } ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Machine Status:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="" class="" value="<?php echo $key->machine_status; ?>" readonly> </div> <div class="col-md-6 col-sm-3"> <label>Blanket Approval:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="" class="" value="<?php echo $key->blank_app; ?>" readonly> </div> <div class="col-md-6 col-sm-3"><label>Area:</label></div> <div class="col-md-6 col-sm-3"><input type="text" name="area_name" class="" value="<?php echo $key->area_name; ?>" readonly></div> <div class="col-md-6 col-sm-3"><label>Pincode:</label></div> <div class="col-md-6 col-sm-3"><input type="text" name="pincode" class="" value="<?php echo $key->pincode; ?>" readonly></div> <div class="col-md-6 col-sm-3"> <label>Location:</label> </div> <div class="col-md-6 col-sm-3"> <input type="text" name="serviceloc" class="" value="<?php echo $key->service_loc; ?>" readonly> </div> <!--<div class="col-md-6 col-sm-3"> <a href="#">Address:</a> </div> <div class="col-md-6 col-sm-3"> <input type="text" value="<?php echo $key->address.' '.$key->address1; ?>" readonly> </div>--> </div> <!--<tr class="work1 box"> <td ><label>Work In Progress</label></td> </tr> <tr class="work2 box"> <td ><label>Quick Changes</label></td> </tr>--> </div> <?php } ?> <?php if(!empty($get_qc_parameters_details)){ foreach($get_qc_parameters_details as $qcp_key){ $qc_master_ids[] = $qcp_key->qc_master_id; } }else{ $qc_master_ids[] = ''; } $qc_models = $this->workin_prog_model->get_qc_params($key->modelid); if(!empty($qc_models)){?> <h5 class="breadcrumbs-title">QC</h5> <table class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>QC Parameters</td> <td>Actual value</td> <td>Result value</td> </tr> <?php foreach($qc_models as $qc_key){ ?> <tr> <td><?php echo $qc_key->qc_param; ?></td> <td><?php echo $qc_key->qc_value; ?></td> <?php if(in_array($qc_key->id, $qc_master_ids) && !empty($qc_master_ids)){ $qc_models = $this->workin_prog_model->get_qc_params_det($qc_key->id); ?> <td><input type="text" name="res_qc_value[]" id="res_qc_value" value="<?php echo $qc_models[0]->result_qc_value; ?>">&nbsp; <input type="hidden" name="qc_param_id[]" id="qc_param_id" value="<?php echo $qc_models[0]->qc_master_id; ?>"></td> <?php } else{?> <td><input type="text" name="res_qc_value[]" id="res_qc_value" value="">&nbsp; <input type="hidden" name="qc_param_id[]" id="qc_param_id" value="<?php echo $qc_key->id; ?>"></td> <?php } ?> </tr> <?php } ?> </table> <?php } ?> <h5 class="breadcrumbs-title">Spare Info</h5> <div class="table-responsive"> <table id="table11" class="tableadd2" style="margin-bottom: 20px;"> <tr class="back" > <td>Spare Name</td> <td>Quantity</td> <td>Amount</td> <td>Status</td> <td>Warranty claim status</td> <td style="width:50px;background: none;border: 0px"><a id="addMoreRows" style="padding: 10px;color: #000; border-radius:5px;"><span class="fa fa-plus" style="margin-right: 0px;"></span></a></td> </tr> <?php if(!empty($spareIds)){ foreach($spareIds as $key3){ foreach($key3 as $key4){ $usedspare[] = $key4->used_spare; $stockspare[] = $key4->spare_qty; $salesprice[] = $key4->sales_price; } } }//exit; $count='0'; foreach($getQuoteReviewSpareDetByID as $ReviewDetKey2){ ?> <tr> <td><input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="<?php if(!empty($usedspare[$count])){echo $usedspare[$count];} ?>"><input type="hidden" name="spare_tbl_id[]" id="spare_tbl_id<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->id;?>"><select name="spare_name[]" id="sparename_<?php echo $count; ?>" class="spare_name"> <option value="">---Select---</option> <?php foreach($spareListByModelId1 as $sparekey1){ if($sparekey1->id==$ReviewDetKey2->spare_id){ ?> <option selected="selected" value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name; ?></option> <?php } else {?> <option value="<?php echo $sparekey1->id; ?>"><?php echo $sparekey1->spare_name; ?></option> <?php } } ?> </select> </td> <td><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="<?php echo $ReviewDetKey2->spare_qty; ?>" class="spare_qty"><input type="hidden" value="<?php if(!empty($stockspare[$count])){echo $stockspare[$count];}?>" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td><input type="text" value="<?php echo $ReviewDetKey2->amt; ?>" name="amt[]" id="amt<?php echo $count; ?>" class="" readonly><input type="hidden" value="<?php if(!empty($salesprice[$count])){echo $salesprice[$count];}?>" name="amt1" id="amt1<?php echo $count; ?>" class=""></td> <td style="border:none;"><a class="delRowBtn1" id="delRowBtn1_<?php echo $count; ?>"><i class="fa fa-trash-o"></i></a></td> </tr> <?php $count++; } ?> </table> </div> <div class="tableadd col-md-12"> <div class="col-md-6"> <?php if($user_type!='7'){?> <div class="col-md-6"><label>Spare Tax Amount:</label></div> <div class="col-md-6"><?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Preventive'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?><?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Warranty'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Chargeable'){ ?><input type="hidden" name="spare_tax1" id="spare_tax1" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <?php $i=0; foreach($getWarrantyInfo as $WarranKey){ if($WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){ ?><input type="hidden" name="amc_typ" id="amc_typ" class="" value="<?php echo $WarranKey->machine_status; ?>" ><?php } }?> <input type="text" name="spare_tax" id="spare_tax" readonly class="" value="" ><input type="hidden" name="tax_type" id="tax_type" class="" value="<?php foreach($getTaxDefaultInfo as $taxKey){ echo $taxKey->tax_percentage; }?>" > </div> <div class="col-md-6"><label>Spare Total Charges:</label></div> <div class="col-md-6"><input type="text" name="spare_tot" id="spare_tot" readonly class="" value="" ></div> <div class="col-md-6"><label>Labours Charges:</label></div> <div class="col-md-6"><input type="text" name="labourcharge" id="labourcharge" readonly class="" value="<?php foreach($getServiceCatbyID as $ServiceKey){if($WarranKey->machine_status=='Warranty' || $WarranKey->machine_status=='Preventive' || $WarranKey->machine_status=='Comprehensive' || $WarranKey->machine_status=='serviceonly'){echo $scharge = $i;}else{echo $scharge = $ServiceKey->service_charge;}} if(isset($getservicecharge)){echo $scharge = $getservicecharge;} ?>" ></div> <?php } ?> <div class="col-md-6"><label>Date Of Delivery:</label></div> <div class="col-md-6"><input type="text" name="delivery_date" id="datetimepicker7" readonly value="<?php echo $del_date;?>" >&nbsp;<input type="hidden" name="sms_mobile" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->emp_mobile; }?>" readonly></div> </div> <div class="col-md-6"> <?php if($user_type!='7'){?> <div class="col-md-6"><label>Conveyance Charges:</label></div> <div class="col-md-6"><input type="text" name="concharge" id="concharge" readonly class="" value="<?php if($WarranKey->machine_status=="Chargeable"){echo $concharg = $key->concharge;}else{echo $concharg = $i;} ?>" ></div> <div class="col-md-6"><label>Total Amount:</label></div> <div class="col-md-6"><input type="text" name="total_amt" id="total_amt" readonly class="" value="" > <input type="hidden" name="total_amt1" id="total_amt1" class="" value="" ></div> <?php } ?> <?php //if(isset($offsite_flag)){ ?> <!--<div class="col-md-6"><label>Discounts:</label></div> <div class="col-md-6"><input type="text" name="disc_amt" id="disc_amt" class="" value="" ></div>--> <?php //}?> <div class="col-md-6"><label>Status:</label></div> <div class="col-md-6"> <?php if(isset($offsite_flag) && $user_type!='7'){?> <select name="status"> <option value="1">---Select---</option> <!--<option value="approve">Approve</option>--> <?php foreach($status_listForoffsiteworkInpro as $statuskey){ ?> <option value="<?php echo $statuskey->id; ?>"><?php echo $statuskey->status; ?></option> <?php } ?> </select> <?php } elseif($user_type=='7'){ ?> <select name="status"> <option value="1">---Select---</option> <!--<option value="approve">Approve</option>--> <?php foreach($status_listForEmpLogin as $Empstatuskey){ ?> <option value="<?php echo $Empstatuskey->id; ?>"><?php echo $Empstatuskey->status; ?></option> <?php } ?> </select> <?php } else{ ?> <select name="status"> <option value="5">---Select---</option> <!--<option value="approve">Approve</option>--> <?php foreach($status_listForquoteInpro as $statuskey){ ?> <option value="<?php echo $statuskey->id; ?>"><?php echo $statuskey->status; ?></option> <?php } ?> </select> <?php } ?> </div> </div> </div> <div class="tableadd col-md-12"> <input type="hidden" name="assign_to_id" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->id; }?>" readonly> <div class="delivery box"> <div class="col-md-3"><label>Date Of Delivery:</label></div> <div class="col-md-3"><input type="text" name="delivery_date1" id="datetimepicker7" value="<?php echo $del_date; ?>" ></div> </div> <div class="delivery box"> <div class="col-md-3"><label>Comments:</label></div> <div class="col-md-3"><input type="text" name="comment_deliver" class="" value="Delivered" ></div> </div> <div class="delivery box"> <div class="col-md-3"><label>Assign To:</label></div> <div class="col-md-3"><input type="text" name="assign_to" class="" value="<?php foreach($service_req_listforEmp1 as $Empkey){echo $Empkey->emp_name; }?>" readonly> </div> </div> <?php foreach($getQuoteByReqId as $statuskey1){ if($statuskey1->status!="5"){ ?> <div class="onhold box"> <div class="col-md-3"><label>Date of On-Hold:</label></div> <div class="col-md-3"><input type="text" name="on_hold" id="datetimepicker71" value="<?php if(isset($req_date)){echo $req_date;} ?>" ></div> <div class="col-md-3"><label>On Hold Reason:</label></div> <div class="col-md-3"><textarea type="text" name="onhold_reason" id="onhold_reason" cols="25" rows="3" class="materialize-textarea"></textarea></div> </div> <?php } } ?> <?php if(isset($offsite_flag)){?> <div style="margin-left:30px;margin-top:15px;"> <label>Ratings</label>: <ul class="rating"> <li><label><input class="rate" type="radio" name="rating" value="1">Satisfied</label></li> <li><label><input class="rate" type="radio" name="rating" value="2">Good</label></li> <li><label><input class="rate" type="radio" name="rating" value="3">Very Good</label></li> <li><label><input class="rate" type="radio" name="rating" value="4">Excellent</label></li> </ul> </div> <?php } ?> </div> <div class="tableadd col-md-12"> <div class="col-md-3"> <label style="margin-left:20px;">Coordinator Instructions:</label> </div> <div class="col-md-3"> <textarea type="text" name="notes" id="notes" cols="25" rows="3" class="materialize-textarea col-md-3"><?php foreach($getQuoteByReqId as $notekey){echo $notekey->notes;} ?></textarea> </div> <div class="col-md-3"> <label>Notes:</label> </div> <div class="col-md-3"> <select name="notes_all"> <option value="">Select</option> <option value="eng_notes">Engineer notes</option> <option value="cust_remark">Customer remarks</option> </select> <div class="eng_notes box"> <!--<div class="tableadd col-md-3"><label>Engg Notes:</label></div>--> <div class="tableadd col-md-3"><textarea type="text" name="eng_notes" id="eng_notes" cols="25" rows="3" class="materialize-textarea"></textarea></div> </div> <div class="cust_remark box"> <!--<div class="tableadd col-md-3"><label>Customer Notes:</label></div>--> <div class="tableadd col-md-3"><textarea type="text" name="cust_remark" id="cust_remark" cols="25" rows="3" class="materialize-textarea"></textarea></div> </div> </div> </div> <input type="hidden" name="countid" id="countid" class="" value="0" > <table class="tableadd" style="margin-top: 25px;"> <tr > <td > <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button>&nbsp; <a class="btn cyan waves-effect waves-light " onclick="history.go(-1);">Exit </a> </td> </tr> </table> </div> </form> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ $('#tot_charge').keyup(function() { var tot_charge = $( this ).val(); $('#pending_amt').val(tot_charge); }); </script> <script> $('#cmr_paid').keyup(function() { var tot_charge = $('#tot_charge').val(); var cmr_paid = $( this ).val(); var pending_amt = parseInt(tot_charge) - parseInt(cmr_paid); $('#pending_amt').val(pending_amt); }); $('#disc_amt').keyup(function() { var disc_amt = $( this ).val(); if(disc_amt!=""){ var total_amt = $('#total_amt1').val(); //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = parseInt(total_amt) - parseInt(disc_amt); //alert(discount_amt); $('#total_amt').val(discount_amt); $('#service_pending_amt').val(discount_amt); $('#service_pending_amt1').val(discount_amt); } }); $('#service_cmr_paid').keyup(function() { var service_pending_amt_val = $('#service_pending_amt1').val(); //alert(pending_amt_val); var service_cmr_paid = $( this ).val(); var service_pending_amt = parseInt(service_pending_amt_val) - parseInt(service_cmr_paid); $('#service_pending_amt').val(service_pending_amt); }); </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }); }); }//]]> </script> <script> $(document).ready(function(){ $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999-19-39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('#datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker71').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker8').datetimepicker({ onChangeDateTime:logic, onShow:logic }); }); </script> <script> $(document).ready(function(){ $('.addresslabel').click(function() { $('.toggleaddress').toggle(); }); }); </script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/models/Servicecategory_model.php <?php class Servicecategory_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_service_category($data){ $this->db->insert('service_category',$data); return true; } public function checkservicename($user) { $this->db->select('service_category'); $this->db->from('service_category'); $this->db->where_in('service_category',$user); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function add_service_charge($data){ $this->db->insert('service_charge',$data); return true; } public function check_service_charge($data1,$data12) { //echo("hii"); //print_r($data1); print_r($data12);exit; $this->db->select('service_cat_id,model'); $this->db->from('service_charge'); $this->db->where('model', $data12); $this->db->where('service_cat_id',$data1); $query=$this->db->get(); //return $query->result(); //echo "<pre>";print_r($query->result());exit; if($query->num_rows()>0) { return 1; } else{ //return $query->result(); return 0; } } public function add_service_chargeadd($data8){ $this->db->insert('service_charge',$data8); return true; } public function service_cat_list(){ $this->db->select("id,service_category",FALSE); $this->db->from('service_category'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_cat_list1(){ $this->db->select("service_category.id,service_category.service_category,service_category.service_charge,products.model",FALSE); $this->db->from('service_category'); $this->db->join('products', 'products.id = service_category.model'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_charge_list(){ $this->db->select("service_charge.id, service_charge.service_charge, service_charge.service_cat_id, service_category.service_category, products.id As Modelid, products.model",FALSE); $this->db->from('service_charge'); $this->db->join('service_category', 'service_category.id = service_charge.service_cat_id'); $this->db->join('products', 'products.id = service_charge.model'); //$this->db->group_by('service_category.id '); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_charge_ByGrp(){ $this->db->distinct(); $this->db->select("service_charge.service_cat_id",FALSE); $this->db->from('service_charge'); //$this->db->group_by('service_category.id '); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_service_charges($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('service_charge', $data1, $where); $this->db->query($qry); /* echo $this->db->last_query(); exit; */ //exit; } public function service_cat_charge_list(){ $this->db->select("service_category.id,service_category.service_category",FALSE); $this->db->from('service_category'); $this->db->join('service_charge', 'service_charge.service_cat_id = service_category.id'); $this->db->group_by('service_category.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_list($id){ $this->db->select("service_category.id,service_category.service_category",FALSE); $this->db->from('service_category'); $this->db->join('service_charge', 'service_charge.service_cat_id = service_category.id'); $this->db->where('service_category.id',$id); $this->db->group_by('service_category.id'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function service_charg($id){ $this->db->select("service_charge.id, service_charge.service_charge, service_charge.service_cat_id, service_category.service_category, products.id As Modelid, products.model",FALSE); $this->db->from('service_charge'); $this->db->join('service_category', 'service_category.id = service_charge.service_cat_id'); $this->db->join('products', 'products.id = service_charge.model'); $this->db->where('service_charge.service_cat_id',$id); //$this->db->group_by('service_category.id '); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function modellist(){ $this->db->select("id, model",FALSE); $this->db->from('products'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); return $query->result(); } public function getservicecatbyid($id){ $this->db->select("id,service_category",FALSE); $this->db->from('service_category'); //$this->db->join('products', 'products.id = service_category.model'); $this->db->where('id',$id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicechargeInfobyid($id){ $query = $this->db->get_where('service_charge', array('service_cat_id' => $id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_serv_cat($data,$id){ $this->db->where('id',$id); $this->db->update('service_category',$data); } public function del_serv_cat($id){ $this->db->where('id',$id); $this->db->delete('service_category'); } public function service_validation($product_id) { $query = $this->db->get_where('service_category', array('service_category' => $product_id)); return $numrow = $query->num_rows(); } }<file_sep>/application/views/templates/headerbk03June2017.php <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"> <link href="<?php echo base_url(); ?>assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/custom-style.css" type="text/css" rel="stylesheet" media="screen,projection"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/font-awesome/css/ionicons.min.css"> <link href="<?php echo base_url(); ?>assets/js/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/css/prism.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/js/plugins/data-tables/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet" media="screen,projection"> <link href="<?php echo base_url(); ?>assets/css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/AdminLTE.min.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery-ui.css"> <link href="<?php echo base_url(); ?>assets/css/print.css" type="text/css" rel="stylesheet" media="print" /> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addrow.js'></script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/addtable.js'></script> <script src="<?php echo base_url(); ?>assets/js/jquery-ui.js"></script> <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script> <style> .btn-box-tool:active { background-color: rgb(5, 94, 135); } .side-nav.fixed a { display: block; padding: 0px 2px 0px 1px !important; color: #055E87; } .side-nav li ul li a { margin: 0px 1rem 0px 0rem !important; } /*.saturate { -webkit-filter: saturate(50); filter: saturate(50); }*/ @media only screen and (min-width:240px) and (max-width:768px){ .nav{ display:none; } .navbar-toggle{ display:none; } .right{ float: none !important; position: relative !important; bottom: 0px !important; width: 134px !important; left: 60px; background: #303f9f; } .img-welcome { width: 25px; height: 25px; float: right !important; position: relative; right: 0px !important; top: 2px; /* border: 1px solid #ccc; */ } ol, ul { margin-top: 0; margin-bottom: -24px !important; } } .bg-aqua, .callout.callout-info, .alert-info, .label-info, .modal-info .modal-body { background-color: #3e0963 !important; } .box-title{ color:#6C217E; } /*header, footer { color: white; background: #DBD0E1 !important; background-image: url(background.png); box-shadow: 0 0 10px rgba(0, 0, 0, 0.51); } */ /* Mega Menu New */ .nav, .nav a, .nav ul, .nav li, .nav div, .nav form, .nav input { margin: 0; padding: 0; border: none; outline: none; } .nav a { text-decoration: none; } .nav li { list-style: none; } .nav { display: inline-block; position: relative; cursor: default; z-index: 500; left:80px; background: transparent; } .nav > li { display: block; float: left; } .nav > li > a { position: relative; display: block; z-index: 510; height: 54px; padding: 0 20px !important; line-height: 54px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; font-stretch: ultra-expanded; color: #522276; text-shadow: 0 0 1px rgba(0,0,0,.35); /*background: #303f9f; border-left: 1px solid #303f9f; border-right: 1px solid #303f9f;*/ -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li:hover > a { /*background: #303f9f;*/ } .nav > li:first-child > a { border-radius: 3px 0 0 3px; border-left: none; } .nav > li.nav-search > form { position: relative; width: inherit; height: 54px; z-index: 510; border-left: 1px solid #4b4441; } .nav > li.nav-search input[type="text"] { display: block; float: left; width: 1px; height: 24px; padding: 15px 0; line-height: 24px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #999999; text-shadow: 0 0 1px rgba(0,0,0,.35); background: #372f2b; -webkit-transition: all .3s ease 1s; -moz-transition: all .3s ease 1s; -o-transition: all .3s ease 1s; -ms-transition: all .3s ease 1s; transition: all .3s ease 1s; } .nav > li.nav-search input[type="text"]:focus { color: #fcfcfc; } .nav > li.nav-search input[type="text"]:focus, .nav > li.nav-search:hover input[type="text"] { width: 110px; padding: 15px 20px; -webkit-transition: all .3s ease .1s; -moz-transition: all .3s ease .1s; -o-transition: all .3s ease .1s; -ms-transition: all .3s ease .1s; transition: all .3s ease .1s; } .nav > li.nav-search input[type="submit"] { display: block; float: left; width: 20px; height: 54px; padding: 0 25px; cursor: pointer; background: #372f2b url(../img/search-icon.png) no-repeat center center; border-radius: 0 3px 3px 0; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; -ms-transition: all .3s ease; transition: all .3s ease; } .nav > li.nav-search input[type="submit"]:hover { background-color: #4b4441; } .nav > li > div { position: absolute; display: block; width: 43em; top: 54px; left: 0; opacity: 0; visibility: hidden; overflow: hidden; background: #fff; border: 1px solid #2e3192; border-radius: 5px; -webkit-transition: all .3s ease .15s; -moz-transition: all .3s ease .15s; -o-transition: all .3s ease .15s; -ms-transition: all .3s ease .15s; transition: all .3s ease .15s; } .nav > li:hover > div { opacity: 1; visibility: visible; overflow: visible; } .nav > li > div:before { content: ""; border-bottom: 15px solid #fff; border-right: 17px solid transparent; border-left: 17px solid transparent; position: absolute; top: -15px; left: 50px; z-index: 1001; } .nav > li > div:after { content: ""; border-bottom: 17px solid #ccc; border-right: 19px solid transparent; border-left: 19px solid transparent; position: absolute; top: -17px; left: 48px; z-index: 800; } .nav .nav-column { float: left; width: auto; padding: 0px 1.5%; } .nav .nav-column h3 { margin: 20px 0 10px 0; line-height: 18px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 13px; color: #2e3192; text-transform: uppercase; } .nav .nav-column h3.orange { color: #ff722b; } .nav .nav-column li a { display: block; line-height: 26px; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 12px; color: #888888; text-decoration:none; } .nav .nav-column li a:hover { color: #666666; } .nav>li>a:hover, .nav>li>a:visited .nav>li>a:active, .nav>li>a:focus { color: #522276; background: #DBD0E1; } .divider{ background-color: #967d58 !important; } .right { float: right !important; position: relative !important; right: 0px !important; top: -50px; background: transparent; } .right li > div a{ color:#522276; font-size:1em; } .waves-block { display: block; color: #522276; } .waves-light{ font-size:13px; font-weight:bold; } .right li > a i.fa-sign-out{ font-size:16px !important; } .fa-arrows-alt{ margin-right:10px; } a.waves-light:hover, a.waves-light:active, a.waves-light:focus { color: #fff !important; } header{ padding:0 !important; height:55px; } .navbar-header { float: left; width: 223px !important; } .navbar-nav>li>a { padding-top: 10px; padding-bottom: 10px; line-height: 54px !important; } .btn-primary { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } .btn-primary:hover { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } .btn-primary:focus { background-color: #dbd0e1; border-color: #3e0963; color:#3e0963; } /* Responsive Menu Style */ .navbar-toggle { position: relative; float: right; padding: 9px 10px; /* margin-top: 8px; */ margin-right: 15px; margin-bottom: 8px; background-color: transparent; background-image: none; border: 1px solid transparent; border-radius: 4px; position: relative; bottom: 40px; } .navbar-toggle .icon-bar { display: block; width: 22px; height: 2px; border-radius: 1px; border:solid #fff; } .in .nav{ left: 0px; position: relative; width: 415px; } .in .nav li{ float: none; position: inherit; border-bottom: 1px solid #ccc; } .collapse.in { display: block; position: relative; z-index: 11; bottom: 50px; background: #fff; padding-left: 0px; height:auto; } .in .nav > li > div{ z-index: 1111; width: 250px; } .in .nav .nav-column{ float: none; width: 70%; padding: 0px 1.5%; } .in .nav .nav-column > ul{ width: 244px; } .in .nav .nav-column > ul >li{ border-bottom:none; } .in .nav .nav-column .divider{ width:244px; } .in ul.right{ float: none !important; position: relative !important; bottom: 0px !important; width: 413px; left: 0px; background: #303f9f; } .img-welcome{ width:20px; height:20px; float:right; position:relative; left:22px; /*border:1px solid #ccc;*/ } .in .right .img-welcome{ width:25px; height:25px; position:relative; left: -260px; bottom: 0px; /*border:1px solid #ccc;*/ } .fa { font-size:21px !important; } .fa-user { font-size: 2.4rem !important; padding-left: 3px; } #slide-out li a i { padding-left: 7px; } .fa-arrow-right { font-size:14px !important; } .coloricon{ background-image:url("<?php echo base_url(); ?>assets/images/icon.png"); height:25px; width:25px; background-repeat: no-repeat; background-size: cover; background-color: transparent; /*position:relative; left:1298px;*/ position: relative; top: 20px; } .theme { height:25px; width:25px; background-repeat: no-repeat; background-size: cover; background-color: transparent; /*position:relative; left:1298px;*/ position: relative; top: 20px; } .coloricon:hover { background-color: transparent !important; box-shadow: none !important; } /*.coloricon:active { background-color: transparent !important; box-shadow: none !important; }*/ .coloricon:focus { background-color: transparent !important; box-shadow: none !important; } .color-picker { background: rgba(255, 255, 255, 0.75); /* padding: 10px; */ border: 1px solid rgba(203, 203, 203, 0.6); border-radius: 2px; position: absolute; width: 160px; right: 95px; top: 50px; /*bottom: 510px;*/ } .picker-wrapper { padding: 0px !important; } .color-picker > div { width: 15px !important; display: inline-block; height: 15px !important; margin: 2px !important; border-radius: inherit !important; opacity: 0.7; } .color-picker > div:before { content: ""; border-left: 17px solid #fff; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -13px; z-index: 1001; } .wrapper { min-height: 100%; position: static; overflow: inherit; } .color-picker > div:after { content: ""; border-left: 17px solid #ccc; border-top: 17px solid transparent; border-bottom: 17px solid transparent; position: absolute; top: -1px; right: -15px; z-index: 800; } .btn-box-tool { padding: 5px; font-size: 12px; background: transparent; color: #000 !important; font-weight:bold; } .toggle-fullscreen:hover { color:white !important; text-decoration:none; } .toggle-fullscreen:focus { color:white !important; text-decoration:none; } .Accordion li.active a { color:black; } @media only screen and (max-width: 992px){ .hide-on-med-and-down { display: block !important; } /*header .brand-logo img { width: 172px !important; position: relative; right: 75px; bottom: 8px; }*/ .waves-effect { position: relative; left: 0px; } .sidebar-collapse { position: absolute; left: -170px; top: -70px; } } @media only screen and (min-width: 301px){ nav, nav .nav-wrapper i, nav a.button-collapse, nav a.button-collapse i { height: 64px !important; line-height: 64px !important; } } .hide-on-med-and-down li { display: -webkit-inline-box; } </style> <style> #header, thead { background: #dbd0e1; } h2 { color: #dbd0e1; } </style> </head> <body> <header id="header" class="page-topbar"> <div class="navbar-header"> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type!='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <img src="<?php echo base_url(); ?>assets/images/eff_logo.png" alt="materialize logo" style="height:55px;color:#fff" class="saturate"></a> <a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"><img src="<?php echo base_url(); ?>assets/images/stlogo.jpg" alt="materialize logo" style="height:55px;color:#fff" class="saturate"> </a> <?php } }?> <?php foreach($user_dat As $Ses_key1){if($Ses_key1->user_type=='7'){ ?><a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <img src="<?php echo base_url(); ?>assets/images/eff_logo.png" alt="materialize logo" style="height:55px;color:#fff;float:left" class="saturate"></a> <a href="<?php echo base_url(); ?>pages/dash" class="brand-logo darken-1"> <img src="<?php echo base_url(); ?>assets/images/stlogo.jpg" alt="materialize logo" style="height:55px"></a> <?php } }?> </div> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".js-navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse js-navbar-collapse"> <ul class="nav navbar-nav"> <li> <a href="#">Sales<span class="caret"></span></a> <div> <div class="nav-column col-md-3"> <h3>Sales Details</h3> <ul> <!--<li><a href="<?php echo base_url(); ?>pages/add_order">New Sales</a></li>--> <li><a href="<?php echo base_url(); ?>pages/order_list">Warranty List</a></li> <li><a href="<?php echo base_url(); ?>pages/amc_list">AMC List</a></li> <li><a href="<?php echo base_url(); ?>pages/expiry_closed">Chargeables</a></li> </ul> </div> <div class="nav-column col-md-3"> <h3>Expiring Products</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list">Expiring Contracts</a></li> </ul> </div> </div> </li> <li> <a href="#">Services<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Service</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/service_req_list">All Request</a></li> <li><a href="<?php echo base_url(); ?>pages/workin_prog_list">Work In-progress</a></li> <li><a href="<?php echo base_url(); ?>pages/comp_engg_list">Completed By Engineer</a></li> </ul> </div> <div class="nav-column"> <h3>Service</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/quality_check_list">QC</a></li> <li><a href="<?php echo base_url(); ?>pages/ready_delivery_list">Ready Delivery</a></li> <li><a href="<?php echo base_url(); ?>pages/delivered_list">Delivered / Invoices</a></li> </ul> </div> <div class="nav-column"> <h3>warranty claim</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/warranty_pending_claims">Pending claim</a></li> </ul> </div> </div> </li> <li> <a href="#">Spares<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Spare</h3> <ul> <!--<li><a href="<?php echo base_url(); ?>pages/add_new_stock">New Spare</a></li>--> <li><a href="<?php echo base_url(); ?>pages/add_spare">View Spares</a></li> <li><a href="<?php echo base_url(); ?>pages/spare_stock">Spare Stock</a></li> <li><a href="<?php echo base_url(); ?>pages/sparerequest">Spare Requests</a> <!--<li><a href="<?php echo base_url(); ?>pages/add_spare_engineers">Spare to Engineer</a></li>--> </ul> </div> <div class="nav-column"> <h3>Spare</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/sparereceipt">Spare Receipt List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/spare_purchase_order">Create Purchase Order</a></li>--> <li><a href="<?php echo base_url(); ?>pages/purchase_orders">Purchase Order</a></li> <li><a href="<?php echo base_url(); ?>pages/min_spare_alerts">Min Spare Alerts</a></li> </ul> </div> </div> </li> <li> <a href="#">Master<span class="caret"></span></a> <div> <div class="nav-column"> <div class="divider"></div> <h3>Customers</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_list">Customer List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_cust">Add Customer</a></li>--> </ul> <div class="divider"></div> <h3>Product Brand</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/brandList">Brand List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_brand">New Brand</a></li>--> </ul> <div class="divider"></div> <h3>Users</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/user_cate_list">User List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_user_cate">New User</a></li>--> </ul> <div class="divider"></div> <h3>Employee</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/emp_list">Employee List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_emp">New Employee</a></li>--> </ul> </div> <div class="nav-column"> <div class="divider"></div> <h3>Products</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_list">Product List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_prod">Add Product</a></li>--> </ul> <div class="divider"></div> <h3>Problem Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prob_cat_list">Problem List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_prob_cat">New Problem</a></li>--> </ul> <div class="divider"></div> <h3>Customer Type</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/cust_type_list">Customer Type List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/cust_type">New Customer Type</a></li>--> </ul> <div class="divider"></div> <h3>Accessories</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/accessories_list">Accessories</a></li> </ul> </div> <div class="nav-column"> <div class="divider"></div> <h3>Product Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_cat_list">Category List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_prod_cat">New Category</a></li>--> </ul> <div class="divider"></div> <h3>Service Zone</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/service_loc_list">Zone List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_service_loc">New Zone</a></li>--> </ul> <div class="divider"></div> <h3>Company Details</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/comp_list">Company Details</a></li> </ul> <div class="divider"></div> <h3>QC</h3> <ul> <!--<li><a href="<?php echo base_url(); ?>pages/qc_masters">Add QC Parameters</a></li>--> <li><a href="<?php echo base_url(); ?>pages/qc_masters_list">QC Parameters List</a></li> </ul> </div> <div class="nav-column"> <div class="divider"></div> <h3>Sub Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/prod_subcat_list">Sub-Category List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_prod_subcat">New Sub-Category</a></li>--> </ul> <div class="divider"></div> <h3>Tax</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/tax_list">Tax List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_tax">New Tax</a></li>--> </ul> <div class="divider"></div> <h3>Service Category</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/service_cat_list">Service Category List</a></li> <!--<li><a href="<?php echo base_url(); ?>pages/add_service_cat">New Service Category</a></li>--> <!--<li><a href="<?php echo base_url(); ?>pages/add_service_charge">New Service Charge</a></li>--> <li><a href="<?php echo base_url(); ?>pages/service_charge_list">Service Charge List</a></li> <div class="divider"></div> <h3>Lab</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/lab_listsss">Lab List</a></li> </ul> </div> </div> </li> <li> <a href="#">Reports<span class="caret"></span></a> <div> <div class="nav-column"> <h3>Reports</h3> <ul> <li><a href="<?php echo base_url();?>pages/revenuereport">Service Report</a></li> <li><a href="<?php echo base_url();?>pages/report_list">Revenue Report</a></li> <li><a href="<?php echo base_url();?>pages/engineer_servicereport_list">Enigneers Report</a></li> <li><a href="<?php echo base_url();?>pages/customerreport_list">Customer Report</a></li> <li><a href="<?php echo base_url();?>pages/service_mach_report">Service Machines Report</a></li> </ul> </div> <div class="nav-column"> <h3>Reports</h3> <ul> <li><a href="<?php echo base_url(); ?>pages/expiry_list1">Warranty Expired Report</a></li> <li><a href="<?php echo base_url();?>pages/agingreport">Aging Report</a></li> <li><a href="<?php echo base_url();?>pages/sparereport_list">Spare Report</a></li> <li><a href="<?php echo base_url();?>pages/engineerreport_list">Spare to Engineer Report</a></li> <li><a href="<?php echo base_url();?>pages/sparepurchase_list">Spare Purchase Report</a></li> </ul> </div> <div class="nav-column"> <h3>Reports</h3> <ul> <!--<li><a href="<?php echo base_url();?>pages/sparecharge_list">Spare Charge Report</a></li> <li><a href="<?php echo base_url();?>pages/stampingreport_list">Stamping Report</a></li> <li><a href="<?php echo base_url();?>pages/monthlyreport_list">Stamping Monthly</a></li>--> <li><a href="<?php echo base_url();?>pages/serial_list">SerialWise Report</a></li> </ul> </div> </div> </li> </ul> </div> <div class="navbar-header right"> <ul class="hide-on-med-and-down"> <li> <div> <a href="#">Welcome <?php foreach($user_dat As $Ses_key1){echo $Ses_key1->name;} ?></a> <img class="img-circle img-responsive img-welcome" src="<?php echo base_url(); ?>assets/images/user.png"> </div> <!--<div class="picker-wrapper"> <button class="btn coloricon"></button> <div class="color-picker"></div> </div>--> <div><input type="color" class="theme" id="bg"></div> </li> <li> <div><a href="<?php echo base_url(); ?>login/logout" class="waves-effect waves-block waves-light"><i class="fa fa-sign-out"></i> Logout</a></div> </li> </ul> </div> </header> <!--<div id="main"> <div class="picker-wrapper"> <button class="btn coloricon"></button> <div class="color-picker"></div> </div>--> <!--<div class="wrapper"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/default.min.css"> <script src="<?php echo base_url(); ?>assets/js/highlight.min.js"></script> <link href="<?php echo base_url(); ?>assets/css/ripples.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/custom.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/highlight.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/piklor.js"></script> <script src="<?php echo base_url(); ?>assets/js/handlers.js"></script>--> <script> $(document).ready(function() { $("#bg").change(function() { $("#header,thead").css("background",$("#bg").val()); $("h2").css("color",$("#bg").val()); }); }); </script><file_sep>/application/views/add_row_scat.php <div class="col-md-12"> <div class="col-md-3"> <input type="text" name="service_catname[]" id="UserName<?php echo $count; ?>" class="firstname" maxlength="80"> <div class="fname" id="lname<?php echo $count; ?>" style="color:red"></div></div><div><a class="delRowBtn btn btn-primary fa fa-trash"></a></div></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#UserName<?php echo $count; ?>" ).val()==""){ $("#lname<?php echo $count; ?>" ).text("Enter Service Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#UserName<?php echo $count; ?>" ).keyup(function(){ if($(this).val()==""){ $("#lname<?php echo $count; ?>" ).show(); } else{ $("#lname<?php echo $count; ?>" ).fadeOut('slow'); } }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <script> $(document).ready(function(){ $('#UserName<?php echo $count; ?>').change(function(){ var name1=$(this).val(); //alert(name); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>Servicecategory/service_validation", data:{ p_id:name1, }, cache:false, success:function(data){ //alert(data); if(data == 0){ $('#lname<?php echo $count; ?>').html(''); } else{ $('#lname<?php echo $count; ?>').html('Service Category Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#UserName<?php echo $count; ?>').val(''); return false; //exit; } } }); }); }); </script><file_sep>/application/views/add_spares_engg_row.php <!--<tr> <td> <select id="spare_name_<?php echo $count; ?>" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> </select> </td> <td><input type="text" name="qty[]"><input type="hidden" name="spare_qty1[]" id="spare_qty1_<?php echo $count; ?>"><input type="hidden" name="used_spare1[]" id="used_spare1_<?php echo $count; ?>"><input type="hidden" name="purchase_price1[]" id="purchase_price1_<?php echo $count; ?>"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_<?php echo $count; ?>"></td> <td><input type="text" name="purchase_date[]"></td> <td><input type="text" name="purchase_price[]"></td> <td><input type="text" name="invoice_no[]"></td> <td><input type="text" name="reason[]"></td> <td style="border:none;"><button class="delRowBtn" >Delete</button></td> </tr>--> <tr> <!--<td> <select name="eng_name" id="eng_name-<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($engg_list as $enggkey){ ?> <option value="<?php echo $enggkey->id; ?>"><?php echo $enggkey->emp_name; ?></option> <?php } ?> </select></td>--> <td><select name="req_id[]" class="chosen-select form-control sample" id="sample1_<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($reqview as $row){ ?> <option value="<?php echo $row->id; ?>"><?php echo $row->request_id; ?></option> <?php } ?> </select> </td> <td class="plus"> <select class="chosen-select form-control name_select test1" name="cust[]" id="cust_id_<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($customerlist as $customerkey){ ?> <option value="<?php echo $customerkey->id; ?>"><?php echo $customerkey->company_name; ?></option> <?php } ?> </select> <!-- <input type="text" Placeholder="Name" name="cust_name[]" class="test1" id="custtest_<?php echo $count; ?>" readonly>--><i class="fa fa-plus-square fa-2x" onclick='brinfo(<?php echo $count; ?>)'></i> </td> <td class="plus"> <select name="modelid[]" id="modelid_<?php echo $count; ?>" class="modelss"> <option value="">---Select---</option> </select> </td> <td><select name="eng_spare_name[]" class="eng_spare_name" id="eng_spare_name-<?php echo $count; ?>"> <option value="">---Select---</option> <?php foreach($spare_list as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; ?></option> <?php } ?> </select></td> <td class="plus"><input type="text" Placeholder="plus" name="plus[]" id="plus-<?php echo $count; ?>" class="plus1">OR<input type="text" placeholder="minus" name="minus[]" id="minus-<?php echo $count; ?>" class="minus1"></td> <td class="qty"><input type="text" class="date" name="engg_date[]" id="enggdate_<?php echo $count; ?>"><input type="hidden" name="spare_qty[]" id="spare_qty-<?php echo $count; ?>"><input type="hidden" name="used_spare[]" id="used_spare-<?php echo $count; ?>" value=""><input type="hidden" name="eng_spare[]" id="eng_spare-<?php echo $count; ?>"><input type="hidden" name="amt[]" id="amt-<?php echo $count; ?>"> <input type="hidden" name="amt1[]" id="amt1-<?php echo $count; ?>"></td> <td style="padding:10px 0;"><textarea type="text" name="engg_reason[]" id="engg_reason-<?php echo $count; ?>"></textarea></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(<?php echo $count; ?>)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> <script> $(function(){ $(".date").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: "1950:2055" }); }) </script> <script> $(function(){ $('#sample1_<?php echo $count; ?>').select2(); $('#cust_id_<?php echo $count; ?>').select2(); }); </script> <script> $(function(){ //alert("bfh"); $('.sample').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); // var idd=$(this).closest(this).attr('id'); //alert(idd); // var arr= idd.split('-'); // var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); // $("#modelid_0 > option").remove(); $('#modelid_'+<?php echo $count; ?>+ "> option").remove(); $('#cust_id_'+<?php echo $count; ?>+ "> option").remove(); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { $('#modelid_'+<?php echo $count; ?>).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ $('#cust_id_<?php echo $count; ?>').append("<option selected='selected' value='"+data.cust+"'>"+data.customer_name+"</option>"); $('#modelid_<?php echo $count; ?>').append("<option value='"+data.prod_id+"'>"+data.model+"</option>"); }); } }); }); $('.modelss').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('_'); var inc = arr['1']; //var vl=$('#countid').val(); //alert(inc); //alert("spareid: "+idd); $('#eng_spare_name-'+inc+ "> option").remove(); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/spareListByModelId", data: dataString, cache: false, success: function(data) { $('#eng_spare_name-'+inc).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ if(data.spare_name.length>0){ $('#eng_spare_name-'+inc).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); } }); } }); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ if(parseInt(data.spare_qty) <= parseInt(data.min_qty)){ alert("Alert!!! Spare meets minimum qty level"); } $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare), $('#amt-'+vl).val(data.sales_price) }); } }); }); }); </script> <script> $('.plus1').keyup(function() { //alert($('#tax_type').val()); //alert("fdgvdfgfd"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('-'); var ctid = arr['1']; if(parseInt($(this).val())){ var cal_amt = parseInt($(this).val()) * parseInt($('#amt-'+ctid).val()); $('#amt1-'+ctid).val(cal_amt); } else{ $('#amt1-'+ctid).val(0); } //$('input[name="res"]').val(val); }); </script> <!--<script> $(function() { /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); </script>--> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <!--<script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script>--> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function() { $(".name_select").select2(); }); </script> <!--<script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <!--<link href="<?php echo base_url(); ?>assets/css/chosen.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <!--<script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('minus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('plus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.sample1').change(function(){ //alert("hiiio"); var id=$(this).attr('id'); var field=$(this).attr('id').split('_').pop(); var v=$('#'+id).val(); var dataString='id='+v; //alert(vl); //alert("spareid: "+idd); // var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_'+field).val(data.customer_name), $('#cust_id_'+field).val(data.cust) }); } }); }); }); </script>--> <file_sep>/application/views_bkMarch_0817/add_purchase_order_row.php <tr> <td class="plus"><input type="text" name="sr_no[]" id="sr_no"></td> <td><select name="spare_name[]" id="spare_name-<?php echo $count;?>" class="chosen-select form-control spare_name"> <option value="">---Select---</option> <?php foreach($spare_list as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; ?></option> <?php } ?> </select></td> <td class="plus"><input type="text" name="spare_qty[]" id="spare_qty-<?php echo $count;?>" class="spare_qty" value="0"></td> <td class="plus"><input type="text" name="rate[]" id="rate-<?php echo $count;?>" readonly></td> <td class="plus"><input type="text" name="spare_tot[]" id="spare_tot-<?php echo $count;?>" style="width:100px" readonly> </tr> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; // alert(vl); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#rate-'+vl).val(data.purchase_price) }); } }); }); }); </script> <script> $(function(){ $('#sample1_<?php echo $count; ?>').select2(); }); </script> <script> $(function(){ //alert("bfh"); $('.sample').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); // var idd=$(this).closest(this).attr('id'); //alert(idd); // var arr= idd.split('-'); // var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_<?php echo $count; ?>').val(data.customer_name), $('#cust_id_<?php echo $count; ?>').val(data.cust) }); } }); }); /*$(".tstfig").change(function(){ alert("hiiio"); var id=$(this).attr('id'); var field=$(this).attr('id').split('_').pop(); var v=$('#'+id).val(); var dataString='id='+v; //alert(vl); //alert("spareid: "+idd); // var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_'+field).val(data.customer_name), $('#cust_id_'+field).val(data.cust) }); } }); });*/ }); </script> <!--<script> $(function() { /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); </script>--> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <!--<script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script>--> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <!--<script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <!--<link href="<?php echo base_url(); ?>assets/css/chosen.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script>--> <!--<script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('minus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; if(document.getElementById('plus-'+vl).value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.sample1').change(function(){ //alert("hiiio"); var id=$(this).attr('id'); var field=$(this).attr('id').split('_').pop(); var v=$('#'+id).val(); var dataString='id='+v; //alert(vl); //alert("spareid: "+idd); // var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ $('#custtest_'+field).val(data.customer_name), $('#cust_id_'+field).val(data.cust) }); } }); }); }); </script>--> <script> $(function(){ $(".date").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: "1950:2055" }); }) </script> <script> $('.spare_qty').keyup(function() { var idd=$(this).closest(this).attr('id'); var arr = idd.split('-'); var ctid = arr['1']; if(parseInt($(this).val()) && parseInt($('#rate-'+ctid).val())){ //alert("hello"); var cal_amt = parseInt($(this).val()) * parseInt($('#rate-'+ctid).val()); $('#spare_tot-'+ctid).val(cal_amt); }else{ $('#spare_tot-'+ctid).val(0); } var vals = 0; $('input[name="spare_tot[]"]').each(function() { //alert("dsd"); //alert($(this).val()); vals += Number($(this).val()); //alert(val); $('#basicamount').val(vals); }); var cst1 = $('#cst1').val(); var cst1_arr = cst1.split('-'); var tax_type = cst1_arr[1]; var tax_amt = (vals * tax_type) / 100; $('#cst').val(tax_amt); var freight_amt = $('#freight').val(); var total_spare_charge = $('#basicamount').val(); if(parseInt($('#freight').val())){ var Total_amount = parseInt(tax_amt) + parseInt(total_spare_charge) + parseInt(freight_amt); //alert(Total_amount); $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); }else{ var Total_amount = parseInt(tax_amt) + parseInt(total_spare_charge); //alert(Total_amount); $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); } }); </script> <script> $('.freight').keyup(function() { var freight_amt = $(this).val(); var totalamount = $('#totalamount1').val(); if(parseInt($(this).val())){ var Totall_amount = parseInt(freight_amt) + parseInt(totalamount); $('#totalamount').val(Totall_amount); }else{ $('#totalamount').val(totalamount); } }); $('#cst1').change(function() { var tax_name1 = $(this).val(); var tax_name1_arr = tax_name1.split('-'); var tax_name = tax_name1_arr[1]; var basicamount= $('#basicamount').val(); var tax_amt = (basicamount * tax_name) / 100; $('#cst').val(tax_amt); var freight_amt = $('#freight').val(); if(parseInt($('#freight').val())){ var Total_amount = parseInt(basicamount) + parseInt(tax_amt) + parseInt(freight_amt); //alert(Total_amount); if(Total_amount){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); } }else{ var Total_amount = parseInt(basicamount) + parseInt(tax_amt); //alert(Total_amount); if(Total_amount){ $('#totalamount').val(Total_amount); $('#totalamount1').val(Total_amount); } } }); </script> <file_sep>/application/controllers/Servicelocation.php <?php class Servicelocation extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Servicelocation_model'); } public function add_service_location(){ $data['serv_loc_code']=$this->input->post('serv_loc_code'); $data['service_loc']=$this->input->post('serv_loc_name'); $data['concharge']=$this->input->post('concharge'); $data['zone_coverage']=$this->input->post('zone_coverage'); $result=$this->Servicelocation_model->add_service_location($data); $area_name = $data1['area_name']=$this->input->post('area_name'); $pincode = $data1['pincode']=$this->input->post('pincode'); $c=$area_name; $count=count($c); if(isset($result)){ $data1 =array(); for($i=0; $i<$count; $i++) { $data1[] = array( 'zone_code' => $result, 'area_name' => $area_name[$i], 'pincode' => $pincode[$i] ); } $this->Servicelocation_model->add_zone_pincode($data1); if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/service_loc_list';alert('Service Location Added Successfully!!!');</script>"; } } } public function update_ser_location(){ $id=$this->uri->segment(3); $data['getserviceLocbyid']=$this->Servicelocation_model->getserviceLocbyid($id); $data['getZonePincodebyid']=$this->Servicelocation_model->getZonePincodebyid($id); $idd=$this->uri->segment(3); $data['editid']=$idd; $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_zone',$data); } public function del_ser_location(){ $id=$this->input->post('id'); $s = $this->Servicelocation_model->del_serv_loc($id); } public function del_zone_pincode(){ $id=$this->input->post('id'); $s = $this->Servicelocation_model->del_zone_pincode($id); } public function addrow2(){ $data['count']=$this->input->post('countid'); //$data['spare_list']=$this->Spare_model->spare_list_engineers(); //$data['engg_list']=$this->Spare_model->engineer_list(); // $modelid=$this->input->post('modelid'); //$data['spareListByModelId']=$this->Spare_model->spareListByModelId($modelid); $this->load->view('add_zone_pin_row',$data); } public function edit_service_location(){ error_reporting(0); $data=array( 'serv_loc_code'=>$this->input->post('serv_loc_code'), 'service_loc'=>$this->input->post('serv_loc_name'), 'concharge'=>$this->input->post('concharge'), 'zone_coverage'=>$this->input->post('zone_coverage') ); $serv_loc_id=$this->input->post('serv_loc_id'); $area_name=$data1['area_name']=$this->input->post('area_name'); $pincode=$data1['pincode']=$this->input->post('pincode'); $serv_zone_pin_rowid=$data1['serv_zone_pin_rowid']=$this->input->post('serv_zone_pin_rowid'); $c=$area_name; $count=count($c); $this->Servicelocation_model->update_serv_loc($data,$serv_loc_id); $data1 =array(); for($i=0; $i<$count; $i++) { $data1 = array( 'area_name' => $area_name[$i], 'pincode' => $pincode[$i], 'zone_code' => $serv_loc_id ); //echo "RowId: ".$ser_loc_id[$i]; if($serv_zone_pin_rowid[$i]!="" && isset($serv_zone_pin_rowid[$i])){ $where = "zone_code=".$serv_loc_id." AND id=".$serv_zone_pin_rowid[$i]; $result=$this->Servicelocation_model->update_zone_pincodes($data1,$where); }else{ $result=$this->Servicelocation_model->add_zone_pincode1($data1); } } echo "<script>alert('Service Zone Updated Successfully!!!');window.location.href='".base_url()."pages/service_loc_list';</script>"; } public function checkpin(){ $id=$this->input->post('id'); $zone=$this->input->post('zone');//echo $zone; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Servicelocation_model->checkpin($id,$zone))); } public function checkname(){ $id=$this->input->post('p_id'); //$zone=$this->input->post('zone');//echo $zone; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Servicelocation_model->checkname($id))); } public function checkcode(){ $id=$this->input->post('p_id');//echo $id;exit; //$zone=$this->input->post('zone');//echo $zone; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Servicelocation_model->checkcode($id))); } } <file_sep>/application/views/tax_list.php <style> .ui-state-default { background:#6c477d; color:#fff; border: 3px solid #fff !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 8px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; } thead { border-bottom: 1px solid #ccc; border: 1px solid #ccc; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } select { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=text]{ background-color: transparent; border: 0px solid #522276; border-radius: 7; width: 55% !important; font-size: 12px; margin: 0 0 -2px 0; padding: 3px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height:17px; } input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .h1, .h2, .h3, h1, h2, h3 { margin-top: 20px; margin-bottom: 0px; } hr { margin-top: 0px; } a{ color: #522276; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } body{ background-color: #fff;} </style> <script> $(document).ready(function(){ $('[id^="pro_cat_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split(','); var procatid = arr['0']; var subid = arr['1']; var data_String; data_String = 'id='+subid+'&procatid='+procatid; $.post('<?php echo base_url(); ?>subcategory/update_sub_category',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Category changed"); //$('#actaddress').val(data.Address1), }); }); }); function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); tax_name = $("#tax_name"+id).val(); tax_percent = $("#tax_percent"+id).val(); //alert("tax name: "+tax_name+"tax_percent: "+tax_percent); //alert(tax_percent); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/update_tax', data: {'id' : id, 'tax_name' : tax_name, 'tax_percent' : tax_percent}, dataType: "text", cache:false, success: function(data){ alert("Tax Updated Successfully!!!"); } }); }); } function Updatedefault(id) { if(document.getElementById('tax_default'+id).checked) { var tax_default = '1'; //alert(tax_default); } else { var tax_default = '0'; //alert(tax_default); } $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/update_default', data: {'id' : id, 'tax_default' : tax_default}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("Tax Selected"); } }); }); } /* function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/del_tax', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want delete?"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/tax_list"; } alert("Tax Deleted Succefully!!!"); } }); }); } */ function InactiveStatus(id){ //alert(id); //$(function() //{ $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/Inactive_tax_list', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Tax Inactive"); window.location = "<?php echo base_url(); ?>pages/tax_list"; } }); // }); } function activeStatus(id){ //alert(id); //$(function() // { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/active_cust_type', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Tax Active"); window.location = "<?php echo base_url(); ?>pages/tax_list"; } }); //}); } </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('.tax_percent').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9.]/g,'') ); }); }); </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Tax List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addtax.png" title="Add Tax" style="width:24px;height:24px;">Add Tax</button>--> <a href="<?php echo base_url(); ?>pages/add_tax" style="position: relative;bottom: 27px;left: 88%;"><i class="fa fa-plus-square" aria-hidden="true" title="Add New Tax"></i></a> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <form id="form1"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr> <th class="hidden">Id</th> <th>S.No.</th> <th style="text-align:center;font-size:13px;color:##303f9f;">Tax Name</th> <th style="text-align:center;font-size:13px;color:##303f9f;">Percentage</th> <th style="text-align:center;font-size:13px;color:##303f9f;">Status</th> </tr> </thead> <tbody> <?php //print_r($tax_list); $i=1;foreach($tax_list as $key){ // print_r($key); ?> <tr> <td class="hidden"> <input type="hidden" name="key_id" id="key_id" value="<?php echo $key->id;?>"> </td> <td><?php echo $i;?></td> <td> <input type="checkbox" name="tax_default" id="tax_default<?php echo $key->id; ?>" onclick="Updatedefault('<?php echo $key->id; ?>')" <?php if($key->tax_default){?> checked="checked" <?php }?>><?php echo $key->tax_name; ?><input type="hidden" value="<?php echo $key->tax_name; ?>" class="" name="tax_name" id="tax_name<?php echo $key->id; ?>"> <span id="dis" style="color:red"></span> </td> <td><input type="text" value="<?php if($key->tax_percentage !=0){echo $key->tax_percentage; }?>" class="tax_percent" name="tax_percent" id="tax_percent<?php echo $key->id; ?>" onChange="UpdateStatus('<?php echo $key->id; ?>')" maxlength="5"> <span id="dis1" style="color:red"></span> </td> <!--<td class="options-width" style="text-align:center;width:40px !important;"> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')" id="edit"><i class="fa fa-floppy-o fa-2x"></i></a>-> <a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-floppy-o fa-2x"></i></a> </td>--> <td class="options-width" style="text-align:center;width:40px !important;"> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')" id="edit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> </a>--> <!--<a href="<?php echo base_url(); ?>pages/tax_list/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x" aria-hidden="true"></i> </a>--> <?php if($key->status!='1') { ?><a href="#" onclick="InactiveStatus('<?php echo $key->id; ?>')">Inactive</a><?php } ?><?php if($key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $key->id; ?>')">Active</a><?php } ?> </td> </tr> <?php $i++;} ?> </tbody> </table> </form> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script>--> <!--prism--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <link rel="stylesheet" href="http://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">\ <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script>--> <script> $(document).ready(function(){ $('#data-table-simple').DataTable(); }); </script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/views_bkMarch_0817/add_service_loc.php <head> <style> body{background-color:#fff;} .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { border: 1px solid gray; text-align: center; } .tableadd1 tr { height: 40px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:white; } .tableadd1 tr td.plus { padding-top: 14px; } .tableadd1 tr td.plus input { width:70px; border:1px solid gray; } .tableadd1 tr td input { height: 25px; border-radius: 5px; padding-left: 10px; margin-bottom: 0px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { margin-top:20px; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:black; } .tableadd tr td input { width: 210px; border-radius: 5px; padding-left: 10px; } .tableadd1 tr td input { width: 210px; border-radius: 5px; padding-left: 10px; } #errorBox{ color:#F00; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Servicelocation/addrow2", data: datastring, cache: false, success: function(result) { //alert(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('minus-0').value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus-0').value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); function UpdateStatus1(id){ //alert(id);alert($("#enggdate_"+id).val()); var eng_name = $("#eng_name-"+id).val(); var eng_spare_name = $("#eng_spare_name-"+id).val(); var engg_date = $("#enggdate_"+id).val(); if(eng_name==""){ alert("Enter the Engineer Name"); }else if(eng_spare_name==""){ alert("Enter the Spare Name"); }else if(engg_date==""){ alert("Enter the Date"); }else{ var plus = $("#plus-"+id).val(); var minus = $("#minus-"+id).val(); //alert(engg_date); var engg_reason = $("#engg_reason-"+id).val(); var spare_qty = $("#spare_qty-"+id).val(); var used_spare = $("#used_spare-"+id).val(); var eng_spare = $("#eng_spare-"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/add_spare_engg', data: {'eng_name' : eng_name, 'eng_spare_name' : eng_spare_name, 'plus' : plus, 'minus' : minus, 'engg_date' : engg_date, 'engg_reason' : engg_reason, 'spare_qty' : spare_qty, 'used_spare' : used_spare, 'eng_spare' : eng_spare}, dataType: "text", cache:false, success: function(data){ alert("Spares For Engineers Added"); } }); }); } } </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var serv_loc_code = document.frmZone.serv_loc_code.value; var serv_loc_name = document.frmZone.serv_loc_name.value; if( serv_loc_code == "" ) { //alert("Hi"); document.frmZone.serv_loc_code.focus() ; document.getElementById("errorBox").innerHTML = "enter the zone code"; return false; } if( serv_loc_name == "" ) { document.frmZone.serv_loc_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the zone name"; return false; } } </script> </head> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Service Zone</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <form name="frmZone" action="<?php echo base_url(); ?>Servicelocation/add_service_location" method="post" onsubmit="return frmValidate()"> <div id="errorBox"></div> <div class="col-md-1"> </div> <div class="col-md-10"> <div class="col-md-12 tableadd" id="addtable"> <div class="col-md-3"> <label>Zone Code&nbsp;<span style="color:red;">*</span></label> <input type="text" name="serv_loc_code" class="corporate"> </div> <div class="col-md-3"> <label>Zone Name&nbsp;<span style="color:red;">*</span></label> <input type="text" name="serv_loc_name" class="corporate"> </div> <div class="col-md-3"> <label>Conveyance charge</label> <input type="text" name="concharge" class="corporate"> </div> <div class="col-md-3"> <label>Zone Coverage</label> <select name="zone_coverage"> <option value="">---Select---</option> <option value="on_site">Onsite</option> <option value="outstation">Out Station</option> </select> </div> </div> <div style="margin: 10px 0px;" class="col-md-12"> <table id="table1" class="tableadd1" style="width:70%;"> <tr style="background: rgb(5, 94, 135) none repeat scroll 0% 0%;"> <td><label>Area</label></td> <td><label>Pincode</label></td><!--<td><label>Action</label></td>--> </tr> <tr> <td style="padding:10px 0;"><input type="text" name="area_name[]" id="area_name-0"></td> <td style="padding:10px 0;"><input type="text" name="pincode[]" id="pincode-0"></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(0)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0" > </div> <a id="addMoreRows" class="rowadd" style="padding: 8.5px;margin-right: 20px;">Add Row</a> <button class="btn cyan waves-effect waves-light" type="submit" name="action">Submit<i class="fa fa-arrow-right"></i></button> </div> <div class="col-md-1"> </div> </form> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/controllers/Service.php <?php class service extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Service_model'); } public function get_zone_list(){ $id=$this->input->post('keyword');//echo $id; exit; $data['zone_list']=$this->Service_model->get_zons($id); $this->load->view('zone_list',$data); } public function delete($idd) { $thisa='1'; $data=array( 'active_req'=>$thisa ); // $sss = $this->Service_model->getOld_forothers($idd); $s = $this->Service_model->update_service_delstatus($data,$idd); if($s) { redirect('pages/service_req_list'); } } public function autocomp($urks) { $searchTerm = $_GET['term']; $this->db->select("*",FALSE); $this->db->from('problem_category'); $this->db->like('prob_category', $searchTerm); $this->db->where('model', $urks); $query = $this->db->get(); $ressullt = $query->num_rows(); // print_r($query); // while ($row = $query->fetch_assoc()) { // $data[] = $row['prob_category']; // } if($ressullt!=0) { foreach ($query->result() as $row) { //print_r($row); $data[] = $row->prob_category; } } else { $data[]='No results found!'; } //get matched data from skills table /*$query = $db->query("SELECT * FROM problem_category WHERE prob_category LIKE '%".$searchTerm."%' ORDER BY prob_category ASC"); while ($row = $query->fetch_assoc()) { $data[] = $row['prob_category']; }*/ //return json data echo json_encode($data); } public function view_claim(){ $this->load->helper('pdf_helper'); $id=$this->uri->segment(3); $data1['warran_mode'] = $this->uri->segment(4); $view_claim=$this->Service_model->view_claim($id); foreach($view_claim as $claimKey){ $quote_req_id = $claimKey->quote_req_id; $desc_failure = $claimKey->desc_failure; $why_failure = $claimKey->why_failure; $correct_action = $claimKey->correct_action; $spare_qty = $claimKey->spare_qty; $request_id = $claimKey->request_id; $request_date = $claimKey->request_date; $serial_no = $claimKey->serial_no; $model = $claimKey->model; $company_name = $claimKey->company_name; $address = $claimKey->address; $address1 = $claimKey->address1; $city = $claimKey->city; $state = $claimKey->state; $pincode = $claimKey->pincode; $spare_details = $claimKey->spare_details; $purchase_date = $claimKey->purchase_date; $emp_name = $claimKey->emp_name; } tcpdf(); $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $obj_pdf->SetCreator(PDF_CREATOR); //$obj_pdf->SetTitle($title); //$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH,'', PDF_HEADER_STRING); //$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); //$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $obj_pdf->SetDefaultMonospacedFont('helvetica'); //$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER); //$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $obj_pdf->SetFont('helvetica', '', 9); $obj_pdf->setFontSubsetting(false); $obj_pdf->AddPage(); $content = '<html> <head> <title>Warranty Claim</title> <style> .tp01 { border-collapse: collapse; } .tp01 th { color: #000; border: 1px solid #e4e4e4; } .tp01 td, .myTable th { padding: 5px; border: 1px solid #e4e4e4; } </style> <style> table { border-collapse: collapse; } table, th, td { border: 1px solid black; } table,td{ height:18px; } </style> </head> <body> <table class="tp01" cellpadding="5" cellspacing="0" border="none"> <tr> <td colspan="1"><img src="assets/images/stagologo.png" alt="materialize logo" style="margin-left:100px;"></td> <td colspan="1" style="text-align:center;"><h2>WARRANTY CLAIM</h2><p>Demande de Garantie</p></td> <td colspan="1" style="line-height:150%;">SUBMIT TO / renvoyer á : <b style="color:red;font-size:8px;">DIAGNOSTICA STAGO - SAVE</b> - B.P.226 92602 ASNIERES CEDEX - FRANCE FAX : (33)(0) 1 46 88 22 40 @: <EMAIL> </td> </tr> <tr> <td colspan="1"><p><b>TYPE OF INSTRUMENT:</b>'.$model.'</p> <p>Type d\'instrument</p> </td> <td colspan="1"><p><b>SERIAL No:</b> '.$serial_no.'</p> <p>N&#176; de série</p> </td> <td colspan="1"><b>DATE OF INSTALLATION(YY MM DD):</b> <p>Date d\'installation (AA MM JJ) '.$purchase_date.'</p></td> </tr> <tr> <td colspan="2"> <table > <tr> <td> <b>NAME OF LABORATORY:</b> <br>Nom du laboratoire: '.$company_name.' </td> </tr> <tr> <td> <b>INSTALLATION ADDRESS:</b> <br>Address dinstallation </td> <td>'.$address.' '.$address1.' '.$city.' '.$state.' '.$pincode.'</td> </tr> </table> </td> <TD colspan="1" style="border-left: 1px solid #ccc;" ><p><b>STAGO RESERVED :</b><br>Réservé STAGO</p></td> </tr> <tr> <td colspan="3"><p style="color:red;text-align:center"><b>ACCURATE AND DETAILED DESCRIPTION OF FAILURE</b></p> <p style="text-align:center">Description précise et détailée du défaut</p> </td> </tr> <tr> <td colspan="3"><b>DATE OF INTERVENTION(YY MM DD) :</b> <br>Date d\'intervention (AA MM JJ) '.$request_date.' </td> </tr> <tr> <td colspan="1" style="border-right: 1px solid #fff;"> <table > <tr colspan="1"> <td > <b style="text-decoration: underline; ">DESCRIPTION OF FAILURE:</b><br>Description du Défaut </td> </tr> </table> </td> <TD colspan="2" >'.$desc_failure.'</td> </tr> <tr> <td colspan="1" style="border-right: 1px solid #fff;"> <table > <tr colspan="1"> <td > <b style="text-decoration: underline; ">WHY AND WHEN DID IT OCCUR ?</b><br>Raisons et circonstances </td> </tr> </table> </td> <TD colspan="2" style="border-left: 1px solid #fff;" >'.$why_failure.'</td> </tr> <tr> <td colspan="1" style="border-right: 1px solid #fff;"> <table > <tr colspan="1"> <td > <b style="text-decoration: underline; ">CORRECTIVE ACTION</b><br>Action corrective </td> </tr> </table> </td> <TD colspan="2" style="border-left: 1px solid #fff;" >'.$correct_action.'</td> </tr> <tr> <td><b>FIELD SERVICE ENGINEER</b><br>Technicien SAV</td> <td>'.$emp_name.'</td> <td><b>DATE OF INTERVENTION(YY MM DD):</b> <br>Date d\'intervention (AA MM JJ) '.$request_date.' </td> </tr> <tr> <td colspan="3" ><p style="color:red;text-align:center"><b>PARTS CLAIMED FOR THE WARRANTY</b></p> <p style="text-align:center">Piéces demandées au titre de la garantie</p> </td> </tr> <table> <tr> <th><b style="text-align:center">PART NUMBERS</b><br><span style="text-align:center">références</span></th> <th style="width:30px;"><b style="text-align:center">QTY</b><br><span style="text-align:center">Qté</span></th> <th><b style="text-align:center">DESIGNATION</b><br><span style="text-align:center">Désignation</span></th> <th style="width:139px;"><b style="text-align:center;">REPLACEMENT PART SN</b><br><span style="text-align:center">Ns piéce défectueuse</span></th> <th><b style="text-align:center">CREDIT*</b><br><span style="text-align:center">crédit*</span></th> <th><b style="text-align:center">REPLACEMENT*</b><br><span style="text-align:center">Remplacement*</span></th> </tr>'; $spare_det = explode(',',$spare_details); for($r=0;$r<count($spare_det);$r++){ $sp_details = explode('-',$spare_det[$r]); $content .= '<tr> <td style="text-align:center;">'.$sp_details[2].'</td> <td style="text-align:center;">'.$spare_qty.'</td> <td style="text-align:center;">'.$sp_details[1].'</td> <td style="text-align:center;"></td> <td style="text-align:center;"></td> <td style="text-align:center;"></td> </tr>'; } $content .= '</table> <tr> <td colspan="2" style="border-right:1px solid #fff;"> <table> <tr colspan="2" > <td style="border-right:1px solid #fff;"> <b>DISTRIBUTOR VISA:</b><br>Visa distributeur </td> </tr> </table> </td> <TD colspan="5" style="border-left: 1px solid #fff;text-align:left;" ><NAME></td> </tr> <tr> <td colspan="6"><p style="color:red;text-align:center"><b>COMMENTS</b></p> <p style="text-align:center"></p> </td> </tr> <tr> <td colspan="6"> </td> </tr> <tr> <td colspan="2" style="border:1px solid #fff">SN = Serial Number</td> <td colspan="1" style="border:1px solid #fff">Ns = N* série</td> <td colspan="2" style="border:1px solid #fff">* = Cross Your choise / Cocher voter Choix</td> </tr> <tr> <td colspan="1" style="border:1px solid #fff">S-0931046</td> <td colspan="4" style="border:1px solid #fff"><b>DISTRBUTION</b> : ORIGINAL : DIAGNOSTICA STAGO : 1st COPY : ISSUER<br>original : DIAGNOSTICA STAGO : 1ére : émetteur</td> <td colspan="1" style="border:1px solid #fff">38786</td> </tr> </table> </body> </html>'; ob_end_clean(); $obj_pdf->writeHTML($content, true, false, true, false, ''); $obj_pdf->Output('warranty_claim.pdf', 'I'); //$obj_pdf->Output('service/assets/testtt.pdf', 'F'); } public function topdf($id=NULL,$option=NULL) { //echo "REquest Id: ".$id;exit; //$this->load->model('invoiceModel'); //$this->load->library('Numbertowords'); //$this->load->model('settings/Mdl_Settings'); $idd=$this->uri->segment(3); $data1['warran_mode'] = $this->uri->segment(4); $data1['view_claim']=$this->Service_model->view_claim($idd); if(!$id) { echo "No More Access"; exit; } else { //$ht=$this->view($id,"without_template","module"); $ht= $this->load->view('view_claim',$data1); $html='<html> <head> </head> <body> <style type="text/css">.cncl-bg{display:none} </style>'.$ht.' <link href="'.base_url().'assets/css/invoice_pdf.css" rel="stylesheet" type="text/css" /></body></html>'; /// echo $html; exit; $paper='A4'; $this->load->library('pdf'); //include('../mpdf.php'); $base=str_replace("system/","",BASEPATH); //$invoiceinfo = $this->invoiceModel->getInvoiceinfoById($id); // if($invoiceinfo->status=='C') //$mark=$base."images/canceled.png"; //else $mark=NULL; //if($option=="") $this->pdf->downloadPdf($html,NULL,$mark); } } public function add_service_req(){//echo "<pre>";print_r($_POST);exit; error_reporting(0); ini_set('max_execution_time', 900); $config = array(); $config['useragent'] = "CodeIgniter"; $config['mailpath'] = "/usr/bin/sendmail"; // or "/usr/sbin/sendmail" $config['protocol'] = "smtp"; $config['smtp_host'] = "localhost"; $config['smtp_port'] = "25"; $config['mailtype'] = 'html'; $config['charset'] = 'utf-8'; $config['newline'] = "\r\n"; $config['wordwrap'] = TRUE; $this->load->library('email'); $this->email->initialize($config); $req=$this->input->post('req_id'); $check_req=$this->Service_model->check_req($req); if(empty($check_req)){ //echo "Hello"; $data['request_id']=$this->input->post('req_id'); $data['cust_name']=$this->input->post('customer_id'); $data['br_name']=$this->input->post('br_name'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['address']=$this->input->post('address'); $data['address1']=$this->input->post('address1'); $data['request_date']=$this->input->post('datepicker'); $data['status']=$this->input->post('status'); //$data['active_req']='1'; date_default_timezone_set('Asia/Calcutta'); $data['created_on'] = date("Y-m-d H:i:s"); $data['updated_on'] = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $data['user_id'] = $data111['user_dat'][0]->id; $req_autoid=$this->input->post('req_id'); $customer_mobile=$this->input->post('mobile'); //echo "Hello"; $result=$this->Service_model->add_services($data); //echo "Helloww"; $res = sprintf("%05d", $result); if($result){ if(isset($customer_mobile) && $customer_mobile!=""){ $cname=$this->input->post('customer_name'); $stype=$this->input->post('service_type'); $sms= "Your service request ID ".$req." created for (".$cname.",".$stype.") thank you. <br>Syndicate Diagnostics pvt ltd.<br>"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $supervisor_mobile='9826938860'; $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$customer_mobile&text=$messages&priority=ndnd&stype=normal"); $msg1 = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$supervisor_mobile&text=$messages&priority=ndnd&stype=normal"); } $data1['request_id']=$res; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); if($this->input->post('warranty_date')!=""){ $data1['warranty_date'] = $this->input->post('warranty_date'); }else{ $data1['warranty_date'] = ""; } $data1['machine_status']=$this->input->post('machine_status'); //$data1['site']=$this->input->post('site'); //$sitee = $this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); //$data1['service_cat']=$this->input->post('service_cat'); $ser_det = $this->input->post('service_cat'); $ser = explode("-",$ser_det); $data1['service_cat'] = $ser['0']; $data1['zone']=$this->input->post('locid'); $data1['service_loc_coverage']=$this->input->post('service_loc_coverage'); $get_all = $this->input->post('skills'); $expll = explode(',',$get_all); $cunt = count($expll); $user_array = array(); $userr_array = array(); for($i=0;$i<$cunt;$i++) { $model = $this->input->post('modelid'); $ffffff = $expll[$i]; $this->db->select("*",FALSE); $this->db->from('problem_category'); $this->db->where('prob_category', $ffffff); $this->db->where('model', $model); $ressult = $this->db->get(); $ressullt = $ressult->num_rows(); if($ressullt>0) { //echo 'elseeee'; foreach($ressult->result() as $empkey) { $getlastt = $empkey->id; array_push($userr_array,$getlastt); } } else if($ressullt==0) { $datsa=array( 'prob_category'=>$ffffff, 'model'=>$model ); $this->db->insert('problem_category',$datsa); //echo $this->db->last_query(); $getlast = $this->db->insert_id(); array_push($user_array,$getlast); } } $data1['problem'] = array_merge($userr_array, $user_array); //$data1['problem']=$this->input->post('probi'); if (is_array($data1['problem'])){ $data1['problem']= implode(",",$data1['problem']); }else{ $data1['problem']=""; } //$data1['problem']=$this->input->post('prob'); //$data1['assign_to']=$this->input->post('assign_to'); $data1['service_priority']=$this->input->post('service_priority'); //$data1['blank_app']=$this->input->post('blank_app'); $eng_id=$this->input->post('assign_to'); for($t=0;$t<count($eng_id);$t++){ if(isset($eng_id[$t]) && $eng_id[$t]!=""){ $em_id = explode("-", $eng_id[$t]); $e_id[] = $em_id['0']; $emp_id = $em_id['0']; $sms_mob = $em_id['1']; } //echo "Hsssssi: ".$em_id['0']; exit; //$site_customer = $this->input->post('site'); if($em_id['1']!="" && isset($em_id['1'])){ $sms_mobs=$em_id['1']; $cust_name = $this->input->post('customer_name'); $modell = $this->input->post('model'); //$brand_name = $this->input->post('brand_name'); $sms= "Request ID:".$req; $sms.= " Name:".$cust_name; if ($this->input->post('address')!=""){ $sms.= ", ".$this->input->post('address').' '.$this->input->post('address1'); } if ($this->input->post('mobile')!=""){ $sms.= ",".$this->input->post('mobile'); } //$sms.= " Brand: ".$brand_name; $sms.= ",Model:".$modell; if ($this->input->post('probi')!=""){ foreach($this->input->post('probi') as $val_pro){ $sms_problemlist=$this->Service_model->sms_problemlist($val_pro); $sms.=",".$sms_problemlist[0]->prob_category; } } /*if ($this->input->post('blank_app')!=""){ $sms.= ",Blanket Appr: ".$this->input->post('blank_app'); }*/ $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); //$msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=arihantmarketing&pass=123&sender=BHASH&phone=$sms_mobs&text=$messages&priority=dnd&stype=normal"); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$sms_mobs&text=$messages&priority=ndnd&stype=normal"); $get_emp_email = $this->Service_model->get_emp_email($em_id['0']); if($get_emp_email[0]->emp_email!=""){ //echo "Eng email: ".$get_emp_email[0]->emp_email; $content = '<tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Request ID: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$req.'</td> </tr> <tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Customer Name: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$cust_name.'</td> </tr> <tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Address: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$this->input->post('address').' '.$this->input->post('address1').'</td> </tr> <tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Mobile: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$this->input->post('mobile').'</td> </tr> <tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Model: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$this->input->post('model').'</td> </tr>'; if ($this->input->post('probi')!=""){ foreach($this->input->post('probi') as $val_pro){ $sms_problemlist=$this->Service_model->sms_problemlist($val_pro); $content .= '<tr> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">Problems: </td> <td style="border-radius: 3px;border:1px solid #ccc;padding:5px;text-align:center">'.$sms_problemlist[0]->prob_category.'</td> </tr>'; } } $this->email->set_mailtype("html"); $this->email->from('<EMAIL>', 'Syndicate Diagnostics'); $this->email->to($get_emp_email[0]->emp_email); //$this->email->cc('<EMAIL>'); $this->email->subject('Syndicate Diagnostics - Service Request: '.$req); $this->email->message($content); if($this->email->send()){ //Success email Sent //echo "Success"; $this->email->print_debugger(); }else{ //Email Failed To Send //echo "Fail"; $this->email->print_debugger(); } } } } //echo "<pre>"; //print_r($e_id); $data1['assign_to'] = implode(',',$e_id); //$data1['assign_to'] //$emp_det = $this->input->post('assign_to'); //$emp = explode(",",$emp_det); //$data1['assign_to'] = $emp['0']; $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } $data1['notes']=$this->input->post('notes'); //$countids=$this->input->post('countids'); $result1=$this->Service_model->add_service_details($data1); $data_log_reassign['engg_id'] = implode(',',$e_id); $data_log_reassign['req_id'] = $res; $data_log_reassign['updated_on'] = date("Y-m-d H:i:s"); $this->Service_model->add_log_reassign_engg($data_log_reassign); } if($result){ echo "<script>alert('Service Request Added. Your Request ID is: '+'".$req_autoid."');window.location.href='".base_url()."pages/service_req_list';window.open('".base_url()."service/print_service/".$res."')</script>"; } }else{ echo "<script>alert('Service Request ID already exists');window.location.href='".base_url()."pages/add_service_req';</script>"; } } public function print_service(){ $id=$this->uri->segment(3); $data['url_id'] = $this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['getBranchservicereqbyid']=$this->Service_model->getBranchservicereqbyid($id); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->print_servicecat_list($id); $data['problemlist']=$this->Service_model->print_problemlist($id); $data['problemlist1']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data['zone_pincodes']=$this->Service_model->zone_pincodes(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('print_preview_request',$data); } public function print_preview(){ $id=$this->input->post('url_id'); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['getBranchservicereqbyid']=$this->Service_model->getBranchservicereqbyid($id); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->print_servicecat_list($id); $data['problemlist']=$this->Service_model->print_problemlist($id); $data['problemlist1']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data['zone_pincodes']=$this->Service_model->zone_pincodes(); $data['spare_replaced']=$this->input->post('spare_replaced'); $data['spare_charge']=$this->input->post('spare_charge'); $data['service_charge']=$this->input->post('service_charge'); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('print_preview_request',$data); } public function stamping_print_service(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->print_servicecat_list($id); $data['problemlist']=$this->Service_model->print_problemlist($id); $data['stamping_details']=$this->Service_model->stamping_details($id); $data['problemlist1']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('stamping_print_service',$data); } public function get_custbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_custbyserialno(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerndorderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function searchByStatus(){ $id=$this->input->post('id'); $data1['user_dat'] = $this->session->userdata('login_data'); $user_acc = $data1['user_dat'][0]->user_access; $user_type = $data1['user_dat'][0]->user_type; if(isset($user_acc) && $user_acc!=""){ $user_access = $user_acc; }else{ $user_access = ""; } if(isset($id) && $id=="all"){ $data['get_searchByStatus']=$this->Service_model->service_req_list($user_access,$user_type); }else{ $data['get_searchByStatus'] = $this->Service_model->get_searchByStatus($id); } $data['service_req_list1']=$this->Service_model->service_req_list1($user_access,$user_type); $data['service_req_listforEmp']=$this->Service_model->service_req_listforEmp(); $data['status_list']=$this->Service_model->status_list(); $data['combine_status_list']=$this->Service_model->combine_status_list(); //$data1['user_dat'] = $this->session->userdata('login_data'); //$this->load->view('templates/header',$data1); $this->load->view('search_service_req_list',$data); } public function get_cus(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_custo())); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid1(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_servicecatbyid1(){ $id=$this->input->post('id');//echo $id; //exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicecatdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_probcatbyid1(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_probcatdetails1($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_servicecatbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicecatdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_probcatbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_probcatdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function addrow(){ $data['count']=$this->input->post('countid'); //echo "Count: ".$data['count']; $data['customerlist']=$this->Service_model->customerlist(); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $this->load->view('add_service_req_row',$data); } public function update_service_req(){ error_reporting(0); $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); //$data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['getBranchservicereqbyid']=$this->Service_model->getBranchservicereqbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); if(!empty($data['list1'])){ $data['list7']=$this->Service_model->getservicereqDetailsbyid($id); }else{ $data['list7']=$this->Service_model->getservicereqDetailsbyid1($id); } $data['get_mods']=$this->Service_model->get_mods(); $model_id = $data['list7'][0]->modelid; $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['service_typelist']=$this->Service_model->service_typelist(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['getProbByModel']=$this->Service_model->getProbByModel($model_id); $data['employee_list']=$this->Service_model->employee_list(); $data['accessories_list']=$this->Service_model->accessories_list(); $data['stamping_details']=$this->Service_model->stamping_details($id); $data['get_cancel_reason']=$this->Service_model->get_cancel_reason($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_req',$data); } public function update_service_status(){ $reqid=$this->input->post('reqid'); //$this->input->post('procatid'); $data=array( 'status'=>$this->input->post('statusid') ); $s = $this->Service_model->update_service_status($data,$reqid); } public function get_serials(){ $id=$this->input->post('id');//echo $id; exit; //$cust_id=$this->input->post('cust_id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_serialdetails($id))); } public function get_serialnos(){ $id=$this->input->post('id');//echo $id; exit; $cust_id=$this->input->post('cust_id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicenodetails($id,$cust_id))); } public function get_modelnos(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_modelnos($id))); } public function edit_service_req(){ date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $get_all = $this->input->post('skills'); $expll = explode(',',$get_all); $cunt = count($expll); $user_array = array(); $userr_array = array(); for($i=0;$i<$cunt;$i++) { $model = $this->input->post('modelid'); $ffffff = $expll[$i]; $this->db->select("*",FALSE); $this->db->from('problem_category'); $this->db->where('prob_category', $ffffff); $this->db->where('model', $model); $ressult = $this->db->get(); $ressullt = $ressult->num_rows(); if($ressullt>0) { //echo 'elseeee'; foreach($ressult->result() as $empkey) { $getlastt = $empkey->id; array_push($userr_array,$getlastt); } } else if($ressullt==0) { $datsa=array( 'prob_category'=>$ffffff, 'model'=>$model ); $this->db->insert('problem_category',$datsa); //echo $this->db->last_query(); $getlast = $this->db->insert_id(); array_push($user_array,$getlast); } } $data1['problem'] = array_merge($userr_array, $user_array); if (is_array($data1['problem'])){ $data1['problem']= implode(",",$data1['problem']); }else{ $data1['problem']=""; } $data=array( 'request_id'=>$this->input->post('req_id'), 'cust_name'=>$this->input->post('cust_name'), 'br_name'=>$this->input->post('br_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email_id'), 'address'=>$this->input->post('address'), 'address1'=>$this->input->post('address1'), 'request_date'=>$this->input->post('datepicker'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $id=$this->input->post('servicereqid'); $rowid=$this->input->post('servicereqdetailid'); //print_r($data);exit; $this->Service_model->update_service_request($data,$id); if($id){ $data1['request_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['batch_no']=$this->input->post('batch_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); //$data1['warranty_date']=$this->input->post('warranty_date'); if($this->input->post('warranty_date')!=""){ $data1['warranty_date'] = $this->input->post('warranty_date'); }else{ $data1['warranty_date'] = ""; } $data1['machine_status']=$this->input->post('machine_status'); $data1['service_type']=$this->input->post('service_type'); //$data1['service_cat']=$this->input->post('service_cat'); $ser_det = $this->input->post('service_cat'); $ser = explode("-",$ser_det); $data1['service_cat'] = $ser['0']; $data1['zone']=$this->input->post('locid'); $data1['service_loc_coverage']=$this->input->post('service_loc_coverage'); // $proble=$this->input->post('probi'); /* echo "<pre>"; print_r($data1['problem']); exit; */ /*if (is_array($proble)){ $data1['problem']= implode(",",$proble); }else{ $data1['problem']=""; }*/ //$data1['problem']=$this->input->post('prob'); //$data1['assign_to']=$this->input->post('assign_to'); $data1['service_priority']=$this->input->post('service_priority'); //$data1['blank_app']=$this->input->post('blank_app'); $emp_det = $this->input->post('assign_to'); $emp = implode(",",$emp_det); $data1['assign_to'] = $emp; $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } $data1['notes']=$this->input->post('notes'); //$countids=$this->input->post('countids'); /* echo "<pre>"; print_r($data1); exit; */ //$this->Service_model->delete_serv_req_details($id); //$result1=$this->Service_model->add_service_details($data1); $where = "id=".$rowid." AND request_id=".$id; $result1=$this->Service_model->update_service_details($data1,$where); $get_reassigned_ById = $this->Service_model->get_reassigned_ById($id); $enggids = $get_reassigned_ById[0]->engg_id; $engg_arr = explode(',',$enggids); $resulttt = array_diff($emp_det,$engg_arr); if(!empty($resulttt)){ //echo "IDS: ";exit; $data_log_reassign['engg_id'] = $emp; $data_log_reassign['req_id'] = $id; $data_log_reassign['updated_on'] = date("Y-m-d H:i:s"); $this->Service_model->add_log_reassign_engg($data_log_reassign); } } echo "<script>alert('Service Request Updated');window.location.href='".base_url()."pages/service_req_list';</script>"; } public function get_branchbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_branchdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_cust_servicezone(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_servicezone($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_branchname(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_branch($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_branchnamee(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_brannch($id))); } public function searchBycustomer() { $search=$this->input->post('username'); //echo $search;exit; $drop=$this->input->post('pwd'); if($drop && $search) { $data['customer']=$this->Service_model->customer_list($search,$drop); $data['stat_list']=$this->Service_model->status_list(); //$data['get_searchByStatus']=$this->Service_model->service_req_list($search); } else { $data['customer']=$this->Service_model->getallreq_list($search); $data['stat_list']=$this->Service_model->status_list(); } $this->load->view('service_list',$data); } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_order(){ $id=$this->input->post('id'); $this->Order_model->delete_order_details($id); $result = $this->Order_model->delete_orders($id); } public function viewclaimup(){ $id = $this->uri->segment(3); $datraa['list']=$this->Service_model->updatestsid($id); $datraa['ide']=$id; //$datraa = array('ide'=>$id); $this->load->view('viewclaimpop',$datraa); } public function updateclaim() { $id = $this->input->post('request_id'); if($this->input->post('code_no') && $this->input->post('date')) { $data=array( 'warranty_mode'=>$this->input->post('status_warran'), 'code_no'=>$this->input->post('code_no'), 'code_date'=>$this->input->post('date'), 'status'=>'credit note received' ); }else if($this->input->post('status_warran')=='credit'){ $data=array( 'warranty_mode'=>$this->input->post('status_warran'), 'code_no'=>'', 'code_date'=>'', 'status'=>'credit note pending' ); } else{ $data=array( 'warranty_mode'=>$this->input->post('status_warran'), 'code_no'=>'', 'code_date'=>'', 'status'=>'replacement' ); } $result = $this->Service_model->updateclaim($data,$id); if($result) { echo "<script> parent.jQuery.fancybox.close(); </script>"; } } public function get_preventive_id() { $row=$this->Service_model->get_preventive_id(); $rid=explode('-',$row->request_id); $res = sprintf("%05d", ++$rid[1]); $reqid='P-'.$res; $this->output ->set_content_type("application/json") ->set_output(json_encode($reqid)); } }<file_sep>/application/views_bkMarch_0817/tax_list.php <style> .ui-state-default { background: #fff !important; border: 3px solid #fff !important; color: #303f9f !important; font-size: 12px; border-bottom:1px solid #000; } .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; background-color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=text]{ background-color: transparent; border: 0px solid #eee; border-radius: 7; width: 55% !important; font-size: 12px; margin: 0 0 -2px 0; padding: 3px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height:17px; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <script> $(document).ready(function(){ $('[id^="pro_cat_"]').change(function(){//alert("hii"); var id = $(this).val(); var arr = id.split(','); var procatid = arr['0']; var subid = arr['1']; var data_String; data_String = 'id='+subid+'&procatid='+procatid; $.post('<?php echo base_url(); ?>subcategory/update_sub_category',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Category changed"); //$('#actaddress').val(data.Address1), }); }); }); function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); tax_name = $("#tax_name"+id).val(); tax_percent = $("#tax_percent"+id).val(); //alert("tax name: "+tax_name+"tax_percent: "+tax_percent); //alert(tax_percent); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/update_tax', data: {'id' : id, 'tax_name' : tax_name, 'tax_percent' : tax_percent}, dataType: "text", cache:false, success: function(data){ alert("Tax updated"); } }); }); } function Updatedefault(id) { if(document.getElementById('tax_default'+id).checked) { var tax_default = '1'; //alert(tax_default); } else { var tax_default = '0'; //alert(tax_default); } $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/update_default', data: {'id' : id, 'tax_default' : tax_default}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("Tax Selected"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>tax/del_tax', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/tax_list"; } alert("Tax deleted"); } }); }); } </script> <section id="content"> <div class="container"> <div class="section"> <h2>Tax List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addtax.png" title="Add Tax" style="width:24px;height:24px;">Add Tax</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Tax" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <form id="form1"> <table id="data-table-simple" class="responsive-table display"> <thead> <tr> <td style="text-align:center;font-size:13px;color:##303f9f;">Tax Name</td> <td style="text-align:center;font-size:13px;color:##303f9f;">Percentage</td> <td style="text-align:center;font-size:13px;color:##303f9f;">Action</td> </tr> </thead> <tbody> <?php foreach($tax_list as $key){ ?> <tr> <td> <input type="checkbox" name="tax_default" id="tax_default<?php echo $key->id; ?>" onclick="Updatedefault('<?php echo $key->id; ?>')" <?php if($key->tax_default){?> checked="checked" <?php }?>><input type="text" value="<?php echo $key->tax_name; ?>" class="" name="tax_name" id="tax_name<?php echo $key->id; ?>"> </td> <td><input type="text" value="<?php echo $key->tax_percentage; ?>" class="" name="tax_percent" id="tax_percent<?php echo $key->id; ?>"> </td> <td class="options-width" style="text-align:center;"> <a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a> <a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a> </td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/accessories_list.php <style> table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); acc_name = $("#acc_name_"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/update_accessories', data: {'id' : id, 'acc_name' : acc_name}, dataType: "text", cache:false, success: function(data){ alert("Accessories updated"); } }); }); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/del_accessories', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/accessories_list"; } alert("Accessories deleted"); } }); }); } </script> <section id="content"> <div class="container"> <div class="section"> <h4 class="header" style="display:inline-block;">Accessories List</h4> <a href="<?php echo base_url(); ?>pages/add_accessories"style="padding: 7px; border: 1px solid #055E87; background: #055E87 none repeat scroll 0% 0%; color: #FFF; border-radius: 5px;">Add New</a> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" cellspacing="0" style="width:50%; margin-top:2%;"> <thead> <tr> <td>Accessories Name</td> <td>Action</td> </tr> </thead> <tbody> <?php foreach($list as $key){ ?> <tr> <td><input type="text" value="<?php echo $key->accessory; ?>" class="" name="acc_name" id="acc_name_<?php echo $key->id; ?>"></td> <td class="options-width"> <a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/search_service_req_list.php <tbody> <?php foreach($get_searchByStatus as $key){?> <tr> <td><?php echo $key->request_id; ?></td> <td><?php echo $key->company_name; ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->model;} } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->machine_status; } }?></td> <td><?php echo $key->request_date; ?></td> <td><?php foreach($service_req_listforEmp as $key2){ if($key2->request_id==$key->id){ echo $key2->emp_name; } } /* foreach($service_req_listfordealers as $dealerkey2){ if($dealerkey2->request_id==$key->id){ echo $dealerkey2->customer_name; } } */ ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->site; } } ?></td> <td><?php foreach($service_req_list1 as $key1){ if($key1->request_id==$key->id){ echo $key1->service_loc; } } ?></td> <td class="options-width"> <select name="service_status[]" id="service_status_<?php echo $key->id; ?>"> <option value="">---Select---</option> <?php foreach($status_list as $statuskey){ if($statuskey->id==$key->status){ // if(in_array($statuskey->id, $statuslists[$i])){ ?> <option selected="selected" value="<?php echo $statuskey->id.','.$key->id; ?>"><?php echo $statuskey->status; ?></option> <?php } else {?> <option value="<?php echo $statuskey->id.','.$key->id; ?>"><?php echo $statuskey->status; ?></option> <?php } } ?> </select> </td> <td class="options-width"> <a href="<?php echo base_url(); ?>service/update_service_req/<?php echo $key->id; ?>" style="padding-left:15px;" ><i class="fa fa-floppy-o fa-2x"></i></a> </td> </tr> <?php } ?> </tbody> <script> $(document).ready(function(){ $('[id^="service_status_"]').change(function(){//alert("hiisss"); var id = $(this).val(); //alert(id); var arr = id.split(','); var statusid = arr['0']; var reqid = arr['1']; var data_String; data_String = 'statusid='+statusid+'&reqid='+reqid; $.post('<?php echo base_url(); ?>service/update_service_status',data_String,function(data){ //var data= jQuery.parseJSON(data); alert("Service status changed"); //$('#actaddress').val(data.Address1), }); }); }); </script><file_sep>/application/views/minus_spares_pop.php <!--<tr> <td><input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="" class="spare_qty"><select name="spare_name[]" id="sparename_<?php echo $count; ?>" class="spare_name"> <option value="">---Select---</option> <?php foreach($spareListByModelId as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; ?></option> <?php } ?> </select> </td> <td><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td><input type="text" value="" name="amt[]" id="amt<?php echo $count; ?>" class=""><input type="hidden" value="" name="amt1" id="amt1<?php echo $count; ?>" class=""></td> <td style="border:none;"><button class="delRowBtn1" style="font-size:20px;" id="delRowBtn1_<?php echo $count; ?>"><i class="fa fa-trash-o"></i></button></td> </tr>--> <tr> <td> <select id="spare_name_<?php echo $count; ?>" class="spare_name" name="spare_name[]"> <option value="">---Select---</option> <?php if(!empty($spare_catId)){ foreach($spare_catId as $spare_catkey){ ?> <option value="<?php echo $spare_catkey->id; ?>"><?php echo $spare_catkey->spare_name; ?></option> <?php } }?> </select> <div id="name_error_<?php echo $count; ?>" style="color:red"></div> </td> <td><input type="text" name="qty[]" id="qty_<?php echo $count; ?>" maxlength="10"><div id="qty_error_<?php echo $count; ?>" style="color:red"></div><input type="hidden" name="spare_qty1[]" id="spare_qty1_<?php echo $count; ?>"><input type="hidden" name="used_spare1[]" id="used_spare1_<?php echo $count; ?>"><input type="hidden" name="purchase_price1[]" id="purchase_price1_<?php echo $count; ?>"><input type="hidden" name="purchase_qty1[]" id="purchase_qty1_<?php echo $count; ?>"></td> <td><input type="text" name="purchase_date[]" id="datetimepicker8" class="datetimepicker8"></td> <!--<td><input type="text" name="purchase_price[]"></td> <td><input type="text" name="invoice_no[]"></td>--> <td><input type="text" name="reason[]" maxlength="100"></td> <td style="border:none;"><button class="delRowBtn" >Delete</button></td> </tr> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); //var idd=$(this).closest(this).attr('id'); var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1_'+vl).val(data.spare_qty), $('#used_spare1_'+vl).val(data.used_spare), $('#purchase_price1_'+vl).val(data.purchase_price), $('#purchase_qty1_'+vl).val(data.purchase_qty) }); } }); }); $('#qty_<?php echo $count; ?>').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); $( "form" ).submit(function( event ) { if ( $( "#spare_name_<?php echo $count; ?>" ).val() === "" ) { $( "#name_error_<?php echo $count; ?>" ).text( " Please Select the Spare Name" ).show().css({'color':'#ff0000','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#qty_<?php echo $count; ?>" ).val() === "" ) { $( "#qty_error_<?php echo $count; ?>" ).text( "Please Enter the Quantity" ).show().css({'color':'#ff0000','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#spare_name_<?php echo $count; ?>").change(function(){ if($(this).val()==""){ $("#name_error_<?php echo $count; ?>").show(); } else{ $("#name_error_<?php echo $count; ?>").hide(); } }); $("#qty_<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#qty_error_<?php echo $count; ?>").show(); } else{ $("#qty_error_<?php echo $count; ?>").hide(); } }); }); </script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js"></script> <script> $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999/19/39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('.datetimepicker8').datetimepicker({ onChangeDateTime:logic, onShow:logic }); </script> <file_sep>/application/views_bkMarch_0817/prod_list.php <script> function InactiveStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Product/update_status_product', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Product made Inactive"); window.location = "<?php echo base_url(); ?>pages/prod_list"; } }); }); } function activeStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Product/update_status_product1', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ alert("Product made Active"); window.location = "<?php echo base_url(); ?>pages/prod_list"; } }); }); } </script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Product List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/proadd.png" style="width:24px;height:24px;">Add Product</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Product" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Category</th> <th>Subcategory</th> <th>Brand</th> <th>Model</th> <?php foreach($accessories_list as $acckey1){ ?> <th><?php echo $acckey1->accessory; ?></th> <?php } ?> <th>Action</th> </tr> </thead> <tbody> <?php foreach($list as $key){ $addl = explode(",",$key->addlinfo); //print_r($addl);exit; ?> <tr> <td><?php echo $key->category; ?></td> <td><?php echo $key->subcategory; ?></td> <td><?php echo $key->brand_name; ?></td> <td><?php echo $key->model; ?></td> <?php foreach($accessories_list as $acckey){ ?> <?php if (in_array($acckey->accessory, $addl)){ ?><td><i class="material-icons">done</i></td><?php } else{ ?><td></td><?php } ?> <?php } ?> <td class="options-width"> <a href="<?php echo base_url(); ?>Product/update_product/<?php echo $key->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a> <?php if($key->status!='1') { ?><a href="#" onclick="InactiveStatus('<?php echo $key->id; ?>')">InActive</a><?php } ?><?php if($key->status!='0') { ?><a href="#" onclick="activeStatus('<?php echo $key->id; ?>')">Active</a><?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views/view_customer.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr> <td> <select> <option>Motorola</option> <option><NAME></option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td><td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-right:20px; } .link:hover { color:black; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } .box{ box-shadow:none !important; margin-bottom: 5px; } .box1{ display: none; box-shadow:none !important; } .col-md-2,.col-md-12,.col-md-10 { padding: 0px; } .card-panel { padding: 20px 0px; } label { position: relative; left: 0px; } </style> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">View Customer Details</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>pages/cust_list" method="post" > <div id="errorBox"></div> <?php foreach($list as $key){?> <div class="tableadd"> <div class="col-md-12"> <div class="col-md-3"> <label>Type Of Customer<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php foreach($customer_type as $custtypekey){ if( $custtypekey->id==$key->customer_type){ echo $custtypekey->type; ?> <?php } }?></div> </div> <!--<div class="col-md-2"><label>Mobile No<span style="color:red;">*</span></label></div><div class="col-md-2"><input type="text" name="mobile" id="mobile" class="mobile" value="<?php echo $key->mobile; ?>"></div>--> <div class="col-md-3"> <label>Customer ID<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->customer_id; ?></div> </div> <div class="col-md-3"> <label>Customer Name<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->company_name; ?></div> </div> <div class="col-md-3"> <?php if($key->mobile=="" && isset($key->mobile)){?> <label class="del1 box1">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <label class="ready1 box1">Landline No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <label class="del box">Mobile No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <label class="ready box">Landline No<span style="color:red;">*</span></label> <?php } ?> <?php if($key->mobile=="" && isset($key->mobile)){?> <input type="text" name="mobile" class="form-group del1 box1" id="mobile" value="" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"> <?php } ?> <?php if($key->land_ln=="" && isset($key->land_ln)){?> <input type="text" name="land_ln" id="land_ln" value="" class="ready1 box1" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"> <?php } ?> <?php if($key->mobile!="" && isset($key->mobile)){?> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->mobile;?></div> <?php } ?> <?php if($key->land_ln!="" && isset($key->land_ln)){?> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->land_ln;?></div> <?php } ?> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Email Id</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->email_id; ?></div> </div> <div class="col-md-3"> <label>Address<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->address; ?></div> </div> <div class="col-md-3"> <label>Address1</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->address1; ?></div> </div> <div class="col-md-3"> <label>Delivery Address</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->del_address; ?></div> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>State<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"> <?php foreach($state_list as $statekey){ if( $statekey->id==$key->state){ echo $statekey->state; }} ?> </div> </div> <div class="col-md-3"> <label>City<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->city; ?><div id="suggesstion-box" ></div></div> </div> <div class="col-md-3"> <label>Pincode<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->pincode; ?></div> </div> <div class="col-md-3"> <label>Area</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php foreach($pincode_list as $pinkey){if($pinkey->id==$key->area_name){echo $pinkey->area_name;}} ?></div> </div> </div> <div class="col-md-12"> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Service Zone<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php foreach($service_zone as $zonekey){ if( $zonekey->id==$key->service_zone){ echo $zonekey->service_loc; ?> <?php } } ?> </div> </div> <div class="col-md-3"> <label>Contact Name<span style="color:red;">*</span></label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key->customer_name; ?></div> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Lab Name</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"></div> </div> </div> <?php foreach($lablist as $lab){ if($lab->customer_id==$key->id){?> <div class="col-md-12"> <div class="col-md-3"> <?php echo $lab->lab_name; ?> </div> <div class="col-md-3" > <?php echo $lab->lab_value; ?> </div> </div> <?php } } ?> <?php } ?> <!--</table>--> <!-- <table id="table1" class="tableadd2" style="margin-bottom: 20px;"> <label style="color: black; font-size: 15px; font-weight: bold; margin-bottom:20px;">Add Product</label> <tr class="back" > <td>Product Name</td> <td>Category</td> <td>Model</td> <td>Serial No</td> </tr> <tr> <td> <select> <option>Motorola</option> <option><NAME></option> <option>Nokia</option> <option>Apple</option> </select> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> </tr> </table> <a id="addRowBtn" style="background: rgb(5, 94, 135) none repeat scroll 0% 0%; padding: 10px; color: white; border-radius:5px;">Add Row</a> <table class="tableadd">--> <?php $i=1; foreach($list1 as $key1){ if($key1->branch_name!=""){ if ($i !=1){?> <div id="myTable" class="tableadd" > <div class="col-md-12" style="border: 1px solid #ccc; background-color: whitesmoke; margin-bottom: 8px;"> <?php }else{?> <div id="myTable" class="tableadd"> <div class="col-md-12" > <?php } ?> <div class="col-md-12"> <div class="col-md-3"><label style="font-weight: bold;font-size: 14px;color: #000;line-height: 4;">Add Service Location</label></div> </div> <!--<?php if($i==1){?> <div class="col-md-12"> <div colspan="2"><em style="font-style: normal;color: rgb(5, 94, 135);">Same as above address</em></div> </div> <?php } ?>--> <div class="col-md-12" > <div class="col-md-3"> <label>Branch Name</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->branch_name; ?></div> </div> <div class="col-md-3"> <label>Landline No</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->landline; ?></div> </div> <div class="col-md-3"> <label>Address</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->address; ?></div> </div> <div class="col-md-3"> <label>Address 1</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->address1; ?></div> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>State</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"></div> <!--<?php foreach($state_list as $state) {if($state->id == $key1->state){ ?> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $state->state; ?></div> <?php } }?>--> </div> <div class="col-md-3"> <label>City </label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->city; ?></div> </div> <div class="col-md-3"> <label>Pincode</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->pincode; ?></div> </div> <div class="col-md-3"> <label>Area</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php foreach($pincode_list as $pinkey){if($pinkey->id==$key1->area){echo $pinkey->area_name;}} ?></div> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Service Zone</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"> <?php foreach($service_zone as $zonekey){ if($zonekey->id == $key1->service_zone_loc){ echo $zonekey->service_loc; ?> <?php } }?> </div> </div> </div> <div class="col-md-12"> <div class="col-md-2"><label style="font-weight: bold;">Add Contact</label></div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Contact Name</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->contact_name; ?></div> </div> <div class="col-md-3"> <label>Designation</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->designation; ?></div> </div> <div class="col-md-3"> <label>Mobile</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->mobile; ?></div> </div> <div class="col-md-3"> <label>Email Id</label> <div class="form-group" style="width: 200px;border: 1px solid #ccc;padding: 4px 0px 5px 4px;height:30px;"><?php echo $key1->email_id; ?></div> </div> </div> </div> <?php } $i++; } ?> </div> <input type="hidden" id="countid" name="countid" value="<?php echo $i; ?>"> <br/><br/> <button class="btn cyan waves-effect waves-light " type="submit" style="margin-top:10px;">Close </button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "<?php echo base_url(); ?>customer/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 99999999'); $('#mobile').mask('9999999999'); $('#mobiles').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> </body> </html><file_sep>/application/views/warranty_pending_claims.php <script> function UpdateStatus(id){ var idd = id.split('-'); var inc = idd['1']; var reqid = idd['0']; var status_warran = $("#status_warran-"+inc).val(); window.open("<?php echo base_url(); ?>service/view_claim/"+reqid+'/'+status_warran, '_blank'); } </script> <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 15px; border: 1px solid #dbd0e1 !important; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 15px !important; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; } td { text-align: left; font-size: 12px; padding: 0px ; } th { padding: 0px; text-align: center; font-size: 12px; /* background-color: #DBD0E1; */ } thead { border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; background:#6c477d; color:#fff; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } #data-table-simple_length { display: block; } /* For info in correct position */ .select-wrapper { position: relative; margin: -5px 6px; } #data-table-simple_length > label { display: inline-flex; max-width: 100%; margin-bottom: 5px; font-weight: 700; padding-right: 0px; } /* Ends Here */ input[type=search]{ background-color: transparent; border: 1px solid #522276; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } .fancybox-outer, .fancybox-inner { position: relative; height: 300px !important; } .fancybox-wrap { height: auto !important; } a{ color: #522276 !important; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Warranty Claim List</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Request ID</th> <th>Customer Name</th> <th>Model</th> <!--<th>Warranty Mode</th> --> <th>Warranty Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $i=0; foreach($warranty_pending_claims as $war_key){?> <tr> <td><a id="<?php echo $war_key->request_id;?>" href="javascript:;"><?php echo $war_key->request_id; ?></a></td> <td><?php echo $war_key->company_name; ?></td> <td><?php echo $war_key->model; ?></td> <!--<td><a id="<?php echo $war_key->request_id;?>" href="javascript:;">Warranty Updated</a></td>--> <!--<td> <select name="status_warran" id="status_warran-<?php echo $i; ?>"> <option value="credit">credit</option> <option value="replacement">replacement</option> </select> </td> --> <td><?php if($war_key->code_no && $war_key->code_date ) { echo $war_key->status; } else if($war_key->warranty_mode=='credit') { echo $war_key->status; }else{ echo $war_key->status; } ?></td> <td style="text-align:center;"><a href="<?php echo base_url(); ?>service/view_claim/<?php echo $war_key->quote_req_id; ?>" target="_blank" ><i class="fa fa-file-pdf-o" aria-hidden="true"></i></a></td> </tr> <script> $(document).ready(function() { //alert("afd"); $("#<?php echo $war_key->request_id;?>").click(function() { //alert("fdh"); $.fancybox.open({ href : '<?php echo base_url(); ?>service/viewclaimup/<?php echo $war_key->request_id; ?>', type : 'iframe', padding : 5, afterClose: function(){ alert('Warranty Claim Updated Successfully!!!'); parent.location.reload(true); } }); }); }); </script> <?php $i++; }?> </tbody> </table> </div> </div> </div> <br> </div> </div> </section> </div> </div> <!-- fancy box --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery-1.10.1.min.js"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/custom.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/piklor.js"></script> <script src="<?php echo base_url(); ?>assets/js/handlers.js"></script> </body> </html><file_sep>/application/views/stampingreport.php <style> body{background-color:#fff;} table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } </style> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/> <?php //print_r($report);exit;?> <section id="content"> <div class="container"> <div class="section"> <h2>Stamping Report List</h2> <hr> <form action="<?php echo base_url(); ?>report/get_stamping" method="post"> <tr> <td><label>From Date:</label></td><td><input type="text" name="from" value="" id="from" class="date"></td> <td><label>To Date:</label></td><td><input type="text" name="to" value="" id="to" class="date"></td> <!--<td><label>Employee Name:</label></td> <td><select name="employee" id="employee"> <option value="">--select--</option> <?php foreach($employee as $emp) {?> <option value="<?php echo $emp->id; ?>"><?php echo $emp->emp_name; ?></option> <?php } ?> </select> </td>--><br><br><br> <input type="submit" name="search" id="search" value="Search" class="submit_button" > </tr> </form> <!--DataTables example--> <br> </div> </div> </section> </div> </div> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ $(document).ready(function(){//alert("hfhh"); $(".date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); });//]]> </script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> </body> </html> <file_sep>/application/views/print_bills.php <style> #printArea { padding: 20px;} #printArea .PrintCnt{ border: 1px solid #999; padding: 0 7px 0 7px; box-shadow: 0 0 0 10px hsl(0, 0%, 80%),0 0 0 15px hsl(0, 0%, 90%);} #printArea .head-part {background-color: #ccc; padding: 10px; text-align: center; border: 1px solid #999; box-shadow: inset 0 0 10px #888;} #printArea .head-part p { font-size: 18px; color: #666;} #printArea .body-part { padding: 10px;} #printArea .btn-print { border-radius: 0;border: 2px solid #ffffff; outline: 1px solid #ccc;} #printArea .body-part table tr, #printArea .body-part table th, #printArea .body-part table td {} } @media print { .btn-print { display: none;} } @page { margin: 0; } body { margin: 1.6cm;} .table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th, .table>thead>tr>td, .table>tbody>tr>td, .table>tfoot>tr>td { padding: 2px 7px !important; line-height: 1.12857143; vertical-align: top; border-top: 1px solid #ddd !important; font-size: 14px; } </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="container"> <div class="row" id="printArea"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="border: 1px solid #999;"><!-- box-shadow: 0 0 0 10px hsl(0, 0%, 80%), 0 0 0 15px hsl(0, 0%, 90%); --> <div class="row"> <!-- <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12"> <h1>PC</h1> </div> <div class="col-lg-10 col-md-10 col-sm-12 col-xs-12"> <p style="font-size: 18px; color: #666;">Building No, Street Name, Place Name</p> <p style="font-size: 18px; color: #666;">District, state-pincode</p> </div> --> <table class="table" style="border-bottom: 1px solid #ccc; background-color: #336499;"> <tbody> <tr> <td style="width: 20%; border-top: 0 !important;"> <img src="<?php echo base_url(); ?>assets/images/logo.png" alt="materialize logo" style="height:70px;color:#fff;float:left;position:relative;margin-top: 25px;" class="saturate"> </td> <td style="width: 80%; padding-top: 20px; border-top: 0 !important;"> <p style="font-size: 18px; color: #ffffff; font-weight: bold; text-align: center;font-size: 24px;">Parshva Creations</p> <p style="font-size: 18px; color: #ffffff; text-align: center;">7, Balaji Complex, Elephant Gate Street, (Near Jain Temple Mint Street), Sowcarpet</p> <p style="font-size: 18px; color: #ffffff; text-align: center;">Tamil Nadu, Chennai - 600079</p> </td> </tr> </tbody> </table> </div> <div class="row body-part" style="padding: 10px;"> <!-- <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h4 style="border: 0; padding: 10px;border-bottom: 1px solid #ccc; width: 23%; text-align: center;">Personal Details</h4> <div class="table-responsive"> <table class="table" style="border: 1px solid #ccc;text-align: center"> <thead> <tr style=" color: #444;background-color: #f2f2f2;"> <th style=" text-align: center;border: 1px solid #ccc;">Bill No</th> <th style=" text-align: center;border: 1px solid #ccc;">Customer Name</th> <th style=" text-align: center;border: 1px solid #ccc;">Mobile</th> <th style=" text-align: center;border: 1px solid #ccc;">Address</th> <th style=" text-align: center;border: 1px solid #ccc;">City</th> <th style=" text-align: center;border: 1px solid #ccc;">State</th> <th style=" text-align: center;border: 1px solid #ccc;">Pincode</th> <th style=" text-align: center;border: 1px solid #ccc;">Purchase Date</th> </tr> </thead> <tbody> <tr><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td><td style="border: 1px solid #ccc;">Content</td></tr> </tbody> </table> </div> </div> --> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h4 style="border: 0; padding: 10px; width: 23%;margin-left:-9px;">Billing Details</h4> <div class="table-responsive"> <table class="table" style="border: 1px solid #ccc;margin-top: -10px;"> <?php foreach($getorderbyid as $ord_key){?> <tbody> <table style="width: 49%; border: 1px solid #ccc;line-height:5px;" align="left"> <tbody> <tr><td style="padding: 10px;">Bill No</td><td>:</td><td><?php echo $ord_key->order_id; ?></td></tr> <tr><td style="padding: 10px;">Customer Name</td><td>:</td><td><?php echo $getCustDetails->customer_name; ?></td></tr> <tr><td style="padding: 10px;">Mobile</td><td>:</td><td><?php echo $ord_key->mobile; ?></td></tr> <tr><td style="padding: 10px;">Address</td><td>:</td><td><?php echo $ord_key->address; ?></td></tr> </tbody> </table> <table style="width: 49%; border: 1px solid #ccc;line-height:5px;" align="right"> <tbody> <tr><td style="padding: 10px;">City</td><td>:</td><td><?php echo $ord_key->city; ?></td></tr> <tr><td style="padding: 10px;">State</td><td>:</td><td><?php echo $ord_key->state; ?></td></tr> <tr><td style="padding: 10px;">Pincode</td><td>:</td><td><?php echo $ord_key->pincode; ?></td></tr> <tr><td style="padding: 10px;">Purchase Date</td><td>:</td><td><?php echo $ord_key->purchase_date; ?></td></tr> </tbody> </table> </tbody> <?php } ?> </table> </div> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h4 style="border: 0; padding: 10px; width: 23%;margin-left:-9px;">Product Details</h4> <div class="table-responsive"> <table class="table" style="border: 1px solid #ccc;"> <thead> <tr style=" color: #444; background-color: #f2f2f2;"> <th style=" text-align: center;border: 1px solid #ccc;">Product Name</th> <th style=" text-align: center;border: 1px solid #ccc;">Unit Price</th> <th style=" text-align: center;border: 1px solid #ccc;">Qty</th> <th style=" text-align: center;border: 1px solid #ccc;">Total Amount</th> </tr> </thead> <tbody> <?php foreach($getorderDetailsbyid as $keyy){?> <tr style=" text-align: center;"><td style="border: 1px solid #ccc;"><?php echo $keyy->p_name; ?></td><td style="border: 1px solid #ccc;"><?php echo $keyy->price; ?></td><td style="border: 1px solid #ccc;"><?php echo $keyy->qty; ?></td><td style="border: 1px solid #ccc;"><?php echo $keyy->sub_total; ?></td></tr><tr></tr> <?php } ?> <?php foreach($getorderbyid as $ord_key){?> <tr style=" text-align: center;"><td colspan="2" style="border: 1px solid #fff;border-right:1px solid #ccc;"></td> <td style="border: 1px solid #ccc;">Sub total</td><td><?php echo $ord_key->sub_total; ?></td></tr> <tr style=" text-align: center;"><td colspan="2"style="border: 1px solid #fff;border-right:1px solid #ccc;"></td><td style="border: 1px solid #ccc;">Discount</td><td><?php echo $ord_key->disc; ?></td></tr> <tr style=" text-align: center;"><td colspan="2" style="border: 1px solid #fff;border-right:1px solid #ccc;"></td><td style="border: 1px solid #ccc;">Grand total</td><td><?php echo $ord_key->grand_total; ?></td></tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="padding: 20px;text-align: center;"> <button id="" class="btn btn-lg fa fa-print" onclick="printDiv('printArea')"> Print</button> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="<?php echo base_url(); ?>assets/css/chosen.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <file_sep>/application/views_bkMarch_0817/sparereport_list.php <script> $(function() { // alert("hi"); $(".firstname").click(function(){ // alert("sdbsd"); if($(this).val()==""){ $("#errorBox").show(); } else{ $("#errorBox").fadeOut('slow'); } }); $(".lastname").click(function(){ // alert("sdbsd"); if($(this).val()==""){ $("#errorBox1").show(); } else{ $("#errorBox1").fadeOut('slow'); } }); }); </script> <style> body{background-color:#fff;} table.dataTable tbody td{ padding: 8px 10px !important; } input { height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } /*input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #000; border-bottom: 1px solid #055E87; border-radius: 0; outline: none; height: 3.9rem; width: 100%; font-size: 1.5rem; margin: 0 0 0 0; padding: 0; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; height: 3rem !important; }*/ #search { height: 3rem !important; margin-top: 10px; margin-left: 30px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } /*.ui-datepicker-calendar { display: none; }*/ #errorBox{ color:#F00; } #errorBox1{ color:#F00; } </style> <?php //print_r($enggname_list);exit;?> <section id="content"> <div class="container"> <div class="section"> <h2>Spare Report List</h2> <hr> <form name="myForm" action="<?php echo base_url(); ?>report/get_engineer_name" method="post" onsubmit="return validateForm()"> <div class="col-md-12"> <!-- <div class="col-md-3"> <label>From Date:</label> <input type="text" name="from" class="date-picker" id="datepicker"> </div>--> <div class="col-md-3"> <label>From Date:</label> <input type="text" name="from" class="date firstname" id="datepicker"><div id="errorBox"></div> </div> <div class="col-md-3"> <label>To Date:</label> <input type="text" name="to" class="date lastname" id="datepicker1"><div id="errorBox1"></div> </div> <div class="col-md-3"> <div><label>Spare Name:</label></div> <div> <select name="spare"> <option value="">--select--</option> <?php foreach($sparename_list as $spare) {?> <option value="<?php echo $spare->id;?>"><?php echo $spare->spare_name;?></option><?php } ?> </select> </div> </div> </div> <!--<td><label>Engineer Name:</label></td> <td><select name="engineer" > <option value="">---select---</option> <?php foreach($enggname_list as $eng) {?> <option value="<?php echo $eng->id;?>"><?php echo $eng->emp_name;?></option><?php } ?></select></td><br><br><br>--> <input type="submit" name="search" id="search" value="Search" class="submit_button btn btn-primary" > </form> <!--DataTables example--> <br> </div> </div> </section> </div> </div> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type='text/javascript'>//<![CDATA[ $(document).ready(function(){//alert("hfhh"); $(".date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); $("#datepicker1").change(function(){ //alert("hi"); var todate=$("#datepicker1").datepicker({ dateFormat: "yy-mm-dd" }).val(); // alert(todate); var stdate=$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val(); //alert(stdate); if(todate<stdate){ alert("To Date Should not be less than From date"); $("#datepicker1").datepicker().val(''); return false; } }); });//]]> </script> <script type="text/javascript"> $(function() { $('.date-picker').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onClose: function(dateText, inst) { $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1)); } }); }); </script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> --> </body> </html> <script> function validateForm() { //alert("sd"); var fromm = document.myForm.from.value, to = document.myForm.to.value; if( fromm == "" ) { document.myForm.from.focus(); document.getElementById("errorBox").innerHTML = "Select the From Date"; return false; } if( to == "" ) { document.myForm.to.focus() ; document.getElementById("errorBox1").innerHTML = "Select the To Date"; return false; } } </script> <file_sep>/application/views/stamping_print_request.php <style> input[readonly] { border:none; } p { margin:0px; } </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Print Invoice</h5> <div class="divider"></div> <div id="printableArea"> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <div id="printheader" > <div class="pull-left" > <h1 class="headingprint" style="font-size: 25px;margin-top: 0px;">S.R SCALES</h1> <P> No:2,BADRI VEERASAMY LANE,</P> <p>(Off:NSC BOSE ROAD) SOWCARPET,CHENNAI-79.</p> </div> <div class="pull-right" > <p>Phone : 9710411488</p> <p>Fax : 42168883</p> <p>Email Id : <EMAIL></p> </div><div style="height:90px;border-bottom:1px dashed gray; "></div> </div> <form action="<?php echo base_url(); ?>delivery/edit_quotereview" method="post" name="frmServiceStatus"> <?php foreach($getQuoteByReqId as $key){?> <br/> <div class="table-responsive"> <table class="table table-borderless" > <tr> <td><label>Request ID</label><span class="pull-right">:</span></td><td><input type="text" name="reque_id" class="" value="<?php echo $key->request_id; ?>" readonly></td> <td><label>Time</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php date_default_timezone_set('Asia/Calcutta'); echo date("d-m-Y H:i:s");?>" readonly></td> </tr> <tr> <td><label>Customer Name</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php echo $key->customer_name; ?>" readonly></td> <td><label>Address</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php echo $key->address.' '.$key->address1; ?>" readonly></td> </tr> <tr> <td><label>Phone</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php echo $key->mobile; ?>" readonly></td> <td><label>Machine Serial No.</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php echo $key->serial_no; ?>" readonly><input type="hidden" name="req_id" id="req_id" class="" value="<?php echo $req_id; ?>"></td> </tr> <tr> <td><label>Date Of Request</label><span class="pull-right">:</span></td><td><input type="text" name="" value="<?php echo $key->request_date; ?>" readonly></td> <td><label>Location</label><span class="pull-right">:</span></td><td><input type="text" name="" class="" value="<?php echo $key->service_loc; ?>" readonly></td> </tr> <?php } ?> <?php foreach($stamping_details As $stkey){ if(isset($stkey->stamping_received)){ $stamping_received = explode(",",$stkey->stamping_received); } ?> <tr> <td><label style="border-bottom:1px solid black;">Stamping Details</label></td> </tr> <tr> <td><label>Year</label><span class="pull-right">:</span></td> <td><input type="text" name="year" id="year" class="" value="<?php echo $stkey->year; ?>" readonly></td> <td><label>Quarter</label><span class="pull-right">:</span></td> <td><input type="text" name="qtr" id="qtr" class="" value="<?php echo $stkey->quarter; ?>" readonly></td> </tr> <tr> <td><label>Kg</label><span class="pull-right">:</span></td> <td><input type="text" name="kg" id="kg" class="" value="<?php echo $stkey->kg; ?>" readonly></td> <td><label>Received</label><span class="pull-right">:</span></td> <td><input type="text" name="kg" id="kg" class="" value="<?php if(in_array('vcplate', $stamping_received)){echo "VC Plate"; } if(in_array('vcpaper', $stamping_received)){echo " VC Paper"; } if(in_array('bothplatepaper', $stamping_received)){echo " VC Plate + Paper"; }?>" readonly> </td> </tr> <tr> <td><label>Stamping Charge</label><span class="pull-right">:</span></td> <td><input type="text" name="stamping_charge" id="stamping_charge" class="" value="<?php echo $stkey->stamping_charge; ?>" readonly></td> <td><label>Penalty</label><span class="pull-right">:</span></td> <td><input type="text" name="agn_charge" id="agn_charge" class="" value="<?php echo $stkey->penalty; ?>" readonly></td> </tr> <tr> <td><label>Total Charge</label><span class="pull-right">:</span></td> <td><input type="text" name="tot_charge" id="tot_charge" class="" value="<?php echo $tot_charge; ?>" readonly></td> </tr> <?php } ?> </table> </div> <br/> <label>Customer Signature</label> <p style="height:50px;"></p> <input class="no-print" id="addRowBtn" type="button" onClick="printDiv('printableArea')" value="Print Request" style="background: rgb(5, 94, 135) none repeat scroll 0% 0%; padding: 11px; color: #FFF; border-radius: 5px; margin-right: 20px;"/> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </div> </section> </div> </div> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/controllers/createpdf.php <?php class createpdf extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); } function pdf() { $this->load->helper('pdf_helper'); $data['orderid'] = $this->input->post('orderid'); $data['charge'] = $this->input->post('charge'); $data['amc_frmdate'] = $this->input->post('amc_frmdate'); $data['amc_todate'] = $this->input->post('amc_todate'); $this->load->view('pdfreport',$data); } function pdf_view() { $data['id'] = $this->uri->segment(3); $this->load->view('pdf_view',$data); } }<file_sep>/application/controllers/Product.php <?php class Product extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Product_model'); } public function add_product(){ //echo "<pre>";print_r($_POST);exit; // $data['serial_no']=$this->input->post('serial_no'); $data['category']=$this->input->post('category'); $data['subcategory']=$this->input->post('subcategory'); $data['model']=$this->input->post('model'); $data['stock_qty']=$this->input->post('stock_qty'); $data['description']=$this->input->post('description'); $result=$this->Product_model->add_prod($data); if($result){ echo "<script>alert(' Product Added Successfully!!!');window.location.href='".base_url()."pages/prod_list';</script>"; } } public function add_product_quick(){ //echo "<pre>";print_r($_POST);exit; // $data['serial_no']=$this->input->post('serial_no'); $data['product_name']=$this->input->post('product_name'); $data['category']=$this->input->post('category'); $data['subcategory']=$this->input->post('subcategory'); $data['brand']=$this->input->post('brand'); $data['model']=$this->input->post('model'); $data['description']=$this->input->post('description'); $data['addlinfo']=$this->input->post('addlinfo'); //print_r($data['addlinfo']); if (is_array($data['addlinfo'])){ $data['addlinfo']= implode(",",$data['addlinfo']); }else{ $data['addlinfo']=""; } //$data['addlinfo']= implode(",",$data['addlinfo']); $result=$this->Product_model->add_prod($data); if($result){ echo "<script>parent.$.fancybox.close();</script>"; } } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Product_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Product_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function update_product(){ $id=$this->uri->segment(3); $data['list']=$this->Product_model->getproductbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $data['prodcatlist']=$this->Product_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Product_model->prod_sub_cat_dropdownlist(); $data['brandlist']=$this->Product_model->brandlist(); $data['accessories_list']=$this->Product_model->accessories_list(); $this->load->view('edit_prod_list',$data); } public function edit_product(){ $data=array( 'category'=>$this->input->post('category'), 'subcategory'=>$this->input->post('subcategory'), 'model'=>$this->input->post('model'), 'stock_qty'=>$this->input->post('stock_qty'), 'description'=>$this->input->post('description') ); $id=$this->input->post('product_id'); $this->Product_model->edit_products($data,$id); $stock_qty = $this->input->post('stock_qty1'); if(isset($stock_qty) && $stock_qty!=""){ $this->Product_model->update_stock_in_hand($stock_qty, $id); } echo "<script>alert('Product Updated Successfully!!!');window.location.href='".base_url()."pages/prod_list';</script>"; } public function update_status_product(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Product_model->update_status_prod($data,$id); echo "<script>alert('Product Category made Inactive');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function update_status_product1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Product_model->update_status_prod1($data,$id); echo "<script>alert('Product Category made Active');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } }<file_sep>/application/views_bkMarch_0817/quote_review - Copy.php <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Quote Review</h4> <div class="divider"></div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0"> <thead> <tr> <th>Request Id</th> <th>Customer Name</th> <th>Product Name</th> <th>Machine Status</th> <th>Requested Date</th> <th>Assign To</th> <th>Site</th> <th>Location</th> <th>Problem</th> </tr> </thead> <!-- <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot>--> <tbody> <tr> <td><a href="quote_review_view.php">001</a></td> <td>Vishnu</td> <td>Air Conditioner</td> <td>Warranty</td> <td>24.8.2015</td> <td>Manikandan</td> <td>OnSite</td> <td>Chennai</td> <td>Repair</td> </tr> <tr> <td><a href="quote_review_view.php">002</a></td> <td>Suresh</td> <td>Television</td> <td>Out of warranty</td> <td>27.8.2015</td> <td>Vishnu</td> <td>OffSite</td> <td>Bangalore</td> <td>Problem 2</td> </tr> <tr> <td><a href="quote_review_view.php">003</a></td> <td>Manikandan</td> <td>Digital Camera</td> <td>AMC</td> <td>24.8.2015</td> <td>Ramesh</td> <td>OnSite</td> <td>Chennai</td> <td>Problem 3</td> </tr> <tr> <td><a href="quote_review_view.php">004</a></td> <td>Vishnu</td> <td>Washing Machine</td> <td>Warranty</td> <td>24.8.2015</td> <td>Kamlesh</td> <td>OnSite</td> <td>Chennai</td> <td>Problem 4</td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/controllers/Monthreport_data.php <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" cellspacing="0" style="width:50%; margin-top:2%;"> <thead> <tr > <td>Request ID</td> <td>stamping Charge</td> <td>Penalty Charge</td> <td>Agent_Charge</td> <td>Conveyance_Charge</td> <td>Pending_Amount</td> </tr> </thead> <tbody> <?php if(!empty($month)) { foreach($month as $row) { ?> <tr > <td><?php echo $row->id;?></td> <td><?php echo $row->stamping_charge;?></td> <td><?php echo $row->penalty;?></td> <td><?php echo $row->agn_charge;?></td> <td><?php echo $row->conveyance;?></td> <td><?php echo $row->pending_amt;?></td> </tr> </tbody> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total : <?php echo $row->total;?></div></td> </tr> <tr> <td colspan="7" style="border:none !important;"></td> <td colspan="2"><div class="pull-right">Total Stamping :<?php echo $row->process;?></div></td> </tr> <?php } }?> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url() ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script><file_sep>/application/views_bkMarch_0817/add_spare_row.php <tr> <td> <select name="model[]" id="model-<?php echo $count; ?>" class="model"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select> </td> <td><input type="text" name="category_name" id="category_name-<?php echo $count; ?>" readonly><input type="hidden" name="category[]" id="category-<?php echo $count; ?>" readonly></td> <td><input type="text" name="subcategory_name" id="subcategory_name-<?php echo $count; ?>" readonly><input type="hidden" name="subcategory[]" id="subcategory-<?php echo $count; ?>" readonly></td> <td><input type="text" name="brand_name" id="brand_name-<?php echo $count; ?>" readonly><input type="hidden" name="brandname[]" id="brandname-<?php echo $count; ?>" readonly> </td> </tr> <script> $(document).ready(function(){ $('.model').change(function(){//alert("ddddd"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); var arr= idd.split('-'); var vl = arr['1']; //alert(id); var dataString = 'modelno='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/get_productinfobyid", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#category_name-'+vl).val(data.product_category), $('#category-'+vl).val(data.category), $('#subcategory_name-'+vl).val(data.subcat_name), $('#subcategory-'+vl).val(data.subcategory), $('#brand_name-'+vl).val(data.brand_name), $('#brandname-'+vl).val(data.brand) }); } }); }); }); </script><file_sep>/application/models/Company_model.php <?php class Company_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function update_company($data,$id){ $this->db->where('id',$id); $this->db->update('company_details',$data); } public function company_list(){ $this->db->select("*",FALSE); $this->db->from('company_details'); $query = $this->db->get(); return $query->result(); } public function state_list(){ $this->db->select("id,state",FALSE); $this->db->from('state'); $this->db->order_by('state', 'asc'); //$this->db->limit(1); $query = $this->db->get(); return $query->result(); } public function add_city($data){ $this->db->insert('city',$data); return true; } }<file_sep>/application/views/spare_engineers.php <head> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script> <style> .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { border: 1px solid gray; text-align: center; } .tableadd1 tr { height: 50px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:white; } .tableadd1 tr td.plus { padding-top: 14px; } .tableadd1 tr td.plus input { width:70px; border:1px solid gray; } .tableadd1 tr td input { height: 33px; border-radius: 5px; padding-left: 10px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { width:50%; margin-top:20px; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:black; } #errorBox{ color:#F00; } .form-control { border-radius: 0; box-shadow: none; border-color: #fcfcfc; } .tableadd tr td select { height:30px; border-radius: 2px; width: 210px; border: 1px solid #ccc; background-color: transparent; -moz-appearance: none; } .tableadd1 tr td select { border: 1px solid #ccc; border-radius: 2px; width: 159px; } .tableadd1 tr td { border: 1px solid #cccccc; text-align: center; } .tableadd1 tr td.plus input { width: 60px; border: 1px solid #cccccc; height: 28px; border-radius: 2px; } .tableadd1 tr td.qty input { width: 100px; border: 1px solid #cccccc; height: 28px; border-radius: 2px; } .tableadd1 tr td textarea { width: 200px; border: 1px solid #cccccc; height: 70px; border-radius: 2px; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); //var total_spare = $("#total_spare_"+id).val(); var used_spare = $("#used_spare_"+id).val(); var purchase_qty = $("#purchase_qty_"+id).val(); var purchase_price = $("#purchase_price_"+id).val(); var purchase_date = $("#purchase_date_"+id).val(); //alert("purchase_qty: "+purchase_qty+"purchase_price: "+purchase_price+"purchase_date: "+purchase_date) var total_spare = parseInt(purchase_qty) - parseInt(used_spare); //alert(stock_spare); //$('#total_amt').val(stock_spare); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_spare_stock', data: {'id' : id, 'used_spare' : used_spare, 'total_spare' : total_spare, 'purchase_qty' : purchase_qty, 'purchase_price' : purchase_price, 'purchase_date' : purchase_date}, dataType: "text", cache:false, success: function(data){ alert("Spare Stock updated"); window.location = "<?php echo base_url(); ?>pages/spare_stock"; } }); }); } </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/addrow2", data: datastring, cache: false, success: function(result) { //alert(result); // $('#table1').append(result); $('#table1').append(result); } }); }); }); </script> <script> $(document).ready(function(){ $('.eng_spare_name').change(function(){ //alert("hiiio"); var id = $(this).val(); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('-'); var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ //alert(data.min_qty); if(parseInt(data.spare_qty) <= parseInt(data.min_qty)){ alert("Alert!!! Spare meets minimum qty level"); } $('#spare_qty-'+vl).val(data.spare_qty), $('#used_spare-'+vl).val(data.used_spare), $('#eng_spare-'+vl).val(data.eng_spare), $('#amt-'+vl).val(data.sales_price) }); } }); }); }); </script> <script> $(document).ready(function(){ $('.plus1').click(function(){ //alert("hiiio"); if(document.getElementById('minus-0').value!=""){ alert("enter any plus or minus"); //$("#plus").attr("disabled", "disabled"); }/* else{ $("#plus").removeAttr("disabled"); } */ }); $('.minus1').click(function(){ //alert("hiiio"); if(document.getElementById('plus-0').value!=""){ alert("enter any plus or minus"); //$("#minus").attr("disabled", "disabled"); }/* else{ $("#minus").removeAttr("disabled"); } */ }); }); function UpdateStatus1(id){ //alert(id);alert($("#enggdate_"+id).val()); var eng_name = $("#eng_name-"+id).val(); var eng_spare_name = $("#eng_spare_name-"+id).val(); var engg_date = $("#enggdate_"+id).val(); if(eng_name==""){ alert("Enter the Engineer Name"); }else if(eng_spare_name==""){ alert("Enter the Spare Name"); }else if(engg_date==""){ alert("Enter the Date"); }else{ var plus = $("#plus-"+id).val(); var minus = $("#minus-"+id).val(); //alert(engg_date); var engg_reason = $("#engg_reason-"+id).val(); var spare_qty = $("#spare_qty-"+id).val(); var used_spare = $("#used_spare-"+id).val(); var eng_spare = $("#eng_spare-"+id).val(); $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/add_spare_engg', data: {'eng_name' : eng_name, 'eng_spare_name' : eng_spare_name, 'plus' : plus, 'minus' : minus, 'engg_date' : engg_date, 'engg_reason' : engg_reason, 'spare_qty' : spare_qty, 'used_spare' : used_spare, 'eng_spare' : eng_spare}, dataType: "text", cache:false, success: function(data){ alert("Spares For Engineers Added"); } }); }); } } </script> <script> $(document).ready(function(){ //alert("bfh"); $('#sample').change(function(){ //alert("hiiio"); var id = $(this).val(); // var idd=$(this).closest(this).attr('id'); //alert(idd); // var arr= idd.split('-'); // var vl = arr['1']; //var vl=$('#countid').val(); //alert(vl); //alert("spareid: "+idd); $("#modelid_0 > option").remove(); $("#cust_id_0 > option").remove(); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/getcust_name", data: dataString, cache: false, success: function(data) { $('#modelid_0').append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ /* $('#custtest_0').val(data.customer_name), $('#cust_id_0').val(data.cust), */ $('#cust_id_0').append("<option selected='selected' value='"+data.cust+"'>"+data.customer_name+"</option>"); $('#modelid_0').append("<option value='"+data.prod_id+"'>"+data.model+"</option>"); }); } }); }); $('.modelss').change(function(){ //alert("hiiio"); var id = $(this).val(); //alert(id); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr= idd.split('_'); var inc = arr['1']; //var vl=$('#countid').val(); //alert(inc); //alert("spareid: "+idd); $('#eng_spare_name-'+inc+ "> option").remove(); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Spare/spareListByModelId", data: dataString, cache: false, success: function(data) { $('#eng_spare_name-'+inc).append("<option value=''>---Select---</option>"); $.each(data, function(index, data){ if(data.spare_name.length>0){ $('#eng_spare_name-'+inc).append("<option value='"+data.id+"'>"+data.spare_name+"</option>"); } }); } }); }); }); </script> <script> function frmValidate(){ //alert("hii"); //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var eng_name = document.frmSpareEng.eng_name.value; spare_receipt = document.frmSpareEng.spare_receipt.value; if(eng_name == "") { document.frmSpareEng.eng_name.focus(); document.getElementById("errorBox").innerHTML = "select the engineer name"; return false; } if(spare_receipt == "") { document.frmSpareEng.spare_receipt.focus(); document.getElementById("errorBox").innerHTML = "select the service type"; return false; } } </script> </head> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Spares for Engineers</h2> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <form action="<?php echo base_url(); ?>Spare/add_spare_engg" method="post" name="frmSpareEng" onsubmit="return frmValidate()" autocomplete="off"> <div class="col-md-12"> <table class="tableadd" id="addtable"> <div id="errorBox"></div> <tr> <td><label>Engineer Name<span style="color:red;">*</span></label></td> <td> <select name="eng_name" id="eng_name-0"> <option value="">---Select---</option> <?php foreach($engg_list as $enggkey){ ?> <option value="<?php echo $enggkey->id; ?>"><?php echo $enggkey->emp_name; ?></option> <?php } ?> </select></td> <td></td> <td></td> <td><label>Service Type:<span style="color:red;">*</span></label></td> <td> <select name="spare_receipt"> <option value="">---Select---</option> <option value="service center">service center</option> <option value="customer site within Chennai">customer site within Chennai</option> <option value="customer site outstation">customer site outstation</option> <option value="without_Service">Without Service</option> </select></td> <td></td> <td></td> </tr> </table> <div style="margin: 30px 0px;"> <table id="table1" class="tableadd1" style="width:100%;"> <tr style="background: rgb(5, 94, 135) none repeat scroll 0% 0%;"><td><label>RequestID</label></td><td><label>CustomerName</label></td><td><label>Model</label></td><td><label>Spare Name</label></td><td><label>Quantity</label></td><td><label>Date</label></td><td><label>Remarks</label></td><!--<td><label>Action</label></td>--></tr> <tr> <td><select class="chosen-select form-control request_id" name="req_id[]" id="sample"> <option value="">---Select---</option> <?php foreach($reqview as $row){ ?> <option value="<?php echo $row->id; ?>"><?php echo $row->request_id; ?></option> <?php } ?> </select></td> <td class="plus"> <select class="chosen-select form-control name_select" name="cust[]" id="cust_id_0"> <option value="">---Select---</option> <?php foreach($customerlist as $customerkey){ ?> <option value="<?php echo $customerkey->id; ?>"><?php echo $customerkey->company_name; ?></option> <?php } ?> </select> <i class="fa fa-plus-square fa-2x" onclick='brinfo(0)'></i> <!--<input type="hidden" name="cust[]" id="cust_id_0" value="">--></td> <td class="plus"> <select name="modelid[]" id="modelid_0" class="modelss"> <option value="">---Select---</option> </select> </td> <td><select name="eng_spare_name[]" id="eng_spare_name-0" class="eng_spare_name"> <option value="">---Select---</option> <?php foreach($spare_list as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; ?></option> <?php } ?> </select></td><td class="plus"><input type="text" Placeholder="plus" name="plus[]" id="plus-0" class="plus1">OR<input type="text" placeholder="minus" name="minus[]" id="minus-0" class="minus1"></td> <td class="qty"><input type="text" class="date" name="engg_date[]" id="enggdate_0"><input type="hidden" name="spare_qty[]" id="spare_qty-0"><input type="hidden" name="used_spare[]" id="used_spare-0"><input type="hidden" name="eng_spare[]" id="eng_spare-0"><input type="hidden" name="amt[]" id="amt-0"> <input type="hidden" name="amt1[]" id="amt1-0"></td> <td style="padding:10px 0;"><textarea type="text" name="engg_reason[]" id="engg_reason-0"></textarea></td> <!-- <td class="save"> <a href="#" onclick="UpdateStatus1(0)"><i class="fa fa-floppy-o fa-3x"></i></a></td>--> </tr> </table> <input type="hidden" name="countid" id="countid" class="" value="0"> </div> <a id="addMoreRows" class="rowadd" style="padding: 8.5px; margin-right: 20px;">Add Row</a><button class="btn cyan waves-effect waves-light" type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> </div> </form> </div> </div> <br> <div class="divider"></div> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $sparekey->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> </div> </div> </section> </div> </div> <script> $(function(){ $(".date").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: "1950:2055" }); }) </script> <script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function() { $(".request_id").select2(); $(".name_select").select2(); /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); </script> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>customer/add_quickforspares/'+id, type : 'iframe', padding : 5 }); } </script> <script> function setSelectedUser(customer_name,cust_idd,spare_rowid) { //alert("JII"); /* $('#custtest_'+spare_rowid).val(customer_name); $('#cust_id_'+spare_rowid).val(cust_idd); */ $('#cust_id_'+spare_rowid+ "> option").remove(); $('#cust_id_'+spare_rowid).append("<option value='"+cust_idd+"'>"+customer_name+"</option>"); } </script> <script> $('.plus1').keyup(function() { //alert($('#tax_type').val()); //alert("fdgvdfgfd"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('-'); var ctid = arr['1']; if(parseInt($(this).val())){ var cal_amt = parseInt($(this).val()) * parseInt($('#amt-'+ctid).val()); $('#amt1-'+ctid).val(cal_amt); } else{ $('#amt1-'+ctid).val(0); } //$('input[name="res"]').val(val); }); </script> </body> </html><file_sep>/application/views/add_prod_subcat.php <!--<script type='text/javascript'>//<![CDATA[ $(function(){ var tb2 = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ i++; $('<div class="col-md-12"><div class="col-md-3 col-sm-3 col-xs-12"><select id="pro_cat'+i+'" name="pro_cat[]"><option value="">---Select---</option><?php foreach($droplist as $dkey){ ?><option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option><?php } ?></select><div id="ghname'+i+'"></div></div><div class="col-md-3 col-sm-3 col-xs-12"><input type="text" name="sub_catname[]" class="model" id="sub_category-'+i+'" maxlength="50"><div id="kname'+i+'" style="color:red"></div></div><div class="col-md-1"><span><a class="delRowBtn btn btn-primary"><i class="fa fa-trash"></i></a></span></div></div>').appendTo(tb2); /*$('.subcat').change(function(){ var a=$(this).attr('id').split('-').pop(); alert(a); var category=$(this).val() var category=$('#pro_cat1'+a).val(); alert(category); var sub_category = $(this).val(); var datastring='category='+category+'&sub_category='+sub_category; //alert(datastring); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>subcategory/subcategory_validation', data: datastring, success: function(data) { // alert(data); if(data == 0){ $('#kname'+a).html(''); } else{ $('#kname'+a).text('Sub-Category Name Already Exist').show().delay(1000).fadeOut(); $('#sub_category-'+a).val(''); } } });*/ //}); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); $(".registersubmit").click(function(event){ if($('#pro_cat'+i).val()==""){ $('#ghname'+i).text("Select Category Name").css({'color':'#ff0000','font-size':'12px'}); } if($('#sub_category-'+i).val()==""){ $('#kname'+i).text("Enter Sub-Category Name").css({'color':'#ff0000','font-size':'12px'}); } }); $('#sub_category-'+i).bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $('#sub_category-'+i).keyup(function(){ if($('#sub_category-1').val()==""){ $('#kname'+i).show(); } else{ $('#kname'+i).fadeOut('slow'); } }); $('#pro_cat'+i).change(function(){ if($('#pro_cat'+i).val()==""){ $('#ghname'+i).show(); } else{ $('#ghname'+i).fadeOut('slow'); } }); }); }); </script>--> <script> $(document).ready(function(){ $('#addRowBtn1').click(function(){ //alert("ddaaassss"); var inc=1; var vl=$('#countid').val(); //var modelid =$('#modelid').val(); //alert(modelid); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Subcategory/add_subcatrow", data: datastring, cache: false, success: function(result) { //alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .tableadd input { width: 238px; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 3px; /* padding-left: 10px; */ margin-left: 13px; } .tableadd input { height: 21px !important; margin-top: 11px; margin-right: -242px; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width:103%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; margin: 0 0 15px 0; height: 30px; width:230px; } </style> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <style> .link{ border: 1px solid #dbd0e1 !important; background: #dbd0e1 none repeat scroll 0% 0% !important; padding: 8px 4px 4px 4px; border-radius: 5px; color: white; margin-left: 12px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .delRowBtn { padding:0px 4px 4px 4px; height: 30px; font-size: 19px !important; } body{background-color:#fff;} .star{ color:#ff0000; font-size:15px; } .btn{text-transform:none !important;} </style> <section id="content"> <div class="container"> <div class="section"> <h2>Add Sub-Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>subcategory/add_sub_category" method="post"> <table id="myTable" class="tableadd"> <!--<tr><td><label>Category Name</label></td><td><label>Sub-Category Name</label></td></tr> <tr> <td> <select id="pro_cat1" name="pro_cat[]" class="cname"> <option value="">---Select---</option> <?php foreach($droplist as $dkey){ ?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } ?> </select><div id="ghname1"></div> </td> <td><input type="text" name="sub_catname[]" class="model" id="sub_category-1" onChange="validateForm();"><div class="fname" id="kname1" style="color:red"></div></td> </tr>--> <div class="col-md-12"> <div class="col-md-4 col-sm-6 col-xs-12"> <label>Category Name <span class="star">*</span></label> <select id="pro_cat1" name="pro_cat[]" class="cname"> <option value="">---Select---</option> <?php foreach($droplist as $dkey){ ?> <option value="<?php echo $dkey->id; ?>"><?php echo $dkey->product_category; ?></option> <?php } ?> </select> <div id="ghname1"></div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <label>Sub-Category Name <span class="star">*</span></label> <input type="text" name="sub_catname[]" class="model" id="sub_category-1" onChange="validateForm();" maxlength="50"> <div id="kname1"></div> <input type="hidden" id="countid" value="1"> </div> <a class="link" id="addRowBtn1" href='#'><i class="fa fa-plus-square" aria-hidden="true" style="color:#5f3282;margin-top:30px;"></i></a> </div> </table> <button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action" id="product" style="margin-left:30px;">Submit</button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function() { //alert("validation jquery"); $(".registersubmit").click(function(event) { if($('#pro_cat1').val()==""){ $(this).parent().find('#ghname1').text("Select Category Name").css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); event.preventDefault(); } if($('#sub_category-1').val()==""){ $(this).parent().find('#kname1').text("Enter Sub-Category Name").css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $('#sub_category-1').bind("keyup blur", function(){ $(this).val($(this).val().replace(/[^a-zA-Z0-9 ]/g,"")); }); $('#sub_category-1').keyup(function(){ if($('#sub_category-1').val()==""){ $('#kname1').show(); } else{ $('#kname1').fadeOut('slow'); } }); $('#pro_cat1').change(function(){ if($('#pro_cat1').val()==""){ $('#ghname1').show(); } else{ $('#ghname1').fadeOut('slow'); } }); }); </script> <script> function validateForm() { //alert("dfg"); //alert($(this').val()); var category=document.getElementById( "pro_cat1" ).value; var sub_category=document.getElementById( "sub_category-1" ).value; var datastring='category='+category+'&sub_category='+sub_category; //alert(datastring); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>subcategory/subcategory_validation', data: datastring, success: function(data) { // alert(data); if(data == 0){ $('#kname1').html(''); } else{ $('#kname1').html('Sub-Category Name Already Exist').show().css({'color':'#ff0000','font-size':'10px','position':'relative','bottom':'10px'}); $('#sub_category-1').val(''); return false; } } }); }; </script> <!--<script> $(function(){ $(".registersubmit").click(function(event){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#pro_cat"+i).val()==""){ $("#ghname"+i).text("Select Category Name").show().css({'color':'#ff0000','position':'relative','bottom-top':'30px'}); event.preventDefault(); } //alert($("#ghname"+i).val()); if($("#sub_category-"+i).val()==""){ $("#kname"+i).text("Enter Sub-Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } }); $("#pro_cat"+i).change(function(){ if($(this).val()==""){ $("#ghname"+i).show(); } else{ $("#ghname"+i).fadeOut('slow'); } }) $("#sub_category-"+i).keyup(function(){ if($(this).val()==""){ $("#kname"+i).show(); } else{ $("#kname"+i).fadeOut('slow'); } }) //alert("xcfg"); if($(".model").val()==""){ $(".fname").text("Enter Sub-Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } //alert($(".model").val()); if($("#pro_cat1").val()==""){ $("#ghname1").text("Select Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } //alert($("#pro_cat1").val()); }); $(".model").keyup(function(){ if($(this).val()==""){ $(".fname").show(); } else{ $(".fname").fadeOut('slow'); } }); $("#pro_cat1").change(function(){ if($(this).val()==""){ $("#ghname1").show(); } else{ $("#ghname1").fadeOut('slow'); } }); }); </script>--> </body> </html><file_sep>/application/controllers/Brand.php <?php class Brand extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Brand_model'); } public function add_brand(){ //echo "<pre>";print_r($_POST);exit; $user=array('brand_name'=>$this->input->post('brand_name')); if($this->Brand_model->checkbrandname($user['brand_name'])) { echo "<script>window.location.href='".base_url()."pages/add_brand';alert(' Brand Name already exist');</script>"; }else{ $brand_name=$this->input->post('brand_name'); $c=$brand_name; $count=count($c); for($i=0; $i<$count; $i++) { if($brand_name[$i]!=""){ $data1 = array('brand_name' => $brand_name[$i]); $result=$this->Brand_model->add_brands($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_brand';alert('Please enter Brand');</script>"; } */ } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/brandList';alert('Brand Added Successfully!!!');</script>"; } } } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Brand_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_cat(){ $id=$this->input->post('catid');//echo $id; exit; $brid=$this->input->post('brid'); $data=array( 'cat_id'=>$this->input->post('catid') ); $res = $this->Brand_model->update_cat($data,$brid); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Brand_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function updatesub_category(){ $id=$this->input->post('brid'); //$this->input->post('procatid'); $data=array( 'subcat_id'=>$this->input->post('subcatid') ); $s = $this->Brand_model->update_subcat($data,$id); } public function update_brand_name(){ $id=$this->uri->segment(3); $data['list']=$this->Brand_model->getbrandbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_brand',$data); } public function edit_brand(){ $new=$this->input->post('brand_name'); $old=$this->input->post('brand_name1'); if($new==$old) { $id=$this->input->post('brandid'); $data=array( 'brand_name'=>$this->input->post('brand_name') ); $s = $this->Brand_model->update_brandname($data,$id); echo "<script>alert('Brand Updated Successfully!!!');window.location.href='".base_url()."pages/brandList';</script>"; }else{ $user=array('brand_name'=>$this->input->post('brand_name')); if($this->Brand_model->checkbrandname($user['brand_name'])) { $brandid=$this->input->post('brandid'); //print_r ($brandid);exit; echo "<script>window.location.href='".base_url()."Brand/update_brand_name/'+$brandid;alert(' Brand Name already exist');</script>"; } else{ $id=$this->input->post('brandid'); $data=array( 'brand_name'=>$this->input->post('brand_name') ); $s = $this->Brand_model->update_brandname($data,$id); echo "<script>alert('Brand Updated Successfully!!!');window.location.href='".base_url()."pages/brandList';</script>"; } } } public function update_product(){ $id=$this->uri->segment(3); $data['list']=$this->Product_model->getproductbyid($id); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $data['prodcatlist']=$this->Product_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Product_model->prod_sub_cat_dropdownlist(); $this->load->view('edit_prod_list',$data); } public function edit_product(){ $data = $this->input->post('addlinfo'); $addlnfo= implode(",",$data); // echo $addlnfo;exit; $data=array( 'serial_no'=>$this->input->post('serial_no'), 'product_name'=>$this->input->post('product_name'), 'category'=>$this->input->post('category'), 'subcategory'=>$this->input->post('subcategory'), 'model'=>$this->input->post('model'), 'description'=>$this->input->post('description'), 'addlinfo'=>$addlnfo ); $id=$this->input->post('product_id'); $this->Product_model->edit_products($data,$id); echo "<script>alert('Product Updated Successfully!!!');window.location.href='".base_url()."pages/prod_list';</script>"; } public function addrow(){ $data['count']=$this->input->post('countid'); //echo "Count: ".$data['count']; $data['prodcatlist']=$this->Brand_model->prod_cat_dropdownlist(); $data['subcatlist']=$this->Brand_model->prod_sub_cat_dropdownlist(); $this->load->view('addrow',$data); } public function update_status_brand_name(){ $id=$this->input->post('id'); $data=array( 'status'=>'1' ); $s = $this->Brand_model->update_status_brand($data,$id); echo "<script>alert('Brand made Inactive');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function update_status_brand_name1(){ $id=$this->input->post('id'); $data=array( 'status'=>'0' ); $s = $this->Brand_model->update_status_brand1($data,$id); echo "<script>alert('Brand made Active');window.location.href='".base_url()."pages/prod_cat_list';</script>"; } public function brand_validation() { //print_r($_POST); exit; $brand = $this->input->post('brand'); $this->output->set_content_type("application/json")->set_output(json_encode($this->Brand_model->brand_validation($brand))); } }<file_sep>/application/views/monthreport_data.php <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <style> table.display {border:1px solid #ccc; margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } #data-table-simple_paginate { display:none; } <!--.dataTables_info { visibility:hidden; } .dataTables_paginate paging_simple_numbers { visibility:hidden; }--> table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.no_border tr td { border:1px solid white !important; } table.dataTable.hover tbody tr:hover,table.dataTable.hover tbody tr.odd:hover,table.dataTable.hover tbody tr.even:hover,table.dataTable.display tbody tr:hover,table.dataTable.display tbody tr.odd:hover,table.dataTable.display tbody tr.even:hover{background-color:#fff} </style> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url() ?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('export', 'W3C Example Table')"> <img src="<?php echo base_url() ?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <?php $i=1; $f=0; $c=0; $s=0; $t=0; $pending=0; $salary=0; $subtotal=0; $profit=0; $profit_subtot=0; $count=0; if(!empty($month)) { $count = count($month); $salary = $count * 60; foreach($month as $report) { $f+=$report->agn_charge; $c+=$report->conveyance; $s+=$report->stamping_charge; $t+=$report->penalty; $pending+=$report->pending_amt; $subtotal=$s+$t; $bustotal = 1000; $profit_subtot = $subtotal - $i - $c - $salary - 1000; $profit = $profit_subtot - $pending; } } ?> <section id="content"> <div class="container"> <div class="section"> <h4 class="header">Stamping Monthly Report List</h4> <div class="divider"></div> <div id="table-datatables" > <div class="row"> <div class="col-md-12"> <?php echo "<table id='export' class='responsive-table display' cellspacing='0' >"; echo "<thead>"; echo "<th>S.No</th>"; echo "<th>RequestID</th>"; echo "<th>CustomerName</th>"; echo "<th>Model</th>"; echo "<th>CmrPaid</th>"; echo "<th>stampingCharge</th>"; echo "<th>PenaltyCharge</th>"; echo "<th>AgentCharge</th>"; echo "<th>ConveyanceCharge</th>"; echo "<th>PendingAmount</th>"; echo "<th>Status</th>"; echo "</thead>"; // $body .= $display; if($i!=1){ $i=1; } //if(!empty($month)) //{ if ($month) { foreach($month as $row) { echo "<tr>"; echo "<td>".$i."</td>"; echo "<td>".stripslashes($row->request_id)."</td>"; echo "<td>".stripslashes($row->customer_name)."</td>"; echo "<td>".stripslashes($row->model)."</td>"; echo "<td>".stripslashes($row->cmr_paid)."</td>"; echo "<td>".stripslashes($row->stamping_charge)."</td>"; echo "<td>".stripslashes($row->penalty)."</td>"; echo "<td>".stripslashes($row->agn_charge)."</td>"; echo "<td>".stripslashes($row->conveyance)."</td>"; echo "<td>".stripslashes($row->pending_amt)."</td>"; echo "<td>".stripslashes($row->status)."</td>"; echo "</tr>"; $i++; } } else { echo "<h4 align='center'>No Data Available</h4>"; } echo "<tr>"; echo "</tr>"; echo "<tr style='visibility: collapse;'>"; echo "<td colspan='10' style='border:1px solid #ccc !important; '></td>"; echo "</tr>"; echo "<tr>"; echo "<td class='no_border' style='border:1px solid white !important;background-color:#fff; '></td>"; echo "<td colspan='8' class='no_border' style='border:1px solid white !important;'>"; echo "<table class='table table-responsive no_border' id='export' style='border:1px solid white !important; '>"; echo "</tr>"; echo "<td style='border:1px solid white !important; '>Total stamping & penalty charge<span class='pull-right'>:</span></td>"; echo "<td style='border:1px solid white !important; '>". $subtotal."</td>"; echo "<td class='border' style='border:1px solid white !important; '></td><td style='border:1px solid white !important; '>Total Stamping recevied<span class='pull-right'>:</span></td>"; echo "<td style='border:1px solid white !important; '>".$count."</td>"; echo "</tr>"; echo "<tr>"; echo "<td style='border:1px solid white !important; '>Total Agent_Charge<span class='pull-right'>:</span></td>"; echo "<td style='border:1px solid white !important; '>".$f."</td> <td style='border:1px solid white !important; ' class='border'></td>"; echo "</tr>"; echo "<tr>"; echo "<td style='border:1px solid white !important; '>Total Conveyance_Charge<span class='pull-right'>:</span></td>"; echo " <td style='border:1px solid white !important; '>".$c."</td> <td style='border:1px solid white !important; ' class='border'></td>"; echo "</tr>"; echo "<tr>"; echo "<td style='border:1px solid white !important; '>Salary<span class='pull-right'>:</span></td>"; echo "<td style='border:1px solid white !important; '>".$salary."</td> <td class='border' style='border:1px solid white !important; '></td><td style='border:1px solid white !important; '>Profit<span class='pull-right'>:</span></td>"; echo " <td style='border:1px solid white !important; '>".$profit_subtot."</td>"; echo "</tr>"; echo " <tr>"; echo " <td style='border:1px solid white !important; '>Bus Pass<span class='pull-right'>:</span></td>"; echo " <td style='border:1px solid white !important; '>1000</td> <td class='border' style='border:1px solid white !important; '></td> <td style='border:1px solid white !important; '>Outstanding Amount<span class='pull-right'>:</span></td>"; echo " <td style='border:1px solid white !important; '>".$pending."</td>"; echo " </tr> "; echo " <tr >"; echo " <td style='border:1px solid white !important; '><b>Profit<span class='pull-right'>:</span></b></td>"; echo " <td style='border:1px solid white !important; '><b>".$profit_subtot."</b></td> <td class='border' style='border:1px solid white !important; ' ></td> <td style='border:1px solid white !important; '><b>Net Profit<span class='pull-right'>:</span></b></td>"; echo " <td style='border:1px solid white !important; '><b>".$profit."</b></td>"; echo " </tr>"; echo " <tr>"; echo " <td style='border:1px solid white !important; '></td>"; echo " <td style='border:1px solid white !important; '></td>"; echo " <td style='border:1px solid white !important; '></td>"; echo " </tr>"; echo "</table>"; //calculation echo "</table>"; ?> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/amc_update.php <style> .link{ padding: 9px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-right:20px; } .link:hover { color:black; text-decoration:none; } .link:focus{ color: white; text-decoration:none; } .tableadd tr td input { width: 210px !important; } .tableadd tr td select { border: 1px solid #093F88; width: 210px; } .chosen-container .chosen-drop .chosen-search input { width:200px !important; } #myTable tr td label{ width:150px !important; } #myTable1 tr td label{ width:150px !important; } .chosen-container { width: 210px !important; } #errorBox{ color:#F00; } h5 { font-size: 22px; border-bottom: 1px solid #055E87 !important; text-align: center; width: 170px; margin: auto auto 35px; } h6 { font-weight: bold; font-size: 16px; margin: 0px; border-bottom: 1px solid gray; width: 145px; margin-top:2%; } .dropdown-content { display: none; } #rowadd { border: 1px solid #055E87 !important; background: #093F88 none repeat scroll 0% 0% !important; padding: 6px; border-radius: 5px; color: #FFF; font-weight: bold; font-family: calibri; font-size: 17px; margin-left: 47%; } .tableadd tr td{ height:40px; } .right p { line-height:5px; font-size: 12px; } .right h1 { line-height:5px; } .toaddress h4 { line-height:5px; } .toaddress p { line-height: 5px; margin-left: 2%; } .toaddress { margin-bottom: 25px; margin-top: 20px; } .subject { /*margin-left:30px;*/ } .box{ display: none; box-shadow:none !important; } .comprehensive { display:block; } .message p { /*text-indent: 30px;*/ text-align:justify; } .message p.dear { text-indent: 0px; } input { border: 1px solid #093F88; border-radius: 3px; } table tr td { width:150px; height:30px; } table tr td.dot { width:50px; } table tr td.bank { width:350px; } table tr td.bank .address { margin-right:20px; } table { margin-left: 10%; } b { text-decoration:underline; } .service { width:400px; } .service b { font-weight:normal; text-decoration:none; } .nos { width:100px !important; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="comprehensive"){ $(".box").not(".comprehensive").hide(); $(".comprehensive").show(); } if($(this).attr("value")=="service_only"){ $(".box").not(".service_only").hide(); $(".service_only").show(); } }); }); </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("#fromdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#todate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#startdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); $("#enddate").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', yearRange: "1950:2055" }); }//]]> </script> <section id="content"> <div class="container"> <div class="section"> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>order/edit_amc_update" method="post" name="frmServiceStatus"> <div class="message"> <table class="tableadd" id="myTable"> <tr> <td><label>AMC Start Date</label></td><td class="dot">:</td><td><input type="text" name="amc_start_date" class="" value="<?php echo $todaydate; ?>" id="amc_start_date"><input type="hidden" name="orderid" value="<?php echo $orderid; ?>" id="orderid"><input type="hidden" name="amc_type" value="<?php echo $amc_type; ?>" id="amc_type"></td> </tr> <tr> <td><label>AMC End Date</label></td><td class="dot">:</td><td><input type="text" name="amc_end_date" class="" value="<?php echo $end_date; ?>" id="amc_end_date"></td> </tr> <tr> <td><label>No. of Preventive</label></td><td class="dot">:</td> <td><select id="amcprenos" name="amcprenos"> <option>---Select---</option> <option value="1">1</option> <option value="3">3</option> <option value="6">6</option> <option value="12">12</option> </select></td> </tr> </table> <table></table> </div> <button class="btn cyan waves-effect waves-light " type="submit" id="rowadd">Submit <i class="fa fa-arrow-right"></i> </button> <table class="tableadd"> <tr> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <!-- <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script>--> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> </body> </html><file_sep>/application/views_bkMarch_0817/add_spare.php <style> .btnstyle{ padding: 3px 8px; margin-left: 925px; margin-top: -37px; } table.dataTable thead th, table.dataTable thead td { padding:4px 18px; border-bottom: 1px solid #111; } table.dataTable tbody th, table.dataTable tbody td { padding: 0px 0px !important; } table.dataTable.no-footer tr td { border: 1px solid #eee !important; } td { text-align: left; font-size: 12px; padding: 0px; } th { padding: 0px; text-align: center; font-size: 12px; background-color: white; } thead { background-color: white; border-bottom: 1px solid #eeeeee; border: 1px solid #eeeeee; color: #303f9f; } .dataTables_wrapper .dataTables_filter { float: right; text-align: left; } input[type=search]{ background-color: transparent; border: 1px solid #eee; border-radius: 7; width: 55%; font-size: 1.5rem; margin: 0 0 15px 0; padding: 1px; box-shadow: #ccc; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } body{ background-color: #fff;} </style> <script> function Updatedefault(id) { if(document.getElementById('dashboard_show'+id).checked) { var dashboard_show = '1'; //alert(tax_default); } else { var dashboard_show = '0'; //alert(tax_default); } $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>Spare/update_important', data: {'id' : id, 'dashboard_show' : dashboard_show}, dataType: "text", cache:false, success: function(data){ //alert(data); alert("Spare Selected"); } }); }); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Spare List</h2> <!--<button type="button" class="btn btn-primary btnstyle"><img src="<?php echo base_url(); ?>assets/images/addspare.png" title="Add Spare" style="width:24px;height:24px;">Add Spare</button>--> <i class="fa fa-plus-square" aria-hidden="true" title="Add New Spare" style="position: relative; float: right;bottom: 27px;right: 22px;"></i> <hr> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" class="responsive-table display" cellspacing="0" style="margin-top:2%;"> <thead> <tr> <td>Spare Name</td> <td>Part No.</td> <td>Sales Price</td> <td>Purchase Price</td> <td>Category-SubCategory-Brand-Model</td> <td>Effective Date</td> <td>Action</td> </tr> </thead> <tbody><?php foreach($sparelist1 as $key1){?> <tr> <td><input type="checkbox" name="dashboard_show" id="dashboard_show<?php echo $key1->id; ?>" onclick="Updatedefault('<?php echo $key1->id; ?>')" <?php if($key1->dashboard_show){?> checked="checked" <?php }?>> <?php echo $key1->spare_name; ?></td> <td style="text-align:right;"><?php echo $key1->sales_price; ?></td> <td style="text-align:right;"><?php echo $key1->sales_price; ?></td> <td style="text-align:right;"><?php echo $key1->purchase_price; ?></td> <td> <ul class="quantity"> <?php foreach($sparelist as $key){ if($key->spare_id==$key1->id){ ?> <li><?php echo $key->product_category.'-'.$key->subcat_name.'-'.$key->brand_name.'-'.$key->model; ?></li> <?php } } ?> </ul> </td> <td style="text-align:right;"><?php echo $key1->effective_date; ?></td> <td style="text-align:center;"><a href="<?php echo base_url(); ?>Spare/update_spare/<?php echo $key1->id; ?>" style="padding-right:10px;" ><i class="fa fa-pencil-square-o fa-2x"></i></a></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> </body> </html><file_sep>/application/views_bkMarch_0817/serailreport_data.php <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script type="text/javascript"> var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() </script> <script> function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <div class="pull-right" style="margin-right:145px;margin-top:9px;"> <img src="<?php echo base_url() ?>assets/images/x1.png" style="height:35px;float:left;" onclick="tableToExcel('export', 'W3C Example Table')"> <img src="<?php echo base_url() ?>assets/images/p1.png" style="margin-left:8px;height:35px;" onClick="printDiv('table-datatables')"> </div> <?php $h=0; $count=0; ?> <style> table.display { margin-top:15px; } table.display th,td { padding:10px; border:1px solid #ccc; } table.dataTable tbody td{ padding: 8px 10px !important; } input { border-style: none !important; height: 2rem !important; } #data-table-simple_filter { display:none; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } </style> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="export" class="responsive-table display" cellspacing="0" > <thead> <tr> <th>S.NO</th> <th>Serial No</th> <th>Request Id</th> <th>Request Date</th> <th>Model</th> <th>Brand</th> <th>Customer Name</th> <th>Zone</th> <th>Machine Status</th> <th>Problem</th> <th>Service Type</th> <th>Service Category</th> </tr> </thead> <tbody> <?php $j=1;if(!empty($list)) { foreach($list as $row) { $requ = $row->ser; $ser_req = explode(',',$requ); $r = count($ser_req); //echo $r; $sd = $row->problem; $m1 = $row->model; $b = $row->brand_name; $c = $row->customer_name; if($m1 && $b && $c!='') { //echo "<pre>"; //print_r($r1); for($i=0;$i<count($ser_req);$i++) { $r1 = explode('//',$ser_req[$i]);?> <tr> <td><?php echo $j;?></td> <!--<td rowspan="<?php //echo ($i == 0) ? count($ser_req) : '';?>"><?php //echo ($i == 0) ? $row->serial_no : '';?></td>--> <td><?php echo ($i == 0) ? $row->serial_no : '';?></td> <td><?php echo $r1[0];?></td> <td><?php if($r1[1]!=""){echo $r1[1];}?></td> <td><?php echo $row->model;?></td> <td><?php echo $row->brand_name;?></td> <td><?php echo $row->customer_name;?></td> <td><?php echo $row->service_loc;?></td> <td><?php echo $row->machine_status;?></td> <td><?php if($sd) { $query=$this->db->query("SELECT group_concat(prob_category) as pc FROM problem_category WHERE id in ($sd)"); extract($query->row_array()); echo $pc;}?></td> <td><?php echo $row->service_type;?></td> <td><?php echo $row->categoryname;?></td> </tr> <?php $j++;} } } }else { echo "<h4 align='center'>No Data Available</h4>"; } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script> var $= jQuery.noConflict(); </script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script><file_sep>/application/views_bkMarch_0817/add_tax.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); $("#addRowBtn").click(function(){ $('<tr><td><input type="text" value="" name="" class="" id=""></td><td><input type="text" value="" name="" class="" id=""></td></tr>').appendTo(tbl); }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.css"> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <style> body{background-color:#fff;} .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; margin-top:10px; } .link:focus{ color: white; text-decoration:none; } .chosen-container-single .chosen-single { height: 34px !important; } .chosen-container { margin-top: -16px !important; } .tableadd tr td select { margin-bottom: 25px !important; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Tax</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>tax/add_tax" method="post"> <div id="myTable" class="tableadd"> <div class="col-md-12" style="padding: 0px;"> <div class="col-md-3"> <label><b>Tax Name</b></label> <input type="text" name="tax_name[]" class="model"> </div> <div class="col-md-3"> <label><b>Percentage</b></label> <input type="text" name="percentage[]" class="model"> </div> </div> </div> <a class="link" href='' onclick='$("<div class=\"col-md-12\" style=\"padding: 0px;\"><div class=\"col-md-3\"><input type=\"text\" name=\"tax_name[]\" class=\"model\"></div><div class=\"col-md-3\"><input type=\"text\" name=\"percentage[]\" class=\"model\"></div></div>").appendTo($("#myTable")); return false;'>Add Tax</a> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit<i class="fa fa-arrow-right"></i></button> <table class="tableadd"> <tr> <td ></td> <td style="padding-top: 25px;"> </td> </tr> </table> </div> </form> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> </body> </html><file_sep>/application/views_bkMarch_0817/add_prob_cat.php <?php //print_r($modellist); ?> <script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type='text/javascript'>//<![CDATA[ /* $(function(){ //alert("sda"); var tb2 = $("#myTable"); var i=1; $("#addRowBtn1").click(function(){ //alert("asdj"); i++; $('<div class="col-md-12" style="padding:0px"><div class="col-md-3"><label style="width:180px;font-weight:bold;">Problem Category Name</label><input type="text" name="prob_cat_name[]" class="corporate"></div><div class="col-md-3"><label style="width:180px;font-weight:bold;">Model</label><select name="model1[]"><option value="">--Select--</option><?php foreach($modellist as $ml){ ?><option value="<?php echo $m1->id;?>"><?php echo "EK * 6100V + EK 03 (33)"; ?></option><?php } ?></select></div></div>').appendTo(tb2); */ /*$('<div class="col-md-12" style="padding:0px"><div class="col-md-3"><label style="width:180px;font-weight:bold;">Model</label><select name="model[]" id="model"><option value="">---Select---</option><?php foreach($modellist as $modelkey){ ?><option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option><?php } ?></select></div><div class="col-md-3"><label style="width:180px;font-weight:bold;">Problem Category Name</label><input type="text" name="prob_cat_name[]" class="corporate"></div></div>').appendTo(tb2);*/ //}); //}); </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ //alert("ddssss"); var inc=1; var vl=$('#countid').val(); var vl1 = (parseFloat(vl)+parseFloat(inc)); //alert(vl1); //alert(vl); $('#countid').val(vl1); var datastring='countid='+vl1; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>problemcategory/addrow", data: datastring, cache: false, success: function(result) { // alert(result); $('#myTable').append(result); } }); }); }); </script> <style> .link{ padding: 10px; margin-right:10px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } body{background-color:#fff;} input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } </style> <section id="content"> <div class="container-fluid"> <div class="section"> <h2>Add Problem Category</h2> <hr> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>problemcategory/add_prob_category" method="post"> <table id="myTable"> <div class="col-md-12" style="padding:0px"> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Problem Category Name</label> <input type="text" name="prob_cat_name[]" id="cate" class="prob_cate"><div id="hname" style="color:red;"></div> </div> <div class="col-md-3"> <label style="width:180px;font-weight:bold;">Model</label> <select name="model[]" id="model"> <option value="">---Select---</option> <?php foreach($modellist as $modelkey){ ?> <option value="<?php echo $modelkey->id; ?>"><?php echo $modelkey->model; ?></option> <?php } ?> </select><div id="dpt_error1" style="color:red;"></div> <input type="hidden" id="countid" value="1"> </div> </div> </table> <!--<a class="link" href='' onclick='$("<tr><td><input type=\"text\" name=\"prob_cat_name[]\" /></td><td><select name=\"model[]\" data-placeholder=\"Select Model...\" class=\"chosen-select\" tabindex=\"2\"><option value=\"\">---Select---</option><?php foreach($modellist as $modelkey){ ?><option value=\"<?php echo $modelkey->id; ?>\"><?php echo $modelkey->model; ?></option><?php } ?></select></td></tr>").appendTo($("#myTable")); return false;'>Add Category</a> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit<i class="fa fa-arrow-right"></i></button>--> <a class="link" id="addMoreRows">Add Category</a><button class="btn cyan waves-effect waves-light registersubmit" type="submit" name="action" id="product">Submit <i class="fa fa-arrow-right"></i> </button> </form> </div> </div> </div> <div class="col-md-1"> </div> </div> </div> </div> </section> </div> </div> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script> $(document).on("change","#model", function(){ var category=$("#cate").val(); var model = $(this).find("option:selected").attr("value"); $.ajax({ type: 'post', url: '<?php echo base_url(); ?>problemcategory/add_prob_category', data: { category:category, model:model, }, success: function (data) { if(data == 0){ $('#dpt_error1').fadeOut('slow'); } else{ $('#dpt_error1').text('Brand Name Already Exist').show().delay(1000).fadeOut(); $('#model').val(''); return false; } } }); }); </script> <script> $(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#cate").val()==""){ $("#hname").text("Enter Problem Category Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px'}); event.preventDefault(); } if($('#model').val()==""){ $(this).parent().find('#dpt_error1').text("Select Model Name").css({'color':'#ff0000','position':'relative','bottom':'-5px'}); event.preventDefault(); } }); $("#cate").keyup(function(){ if($(this).val()==""){ $("#hname").show(); } else{ $("#hname").fadeOut('slow'); } }); $("#model").click(function(){ if($(this).val()==""){ $("#dpt_error1").show(); } else{ $("#dpt_error1").fadeOut('slow'); } }); }); </script> </body> </html><file_sep>/application/controllers/Servicecategory.php <?php class Servicecategory extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('Servicecategory_model'); } public function add_service_category(){ $service_catname=$this->input->post('service_catname'); //$service_charge=$this->input->post('service_charge'); //$model=$this->input->post('model'); date_default_timezone_set('Asia/Calcutta'); $created_on = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $c=$service_catname; $count=count($c); for($i=0; $i<$count; $i++) { if($service_catname[$i]!=""){ $data1 = array('service_category' => $service_catname[$i], 'created_on' => $created_on, 'updated_on' => $updated_on, 'user_id' => $user_id); $result=$this->Servicecategory_model->add_service_category($data1); } /* else{ echo "<script>window.location.href='".base_url()."pages/add_service_cat';alert('Please enter Service Category');</script>"; } */ } if(isset($result)){ echo "<script>window.location.href='".base_url()."pages/service_cat_list';alert('Service Category Added Successfully!!!');</script>"; } } public function update_service_cat(){ $id=$this->uri->segment(3); $data['list']=$this->Servicecategory_model->getservicecatbyid($id); $data['modellist']=$this->Servicecategory_model->modellist(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_sercat_list',$data); } public function view_models(){ $id = $this->uri->segment(3); $data1['service_charge']=$this->Servicecategory_model->service_charg($id); $data1['service_list']=$this->Servicecategory_model->service_list($id); $this->load->view('view_servicecat_models',$data1); } public function edit_service_category(){ $id=$this->input->post('service_catid'); date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $data=array( 'service_category'=>$this->input->post('service_catname'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $s = $this->Servicecategory_model->update_serv_cat($data,$id); echo "<script>window.location.href='".base_url()."pages/service_cat_list';alert('Service Category Updated Successfully!!!');</script>"; } public function check(){ echo ("php"); $data1=$this->input->post('category1'); $data12=$this->input->post('model1'); print_r($data12); //$this->output->set_content_type("application/json")->set_output(json_encode($this->Servicecategory_model->check_service_charge($data1,$data12))); } public function check_charge(){ $data1=$this->input->post('category1'); $data12=$this->input->post('model1'); //print_r($data12);exit; $check=$this->Servicecategory_model->check_service_charge($data1,$data12); if($check ==0){ $this->output->set_content_type("application/json")->set_output(json_encode($check)); } else{ //$data['modellist']=$this->Servicecategory_model->modellist(); //print_r($data['modellist']);exit; $this->output->set_content_type("application/json")->set_output(json_encode($this->Servicecategory_model->modellist())); } } public function add_service_charge(){ $service_cat=$this->input->post('service_cat'); date_default_timezone_set('Asia/Calcutta'); $created_on = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $model=$data1['model']=$this->input->post('model'); $service_charge=$data1['service_charge']=$this->input->post('service_charge'); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $c=$model; $count=count($c); $data2 =array(); for($i=0; $i<$count; $i++) { if($model[$i]!=""){ $data2 = array( 'service_cat_id' => $service_cat, 'model' => $model[$i], 'service_charge' => $service_charge[$i], 'created_on' => $created_on, 'updated_on' => $updated_on, 'user_id' => $user_id ); $this->Servicecategory_model->add_service_charge($data2); echo "<script>alert('Service Charge Added Successfully!!!');window.location.href='".base_url()."pages/service_charge_list';</script>"; }else{ echo "<script>window.location.href='".base_url()."pages/add_service_charge';alert('Please select model');</script>"; } } } public function update_servicecharge(){ $id=$this->uri->segment(3); $data['list']=$this->Servicecategory_model->getservicecatbyid($id); $data['getservicechargeInfobyid']=$this->Servicecategory_model->getservicechargeInfobyid($id); $data['service_cat_list']=$this->Servicecategory_model->service_cat_list(); $data['modellist']=$this->Servicecategory_model->modellist(); $data['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data); $this->load->view('edit_service_charge',$data); } public function edit_service_charge(){ $service_cat_id=$this->input->post('service_cat'); $rowid=$data1['service_charge_id']=$this->input->post('service_charge_id'); $model=$data1['model']=$this->input->post('model'); $service_charge=$data1['service_charge']=$this->input->post('service_charge'); date_default_timezone_set('Asia/Calcutta'); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $user_id = $data111['user_dat'][0]->id; $c=$model; $count=count($c); //print_r ($count); //$data8 =array(); for($i=0; $i<$count; $i++) { $data8 = array( 'service_cat_id' => $service_cat_id, 'model' => $model[$i], 'service_charge' => $service_charge[$i], 'updated_on' => $updated_on, 'user_id' => $user_id ); if($rowid[$i]!="" && isset($rowid[$i])){ $where = "service_cat_id=".$service_cat_id." AND id=".$rowid[$i]; $result=$this->Servicecategory_model->update_service_charges($data8,$where); }else{ $this->Servicecategory_model->add_service_charge($data8); } } echo "<script>alert('Service Charge Updated Successfully!!!');window.location.href='".base_url()."pages/service_charge_list';</script>"; } public function del_serv_category(){ $id=$this->input->post('id'); $s = $this->Servicecategory_model->del_serv_cat($id); } public function addrow2(){ $data['count']=$this->input->post('countid'); $data['cat_id']=$this->input->post('category'); // $data1a=$this->input->post('countid'); // print($data1a);exit; //$data['getservicechargeInfobyid']=$this->Servicecategory_model->getservicechargeInfobyid($id); $data['modellist']=$this->Servicecategory_model->modellist(); $this->load->view('add_service_charge_row',$data); } public function service_validation() { $product_id = $this->input->post('p_id'); $this->output->set_content_type("application/json")->set_output(json_encode($this->Servicecategory_model->service_validation($product_id))); } public function add_scatrow(){ $data['count']=$this->input->post('countid'); //echo($this->input->post('countid')); echo"hiii";exit; $this->load->view('add_row_scat',$data); } }<file_sep>/application/views/add_row_accs.php <tr> <td width="25.35%"> <input type="text" name="acc_name[]" id="acc<?php echo $count; ?>"> <div id="dname<?php echo $count; ?>"></div> </td> <td> <a class="delRowBtn btn btn-primary fa fa-trash" style="height:36px; margin-left: 15px"></a> </td> </tr> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $(".registersubmit").click(function(event){ //alert("xcfg"); if($("#acc<?php echo $count; ?>" ).val()==""){ $("#dname<?php echo $count; ?>" ).text("Enter Accessories Name").show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); $("#acc<?php echo $count; ?>" ).keyup(function(){ if($(this).val()==""){ $("#dname<?php echo $count; ?>" ).show(); } else{ $("#dname<?php echo $count; ?>" ).fadeOut('slow'); } }); $(document.body).delegate(".delRowBtn", "click", function(){ $(this).closest("div").parent().remove(); }); }); </script> <script> $(document).ready(function(){ $('#acc<?php echo $count; ?>').change(function(){ var name=$(this).val(); //alert(name); $.ajax({ type:"POST", url:"<?php echo base_url(); ?>accessories/acc_validation", data:{ p_id:name, }, cache:false, success:function(data){ //alert(data); if(data == 0){ $('#dname<?php echo $count; ?>').html(''); } else{ $('#dname<?php echo $count; ?>').html('Accessories Name Already Exist').show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); $('#acc<?php echo $count; ?>').val(''); return false; //exit; } } }); }); }); </script> <file_sep>/application/views/add_spares_row.php <tr> <td><input type="hidden" id="eng_idd" value="<?php echo $engidd;?>"> <input type="hidden" name="used_spare[]" id="used_spare<?php echo $count; ?>" value="" class="spare_qty"> <select name="spare_name[]" id="sparename_<?php echo $count; ?>" class="spare_name"> <option value="">---Select---</option> <?php foreach($spareListByModelId as $sparekey){ ?> <option value="<?php echo $sparekey->id; ?>"><?php echo $sparekey->spare_name; echo " - "; ?><?php echo $sparekey->part_no; ?></option> <?php } ?> </select> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Description of Failure</label> <textarea name="desc_failure[]" id="desc_failure" value="" class="noresize"></textarea> </div> <div id="errorBox1<?php echo $count; ?>" style="color:red"></div> </td> <td> <input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""> <input type="hidden" value="0" name="qty_plus" id="qty_plus<?php echo $count; ?>"> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Why & When did it occur?</label> <textarea name="why_failure[]" id="why_failure" value="" class="noresize"></textarea> </div> <div id="errorbox2<?php echo $count; ?>" style="color:red"></div> </td> <td> <input type="text" value="" name="amt12" id="amt12<?php echo $count; ?>" class="" readonly></td> <td> <input type="text" value="" name="amt[]" id="amt<?php echo $count; ?>" class="" readonly><input type="hidden" value="" name="amt1" id="amt1<?php echo $count; ?>" class=""> <div class="appendtr<?php echo $count; ?>"> <label class="form-control">Corrective Action</label> <textarea name="correct_action[]" id="correct_action" value="" class="noresize"></textarea> </div> </td> <td></td> <td> <select name="warranty_claim_status[]" class="warranty" id="warranty<?php echo $count; ?>"> <option value="">---select---</option> <option value="to_claim">To claim</option> </select> </td> <td style="border:none;"><a class="delRowBtn1" style="font-size:20px;color: #000; cursor:pointer;" id="delRowBtn1_<?php echo $count; ?>"><span class="fa fa-trash-o" style="margin-right: 0px;"></span></a></td> </tr> <!--<tr class="appendtr"> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> <td style="border:none"><input type="text" name="spare_qty[]" id="spareqty_<?php echo $count; ?>" value="" class="spare_qty"><input type="hidden" value="" name="spare_qty1[]" id="spare_qty1<?php echo $count; ?>" class=""></td> </tr>--> <link href="<?php echo base_url(); ?>assets/css/chosen.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script> $(function(){ $(".spare_name").chosen(); }); </script> <script> $(function(){ $(".appendtr<?php echo $count; ?>").hide(); $(".spare_name").chosen(); $("#warranty<?php echo $count; ?>").change(function(){ if($(this).find("option:selected").attr("value")=="to_claim"){ $(".appendtr<?php echo $count; ?>").show(); } else{ $(".appendtr<?php echo $count; ?>").hide(); } }); }); </script> <script> $('.spare_qty').keyup(function() { //alert($(this).val()); var idd=$(this).closest(this).attr('id'); var arr = idd.split('_'); var ctid = arr['1']; var warran = $('#spare_tax1').val(); var amc_type = $('#amc_typ').val(); //alert($('#eengid').val()); var engid; if($('#eng_idd').val()!=0){ engid=$('#eng_idd').val(); }else{ engid=$('#eengid').val(); } var spareid=$('#sparename_'+ctid).val(); //alert(spareid); var datastring='spareid='+spareid+'&engid='+engid; var qty = $(this).val(); //alert(datastring); // var actual_qty = $('#spare_qty1'+ctid).val(); if(parseInt($(this).val()) && $(this).val()){ var qtyplus=$('#qty_plus'+ctid).val(); //alert(qty); if(parseInt(qty) > parseInt(qtyplus)){ //alert("hiii"); alert("Qty is only: "+ qtyplus + " nos. So please enter below that."); $('#spareqty_'+ctid).val(''); $('#amt'+ctid).val(''); }else{ //alert("true"); var cal_amt = parseInt(qty) * parseInt($('#amt12'+ctid).val()); if(parseInt(cal_amt)){ $('#amt'+ctid).val(cal_amt); } } /* } else{ alert("Qty is only: 0 nos. So please enter below that."); $('#spareqty_'+ctid).val(''); } */ }else{ //alert("else"); $('#amt'+ctid).val(''); } var vals = 0; var ii=0; $('input[name="amt[]"]').each(function() { //alert("dsd"); //alert($(this).val()); if($('#approval_statusid_'+ii).val()=='approved'){ vals += Number($(this).val()); //alert(val); $('#spare_tot').val(vals); } ii++; }); var tax_amt = (vals * $('#tax_type').val()) / 100; //alert(tax_amt); if(warran=='Preventive' || warran=='Warranty' || warran=='Rental' || amc_type=='Comprehensive'){ $('#spare_tax').val(0); $('#spare_tot').val(0); $('#labourcharge').val(0); $('#concharge').val(0); $('#total_amt').val(0); $('#total_amt1').val(0); }else{ $('#spare_tax').val(tax_amt); var tax = $('#spare_tax').val(); var total_spare_charge = $('#spare_tot').val(); var labourcharge = $('#labourcharge').val(); var concharge = $('#concharge').val(); if(parseInt(labourcharge)){ var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(labourcharge) + parseInt(concharge); }else if(parseInt(concharge)){ var Total_amount = parseInt(tax) + parseInt(total_spare_charge) + parseInt(concharge); }else if(parseInt(tax)){ var Total_amount = parseInt(tax) + parseInt(total_spare_charge) ; }else{ var Total_amount = parseInt(total_spare_charge) ; } $('#total_amt').val(Total_amount); $('#total_amt1').val(Total_amount); $('#service_pending_amt').val(Total_amount); $('#service_pending_amt1').val(Total_amount); } //$('input[name="res"]').val(val); }); </script> <script> $(document).ready(function(){ $('.spare_name').change(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id = $(this).val(); //alert("spareid: "+id); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){//alert(data.sales_price); $('#spare_qty1'+ctid).val(data.spare_qty), $('#amt1'+ctid).val(data.sales_price), $('#amt12'+ctid).val(data.sales_price), $('#used_spare'+ctid).val(data.used_spare) }); } }); var engid; if($('#eng_idd').val()!=0){ engid=$('#eng_idd').val(); }else{ engid=$('#eengid').val(); } var datastrings='spareid='+id+'&engid='+engid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>work_inprogress/getpettyspare", data: datastrings, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ //alert(data.qty_plus); //var qtyplus=data.qty_plus; //alert(qty); $('#qty_plus'+ctid).val(data.qty_plus); }); } }); }); }); </script> <script> $(document).ready(function(){ //alert("hii"); $("#resgister").click(function(event){ //var count=<?php echo $count; ?>; //alert(count); if ( $( "#sparename_<?php echo $count; ?>" ).val() === "" ) { $( "#errorBox1<?php echo $count; ?>" ).text( " Select Spare Name" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } if ( $( "#spareqty_<?php echo $count; ?>" ).val() === "" ) { $( "#errorbox2<?php echo $count; ?>" ).text( " Enter the Spare Quantity" ).show().css({'color':'#ff0000','position':'relative','bottom':'10px','font-size':'10px'}); event.preventDefault(); } }); }); </script> <script> $(document).ready(function(){ $('#spareqty_<?php echo $count; ?>').bind('keyup blur', function(){ $(this).val( $(this).val().replace(/[^0-9]/g,'') ); }); }); </script> <script> $(document).ready(function(){ $("#sparename_<?php echo $count; ?>").change(function(){ if($(this).val()==""){ $("#errorBox1<?php echo $count; ?>").show(); } else{ $("#errorBox1<?php echo $count; ?>").hide(); } }); $("#spareqty_<?php echo $count; ?>").keyup(function(){ if($(this).val()==""){ $("#errorbox2<?php echo $count; ?>").show(); } else{ $("#errorbox2<?php echo $count; ?>").hide(); } }); }); </script> <style> label{ border:none !important; font-size: 0.85em !important; } textarea{ border:1px solid #ccc !important; width:95% !important; border-radius:5px !important; } .noresize{ resize:none; } a > span.fa { color: #fff !important; background: #6c477d; padding: 5px; } .chosen-container .chosen-drop { position: absolute; width: auto !important; } </style> <file_sep>/application/models/qc_master_model.php <?php class Qc_master_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->database(); } public function add_qc_master($data){ $this->db->insert('qc_masters',$data); return true; } public function add_qc_master1($data){ $this->db->insert('qc_masters',$data); return true; } public function checkqcmodel($model) { $this->db->select('model'); $this->db->from('qc_masters'); $this->db->where_in('model',$model); //$this->db->order_by('id','desc'); $query=$this->db->get(); //return $query->result(); if($query->num_rows()>0) { return $query->result(); } else{ return $query->result(); return false; } } public function update_service_charges($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('service_charge', $data1, $where); $this->db->query($qry); /* echo $this->db->last_query(); exit; */ //exit; } public function qc_masters_list(){ $this->db->select("qc_masters.id, qc_masters.model as qc_master_model_id, products.model",FALSE); $this->db->from('qc_masters'); $this->db->join('products', 'products.id = qc_masters.model'); $this->db->group_by('qc_masters.model'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function modellist(){ $this->db->select("id, model",FALSE); $this->db->from('products'); $this->db->order_by('model', 'asc'); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getqcparametersbyid($id){ $this->db->select("*",FALSE); $this->db->from('qc_masters'); $this->db->where('model',$id); $query = $this->db->get(); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function getservicechargeInfobyid($id){ $query = $this->db->get_where('service_charge', array('service_cat_id' => $id)); //echo "<pre>";print_r($query->result());exit; return $query->result(); } public function update_serv_cat($data,$id){ $this->db->where('id',$id); $this->db->update('service_category',$data); } public function update_qc_param($data1,$where){ /* echo "<pre>"; print_r($data1); echo "Where: ".$where; exit; */ $qry = $this->db->update_string('qc_masters', $data1, $where); $this->db->query($qry); /* echo $this->db->last_query(); exit; */ //exit; } public function delete_qc_master($id){ $this->db->where('id',$id); $this->db->delete('qc_masters'); } }<file_sep>/application/views/edit_bills.php <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ var tbl = $("#table1"); var i=1; $("#addRowBtn").click(function(){ $(' <tr><td> <select id="sparename_'+i+'"> <option value="">---Select---</option> <option>Spare 1</option> <option>Spare 2</option> <option>Spare 3</option> <option>Spare 4</option> </select> <div class="spare-error'+i+'"></div> </td> <td><input type="text" value="" name="" class="" id=""></td> <td><input type="text" value="" name="" class="" id=""></td> <td style="border:none;"><button class="delRowBtn" style="font-size:20px;"><i class="fa fa-trash-o"></i></button></td></tr>').appendTo(tbl); $("#resgister").click(function(event){ //alert("test"); if($("#sparename_"+i).find("option:selected").attr("value")==""){ alert("inside if"); $(".spare-error"+i).text("Please choose any one spare").show().css({ 'font-size':'12px', 'color':'#ff0000' }); event.preventDefault(); } }); i++; }); $(document.body).delegate("#delRowBtn1", "click", function(){ $(this).closest("tr").remove(); }); }); });//]]> </script> <script> $(document).ready(function(){ $('#addMoreRows').click(function(){ var count_id = $('#count_id').val(); var cnt = parseInt(count_id) + 1; var tbl = $("#table11 > tbody"); $('<tr><td><input type="hidden" name="ord_id[]" id="ord_id-'+cnt+'" value=""><select name="p_name[]" id="p_name-'+cnt+'" class="form-control" style="width: 80% !important;"><option value="">--Select--</option><?php foreach($prod_list as $prod_key){?><option value="<?php echo $prod_key->id; ?>"><?php echo $prod_key->model; ?></option><?php } ?></select></td><td><input type="text" name="price[]" id="price-'+cnt+'" maxlength="7" class="price"></td><td><input type="text" name="qty[]" id="qty-'+cnt+'" class="qty" maxlength="7"></td><td><input type="text" name="sub_total[]" id="sub_total-'+cnt+'" readonly></td><td style="width:50px;"><span id="delRowBtn1" class="fa fa-trash-o"></span></td></tr>').appendTo(tbl); $('#count_id').val(cnt); }); }); </script> <style> td, th { padding: 15px 5px; display: table-cell; text-align: left; vertical-align: top; border-radius: 2px; } label { display: inline-block; max-width: 100%; margin-bottom: 0px !important; font-weight: 700; } .tableadd tr td input { width: 210px !important; border:none; } .tableadd tr td select { width: 210px !important; } .tableadd2 tr td select { width: 165px; margin-bottom: 15px; } /*.tableadd2 tr.back td { background: #6c477d !important; border: 1px solid #6c477d !important; color: #fff; padding: 8px; } */ .tableadd2 tr.back td { background: black !important; border: 1px solid #ccc !important; color: #fed700; font-weight:bold; padding: 8px; } .tableadd tr td label{ width: 180px !important; font-weight: bold; font-size: 13px; } td a > span.fa { background:#6c477d; color: #fff !important; width: 32px; } .breadcrumbs-title { font-size: 1.8rem; line-height: 5.804rem; margin: 0 0 0; color:#6C217E; font-weight:bold; } .box{ padding: 20px; display: none; margin-top: 20px; box-shadow:none !important; } .box1{ display: none; } .rating label { font-weight: normal; padding-right: 5px; } .rating li { display: inline; } input[type=text], input[type=textarea], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: auto; border:1px solid #ccc !important; } [type="radio"]:not(:checked), [type="radio"]:checked { position:relative; } [type="radio"] + label:before, [type="radio"] + label:after { } [type="radio"] + label:before, [type="radio"] + label:after { content: ''; position: absolute; left: 0; top: 0; margin: 4px; width: 16px; height: 16px; display:none; z-index: 0; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; } [type="radio"]:not(:checked) + label, [type="radio"]:checked + label { position: relative; padding-left: 5px; cursor: pointer; display: inline-block; height: 25px; line-height: 25px; font-size: 14px; -webkit-transition: 0.28s ease; -moz-transition: 0.28s ease; -o-transition: 0.28s ease; -ms-transition: 0.28s ease; transition: 0.28s ease; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; } .tableadd { padding: 0px; } .chosen-container { position:relative; right:20px; } /*.addressdiv, .toggleaddress { display: none; }*/ @media only screen and (min-width: 301px){ .xdsoft_datetimepicker .xdsoft_datepicker.active+.xdsoft_timepicker { margin-top: 41px !important; margin-bottom: 3px; } .xdsoft_datetimepicker .xdsoft_datepicker { width: 154px !important; float: left; margin-left: 8px; } } @media only screen and (max-width: 350px) { .headerDivider { border-left:1px solid #c5c5c5 !important; border-right:1px solid #c5c5c5 !important; height:25px !important; position: absolute !important; top:102px !important; left: 40px !important; } .toggleaddress { display: none; } } .fa { margin-right: 15px; } input[type=radio] { margin-left: 10px; margin-right: 2px; } .col-md-2, .col-md-1 { padding:0px; } .headerDivider { border-left:1px solid #c5c5c5; border-right:1px solid #c5c5c5; height:25px; position: absolute; top:73px; left: 280px; } textarea { width: 100%; height: auto !important; background-color: transparent; } .noresize { resize: none; } .linkaddress { cursor: pointer; } #errorBox { color:#F00; } .tableadd2 tr td input { margin: 10px; height: 30px; } @media only screen and (max-width: 380px) { td { padding: 3px !important; } a { padding: 3px !important; } select { width: 100px !important; } .tableadd2 tr td input { border-radius: 5px; height: 33px; margin-top: 17px; width: 50px; margin-left: 3px; margin-right: 3px; } .tableadd2 tr td select { padding: 0 30px 0 0; } } @media only screen and (max-width: 768px) and (min-width: 240px) { ol, ul { margin-top: 0; margin-bottom: 0 !important; } } /*.cyan { background-color: #6c477d !important; width: 90px; }*/ .cyan { background-color: black !important; width: 90px; color:#fed700; } label.appendfont{ border:none !important; font-size: 0.85em !important; } span.pagerefresh{ color: #444 !important; } input:read-only{ background:#eee; border:1px solid #ccc; height:30px; } input[type=text]{ border:1px solid #ccc; height:30px; } input:-moz-read-only { background-color: #eee !important; } textarea:read-only{ border:1px solid #ccc; height:30px; background:#eee; } .header-buttons{ width: 190px; position: relative; left: 320px; } select{ width:84%; } input[type=text], input[type=textarea], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: 100%; } .btn{text-transform:none !important;} .chosen-container .chosen-drop { position: absolute; width: auto !important; } /* a > span.fa { color: #6c477d !important; } */ </style> <script> $(document).ready(function(){ $('.work_spare_name').change(function(){ //alert("hiiio"); var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('_'); var ctid = arr['1']; //alert(ctid); var id = $(this).val(); //alert("spareid: "+id); var dataString = 'id='+id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>quotereview/getsparedet", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#spare_qty1'+ctid).val(data.spare_qty), $('#amt1'+ctid).val(data.sales_price), $('#used_spare'+ctid).val(data.used_spare) }); } }); var engid; if($('#eng_idd').val()!=0){ engid=$('#eng_idd').val(); }else{ engid=$('#eengid').val(); } var datastrings='spareid='+id+'&engid='+engid; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>work_inprogress/getpettyspare", data: datastrings, cache: false, success: function(data) { //alert(data); $.each(data, function(index, data){ //alert(data.qty_plus); //var qtyplus=data.qty_plus; //alert(qty); $('#qty_plus'+ctid).val(data.qty_plus); }); } }); }); }); </script> <script> $(document).ready(function(){ $( ".pagerefresh" ).click(function() { location.reload(true); }); $('#cust_name').change(function() { var id=$(this).val(); //alert(id); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Order/get_customerById", data: dataString, cache: false, success: function(data) { $.each(data, function(index, data){ $('#mobile').val(data.mobile); $('#address').val(data.address); $('#city_name').val(data.city); $('#state_name').val(data.st_name); $('#pincode').val(data.pincode); }); } }); }); }); </script> <script> function frmValidate(){ var bill_no = document.add_bills.bill_no.value, cust_name = document.add_bills.cust_name.value, mobile = document.add_bills.mobile.value, address = document.add_bills.address.value, city_name = document.add_bills.city_name.value, state_name = document.add_bills.state_name.value, pincode = document.add_bills.pincode.value, puchase_date = document.add_bills.puchase_date.value; if( bill_no == "" ) { document.add_bills.bill_no.focus() ; document.getElementById("errorBox").innerHTML = "enter the bill #."; return false; } if( cust_name == "" ) { document.add_bills.cust_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the customer name."; return false; } if( mobile == "" ) { document.add_bills.mobile.focus() ; document.getElementById("errorBox").innerHTML = "enter the mobile."; return false; } if( address == "" ) { document.add_bills.address.focus() ; document.getElementById("errorBox").innerHTML = "enter the address."; return false; } if( city_name == "" ) { document.add_bills.city_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the city."; return false; } if( state_name == "" ) { document.add_bills.state_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the state."; return false; } if( pincode == "" ) { document.add_bills.pincode.focus() ; document.getElementById("errorBox").innerHTML = "enter the pincode."; return false; } if( puchase_date == "" ) { document.add_bills.puchase_date.focus() ; document.getElementById("errorBox").innerHTML = "enter the puchase date."; return false; } } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <div class="header-buttons pull-right"><a class="btn cyan waves-effect waves-light" onclick="history.go(-1);" style="width:19%;margin-right:10px;height:29px;padding:3px 7px;"><span class="fa fa-arrow-left" data-toggle="tooltip" title="Back"></span></a> <div class="headerDivider"></div><span class="fa fa-refresh pagerefresh" data-toggle="tooltip" title="Refresh"></span></div> <h2>Edit Bills</h2> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div> <form action="<?php echo base_url(); ?>order/edit_bills" method="post" name="add_bills" onsubmit="return frmValidate()"> <div id="errorBox"></div> <?php foreach($getorderbyid as $ord_key){?> <div class="tableadd col-md-12"> <div class="col-md-12" id="radio_errorbox" style="color:red;font-size:11px;margin-left:232px;"></div> <!--<div class="col-md-6">--> <div class="col-md-12"> <div class="col-md-3"> <label>Bill #:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="bill_no" class="" value="<?php echo $ord_key->order_id; ?>" readonly> <input type="hidden" name="bill_id" value="<?php echo $ord_key->id; ?>" > </div> <div class="col-md-3"> <label>Customer Name:&nbsp;<span style="color:red;">*</span></label> <select name="cust_name" id="cust_name" disabled> <option value="">--Select--</option> <?php foreach($customer_list as $cust_key){ if($cust_key->id==$ord_key->customer_id){ ?> <option selected='selected' value="<?php echo $cust_key->id; ?>"><?php echo $cust_key->customer_name; ?></option> <?php }else{?> <option value="<?php echo $cust_key->id; ?>"><?php echo $cust_key->customer_name; ?></option> <?php }}?> </select> </div> <div class="col-md-3"> <label>Mobile:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="mobile" id="mobile" readonly class="" value="<?php echo $ord_key->mobile; ?>" > </div> <div class="col-md-3"> <label>Address: &nbsp;<span style="color:red;">*</span></label> <textarea name="address" readonly id="address" maxlength="250"><?php echo $ord_key->address; ?></textarea> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>City&nbsp;<span style="color:red;">*</span></label> <input type="text" name="city_name" readonly id="city_name" class="" value="<?php echo $ord_key->city; ?>" maxlength="100"> </div> <div class="col-md-3"> <label>State:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="state_name" readonly id="state_name" class="" value="<?php echo $ord_key->state; ?>" > </div> <div class="col-md-3"> <label>Pincode:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="pincode" readonly id="pincode" class="" value="<?php echo $ord_key->pincode; ?>" > </div> <div class="col-md-3"> <label>Purchase Date:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="puchase_date" id="datetimepicker7" class="date" value="<?php echo $ord_key->purchase_date; ?>" > </div> </div> <div class="col-md-12"> <div class="col-md-3"> <div class="form-group"> <label>E-Mail:&nbsp;<span style="color:red;">*</span></label> <input type="text" name="email_id" id="email_id" value="<?php echo $ord_key->email_id; ?>" readonly> </div> </div> </div> </div> <?php } ?> <h5 class="breadcrumbs-title">Add Products</h5> <div class=""> <table id="table11" class="tableadd2" style="margin-bottom: 20px; width: 96% !important; margin-left: 28px;"> <tr class="back" > <td>Product Name</td> <td>Unit Price</td> <td>Qty</td> <td>Sub Total</td> <td>Action</td> </tr> <?php $i=0; foreach($getorderDetailsbyid as $keyy){?> <tr> <td><input type="hidden" name="ord_id[]" id="ord_id-<?php echo $i; ?>" value="<?php echo $keyy->id; ?>"> <select name="p_name[]" id="p_name-<?php echo $i; ?>" class="form-control" style="width: 80% !important;"> <option value="">--Select--</option> <?php foreach($prod_list as $prod_key){ if($prod_key->id==$keyy->p_name){ ?> <option selected="selected" value="<?php echo $prod_key->id; ?>"><?php echo $prod_key->model; ?></option> <?php }else{?> <option value="<?php echo $prod_key->id; ?>"><?php echo $prod_key->model; ?></option> <?php } }?> </select> </td> <td><input type="text" name="price[]" id="price-<?php echo $i; ?>" value="<?php echo $keyy->price; ?>" maxlength="7" class="price"></td> <td><input type="text" name="qty[]" id="qty-<?php echo $i; ?>" class="qty" value="<?php echo $keyy->qty; ?>" maxlength="7"></td> <td><input type="text" name="sub_total[]" id="sub_total-<?php echo $i; ?>" value="<?php echo $keyy->sub_total; ?>" readonly></td> <td style="width:50px;"> <?php if($i!=0){?> <span id="delRowBtn1" class="fa fa-trash-o"></span> <?php } ?> </td> </tr> <?php $i++;}?> </table> </div> <div align="right"><a id="addMoreRows"><span class="fa fa-plus"></span></a></div> <div> <input type="hidden" name="count_id" id="count_id" value="<?php echo $i-1; ?>"> <div class="col-md-12"> <div class="col-md-9"></div> <div class="col-md-1" style="margin-left: -5%;margin-top: 0.5%;"> <label>Sub Total: </label> </div> <div class="col-md-2"> <input type="text" name="sub_total1" id="sub_total1" readonly value="<?php echo $ord_key->sub_total; ?>"> </div> </div> </div> <br> <div class="col-md-12"> <div class="col-md-9"></div> <div class="col-md-1" style="margin-left: -5%;margin-top: 0.5%;"> <label>Discount(in % only): </label> </div> <div class="col-md-2"> <input type="text" name="disc_amt" id="disc_amt" maxlength = "7" value="<?php if($ord_key->disc=='0'){echo "";}else{echo $ord_key->disc;} ?>"> </div> </div> <div class="col-md-12"> <div class="col-md-9"></div> <div class="col-md-1" style="margin-left: -5%;margin-top: 0.5%;"> <label>Amount Paid: </label> </div> <div class="col-md-2"> <input type="text" name="amt_paid" id="amt_paid" value="" ><input type="hidden" name="amt_paid1" id="amt_paid1" value="<?php echo $ord_key->amt_paid; ?>"><input type="hidden" name="amt_pending1" id="amt_pending1" readonly value="<?php echo $ord_key->amt_pending; ?>"> </div> </div> <div class="col-md-12"> <div class="col-md-9"></div> <div class="col-md-1" style="margin-left: -5%;margin-top: 0.5%;"> <label>Amount Pending: </label> </div> <div class="col-md-2"> <input type="text" name="amt_pending" id="amt_pending" readonly value="<?php echo $ord_key->amt_pending; ?>"> </div> </div> </div> <br> <div class="col-md-12"> <div class="col-md-9"></div> <div class="col-md-1" style="margin-left: -5%;margin-top: 0.5%;"> <label>Grand Total: </label> </div> <div class="col-md-2"> <input type="text" name="grand_total" id="grand_total" readonly value="<?php echo $ord_key->grand_total; ?>"> </div> </div> <div class="tableadd col-md-12"> <table class="tableadd" style="margin-top: 25px;"> <tr> <td> <!--<button class="btn cyan waves-effect waves-light " type="submit" name="action" id="resgister">Submit </button>--> <a href="#" class="btn cyan waves-effect waves-light " type="submit" name="action" id="resgister">Submit </a> <a href='<?php echo base_url(); ?>pages/dash' class="btn cyan waves-effect waves-light ">Exit</a> </td> </tr> </table> </div> </form> </div> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="<?php echo base_url(); ?>assets/css/chosen.css" rel="stylesheet"> <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function(){ $(document.body).delegate(".qty", "keyup", function(evt){ var idd=$(this).closest(this).attr('id'); //alert(idd); var arr = idd.split('-'); var ctid = arr['1']; evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (isNaN($('#qty-'+ctid).val())) { alert("Please enter only Numbers."); $('#qty-'+ctid).val(''); }else{ if($('#price-'+ctid).val()==''){ alert("Please enter the price"); $('#qty-'+ctid).val(''); $('#sub_total-'+ctid).val(''); }else{ if(parseInt($(this).val()) && $(this).val()){ if(parseInt($('#price-'+ctid).val())){ var cal_amt = parseInt($(this).val()) * parseInt($('#price-'+ctid).val()); if(parseInt(cal_amt)){ $('#sub_total-'+ctid).val(cal_amt); } } if(parseFloat($('#price-'+ctid).val())){ var cal_amt = parseInt($(this).val()) * parseFloat($('#price-'+ctid).val()); if(parseFloat(cal_amt) || parseInt(cal_amt)){ $('#sub_total-'+ctid).val(cal_amt); } } }else{ $('#sub_total-'+ctid).val(''); } } var vals = 0; var ii=0; $('input[name="sub_total[]"]').each(function() { vals += Number($(this).val()); $('#sub_total1').val(vals); ii++; }); $('#grand_total').val(vals); } }); $(document.body).delegate(".price", "keyup", function(evt){ var idd=$(this).closest(this).attr('id'); var arr = idd.split('-'); var ctid = arr['1']; if (isNaN($('#price-'+ctid).val())) { alert("Please enter only Numbers."); $('#price-'+ctid).val(''); } }); }); </script> <script> $('#disc_amt').keyup(function(evt) { var disc_amt = $( this ).val(); var total_amt = $('#sub_total1').val(); evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (isNaN(disc_amt)) { alert("Please enter only Numbers."); $('#disc_amt').val(''); }else{ if(disc_amt && total_amt){ //alert(total_amt); var disc_amt = $( this ).val(); //alert(disc_amt); var discount_amt = (parseInt(total_amt) * parseInt(disc_amt)) / 100; var result = parseInt(total_amt) - parseInt(discount_amt); //alert(discount_amt); $('#grand_total').val(result); }else{ var total_amt = $('#sub_total1').val(); $('#grand_total').val(total_amt); } } }); $('#amt_paid').keyup(function() { var amt_paid = $( this ).val(); if (isNaN(amt_paid)) { alert("Please enter only Numbers."); $('#amt_paid').val(''); }else{ if(parseInt(amt_paid)){ var amt_pending1 = $('#amt_pending1').val(); //alert(total_amt); var amt_paid = $( this ).val(); //alert(disc_amt); var pending_amt = parseInt(amt_pending1) - parseInt(amt_paid); //alert(discount_amt); $('#amt_pending').val(pending_amt); }else{ var amt_pending1 = $('#amt_pending1').val(); $('#amt_pending').val(amt_pending1); } } }); </script> <script> $(document).ready(function(){ $.datetimepicker.setLocale('en'); $('#datetimepicker_mask').datetimepicker({ mask:'9999-19-39 29:59' }); var logic = function( currentDateTime ){ if (currentDateTime && currentDateTime.getDay() == 6){ this.setOptions({ minTime:'11:00' }); }else this.setOptions({ minTime:'8:00' }); }; $('#datetimepicker7').datetimepicker({ onChangeDateTime:logic, onShow:logic }); $('#datetimepicker71').datetimepicker({ onChangeDateTime:logic, onShow:logic }); }); </script> <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery.datetimepicker.full.js'></script> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/jquery.datetimepicker.css"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> </body> </html><file_sep>/application/views_bkMarch_0817/edit_emp_list.php <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript'>//<![CDATA[ $(function(){ $('[name="cand_no"]').on('change', function() { // Not checking for Invalid input if (this.value != '') { var val = parseInt(this.value, 10); var rows = $('#studentTable tr'), rowCnt = rows.length - 1; // Allow for header row if (rowCnt > val) { for (var i = rowCnt; i > val; i--) { rows[i].remove(); } } if (rowCnt < val) { for (var i = 0; i < val - rowCnt; i++) { // Clone the Template var $cloned = $('.template tbody').clone(); // For each Candidate append the template row $('#studentTable tbody').append($cloned.html()); } } } }); });//]]> </script> <script> function frmValidate(){ //var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/; var emp_id = document.frmEmp.emp_id.value, emp_name = document.frmEmp.emp_name.value, emp_mobile = document.frmEmp.emp_mobile.value, emp_email = document.frmEmp.emp_email.value, emp_edu = document.frmEmp.emp_edu.value; if( emp_id == "" ) { document.frmEmp.emp_id.focus() ; document.getElementById("errorBox").innerHTML = "enter the employee id"; return false; } if( emp_name == "" ) { document.frmEmp.emp_name.focus() ; document.getElementById("errorBox").innerHTML = "enter the employee name"; return false; } if( emp_mobile == "" ) { document.frmEmp.emp_mobile.focus() ; document.getElementById("errorBox").innerHTML = "enter the mobile"; return false; } if( emp_email == "" ) { document.frmEmp.emp_email.focus() ; document.getElementById("errorBox").innerHTML = "enter the email"; return false; } if( emp_edu == "" ) { document.frmEmp.emp_edu.focus() ; document.getElementById("errorBox").innerHTML = "enter the educational qualification"; return false; } } </script> <style> #studentTable .skill td { background: #055E87 none repeat scroll 0% 0%; border: 1px solid #B3B3B3; padding: 8px; color: #FFF; } #studentTable tr td { border: 1px solid #B3B3B3; text-align: center; padding: 10px; } #studentTable tr td select { width: 106px; height: 33px; border-width: medium medium 1px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color #055E87; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; background-color: transparent; background-image: linear-gradient(45deg, transparent 50%, #333 50%), linear-gradient(135deg, #070708 50%, transparent 50%), linear-gradient(to right, #F6F8F9, #FBFBFB); background-attachment: scroll, scroll, scroll; background-clip: border-box, border-box, border-box; background-origin: padding-box, padding-box, padding-box; background-position: calc(100% - 21px) calc(1em + 2px), calc(100% - 16px) calc(1em + 2px), 100% 0px; background-size: 5px 5px, 5px 5px, 2.5em 2.5em; background-repeat: no-repeat; font: 300 1em/1.5em "Helvetica Neue",Arial,sans-serif; padding: 0.5em 3.5em 0.5em 1em; margin: 0px 3px; box-sizing: border-box; -moz-appearance: none; border-radius: 5px; } #studentTable tr td select:focus { border:1px solid #055E87; } input.number { border-radius:5px; } #errorBox{ color:#F00; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: 1px solid #ccc; /* border-bottom: 1px solid #055E87; */ border-radius: 2px; outline: none; height: 2.0rem; width: 100%; font-size: 12px; margin: 0 0 15px 0; padding: 4px; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } select { border: 1px solid #ccc !important; } #studentTable input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { width: 106px; } </style> <style> .frmSearch {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;} #country-list{float:left;list-style:none;margin:0;padding:0;width:190px;} #country-list li{padding: 10px; background:#FAFAFA;border-bottom:#F0F0F0 1px solid;} #country-list li:hover{background:#F0F0F0;} </style> <section id="content"> <div class="container"> <div class="section"> <h5 class="breadcrumbs-title">Edit Employee</h5> <div class="divider"></div> <div id="basic-form" class="section"> <div class="card-panel"> <div class="row"> <div class="col-md-1"> </div> <div class="col-md-10"> <form action="<?php echo base_url(); ?>Employee/edit_employee" method="post" name="frmEmp" onsubmit="return frmValidate()" autocomplete="off"> <div id="errorBox"></div> <?php error_reporting(0); foreach($list as $key){?> <div class="tableadd"> <div class="col-md-12"> <div class="col-md-3"> <label>Employee ID&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_id" value="<?php echo $key->emp_id; ?>" class="" readonly><input name="empid" value="<?php echo $key->id; ?>" type="hidden"> </div> <div class="col-md-3"> <label>Employee Name&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_name" value="<?php echo $key->emp_name; ?>" class=""> </div> <div class="col-md-3"> <label>Designation</label> <input type="text" name="emp_designation" class="" value="<?php echo $key->emp_designation; ?>"> </div> <div class="col-md-3"> <label>Mobile&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_mobile" id="mobile" class="" value="<?php echo $key->emp_mobile; ?>"> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Email Id&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_email" class="" value="<?php echo $key->emp_email; ?>"> </div> <div class="col-md-3"> <label>Educational Qualification&nbsp;<span style="color:red;">*</span></label> <input type="text" name="emp_edu" class="" value="<?php echo $key->emp_edu; ?>"> </div> <div class="col-md-3"> <label>Experience</label> <input type="text" name="emp_exp" class="" value="<?php echo $key->emp_exp; ?>"> </div> <div class="col-md-3"> <label>Date of Joining</label> <input type="text" name="doj" class="date" value="<?php echo $key->doj; ?>"> </div> </div> <!--<div class="col-md-12"> <div class="col-md-3"><label>Stampings</label></div><div class="col-md-3"><input type="checkbox" name="emp_stamping" class="" value="1" <?php if($key->emp_stamping=='1'){?> checked="checked" <?php }?>></div> </div>--> <div class="col-md-12"> <div class="col-md-3"> <label>Address</label> <input type="text" name="emp_addr" class="" value="<?php echo $key->emp_addr; ?>"> </div> <div class="col-md-3"> <label>Address 1</label> <input type="text" name="emp_addr1" class="" value="<?php echo $key->emp_addr1; ?>"> </div> <div class="col-md-3"> <label>City</label> <input type="text" name="emp_city" class="" id="search-box" value="<?php echo $key->emp_city; ?>"><div id="suggesstion-box" ></div> </div> <div class="col-md-3"> <label>State</label> <select name="emp_state" id="emp_state"> <option value="">---Select---</option> <?php foreach($state_list as $statekey){ if($statekey->id==$key->emp_state){ ?> <option selected="selected" value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } else{ ?> <option value="<?php echo $statekey->id; ?>"><?php echo $statekey->state; ?></option> <?php } } ?> </select> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Pincode</label> <input type="text" name="emp_pincode" id="pincode" class="" value="<?php echo $key->emp_pincode; ?>"> </div> </div> </div> <?php } ?> <table id="studentTable" border="0"> <tr class="skill"> <td>Category </td> <td>Sub-category</td> <td>Brand</td> <td>Model</td> <?php foreach($servicecatlist as $key1){ ?> <td><?php echo $key1->service_category; ?></td> <?php } ?> </tr> <?php foreach($empservicelist as $key4) { $ser_cat = $key4->service_category; $service_cat[] = explode(",",$ser_cat); $emp_ser_id[] = $key4->id; } $i=0; //for($i=0;$i<count($service_cat);$i++){ foreach($plist as $key2){ ?> <tr> <td><input name="p_category[]" type="text" value="<?php echo $key2->category; ?>"/></td> <td><input name="sub_category[]" type="text" value="<?php echo $key2->subcategory; ?>"/></td> <td><input name="brand[]" type="text" value="<?php echo $key2->brand_name; ?>"/></td> <td><input name="p_model[]" type="text" value="<?php echo $key2->model; ?>"/><input name="ids[]" type="hidden" value="<?php echo $key2->id; ?>"/></td> <?php //echo "<pre>"; print_r($empservicelist); foreach($servicecatlist as $key1){ //echo "Count: ".count($service_cat); ?> <td><input name="service_cat<?php echo $key2->id; ?>[]" value="<?php echo $key1->service_category; ?>" type="checkbox" <?php if(is_array($service_cat[$i])){ if(in_array($key1->service_category, $service_cat[$i])){?> checked='checked' <?php } } ?>/> </td> <?php } //$i++; ?> </tr> <?php $i++; } //}?> </table> <!--<table class="tableadd1"> <tr> <td><label style="font-weight: bold;">Service Skills</label></td><td></td> </tr> <tr> <th><label>Category</label></th><th><label>Sub-category</label></th> <th><label>Model</label></th><th><label>Installation</label></th><th><label>AMC</label></th><th><label>General</label></th><th><label>Major</label></th><th><label>Extra Fitting</label></th> </tr> <tr> <td><input type="text" class="" name=""></td> <td><input type="text" class="" name=""></td><td><input type="text" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td><td><input type="checkbox" class="" name=""></td> </tr> <tr> <td style="padding-top: 25px;"> <button class="btn cyan waves-effect waves-light " type="submit" name="action">Submit <i class="fa fa-arrow-right"></i> </button> </td> </tr> </table>--> <!--<label style="font-weight: bold; font-size: 15px; color: black;padding-top:10px; padding-bottom:10px;">Service Skills:</label> <p> <label style="font-weight: bold; font-size: 13px; color: black; width: 230px;">Enter No Of Service</label> <label><input name="cand_no" type="text" placeholder="Enter Number" style="width: 405px;" class="number"/></label> <div class="clear"></div> </p> <div class="cand_fields"> <table id="studentTable" width="630" border="0"> <tr class="skill"> <td>Category</td> <td>Sub-category</td> <td>Model</td> <td>Installation</td> <td>AMC</td> <td>General</td> <td>Major</td> <td>Extra Fitting</td> </tr> <tr> <td style="width:200px;"> <select > <option value="">---Select---</option> <option value="Motorola">Air Conditioner</option> <option value="<NAME>">Television</option> <option value="Nokia">Digital Camera</option> <option value="Apple">Mobile Phone</option> <option value="Samsung">Cash Counting Machine</option> <option value="Samsung">Washing Machine</option> </select> </td> <td style="width:200px;"> <select > <option value="">---Select---</option> <option value="Motorola">Subcategory 1</option> <option value="<NAME>">Subcategory 2</option> <option value="Nokia">Subcategory 3</option> <option value="Apple">Subcategory 4</option> <option value="Samsung">Subcategory 5</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Model 1</option> <option value="<NAME>">Model 2</option> <option value="Nokia">Model 3</option> <option value="Apple">Model 4</option> <option value="Samsung">Model 5</option> </select> </td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> </tr> </table> </div> <div class="template" style="display: none"> <table > <tr> <td > <select > <option value="">---Select---</option> <option value="Motorola">Air Conditioner</option> <option value="<NAME>">Television</option> <option value="Nokia">Digital Camera</option> <option value="Apple">Mobile Phone</option> <option value="Samsung">Cash Counting Machine</option> <option value="Samsung">Washing Machine</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Subcategory 1</option> <option value="<NAME>">Subcategory 2</option> <option value="Nokia">Subcategory 3</option> <option value="Apple">Subcategory 4</option> <option value="Samsung">Subcategory 5</option> </select> </td> <td > <select > <option value="">---Select---</option> <option value="Motorola">Model 1</option> <option value="<NAME>">Model 2</option> <option value="Nokia">Model 3</option> <option value="Apple">Model 4</option> <option value="Samsung">Model 5</option> </select> </td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> <td><input name="" type="checkbox" /></td> </tr> </table> href="<?php echo base_url(); ?>pages/service_skill" </div>--> <!--<a class="btn cyan waves-effect waves-light " type="submit" name="action" style="margin-top: 25px;">Add Service Skill <i class="fa fa-arrow-right"></i> </a>--> <button class="btn cyan waves-effect waves-light " type="submit" >Submit <i class="fa fa-arrow-right"></i> </button> </form> </div> </div> <div class="col-md-1"> </div> </div> </div> </div> </div> </div> </section> </div> </div> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <script> $(document).ready(function(){ $("#search-box").keyup(function(){ //alert("haiii"); $.ajax({ type: "POST", url: "<?php echo base_url(); ?>Employee/get_city", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data) { $("#suggesstion-box").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }); }); }); function selectCountry(val) { $("#search-box").val(val); $("#suggesstion-box").hide(); } </script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> <script type='text/javascript' src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('#phone').mask('(999) 999-9999'); $('#mobile').mask('9999999999'); $('#pincode').mask('999999'); $('#re-pincode').mask('999999'); $('#re-pincode11').mask('999999'); }); });//]]> </script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $(document).on('click', function() { $('.date').each(function() { $(this).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', yearRange: "1950:2055" }); }); }); }//]]> </script> <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script> --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!-- <script src="js/bootstrap.min.js" type="text/javascript"></script>--> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var jQuery_2_1_1 = $.noConflict(true); </script> </body> </html><file_sep>/application/views_bkMarch_0817/qc_pending.php <head> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script>--> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> <script type="text/javascript" src="http://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script> <link href="<?php echo base_url(); ?>assets/select/select2.css" rel="stylesheet"/> <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!-- data-tables --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script>--> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script>--> <!-- chartist --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <!--<script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="<?php echo base_url(); ?>assets/select/jquery-1.8.0.min.js"></script>--> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <!--<script src="https://code.jquery.com/jquery-1.12.4.js"></script>--> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>--> <script> $( function() { $( ".datepicker" ).datepicker({ dateFormat:"dd-mm-yy", changeMonth:true, changeYear:true, yearRange:'1950:2016' }); } ); </script> <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"/> <script> $(document).ready(function(){ $('#myTable').DataTable(); $('#myTable1').DataTable(); }); </script> <style> .btn { border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; border: 1px solid transparent; } .btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } .waves-effect { position: relative; cursor: pointer; display: inline-block; overflow: hidden; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; vertical-align: middle; z-index: 1; will-change: opacity, transform; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; transition: all 0.3s ease-out; } .btn, .btn-large { text-decoration: none; color: #FFF; background-color: #ff4081; text-align: center; letter-spacing: .5px; -webkit-transition: 0.2s ease-out; -moz-transition: 0.2s ease-out; -o-transition: 0.2s ease-out; -ms-transition: 0.2s ease-out; transition: 0.2s ease-out; cursor: pointer; } .btn, .btn-large, .btn-flat { border: none; border-radius: 2px; display: inline-block; height: 36px; line-height: 36px; outline: 0; padding: 0 2rem; text-transform: uppercase; vertical-align: middle; -webkit-tap-highlight-color: transparent; } .z-depth-1, nav, .card-panel, .card, .toast, .btn, .btn-large, .btn-floating, .dropdown-content, .collapsible, .side-nav { box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); } .cyan { background-color: #00bcd4 !important; background-color: #25555C !important; background-color: #055E87 !important; } button, input, select, textarea { font-family: inherit; font-size: inherit; line-height: inherit; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button, select { text-transform: none; } button { overflow: visible; } button, input, optgroup, select, textarea { margin: 0; font: inherit; color: inherit; } html input[type="button"], button, input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button, select { text-transform: none; } button { overflow: visible; } button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0; } table { border-color: grey; } .link{ padding: 10px; margin-right: 20px; border: 1px solid #B3B3B3; background: #B3B3B3 none repeat scroll 0% 0%; color: white; font-weight: bold; border-radius: 5px; } .link:focus{ color: white; text-decoration:none; } .icon { padding-right: 20px; } .fancybox-custom .fancybox-skin { box-shadow: 0 0 50px #222; } .tableadd1 tr td { text-align: center; } .tableadd1 tr { height: 50px; } .tableadd1 tr td select { border: 1px solid #9A9A9B; border-radius: 5px; width:150px; } .tableadd1 tr td textarea { width:200px; border: 1px solid #9A9A9B; height:70px; border-radius: 5px; } .tableadd1 tr td label { line-height: 0; color:white; } .tableadd1 tr td.plus { padding-top: 0px; } .tableadd1 tr td.plus input { width:50px; border:1px solid gray; } .tableadd1 tr td input { height: 33px; border-radius: 3px; padding-left: 0px; } .tableadd1 tr td.qty { padding-top: 14px; } .tableadd1 tr td.qty input { width:100px; border:1px solid gray; } .tableadd1 tr td.save .fa { font-size: 30px !important; } .rowadd { border: 1px solid #055E87 !important; background: #055E87 none repeat scroll 0% 0% !important; padding: 4px; border-radius: 5px; color: white; font-weight: bold; font-family: calibri; font-size: 15px; margin-top: 30px; } #addtable { width:51%; margin-top:20px; } #addtable tr td { border:none; text-align:left; } #addtable tr td label { color:black; } #errorBox{ color:#F00; } #errorBox1{ color:#F00; } #errorBox2{ color:#F00; } #errorBox3{ color:#F00; } #errorBox4{ color:#F00; } #errorBox5{ color:#F00; } #errorBox6{ color:#F00; } #errorBox7{ color:#F00; } #errorBox8{ color:#F00; } #errorBox9{ color:#F00; } #errorBox10{ color:#F00; } input[id=basicamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 5px; left: 29px; } input[id=cst]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 20px; left: 208px; } input[id=freight]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 35px; left: 364px; } input[id=totalamount]{ width: 100px; border: 1px solid gray; border-radius: 4px; padding: 1px; float:right; position: relative; top: 50px; left: 560px; } .purchasedetail{ position: relative; top: -63px; left: 50px; } .pipurchasedetail{ position: relative; top: -63px; left: 90px; } .cstpurchasedetail{ position: relative; top: -63px; left: 95px; } .tableadd tr td input { width:100%; height: 33px; /* border: 1px solid #B3B3B3; */ border-radius: 5px; padding-left: 10px; } .recvd_qty_cl{ color:#F00; } </style> <script> function frmValidate(){ if ($('.chkNumber:checked').length) { var cln = ''; $('.chkNumber:checked').each(function () { cln = $(this).val(); var loc_name = $('#loc_name').val(); var stats_name = $('#stats_name').val(); var batch_inc_id = $('#batch_inc_id-'+cln).val(); var prod_cat = $('#prod_cat-'+cln).val(); //alert(batch_inc_id); //var success_msg = 'Good Successfully received'; //parent.setSelectedMsg(success_msg); var dataString = 'loc_name='+loc_name+'&stats_name='+stats_name+'&batch_inc_id='+batch_inc_id+'&prod_cat='+prod_cat; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/updating_batchno_status", data: dataString, cache: false, success: function(data) { location.reload(); document.getElementById("errorBox").innerHTML = "Batch # updated"; } }); }); //chkId = chkId.slice(0, -1); //alert(chkId); return false; } else { document.getElementById("errorBox").innerHTML = "please check any Batch # to update"; return false; } } </script> <script> $(document).ready(function(){ $('.acc_qc_update').change(function(){ var idd=$(this).closest(this).attr('id'); var arr = idd.split('-'); var rowid = arr['1']; var qc_status_id = $('#acc_qc_update-'+rowid).val(); var dataString = 'id='+rowid+'&status_id='+qc_status_id; $.ajax ({ type: "POST", url: "<?php echo base_url(); ?>Product/update_qc_status", data: dataString, cache: false, success: function(data) { alert("QC Updated"); } }); }); }); </script> </head> <section id="content"> <div class="container"> <form action="<?php echo base_url(); ?>Product/qc_pending" method="post" name="frmQcpending" autocomplete="off" onsubmit="return frmValidate()"> <div class="section"> <h4 class="header" style="margin-top:8px; font-size: 22px; color: #055e87;">QC Pending SR Batch #</h4> <hr style="border: 1px solid #feca08; margin-top:17px;"> <!--<div class="divider"></div>--> <div id="errorBox" style="margin-left:310px;"></div> <div class="col-md-12"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#home">Product</a></li> <li><a data-toggle="tab" href="#menu1">Accessories</a></li> </ul> </div> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <div style="margin: 30px 0px;" class="tab-content"> <div id="home" class="tab-pane fade in active"> <table class="tableadd1" style="width:100%;" id="myTable"> <thead> <tr style="background: rgb(5, 94, 135) none repeat scroll 0% 0%;border:1px solid grey;"> <td style="border:1px solid grey;"><label>Model</label></td> <td style="width: 350px;border:1px solid grey;"><label>SR Batch #</label></td> <td style="border:1px solid grey;"><label>Serial #</label></td> <td ><label>PO #</label></td> <td style="width: 90px;border:1px solid grey;"><label>Location</label></td> <td style="width: 90px;border:1px solid grey;"><label>Action</label></td> </tr> </thead> <tbody> <?php $i=1; foreach($qc_pending as $key){?> <tr> <td style="border:1px solid grey;"><?php echo $key->model; ?></td> <td style="border:1px solid grey;"><?php echo $key->batch_no; ?></td> <td style="border:1px solid grey;"><?php echo $key->serial_no; ?></td> <td style="border:1px solid grey;"><?php echo $key->po_no; ?> <input type="hidden" name="batch_inc_id" id="batch_inc_id-<?php echo $i; ?>" class="bamount" value="<?php echo $key->batch_inc_id; ?>" > <input type="hidden" name="prod_cat" id="prod_cat-<?php echo $i; ?>" class="bamount" value="<?php echo $key->category; ?>" ></td> <td style="border:1px solid grey;"><?php foreach($location_list as $loc_key){ if(isset($loc_key->location_name) && $loc_key->location_name!=""){ if($loc_key->id==$key->loc_id){ echo $loc_key->location_name; }} } ?> </td> <td class="options-width" style="border:1px solid grey;"> <a href="<?php echo base_url(); ?>Product/qc_report/<?php echo $key->category; ?>/<?php echo $key->batch_no; ?>/<?php echo $key->model_id; ?>" >QC Report</a> </td> </tr> <?php $i++; } ?> </tbody> <!--<input type="text" name="chked_item" id="chked_item" class="bamount" value="" readonly>--> </table> </div> <div id="menu1" class="tab-pane fade"> <table class="tableadd1" style="width:100%;" id="myTable1"> <thead> <tr style="background: rgb(5, 94, 135) none repeat scroll 0% 0%;border:1px solid grey;"> <td style="border:1px solid grey;"><label>Accessories</label></td> <td style="width: 350px;border:1px solid grey;"><label>Serial #</label></td> <td ><label>PO #</label></td> <td style="width: 90px;border:1px solid grey;"><label>Location</label></td> <td style="width: 90px;border:1px solid grey;"><label>Action</label></td> </tr> </thead> <tbody> <?php $j=1; foreach($acc_qc_pending as $key11){?> <tr> <td style="border:1px solid grey;"><?php echo $key11->accessory; ?></td> <td style="border:1px solid grey;"><?php echo $key11->serial_no; ?></td> <td style="border:1px solid grey;"><?php echo $key11->po_no; ?><input type="hidden" name="batch_inc_id" id="batch_inc_id-<?php echo $j; ?>" class="bamount" value="<?php echo $key11->batch_inc_id; ?>" ></td> <td style="border:1px solid grey;"><?php foreach($location_list as $loc_key){ if(isset($loc_key->location_name) && $loc_key->location_name!=""){ if($loc_key->id==$key11->loc_id){ echo $loc_key->location_name; }} } ?> </td> <td class="options-width" style="border:1px solid grey;"> <select name="acc_qc_update" id="acc_qc_update-<?php echo $key11->batch_inc_id; ?>" class="acc_qc_update"> <option value="11">Select</option> <option value="12">QC Accepted</option> <option value="13">QC Rejected</option> </select> </td> </tr> <?php $j++; } ?> </tbody> <!--<input type="text" name="chked_item" id="chked_item" class="bamount" value="" readonly>--> </table> </div> </div> </div> </div> </div> </div> </div> </section> </div> </form> </div> <script> $('.chkSelectAll').click(function () { $('.chkNumber').prop('checked', $(this).is(':checked')); }); $('.chkNumber').click(function () { if ($('.chkNumber:checked').length == $('.chkNumber').length) { $('.chkSelectAll').prop('checked', true); } else { $('.chkSelectAll').prop('checked', false); } }); </script> <!--<script type='text/javascript' src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <script src="<?php echo base_url(); ?>assets/select/select2.js"></script> <script> var config = { '.chosen-select' : {}, '.chosen-select-deselect' : {allow_single_deselect:true}, '.chosen-select-no-single' : {disable_search_threshold:10}, '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, '.chosen-select-width' : {width:"95%"}, '.enable_split_word_search' : {enable_split_word_search:true}, '.chosen-select' : {search_contains:true} } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script> $(function() { $(".product_name").select2(); $(".vendor_name").select2(); /*$(".property_name").select2(); $(".property_type").select2(); $(".property1_name").select2(); $(".propertymulti").select2(); $(".propertymulti1").select2(); $(".reference_con").select2(); */ }); </script>--> <!-- Add jQuery library --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.js?v=2.1.5"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/jquery.fancybox.css?v=2.1.5" media="screen" /> <!-- Add Button helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <!-- Add Thumbnail helper (this is optional) --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <!-- Add Media helper (this is optional) --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <script> var $= jQuery.noConflict(); function brinfo(id){ $.fancybox.open({ href : '<?php echo base_url(); ?>Product/qc_report/'+id, type : 'iframe', padding : 5 }); } </script> </body> </html><file_sep>/application/views/accessories_list.php <style> table.dataTable tbody td{ padding: 0px 10px !important; } input { /*border-style: none !important;*/ height: 2rem !important; } #data-table-simple_filter { display:block; } #data-table-simple_length { display:block; } table.dataTable thead .sorting { background-image: url("../images/sort_bo.png") !important; } table.dataTable thead .sorting_asc { background-image: url("../images/sort_a.png") !important; } table.dataTable thead th, table.dataTable thead td { padding: 5px 18px; border: 1px solid #dbd0e1; } thead { border-bottom: 1px solid #d0d0d0; border: 1px solid #522276; background:#6c477d; color:#fff; font-weight:bold; font-size:13px; } table.dataTable.no-footer tr td { border: 1px solid #522276 !important; padding:4px 10px; } .divider{ width:100%; } .acc_name{ border-style: none !important; } .fa-plus-square{ color: #522276; } a { color: #522276; } input[type=text], input[type=password], input[type=email], input[type=url], input[type=time], input[type=date], input[type=datetime-local], input[type=tel], input[type=number], input[type=search], textarea.materialize-textarea { background-color: transparent; border: none; border-bottom: 1px solid #522276; border-radius: 0; outline: none; /* height: 3.9rem; */ width: 100%; font-size: 0.9em; margin: 0; padding: 0; box-shadow: none; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; transition: all .3s; } label { color: #522276; } hr{ border-top:1px solid #522276; } input[type=search]{ width:55%; border:1px solid #522276; padding:0px 8px; } input:focus{ border:1px solid #522276; } input:active{ border:1px solid #522276; } a:hover{ color: #522276; } a:focus{ color: #522276; } a:active{ color: #522276; } </style> <script> function UpdateStatus(id){//alert(id); //id = $("#status_id").val(); acc_name = $("#acc_name_"+id).val(); //$(function() //{ $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/update_accessories', data: {'id' : id, 'acc_name' : acc_name}, dataType: "text", cache:false, success: function(data){ alert("Accessories updated"); } }); //}); } function DelStatus(id){ $(function() { $.ajax({ type: "POST", url: '<?php echo base_url(); ?>accessories/del_accessories', data: {'id' : id}, dataType: "text", cache:false, success: function(data){ var r=confirm("Are you sure want to delete"); if (r==true) { window.location = "<?php echo base_url(); ?>pages/accessories_list"; } alert("Accessories deleted"); } }); }); } </script> <section id="content"> <div class="container-fluid"> <div class="section"> <h2 class="header" style="display:inline-block;">Accessories List</h2> <a href="<?php echo base_url(); ?>pages/add_accessories"style="color: #FFF; border-radius: 5px;position: relative; float: right; top: 30px; left: 100px;"><i class="fa fa-plus-square" aria-hidden="true" title="Add Accessories"></i></a> <hr> <!--<div class="divider"></div>--> <!--DataTables example--> <div id="table-datatables"> <div class="row"> <div class="col-md-12"> <table id="data-table-simple" cellspacing="0" style="margin-top:2%;"> <thead> <tr> <th>S.No.</th> <th>Accessories Name</th> <th>Action</th> </tr> </thead> <tbody> <?php $i=1;foreach($list as $key){ ?> <tr> <td><?php echo $i;?></td> <td><input type="text" value="<?php echo $key->accessory; ?>" class="acc_name" name="acc_name" id="acc_name_<?php echo $key->id; ?>" readonly></td> <td class="options-width"> <a href="<?php echo base_url(); ?>accessories/update_accessories_name/<?php echo $key->id;?>" style="padding-right:10px;" ><i class="fa fa-floppy-o fa-2x"></i></a> <!--<a href="#" style="padding-right:10px;" onclick="UpdateStatus('<?php echo $key->id; ?>')"><i class="fa fa-floppy-o fa-2x"></i></a>--> <!--<a href="#" ><i onclick="DelStatus('<?php echo $key->id; ?>')" class="fa fa-trash-o fa-2x"></i></a>--> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <br> <div class="divider"></div> </div> </div> </section> </div> </div> <!--materialize js--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.js"></script> <!--prism--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/prism.js"></script> <!--scrollbar--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script> <!-- data-tables --> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/data-tables/data-tables-script.js"></script> <!-- chartist --> <!--<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins/chartist-js/chartist.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.11.2.min.js"></script>--> <!--plugins.js - Some Specific JS codes for Plugin Settings--> <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/plugins.js"></script> <!--<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>--> </body> </html><file_sep>/application/controllers/Work_inprogress.php <?php class work_inprogress extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->model('workin_prog_model'); } public function workin_prog_status(){ $id=$this->uri->segment(3); $data1['job_done'] = $this->uri->segment(4); $data1['req_id'] = $id; $data1['get_status']=$this->workin_prog_model->get_status($id); $data1['get_log_onholds']=$this->workin_prog_model->get_log_onholds($id); $data1['getQuoteReviewDetByID1']=$this->workin_prog_model->getQuoteReviewDetByID1($id); if(!empty($data1['getQuoteReviewDetByID1'])){ $modelid = $data1['getQuoteReviewDetByID1'][0]->model_id; $data1['spareListByModelId1']= $this->workin_prog_model->spareListByModelId($modelid); }else{ $data1['spareListByModelId1']= $this->workin_prog_model->spareList(); } $data1['getQuoteReviewSpareDetByID']=$this->workin_prog_model->getQuoteReviewSpareDetByID($id); //print_r($data1['getQuoteReviewSpareDetByID']); if(!empty($data1['getQuoteReviewSpareDetByID'])){ foreach($data1['getQuoteReviewSpareDetByID'] as $ReviewDetKey3){ $spare_id = $ReviewDetKey3->spare_id; $data1['spareIds'][]= $this->workin_prog_model->getsparedetForEditbyid($spare_id); $data1['spare_amtt'][] = $ReviewDetKey3->amt; } }//echo "<pre>";print_r($data1['spareIds']);exit; $get_request_details = $this->workin_prog_model->get_request_details($id); $sr_no = $get_request_details[0]->serial_no; if($sr_no!=""){ $data1['getQuoteByReqId']=$this->workin_prog_model->getQuoteByReqId($id); }else{ $data1['getQuoteByReqId']=$this->workin_prog_model->getQuoteByReqId1($id); } if(!empty($data1['getQuoteByReqId'])){ if($data1['getQuoteByReqId'][0]->modelid!=""){ $service_modelid = $data1['getQuoteByReqId'][0]->modelid; }else{ $service_modelid = ""; } if($data1['getQuoteByReqId'][0]->service_cat!=""){ $service_service_cat = $data1['getQuoteByReqId'][0]->service_cat; }else{ $service_service_cat = ""; } } $data1['getProbforQuoteByReqId']=$this->workin_prog_model->getProbforQuoteByReqId($id); $data1['getServiceCatbyID']=$this->workin_prog_model->getServiceCatbyID($service_service_cat, $service_modelid); if(empty($data1['getServiceCatbyID'])){ $data1['getservicecharge'] = '0'; } $data1['status_list']=$this->workin_prog_model->status_list(); $data1['status_listForquoteInpro']=$this->workin_prog_model->status_listForquoteInpro(); $data1['status_listForworkInpro']=$this->workin_prog_model->status_listForworkInpro(); $data1['status_listForoffsiteworkInpro']=$this->workin_prog_model->status_listForoffsiteworkInpro(); $data1['status_listForEmpLogin']=$this->workin_prog_model->status_listForEmpLogin(); $data1['status_listForStampingworkInpro']=$this->workin_prog_model->status_listForStampingworkInpro(); $data1['service_req_listforEmp1']=$this->workin_prog_model->service_req_listforEmp1($id); $data1['service_req_listforaddlEmp1']=$this->workin_prog_model->service_req_listforaddlEmp1($id); $data1['getTaxDefaultInfo']=$this->workin_prog_model->getTaxDefaultInfo(); $data1['problemlist1']=$this->workin_prog_model->problemlist(); $data1['getWarrantyInfo']=$this->workin_prog_model->getWarrantyInfo($id); $data1['stamping_details']=$this->workin_prog_model->stamping_details($id); $data1['log_stamping_details']=$this->workin_prog_model->log_stampings($id); $data1['get_qc_parameters_details']=$this->workin_prog_model->get_qc_parameters_details($id); date_default_timezone_set('Asia/Calcutta'); $data1['del_date'] = date("Y-m-d H:i:s"); $data1['req_date'] = date("Y-m-d H:i:s"); $data1['offsite_flag'] = "working"; $data111['user_dat'] = $this->session->userdata('login_data'); $data1['user_type'] = $data111['user_dat'][0]->user_type; $data1['user_id'] = $data111['user_dat'][0]->id; //$data1['getQuoteReviewDetByID']=$this->Quotereview_model->getQuoteReviewDetByID($id); if(!empty($data1['getQuoteReviewDetByID1'])){ $data111['user_dat'] = $this->session->userdata('login_data'); $data1['user_type'] = $data111['user_dat'][0]->user_type; $data1['emp_id'] = $data111['user_dat'][0]->emp_id; $this->load->view('templates/header',$data111); $this->load->view('workin_prog_view',$data1); }else{ $data111['user_dat'] = $this->session->userdata('login_data'); $data1['user_type'] = $data111['user_dat'][0]->user_type; $data1['emp_id'] = $data111['user_dat'][0]->emp_id; $this->load->view('templates/header',$data111); $this->load->view('service_status_new',$data1); } } public function addrow(){ $data['count']=$this->input->post('countid'); $modelid=$this->input->post('modelid'); $data['spareListByModelId']=$this->Quotereview_model->spareListByModelId($modelid); $this->load->view('add_spares_row',$data); } public function getsparedet(){ $id=$this->input->post('id'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Quotereview_model->getsparedetbyid($id))); } public function add_quotereview(){ //echo "<pre>";print_r($_POST);exit; $reqid = $this->input->post('req_id'); $data['req_id']=$this->input->post('req_id'); $data['model_id']=$this->input->post('modelid'); $data['spare_tax']=$this->input->post('spare_tax'); //$data['tax_type']=$this->input->post('tax_type'); $data['spare_tot']=$this->input->post('spare_tot'); $data['labourcharge']=$this->input->post('labourcharge'); $data['concharge']=$this->input->post('concharge'); $data['total_amt']=$this->input->post('total_amt'); $data['delivery_date']=$this->input->post('delivery_date'); $result=$this->Quotereview_model->add_quotereview($data); $data4=array( 'status'=>$this->input->post('status') ); $this->Quotereview_model->update_stats($data4,$reqid); $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $amt=$data1['amt']=$this->input->post('amt'); $c=$spare_name; $count=count($c); if($reqid){ $data1 =array(); for($i=0; $i<$count; $i++) { $bal_spare = $spare_qty1[$i] - $spare_qty[$i]; $used_spare = $spare_qty[$i] + $used_spares[$i]; $data2[] = array( 'id' => $spare_name[$i], 'spare_qty' => $bal_spare, 'used_spare' => $used_spare ); $data1[] = array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i] ); } if(!empty($data2)){ $this->Quotereview_model->update_spare_balance($data2); } if(!empty($data1)){ $this->Quotereview_model->add_quotereview_spares($data1); } echo "<script>alert('Quote Review Added');window.location.href='".base_url()."pages/quote_in_progress_list';</script>"; } } public function edit_quotereview(){ //echo "<pre>";print_r($_POST);exit; error_reporting(0); //exit; $id=$this->input->post('spare_id'); $id1=$this->input->post('spare_tbl_id'); $result = array_diff($id, $id1); //print_r($result);exit; if(!empty($result)){ $this->workin_prog_model->delete_spare_details($result); } $reqid = $this->input->post('req_id'); $id = $this->input->post('req_id'); //$data['req_id']=$this->input->post('req_id'); date_default_timezone_set('Asia/Calcutta'); $data['updated_on'] = date("Y-m-d H:i:s"); $updated_on = date("Y-m-d H:i:s"); $data111['user_dat'] = $this->session->userdata('login_data'); $data['user_id'] = $data111['user_dat'][0]->id; $user_id = $data111['user_dat'][0]->id; $stats=$this->input->post('status'); $nostes_all = $this->input->post('notes_all'); $assignn_to = $this->input->post('assignn_to'); $cassign=$this->input->post('eengid'); $user_typess = $data111['user_dat'][0]->user_type; //echo $user_typess;exit; $spare_taxx = $this->input->post('spare_tax'); if($spare_taxx!=""){ $data['spare_tax']=$this->input->post('spare_tax'); }else{ $data['spare_tax']='0'; } $spare_tott = $this->input->post('spare_tot'); if($spare_tott!=""){ $data['spare_tot']=$this->input->post('spare_tot'); }else{ $data['spare_tot']='0'; } $labourchargee = $this->input->post('labourcharge'); if($labourchargee!=""){ $data['labourcharge']=$this->input->post('labourcharge'); }else{ $data['labourcharge']='0'; } $conchargee = $this->input->post('concharge'); if($conchargee!=""){ $data['concharge']=$this->input->post('concharge'); }else{ $data['concharge']='0'; } $total_amtt = $this->input->post('total_amt'); if($total_amtt!=""){ $data['total_amt']=$this->input->post('total_amt'); $data['pending_amt']=$this->input->post('total_amt'); }else{ $data['total_amt']='0'; $data['pending_amt']='0'; } /*$coord_notes=$this->input->post('notes'); $old_cordnotes=$this->input->post('oldnotes'); if($coord_notes!=""){ if($old_cordnotes != $coord_notes) { $data['notes']=$this->input->post('notes'); $data5q1['co_notess']=$this->input->post('notes'); $data5q1['created_on'] = date("Y-m-d H:i:s"); $data5q1['usrr_id'] = $assignn_to; $data5q1['req_id'] = $this->input->post('req_id'); $this->workin_prog_model->history_notess($data5q1); } }else{ $data['notes']=''; }*/ $userty =$this->input->post('usrtyp'); /* if($notes_all!=''){ if($notes_all=='eng_notes'){ $data['eng_notes']=$this->input->post('eng_notes'); } if($notes_all=='cust_remark'){ $data['cust_remark']=$this->input->post('cust_remark'); } } */ //$maijnn = $this->input->post('reporttyt'); //if($this->input->post('reporttyt')!=''){ /* if($maijnn=="eng_notes"){ if($this->input->post('eng_notes')!=""){ $data5['eng_notes']=$this->input->post('eng_notes'); $data5['created_on'] = date("Y-m-d H:i:s"); $data5['engg_id'] = $user_id; $data5['req_id'] = $this->input->post('req_id'); $data5r['eng_notes']=$this->input->post('eng_notes'); $data5r['cust_remark'] = ''; $this->workin_prog_model->history_insr($data5r,$id); $this->workin_prog_model->history_ins($data5); } } if($maijnn=="cust_remark"){ if($this->input->post('cust_remark')!=""){ $data51['cust_remark']=$this->input->post('cust_remark'); $data51['created_on'] = date("Y-m-d H:i:s"); $data51['engg_id'] = $user_id; $data51['given_by'] = $userty; $data51['req_id'] = $this->input->post('req_id'); $data51r['cust_remark']=$this->input->post('cust_remark'); $data51r['eng_notes'] = ''; $this->workin_prog_model->history_cust_remarkr($data51r,$id); $this->workin_prog_model->history_cust_remark($data51); } } */ //if($maijnn=="eng_notess"){ if($this->input->post('eng_notess')!=""){ $data52['eng_notess']=$this->input->post('eng_notess'); $data52['created_on'] = date("Y-m-d H:i:s"); $data52['engg_id'] = $assignn_to; $data52['req_id'] = $this->input->post('req_id'); $data25r['eng_notess']=$this->input->post('eng_notess'); //$data25r['cust_solution'] = ''; $this->workin_prog_model->history_insrr($data25r,$id); $this->workin_prog_model->history_inss($data52); } //} //if($maijnn=="cust_solution"){ if($this->input->post('cust_solution')!=""){ $data5e1['cust_solution']=$this->input->post('cust_solution'); $data5e1['created_on'] = date("Y-m-d H:i:s"); $data5e1['engg_id'] = $assignn_to; $data5e1['given_by'] = $userty; $data5e1['req_id'] = $this->input->post('req_id'); $data5e1r['cust_solution']=$this->input->post('cust_solution'); //$data5e1r['eng_notess'] = ''; $this->workin_prog_model->history_cust_solutionr($data5e1r,$id); $this->workin_prog_model->history_cust_solution($data5e1); } //} //} //$data['cust_remark'] = $this->input->post('cust_remarkk'); $ratings = $this->input->post('rating'); if(isset($ratings) && $ratings!=''){ $data['rating']=$this->input->post('rating'); } $total_amt=$this->input->post('total_amt'); //$service_cmr_paid = $this->input->post('service_cmr_paid'); //$service_cmr_paid1 = $this->input->post('service_cmr_paid1'); //$tot_service_cmr_paid = $service_cmr_paid + $service_cmr_paid1; //$data['cmr_paid'] = $tot_service_cmr_paid; //$data['pending_amt']=$this->input->post('service_pending_amt'); //$data['payment_mode']=$this->input->post('payment_mode'); /* if($service_cmr_paid!='0' && $service_cmr_paid!=''){ $log_payment_data=array( 'req_id'=>$reqid, 'cmr_paid'=>$this->input->post('service_cmr_paid'), 'payment_mode'=>$this->input->post('payment_mode'), 'pending_amt'=>$this->input->post('service_pending_amt'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $this->workin_prog_model->log_service_payment_details($log_payment_data); } */ /* $disc_amt=$this->input->post('disc_amt'); $disc_amt1=$this->input->post('disc_amt1'); $disc_amt2 = $disc_amt + $disc_amt1; if($disc_amt!=""){ $data['disc_amt']= $disc_amt2; $data['total_amt']=$this->input->post('total_amt'); $data['pending_amt'] = $this->input->post('service_pending_amt'); }else{ $data['total_amt']=$this->input->post('total_amt'); $data['pending_amt'] = $this->input->post('service_pending_amt'); } */ if($this->input->post('cust_remarkk')!=""){ $data51['cust_remark']=$this->input->post('cust_remarkk'); $data51['created_on'] = date("Y-m-d H:i:s"); $data51['engg_id'] = $cassign; $data51['given_by'] = $userty; $data51['req_id'] = $this->input->post('req_id'); $data51r['cust_remark']=$this->input->post('cust_remarkk'); $this->workin_prog_model->history_cust_remarkr($data51r,$id); $this->workin_prog_model->history_cust_remark($data51); } $data4=array( 'status'=>$this->input->post('status'), 'updated_on'=>$updated_on, 'user_id'=>$user_id ); $this->workin_prog_model->update_stats($data4,$id); $eng_ack = $this->input->post('eng_ack'); if($eng_ack!=""){ $data_ackupdate['eng_ack']=$this->input->post('eng_ack'); $data_ackupdate['accepted_engg_id']=$this->input->post('empiid'); $this->workin_prog_model->update_eng_ack($data_ackupdate,$reqid); } if($eng_ack!='' && isset($eng_ack)){ $cust_site_mobile1 = '9962135225'; $reque_id=$this->input->post('reque_id'); if($eng_ack=='accept'){ $eng_ack_msg = 'accepted'; $sms= "Hi. Request Id: ".$reque_id." is ".$eng_ack_msg; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } if($eng_ack=='reject'){ $eng_ack_msg = 'rejected'; $sms= "Hi. Request Id: ".$reque_id." is ".$eng_ack_msg; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } if($eng_ack=='later'){ $sms= "Hi. Request Id: ".$reque_id." will be serviced later"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile1&text=$messages&priority=ndnd&stype=normal"); } } foreach ($data4 as $datakey => $datavalue) { //echo $datakey.'-'.$datavalue; if (!empty($datavalue)){ $this->workin_prog_model->update_stats($data4,$reqid); if($datavalue=='3'){ $data['delivery_date']=$this->input->post('delivery_date'); $data['comments']=$this->input->post('comment_ready'); $customer_mobile = $this->input->post('cust_mobile'); $customer_name = $this->input->post('cust_name'); $p_name = $this->input->post('p_name'); $serial_no = $this->input->post('serial_no'); $service_type = $this->input->post('service_type'); if(isset($customer_mobile) && $customer_mobile!=""){ $sms="Your machine ".$p_name."/".$serial_no."/ purpose(".$service_type.")is CALL COMPLETED.<br> Thank you.<br> Syndicate Diagnostics.<br>"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $supervisor_mobile='9826938860'; $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$customer_mobile&text=$messages&priority=ndnd&stype=normal"); $sms1="(".$customer_name.")".$p_name."/".$serial_no."/ purpose(".$service_type.")is CALL COMPLETED. <br>Thank you.<br> Syndicate Diagnostics.<br>"; $messages1 = strip_tags($sms1); $messages1 = str_replace(' ','%20',$messages1); $msg1 = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$supervisor_mobile&text=$messages1&priority=ndnd&stype=normal"); } } if($datavalue=='5'){ $cust_site_mobile = '9962135225'; $reque_id=$this->input->post('reque_id'); //$cust_site_mobile = '7200669999'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $sms= "Hi. Please prepare quotation and get customer approval for request ID: ".$reque_id; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($datavalue=='16'){ $cust_site_mobile = '9962135225'; $reque_id=$this->input->post('reque_id'); //$cust_site_mobile = '7200669999'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $sms= "Hi. request ID: ".$reque_id." has been done"; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=efficiency&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } if($datavalue=='9'){ $cust_site_mobile = '9962135225'; //$cust_site_mobile = '7200669999'; if(isset($cust_site_mobile) && $cust_site_mobile!=""){ $reque_id=$this->input->post('reque_id'); $onhold_date = $this->input->post('on_hold'); $onhold_reason = $this->input->post('onhold_reason'); $sms= "Hi. Request ID: ".$reque_id." is on-hold. Date: ".$onhold_date." Reason: ".$onhold_reason; $messages = strip_tags($sms); $messages = str_replace(' ','%20',$messages); $msg = file_get_contents("http://bhashsms.com/api/sendmsg.php?user=9840121544&pass=<PASSWORD>&sender=SYNDPL&phone=$cust_site_mobile&text=$messages&priority=ndnd&stype=normal"); } } /* if($datavalue=='4'){ $data['delivery_date']=$this->input->post('delivery_date1'); $data['comments']=$this->input->post('comment_deliver'); $data['assign_to']=$this->input->post('assign_to_id'); } */ if($datavalue=='9'){ $data['onhold_date']=$this->input->post('on_hold'); $data['onhold_reason']=$this->input->post('onhold_reason'); $data7['on_hold'] = $this->input->post('on_hold'); $data7['onhold_reason']=$this->input->post('onhold_reason'); $data7['req_id'] = $this->input->post('req_id'); $data7['emp_id']=$this->input->post('assign_to_id'); $this->workin_prog_model->log_onhold($data7); } } } $this->workin_prog_model->update_quotereview($data,$reqid); $order_row_id=$this->input->post('order_row_id'); $batch_no = $this->input->post('batch_no'); $serial_no = $this->input->post('serial_no'); if(isset($serial_no) && $serial_no!="" && $serial_no!='update sr no'){ $data_order_det['batch_no']=$this->input->post('batch_no'); $data_order_det['serial_no']=$this->input->post('serial_no'); $this->workin_prog_model->update_order_srno($data_order_det,$order_row_id); $data_service_det['batch_no']=$this->input->post('batch_no'); $data_service_det['serial_no']=$this->input->post('serial_no'); $this->workin_prog_model->update_service_srno($data_service_det,$reqid); } $spare_name=$data1['spare_name']=$this->input->post('spare_name'); $spare_qty=$data1['spare_qty']=$this->input->post('spare_qty'); $spare_qty1=$data1['spare_qty1']=$this->input->post('spare_qty1'); $used_spares=$data1['used_spare']=$this->input->post('used_spare'); $warranty_claim_status=$data1['warranty_claim_status']=$this->input->post('warranty_claim_status'); $desc_failure=$data1['desc_failure']=$this->input->post('desc_failure'); $why_failure=$data1['why_failure']=$this->input->post('why_failure'); $correct_action=$data1['correct_action']=$this->input->post('correct_action'); /* echo "<pre>"; print_r($warranty_claim_status); echo "<pre>"; print_r($desc_failure); echo "<pre>"; print_r($why_failure); echo "<pre>"; print_r($correct_action); exit; */ $amt=$data1['amt']=$this->input->post('amt'); //$this->workin_prog_model->delete_quote_review($reqid); $spare_tbl_id1=$data1['spare_tbl_id']=$this->input->post('spare_tbl_id'); $c=$spare_name; $count=count($c); if($reqid){ //$data1 = array(); for($i=0; $i<$count; $i++) { if($spare_name[$i]!="" && $spare_qty[$i]!=""){ if($warranty_claim_status[$i]=='to_claim'){ $desc_failure1 = $desc_failure[$i]; $why_failure1 = $why_failure[$i]; $correct_action1 = $correct_action[$i]; }else{ $desc_failure1 = ''; $why_failure1 = ''; $correct_action1 = ''; } $data1 = array( 'request_id' => $reqid, 'spare_id' => $spare_name[$i], 'spare_qty' => $spare_qty[$i], 'amt' => $amt[$i], 'warranty_claim_status' => $warranty_claim_status[$i], 'desc_failure' => $desc_failure1, 'why_failure' => $why_failure1, 'correct_action' => $correct_action1 ); } if($spare_tbl_id1[$i]!=""){ $where = "id=".$spare_tbl_id1[$i]." AND request_id=".$reqid; $this->workin_prog_model->update_quotereview_spares($data1,$where); }else{ $this->workin_prog_model->add_quotereview_spares($data1); } $job_done1 = $this->input->post('status'); $aprovalid = $this->input->post('approval_statusid'); if($job_done1=='3' && isset($job_done1) && $aprovalid[$i]=='approved'){ $getsparebyid = $this->workin_prog_model->getsparebyid($spare_name[$i]); $spare_qtt = $getsparebyid[0]->spare_qty; $used_sparr = $getsparebyid[0]->used_spare; $eng_sparr = $getsparebyid[0]->eng_spare; $bal_spare = $spare_qtt - $spare_qty[$i]; $used_spare = $spare_qty[$i] + $used_sparr; $enggs_spare = $spare_qty[$i] + $eng_sparr; $data2[] = array( 'id' => $spare_name[$i], 'used_spare' => $used_spare, 'eng_spare' => $enggs_spare ); $eng_idd = $this->input->post('eng_idd'); $where = "spare_id=".$spare_name[$i]." AND employee=".$eng_idd; $engg_spare_cnt = $this->workin_prog_model->getupspare($where); $engg_sp_count = $engg_spare_cnt[0]->qty_plus; if($engg_sp_count!="" && $engg_sp_count!="0"){ $p_qty = $engg_sp_count - $spare_qty[$i]; $n_data=array( 'qty_plus'=>$p_qty ); $this->workin_prog_model->updatepspare($n_data,$where); } } } if(!empty($data2)){ $this->workin_prog_model->update_spare_balance($data2); } /* if(!empty($data1)){ $this->workin_prog_model->add_quotereview_spares($data1); } */ /// echo "<script>alert('Work In-progress Updated');window.location.href='".base_url()."pages/workin_prog_list';</script>"; } $res_qc_value = $this->input->post('res_qc_value'); $qc_param_id = $this->input->post('qc_param_id'); $this->workin_prog_model->delete_qc_param_details($reqid); if(!empty($res_qc_value)){ $qc_data = array(); for($i=0; $i<count($res_qc_value); $i++) { $qc_data = array( 'request_id' => $reqid, 'qc_master_id' => $qc_param_id[$i], 'result_qc_value' => $res_qc_value[$i] ); $this->workin_prog_model->add_qc_param_details($qc_data); } } $eemail = $this->input->post('email'); if($eemail!=""){ //email $config = Array( 'mailtype' => 'html' ); $this->load->library('email', $config); $this->email->from('<EMAIL>', 'Admin'); // $text = $this->input->post('eng_notes'); //echo $text;exit; $this->email->to($eemail); $this->email->subject('Subject'); $data_email['sub'] = $this->input->post('eng_notes'); // print_r($data['sub']); exit; $message="<table> <tr><td>". $data_email['sub']."</td></tr> <tr><td colspan='2' style='text-align:center;font-size:15px;font-weight:bolder'> Thank you for Contact Us ..! </td></tr> </table>"; // echo $message; exit; $this->email->message($message); $this->email->send(); } $job_donee = $this->input->post('job_done'); if($job_donee=='completed'){ echo "<script>alert('Call Updated Successfully!!!');window.location.href='".base_url()."pages/comp_engg_list';</script>"; }else{ echo "<script>alert('Call Updated Successfully!!!');window.location.href='".base_url()."pages/workin_prog_list';</script>"; } } public function getpettyspare(){ $id=$this->input->post('engid'); $spareid=$this->input->post('spareid');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->workin_prog_model->get_sp($id,$spareid))); } public function add_service_req(){ //echo "<pre>";print_r($_POST);exit; $data['request_id']=$this->input->post('req_id'); $data['cust_name']=$this->input->post('cust_name'); $data['mobile']=$this->input->post('mobile'); $data['email_id']=$this->input->post('email_id'); $data['request_date']=$this->input->post('datepicker'); $result=$this->Service_model->add_services($data); if($result){ $data1['request_id']=$result; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); $result1=$this->Service_model->add_service_details($data1); } if($result){ echo "<script>alert('Service Request Added');window.location.href='".base_url()."pages/service_req_list';</script>"; } } public function get_custbyid(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_customerdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_orderbyid(){ $id=$this->input->post('serialno');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Service_model->get_orderdetails($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function update_service_req(){ $id=$this->uri->segment(3); $data['list']=$this->Service_model->getservicereqbyid($id); $data['list1']=$this->Service_model->getservicereqDetailsbyid($id); $data['list2']=$this->Service_model->getserviceEmpbyid($id); $data['list_serialnos']=$this->Service_model->list_serialnos(); $data['customerlist']=$this->Service_model->customerlist(); $data['servicecat_list']=$this->Service_model->servicecat_list(); $data['problemlist']=$this->Service_model->problemlist(); $data['employee_list']=$this->Service_model->employee_list(); $data1['user_dat'] = $this->session->userdata('login_data'); $this->load->view('templates/header',$data1); $this->load->view('edit_service_req',$data); } public function edit_service_req(){ $data=array( 'request_id'=>$this->input->post('req_id'), 'cust_name'=>$this->input->post('cust_name'), 'mobile'=>$this->input->post('mobile'), 'email_id'=>$this->input->post('email_id'), 'request_date'=>$this->input->post('datepicker') ); $id=$this->input->post('servicereqid'); $this->Service_model->update_service_request($data,$id); if($id){ $data1['request_id']=$id; $data1['serial_no']=$this->input->post('serial_no'); $data1['cat_id']=$this->input->post('categoryid'); $data1['subcat_id']=$this->input->post('subcategoryid'); $data1['brand_id']=$this->input->post('brandid'); $data1['model_id']=$this->input->post('modelid'); $data1['warranty_date']=$this->input->post('warranty_date'); $data1['machine_status']=$this->input->post('machine_status'); $data1['site']=$this->input->post('site'); $data1['service_type']=$this->input->post('service_type'); $data1['service_cat']=$this->input->post('service_cat'); $data1['zone']=$this->input->post('locid'); $data1['problem']=$this->input->post('prob'); $data1['assign_to']=$this->input->post('assign_to'); $data1['received']=$this->input->post('received'); if (is_array($data1['received'])){ $data1['received']= implode(",",$data1['received']); }else{ $data1['received']=""; } //$countids=$this->input->post('countids'); //echo "<pre>"; //print_r($data1); $this->Service_model->delete_serv_req_details($id); $result1=$this->Service_model->add_service_details($data1); } echo "<script>alert('Service Request Updated');window.location.href='".base_url()."pages/service_req_list';</script>"; } public function get_branchname(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_branch($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function getsub_category(){ $id=$this->input->post('id');//echo $id; exit; $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->getsub_cat($id))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_brand(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_brands($categoryid,$subcatid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function get_model(){ $subcatid=$this->input->post('subcatid');//echo $id; exit; $categoryid=$this->input->post('categoryid'); $brandid=$this->input->post('brandid'); $this->output ->set_content_type("application/json") ->set_output(json_encode($this->Order_model->get_models($categoryid,$subcatid,$brandid))); //$query=$this->Product_model->getsub_cat($id); //return $query; } public function del_order(){ $id=$this->input->post('id'); $this->Order_model->delete_order_details($id); $result = $this->Order_model->delete_orders($id); } public function view_history() { $id = $this->uri->segment(3); $usr_typ = $this->uri->segment(4); $sassign = $this->uri->segment(5); $val=sprintf("%05d", $id); //echo $id; exit; $data111['user_dat'] = $this->session->userdata('login_data'); $data2['user_id'] = $data111['user_dat'][0]->id; $user_id = $data111['user_dat'][0]->id; $data1['get_log_onholds']=$this->workin_prog_model->get_log_onholds1($val); //print_r($data1['get_log_onholds']);exit; $data1['history_remark'] = $this->workin_prog_model->view_remark($id); $data1['history_sol'] = $this->workin_prog_model->view_history_sol($id); $data1['history_conotes'] = $this->workin_prog_model->view_history_notes($id); $data1['history_engnotess'] = $this->workin_prog_model->view_history_notess($id); $this->load->view('view_history_all',$data1); /* if($usr_typ=='1') { $data1['history_remark'] = $this->workin_prog_model->view_remark($id,$sassign); $data1['history_sol'] = $this->workin_prog_model->view_history_sol($id,$sassign); $data1['history_conotes'] = $this->workin_prog_model->view_history_notes($id,$sassign); $data1['history_engnotess'] = $this->workin_prog_model->view_history_notess($id,$sassign); $this->load->view('view_history_all',$data1); } if($usr_typ=='7') { $data2['history_sol'] = $this->workin_prog_model->view_history_sol($id,$user_id); $data2['history_engnotess'] = $this->workin_prog_model->view_history_notess($id,$user_id); $data2['history_conotes'] = $this->workin_prog_model->view_history_notes($id,$user_id); $data2['history_remark'] = $this->workin_prog_model->view_remark($id); $this->load->view('view_history',$data2); } */ } }
12a8cdd9670ee8d3d6d1be31a645fd3a797b8015
[ "SQL", "PHP" ]
215
PHP
sathishalways/billing
d79f6e1c8ff50794cc782f2de8b5fc7eacdc84d1
a80f8b41e438ad2a80182b42c861ea438d2cdd32
refs/heads/master
<repo_name>deejaan/TPspremnik<file_sep>/main.cpp #include <iostream> #include <string> #include <vector> #include <stdexcept> class Spremnik { protected: double tezina; std::string naziv_sadrzaja; public: Spremnik(double tezina, std::string naziv_sadrzaja) : tezina(tezina), naziv_sadrzaja(naziv_sadrzaja) {} double DajTezinu() const { return tezina; } virtual double DajUkupnuTezinu() const=0; virtual void Ispisi() const=0; virtual Spremnik* DajKopiju() const=0; virtual ~Spremnik() {} }; class Sanduk : public Spremnik { std::vector<double> tezine_predmeta; public: Sanduk(double tezina, std::string naziv_sadrzaja, std::vector<double> tezine_predmeta) : Spremnik(tezina, naziv_sadrzaja), tezine_predmeta(tezine_predmeta) {} double DajUkupnuTezinu() const override; void Ispisi() const override; Spremnik* DajKopiju() const override { return new Sanduk(*this); } ~Sanduk() {} }; class Vreca : public Spremnik { double tezina_materije; public: Vreca(double tezina, std::string naziv_sadrzaja, double tezina_materije) : Spremnik(tezina, naziv_sadrzaja), tezina_materije(tezina_materije) {} double DajUkupnuTezinu() const override { return tezina + tezina_materije; } void Ispisi() const override { std::cout << "Vrsta spremnika: Vreca\nSadrzaj: " << naziv_sadrzaja << "\nVlastita tezina: " << DajTezinu() << " (kg)\nTezina pohranjene materije: " << tezina_materije << " (kg)\nUkupna tezina: " << DajUkupnuTezinu() << " (kg)" << std::endl; } Spremnik* DajKopiju() const override { return new Vreca(*this); } ~Vreca() {} }; class Bure : public Spremnik { double spec_tezina_tecnosti, zapremina; public: Bure(double tezina, std::string naziv_sadrzaja, double spec_tezina_tecnosti, double zapremina) : Spremnik(tezina, naziv_sadrzaja), spec_tezina_tecnosti(spec_tezina_tecnosti), zapremina(zapremina) {} double DajUkupnuTezinu() const override { return tezina + spec_tezina_tecnosti*zapremina/1000; } void Ispisi() const override { std::cout << "Vrsta spremnika: Bure\nSadrzaj: " << naziv_sadrzaja << "\nVlastita tezina: " << DajTezinu() << " (kg)\nSpecificna tezina tecnosti: " << spec_tezina_tecnosti << " (kg/m^3)\nZapremina tecnosti: " << zapremina << " (l)\nUkupna tezina: " << DajUkupnuTezinu() << " (kg)" << std::endl; } Spremnik* DajKopiju() const override { return new Bure(*this); } ~Bure() {} }; class PolimorfniSpremnik { Spremnik *p_spremnik; void Test() const { if(!p_spremnik) throw std::logic_error("Nespecificiran spremnik"); } public: PolimorfniSpremnik() : p_spremnik(nullptr) {} ~PolimorfniSpremnik() { delete p_spremnik; } PolimorfniSpremnik(const Spremnik &spr) : p_spremnik(spr.DajKopiju()) {} PolimorfniSpremnik(const PolimorfniSpremnik &spr) { if (!spr.p_spremnik) p_spremnik=nullptr; else p_spremnik = spr.p_spremnik->DajKopiju(); } PolimorfniSpremnik &operator =(const PolimorfniSpremnik &spr) { Spremnik *p_novi=nullptr; if (spr.p_spremnik != nullptr) p_novi = spr.p_spremnik->DajKopiju(); delete p_spremnik; p_spremnik = p_novi; return *this; } PolimorfniSpremnik &operator =(PolimorfniSpremnik &&spr) { std::swap(p_spremnik, spr.p_spremnik); return *this;} double DajTezinu() const { Test(); return p_spremnik->DajTezinu(); } double DajUkupnuTezinu() { Test(); return p_spremnik->DajUkupnuTezinu(); } void Ispisi() const { Test(); p_spremnik->Ispisi(); } }; double Sanduk::DajUkupnuTezinu() const { double suma_tezina=0; for (const auto &el : tezine_predmeta) suma_tezina += el; return suma_tezina + tezina; } void Sanduk::Ispisi() const { std::cout << "Vrsta spremnika: Sanduk\nSadrzaj: " << naziv_sadrzaja << "\nTezine predmeta: "; for (const auto &el : tezine_predmeta) std::cout << el << " "; std::cout << "(kg)\nVlastita tezina: " << DajTezinu() << " (kg)\nUkupna tezina: " << DajUkupnuTezinu() << " (kg)" << std::endl; } int main () { return 0; }
a55225cf69368ad3a028d77fbe7374591170e0ef
[ "C++" ]
1
C++
deejaan/TPspremnik
a3d6905b299eff78c0aa715229efb1c6a63c4ab4
4a130d7c8dac7fb3c6791dd4a2375fe0cf13e606
refs/heads/master
<file_sep> export const addGreeting = text => { return { type: "ADD_GREETING", text } } <file_sep>import React from 'react' import PropTypes from 'prop-types' const Greeting = ({ greeting = 'hello' }) => ( <h2> {greeting} </h2> ) Greeting.propTypes = { greeting: PropTypes.string.isRequired } export default Greeting <file_sep>import React from 'react' import PropTypes from 'prop-types' import Greeting from './Greeting' const Greetinglist = ({ greetings }) => ( <ul> {greetings.map(greeting => ( <Greeting {...greeting} /> ))} </ul> ) Greetinglist.propTypes = { greetings: PropTypes.arrayOf( PropTypes.shape({ greeting: PropTypes.string.isRequired }).isRequired ).isRequired } export default Greetinglist <file_sep>import { combineReducers } from 'redux' import greetings from './greetings' const greetingApp = combineReducers({ greetings }) export default greetingApp <file_sep>import React from 'react' import AddGreeting from './containers/AddGreeting' import VisibleGreeting from './containers/VisibleGreeting' const App = () => ( <div> <AddGreeting /> <VisibleGreeting /> </div> ) export default App <file_sep>import { connect } from 'react-redux' import Greetinglist from '../components/Greetinglist' const getVisibleGreetings = (greetings) => { return greetings } const mapStateToProps = state => { return { greetings: getVisibleGreetings(state.greetings) } } const VisibleGreeting = connect( mapStateToProps )(Greetinglist) export default VisibleGreeting
77282bd527cf7e333dca64e49f8bfc5d08b4c91a
[ "JavaScript" ]
6
JavaScript
arr0nax/redux-practice
32de0cc6f1a2683436be21659a8e17057c1facd1
3a891d24eab2fe9477ab642713fcdeb3ac71df3e
refs/heads/master
<repo_name>ionosnetworks/inf<file_sep>/sql.go package inf import ( "database/sql/driver" "errors" "fmt" "math" "strconv" "strings" ) var errInvalidType = errors.New("invalid type for inf.Dec") var errParseFailure = errors.New("parse failure for inf.Dec") func (z *Dec) Scan(value interface{}) error { var s string switch v := value.(type) { case []byte: s = string(v) case string: s = v default: return errInvalidType } _, ok := z.SetString(s) if !ok { return errParseFailure } return nil } func (z *Dec) Value() (driver.Value, error) { return z.String(), nil } func (z *Dec) Float64() float64 { f, _ := strconv.ParseFloat(z.String(), 64) return f } func (z *Dec) SetFromFloat(f float64) *Dec { switch { case math.IsInf(f, 0): panic("cannot create a decimal from an infinte float") case math.IsNaN(f): panic("cannot create a decimal from an NaN float") } s := strconv.FormatFloat(f, 'e', -1, 64) // Determine the decimal's exponent. var e10 int64 e := strings.IndexByte(s, 'e') for i := e + 2; i < len(s); i++ { e10 = e10*10 + int64(s[i]-'0') } switch s[e+1] { case '-': e10 = -e10 case '+': default: panic(fmt.Sprintf("malformed float: %v -> %s", f, s)) } e10++ // Determine the decimal's mantissa. var mant int64 i := 0 neg := false if s[0] == '-' { i++ neg = true } for ; i < e; i++ { if s[i] == '.' { continue } mant = mant*10 + int64(s[i]-'0') e10-- } if neg { mant = -mant } return z.SetUnscaled(mant).SetScale(Scale(-e10)) }
4c59d0df96b12ca352b4f572f4975532b69f5d9e
[ "Go" ]
1
Go
ionosnetworks/inf
b8f6ac92a9a1a128e7ba78cd3a8efebd013b190d
da89acd2c2ba796d344f25b1242a0b632730d2f5
refs/heads/master
<repo_name>winnemucca/angular2-fire<file_sep>/src/app/routes.ts import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './components/home-component/home-component.component'; import { ListingsComponent } from './components/daycareListings/listings/listings.component'; import { ListingComponent } from './components/daycareListings/listing/listing.component'; import { PageNotFoundComponent } from './components/page-not-found-component/page-not-found-component.component'; import { AddListingComponent } from './components/add-listing/add-listing.component'; import { EditListingComponent } from './components/edit-listing/edit-listing.component'; export const appRoutes: Routes = [ { path: '', component: HomeComponent}, { path: 'listings', component: ListingsComponent}, { path: 'listing/:id', component: ListingComponent}, { path: 'add-listing', component: AddListingComponent}, { path: 'edit-listing/:id', component: EditListingComponent}, { path: '**', component: PageNotFoundComponent} ]; <file_sep>/src/app/components/daycareListings/index.ts export * from './listing/listing.component'; export * from './listings/listings.component';
dedd88b5c5a473de0eeb569803d49f546bf33307
[ "TypeScript" ]
2
TypeScript
winnemucca/angular2-fire
71cf7889bf38b2511dcc819f2b8a883bd0d0bf69
8b602ad8df00020537c43cdce0a57c87263b986f
refs/heads/master
<repo_name>SerafimLazuko/MMF-4-ClientBillSystem<file_sep>/ClientBillWebApp/ClientBillWebApp/Service/IServices/IBillService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; namespace ClientBillWebApp.Service.IServices { interface IBillService { BillModel CreateBill(); bool DeleteBill(Guid billId); BillModel GetBill(Guid billId); } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Service/Services/CientService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; using ClientBillWebApp.Service.IServices; namespace ClientBillWebApp.Service.Services { public class CientService : IClientService { public ClientModel CreateClient() { throw new NotImplementedException(); } public bool DeleteClient(Guid clientId) { throw new NotImplementedException(); } public ClientModel GetClient(Guid clientId) { throw new NotImplementedException(); } public void UpdateClient(Guid clientId) { throw new NotImplementedException(); } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Models/TransferModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ClientBillWebApp.Models { public class TransferModel { public Guid Id { get; set; } public Guid DestinationBillId { get; set; } public Guid SourceBillId { get; set; } public double TransferAmount { get; set; } public DateTime DateTime { get; set; } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Models/OrderModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ClientBillWebApp.Models { public class OrderModel { public Guid Id { get; set; } public double OrderCost { get; set; } } } <file_sep>/README.md # MMF-4-ClientBillSystem<file_sep>/ClientBillWebApp/ClientBillWebApp/Service/Services/CreditCardService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; using ClientBillWebApp.Service.IServices; namespace ClientBillWebApp.Service.Services { public class CreditCardService: ICreditCardService { public CreditCardModel CreateCreditCard() { throw new NotImplementedException(); } public bool DeleteCreditCard(Guid creditCardId) { throw new NotImplementedException(); } public CreditCardModel GetCreditCard(Guid creditCardId) { throw new NotImplementedException(); } public bool IsCardActive(Guid creditCardId) { throw new NotImplementedException(); } public bool BlockCreditCard(Guid creditCardId) { throw new NotImplementedException(); } public bool MakeTransfer(Guid sourceCardId, Guid destinationCardId, double transferAmount) { throw new NotImplementedException(); } public bool PayOrder(Guid sourceCardId, Guid orderId, double orderCost) { throw new NotImplementedException(); } public bool CancelBill(Guid creditCardId, Guid billId) { throw new NotImplementedException(); } public double PrintBalance(Guid creditCardId) { throw new NotImplementedException(); } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Service/IServices/ICreditCardService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; namespace ClientBillWebApp.Service.IServices { interface ICreditCardService { CreditCardModel CreateCreditCard(); bool DeleteCreditCard(Guid creditCardId); CreditCardModel GetCreditCard(Guid creditCardId); bool IsCardActive(Guid creditCardId); bool BlockCreditCard(Guid creditCardId); bool MakeTransfer(Guid sourceCardId, Guid destinationCardId, double transferAmount); bool PayOrder(Guid sourceCardId, Guid orderId, double orderCost); bool CancelBill(Guid creditCardId, Guid billId); double PrintBalance(Guid creditCardId); } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Controllers/ClientController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ClientBillWebApp.Models; using ClientBillWebApp.Data; namespace ClientBillWebApp.Controllers { public class ClientController : Controller { private ApplicationDbContext db; public ClientController(ApplicationDbContext context) { db = context; } public async Task<IActionResult> Index(Guid clientId) { return View(await db.Clients.FindAsync(clientId)); //return View(); } public IActionResult Create() { return View(); } public async Task<IActionResult> About(Guid clientId) { return View(await db.Clients.FindAsync(clientId)); } [HttpPost] public async Task<IActionResult> Create(ClientModel clientModel) { clientModel.Id = new Guid(); clientModel.AssosiatedBills = new List<BillModel>(); clientModel.AssosiatedCards = new List<CreditCardModel>(); db.Clients.Add(clientModel); await db.SaveChangesAsync(); return RedirectToAction("Index", clientModel.Id); } } }<file_sep>/ClientBillWebApp/ClientBillWebApp/Data/ApplicationDbContext.cs using System; using System.Collections.Generic; using System.Text; using ClientBillWebApp.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace ClientBillWebApp.Data { public class ApplicationDbContext : IdentityDbContext { public DbSet<BillModel> Bills { get; set; } public DbSet<ClientModel> Clients { get; set; } public DbSet<CreditCardModel> CreditCards { get; set; } public DbSet<OrderModel> Orders { get; set; } public DbSet<TransferModel> Transfers{ get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { Database.EnsureCreated(); } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Service/Services/BillService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; using ClientBillWebApp.Service.IServices; namespace ClientBillWebApp.Service.Services { public class BillService : IBillService { public BillModel CreateBill() { throw new NotImplementedException(); } public bool DeleteBill(Guid billId) { throw new NotImplementedException(); } public BillModel GetBill(Guid billId) { throw new NotImplementedException(); } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Models/BillModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ClientBillWebApp.Models { public class BillModel { public Guid Id { get; set; } public Guid HolderGuid { get; set; } public List<CreditCardModel> AssosiatedCards { get; set; } public bool IsActive { get; set; } public double Balance { get; set; } } } <file_sep>/ClientBillWebApp/ClientBillWebApp/Service/IServices/IClientService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClientBillWebApp.Models; namespace ClientBillWebApp.Service.IServices { interface IClientService { ClientModel CreateClient(); bool DeleteClient(Guid clientId); ClientModel GetClient(Guid clientId); void UpdateClient(Guid clientId); } }<file_sep>/ClientBillWebApp/ClientBillWebApp/Controllers/TransferController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ClientBillWebApp.Data; using ClientBillWebApp.Models; namespace ClientBillWebApp.Controllers { public class TransferController : Controller { private ApplicationDbContext context; public TransferController(ApplicationDbContext appContext) { context = appContext; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> Transfer() { TransferModel model = new TransferModel(); model.DateTime = DateTime.UtcNow; model.Id = new Guid(); model.TransferAmount = ViewBag.TransferAmount; model.SourceBillId = ViewBag.SourceBillId; model.DestinationBillId = ViewBag.DestinationBillId; await context.Transfers.AddAsync(model); await context.SaveChangesAsync(); return View(model); } } }<file_sep>/ClientBillWebApp/ClientBillWebApp/Models/CreditCardModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ClientBillWebApp.Models { public class CreditCardModel { public Guid Id { get; set; } public BillModel AssosiatedBillId { get; set; } public Guid HolderId { get; set; } //public PayHistory PayHistory { get; set; } public bool IsBlocked { get; set; } } }
381785baddce39d2dd43603f0b7448f50f689bac
[ "Markdown", "C#" ]
14
C#
SerafimLazuko/MMF-4-ClientBillSystem
05f3187bcdf64e646994d8c80f0c9b6f2b52e619
cd7a4a331e824663992d39d5969cb9b40482ea2d
refs/heads/master
<repo_name>gio00/RealDebrid-Menubar<file_sep>/RealDebrid/AppDelegate.swift // // AppDelegate.swift // RealDebrid // // Created by Gio on 06/09/14. // Copyright (c) 2014 Gio. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate, NSURLConnectionDelegate { @IBOutlet weak var menu: NSMenu! @IBOutlet weak var field: NSTextField! @IBOutlet weak var textArea: NSTextField! var statusItem:NSStatusItem! override func awakeFromNib() { statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) statusItem.menu = menu statusItem.title = "RD" statusItem.highlightMode = true } //MARK: BUTTONS @IBAction func paste(sender: AnyObject) { var text = NSPasteboard.generalPasteboard().stringForType(NSPasteboardTypeString) field.stringValue = text! } @IBAction func copyUnrestricted(sender: AnyObject) { NSPasteboard.generalPasteboard().clearContents() NSPasteboard.generalPasteboard().setString(textArea.stringValue, forType: NSStringPboardType) } @IBAction func unrestrict(sender: AnyObject) { var com = field.stringValue.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " \n")) if com.count > 0{ for x in com{ var url = NSURL(string: "https://real-debrid.com/ajax/unrestrict.php?link=\(x)")! var request = NSURLRequest(URL: url) if let response = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: NSErrorPointer()) { let jsonDict:Dictionary = NSJSONSerialization.JSONObjectWithData(response, options:NSJSONReadingOptions.MutableContainers, error: NSErrorPointer()) as NSDictionary let error = jsonDict["error"] as Int if error == 0 { var url = jsonDict["main_link"] as String textArea.stringValue = url }else{ var url = jsonDict["message"] as String textArea.stringValue = url } } } }else{ var url = NSURL(string: "https://real-debrid.com/ajax/unrestrict.php?link=\(field.stringValue)")! var links:NSString = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: nil)! textArea.stringValue = links } } //MARK: LOGIN func login(){ var username = "YourUsername" // Your RealDebrid Username var password = "<PASSWORD>" // ..and your Password // md5 of the Password let task = NSTask() task.launchPath = "/sbin/md5" task.arguments = ["-s", password] let pipe = NSPipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! var outComp:NSArray = output.componentsSeparatedByString(" ") var md5pass = outComp[3].stringByReplacingOccurrencesOfString("\n", withString: "") // Get Session var login_data:NSString = "user=\(username)&pass=\(<PASSWORD>)" var url = NSURL(string: "https://real-debrid.com/ajax/login.php?\(login_data)")! var request:NSURLRequest = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 1.0) var conn:NSURLConnection = NSURLConnection(request: request , delegate: nil)! } //MARK: DELEGATES func connection(connection: NSURLConnection, didFailWithError error: NSError) { println("FailWithError \(error.description)") } func applicationDidFinishLaunching(aNotification: NSNotification?) { // Login at launch login() } func applicationWillTerminate(aNotification: NSNotification?) { } } <file_sep>/RealDebrid/main.swift // // main.swift // RealDebrid // // Created by Gio on 06/09/14. // Copyright (c) 2014 Gio. All rights reserved. // import Cocoa NSApplicationMain(C_ARGC, C_ARGV) <file_sep>/README.md RealDebrid-Menubar ================== An useful menubar application for OSX. You can quicly unrestrict links as you were on RealDebrid site - First setup your username and password in the project.
40d8eb94d95269586fc701ac978f9f33e078731e
[ "Swift", "Markdown" ]
3
Swift
gio00/RealDebrid-Menubar
5acc394af3a59b52c851796f4f91f5ba66549bb2
feae2dea8405159fb61f296380c1b83bbfe1a77c
refs/heads/master
<repo_name>milgrimwang/fireplace<file_sep>/fireplace/cards/removed/all.py """ Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.buff(self.hero.weapon, "CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Repairs! (Antique Healbot) class GVG_069a: Health = 4 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
57a88211622043b59972bef5b26c359d187b899c
[ "Python" ]
1
Python
milgrimwang/fireplace
42735e792fd39b74a83ea6774bfaa35eaf204546
3f9619796f5c2bd5df84781a6ec0f795f8002595
refs/heads/main
<file_sep>#pragma once #include "heading.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Заголовочный файл библиотеки mystr // // Лабораторной работы №4 // // Вариант №12 // // Разработчик: студент группы 19-ИВТ-3 // // <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса TCharArray (Динамическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// class TCharArray{ protected: //спецификатор protected для доступа к полям из производного класса char *str; //указатель настроку типа char(безразмерный массив) unsigned int SIZE; //размер public: TCharArray(); //конструктор по умолчанию ~TCharArray(); //деструктор char& at(int n); //метод at char& operator[](int n); //перегружденный оператор доступа к элементу массива [] }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса MyString (Динамическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// class MyString : public TCharArray{ public: MyString(); //конструктор по умолчанию // операции сравнения // bool operator == (MyString &str) const; bool operator != (MyString &str) const; bool operator < (MyString &str) const; bool operator > (MyString &str) const; MyString operator + (MyString &str); //конкатенация строк MyString& operator = (const char* otherStr); /*перегруженный оператор присваивания строки MyString массива char*/ MyString& operator = (const MyString& otherStr); //присваивание MyString строки MyString, для конкатенации // дружественный метод для вывода в стандартный поток // friend std::ostream& operator << (std::ostream& os, const MyString& str); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса TCharArray_stat (Статическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// enum{MaxSIZE = 256}; //ограничение на кол-во символов в строке class TCharArray_stat{ protected: //спецификатор для доступа к полям из класса наследника char str[MaxSIZE]; //массив типа char - статическая строка int SIZE; //размер строки public: TCharArray_stat(); //конструктор по умолчанию // пускай дальнеший функциал и не будет использован, но пусть будет // char& at(int n); //метод at() char& operator[](int n); //перегружденный оператор доступа к элементу массива [] }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса MyString_stat (Статическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// class MyString_stat : public TCharArray_stat{ public: MyString_stat(); //конструктор по умолчанию //описывать деструктор бессмысленно, т.к. все поля статичны MyString_stat& operator = (const char* otherStr); //перегруженный оператор присваивания static std::string alignLinesOfMyStr(MyString_stat &str, int width); // // дружественный метод для вывода в стандартный поток // friend std::ostream& operator << (std::ostream& os, const MyString_stat& str); // пускай дальнеший функциал и не будет использован, но пусть будет // bool operator == (MyString_stat &str) const; bool operator != (MyString_stat &str) const; bool operator < (MyString_stat &str) const; bool operator > (MyString_stat &str) const; }; // Функция проверки класса MyString_stat // void MyString_check(); <file_sep>#include "car.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // клиентский код // int main (int argc, char* argv[]){ switch (argc){ //////////////////////////////////////////////////////////////////////////////////////////////////////////// // 2 аргумента // case 2:{ // флаг -h/--help для вывода справки // if(!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")) { PrintFullReferens(04.05, 04.05); exit(0); }; // флаг -strtest для проверки класса MySting // if(!strcmp(argv[1],"-strtest")){ MyString_check(); break; } //Если 2 аргумента, но не 1 из флагов не совпал, то выводим сообщение об ошибке и завершаем работу// PrintErrorFlag(); break; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // 3 аргумента // case 3:{ // флаг -c для создания записей об автомобилях // if (!strcmp(argv[1],"-c")){ std::ofstream res(argv[2], std::ofstream::binary); //открытие и проверка открытия файлового потока для записи CheckFile(res); PrintLogotip(); PrintHat(4, 12); int numberOfLines = GetQuantityOfPoints(); //Ввод кол-ва пунктов для записи Car *arrayOfCar = new Car[numberOfLines]; //создание массива объектов класса и его заполнение PrintWarning(); for(int i = 0; i < numberOfLines; i++){ arrayOfCar[i].SetInfo(); res.write(reinterpret_cast<char*>(&arrayOfCar[i]), sizeof(arrayOfCar[i])); } cout << endl << "\t\t Записи успешно сохранены!" << endl; delete[] arrayOfCar; //освобождение памяти от динамического массива объектов класса res.close(); //закрытие файловго потока записи cout << endl << red << "\t\tЗавершение работы программы!" << reset << endl; break; } // флаг -r для чтения записей из файла // if (!strcmp(argv[1],"-r")) { std::ifstream text(argv[2], std::ifstream::binary);//открытие файла для чтения CheckFile(text); Car car; //чтение и вывод информации через перезапись 1 объекта GetInfoFromFile(car, text); text.close(); //закрытие файлового потока чтения cout << endl << red << "\t\tЗавершение работы программы!" << reset << endl; break; } //Если 3 аргумента, но не 1 из флагов не совпал, то выводим сообщение об ошибке и завершаем работу// PrintErrorFlag(); break; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // 4 аргумента // case 4:{ // флаги -c -n для создания определенного кол-ва записей об автомобилях // if (!strcmp(argv[1],"-c")) { int numberOfLines = GetQuantityOfPoints(argv[2]); //Получение кол-ва пунктов для записи из аргументов запуска std::ofstream res(argv[3]); //открытие и проверка открытия файлового потока для записи CheckFile(res); PrintLogotip(); PrintHat(4, 12); Car *arrayOfCar = new Car[numberOfLines]; //создание массива объектов класса и его заполнение PrintWarning(); for(int i = 0; i < numberOfLines; i++){ arrayOfCar[i].SetInfo(); res.write(reinterpret_cast<char*>(&arrayOfCar[i]), sizeof(arrayOfCar[i])); } cout << endl << "\t\t Записи успешно сохранены!" << endl; res.close(); //закрытие файла cout << endl << red << "\t\tЗавершение работы программы!" << reset << endl; break; } // флаги -r -n для чтениия определенного кол-ва записей из файла // if (!strcmp(argv[1],"-r")) { std::ifstream text(argv[3]); //открытие файла для чтения CheckFile(text); int numberOfLines = GetQuantityOfPoints(argv[2]); //Получение кол-ва пунктов для записи из аргументов запуска Car car; //Чтение и вывод информации из файла через перезапись одного объекта GetInfoFromFile(car, text, numberOfLines); text.close(); //закрытие файла cout << endl << red << "\t\tЗавершение работы программы!" << reset << endl; break; } PrintErrorFlag(); break; } //Если 4 аргумента, но не 1 из флагов не совпал, то выводим сообщение об ошибке и завершаем работу// default:{ PrintShortreferens(); exit(1); break; } } return 0; } <file_sep>#include "mystr.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Файл реализации библиотеки mystr // // Лабораторной работы №4 // // Вариант №12 // // Разработчик: студент группы 19-ИВТ-3 // // <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Реализация методов и конструкторов класса TCharArray(динамическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Конструктор по умолчанию TCharArray // TCharArray::TCharArray():str(nullptr), SIZE(0){}; // Деструктор TCharArray // TCharArray::~TCharArray(){ if(this->str != nullptr){ delete[] this->str; str = nullptr; } } // метод at - безопасный доступ к элементу массива // char& TCharArray::at(int i){ if(this->str == nullptr){ cerr << endl << red << " Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << endl; cerr << " Данная строка нулевой длины и не содержит символов!" << endl; cerr << " Исправте ошибку и попробуйте еще раз!" << reset << endl << endl; exit(1); } if(i<0 || i>= SIZE){ cerr << red << endl << "Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << endl; cout << "Исправте ошибку и попробуйте еще раз!" << reset << endl << endl; exit(1); } return str[i]; } // перегруженный оператор[], тоже с проверкой на безопасность // char& TCharArray::operator[](int i){ if(this->str == nullptr){ cerr << endl << red << " Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << endl; cerr << " Данная строка нулевой длины и не содержит символов!" << endl; cerr << " Исправте ошибку и попробуйте еще раз!" << reset << endl << endl; exit(1); } if(i<0 || i>= SIZE){ cerr << red << endl << "Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << endl; cout << "Исправте ошибку и попробуйте еще раз!" << reset << endl << endl; exit(1); } return str[i]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Реализация методов и конструкторов класса MyString (динамическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Конструктор по умолчанию MyString // MyString::MyString():TCharArray(){}; // Оператор тождественно равно MyString // bool MyString::operator == (MyString &OtherStr) const { if(this->SIZE != OtherStr.SIZE){ return false; } for(int i = 0; i < this->SIZE; i++){ if(this->str[i] != OtherStr.str[i]){ return false; } } return true; }; // Оператор тождественно не равно MyString // bool MyString::operator != (MyString &OtherStr) const { if(this->SIZE != OtherStr.SIZE){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] != OtherStr.str[i]){ return true; } } return false; }; // Оператор меньше MyString // bool MyString::operator < (MyString &OtherStr) const { if(this->SIZE < OtherStr.SIZE){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] < OtherStr.str[i]){ return true; } } return false; }; // Оператор больше MyString // bool MyString::operator > (MyString &OtherStr) const { if(strlen(this->str) > strlen(OtherStr.str)){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] > OtherStr.str[i]){ return true; } } return false; }; // конкатенация строк MyString // MyString MyString::operator + (MyString &OtherStr) { MyString newStr; unsigned int len1 = strlen(this->str); unsigned int len2 = strlen(OtherStr.str); SIZE = len1+len2; newStr.str = new char[SIZE+1]; int i=0; for( ; i < len1; i++){ newStr.str[i] = this->str[i]; } for(int j=0; j < len2; i++, j++){ newStr.str[i] = OtherStr.str[j]; } newStr.str[SIZE] = '\0'; return newStr; } // оператор присваивания MyString // MyString& MyString::operator =(const char* otherStr){ if(str != nullptr){ delete[] this->str; } SIZE = strlen(otherStr); this->str = new char [SIZE+1]; for(int i = 0; i < SIZE; i++){ this->str[i] = otherStr[i]; } this->str[SIZE] = '\0'; return *this; } // оператор присваивания MyString // MyString& MyString::operator =(const MyString& otherStr){ if(str != nullptr){ delete[] this->str; } SIZE = strlen(otherStr.str); this->str = new char [SIZE+1]; for(int i = 0; i < SIZE; i++){ this->str[i] = otherStr.str[i]; } this->str[SIZE] = '\0'; return *this; } // Дружественный метод вывода MyString // std::ostream& operator << (std::ostream& os, const MyString& OtherStr){ int allStr = strlen(OtherStr.str); for(int i = 0; i < allStr; i++){ os << OtherStr.str[i]; } return os; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Реализация методов и конструкторов класса TCharArray_stat(статическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Конструктор по умолчанию TCharArray_stat // TCharArray_stat::TCharArray_stat(){ strcpy(str,""); SIZE = strlen(this->str); }; // метод at() // char& TCharArray_stat::at(int i){ if(i<0 || i>= SIZE){ cerr << red << endl << "Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << endl; cout << "Исправте ошибку и попробуйте еще раз!" << reset << endl << endl; exit(1); } return str[i]; } // перегруженный оператор[], тоже с проверкой на безопасность // char& TCharArray_stat::operator[](int i){ if(i<0 || i>= SIZE){ std::cout << std::endl << " Ошибочный индекс: " << i << "! Выход за пределы массива!!!" << std::endl; std::cout << " Исправте ошибку и попробуйте еще раз!" << std::endl << std::endl; exit(1); } return str[i]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Реализация методов и конструкторов класса MyString_stat(статическая строка) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Конструктор по умолчанию MyString_stat // MyString_stat::MyString_stat():TCharArray_stat(){}; // оператор присваивания MyString_stat // MyString_stat& MyString_stat::operator =(const char* otherStr){ strcpy(this->str, otherStr); return *this; } // Дружественный метод вывода MyString_stat // std::ostream& operator << (std::ostream& os, const MyString_stat& OtherStr){ int allStr = strlen(OtherStr.str); for(int i = 0; i < allStr; i++){ os << OtherStr.str[i]; } return os; }; // Оператор тождественно равно MyString_stat // bool MyString_stat::operator == (MyString_stat &OtherStr) const { if(this->SIZE != OtherStr.SIZE){ return false; } for(int i = 0; i < this->SIZE; i++){ if(this->str[i] != OtherStr.str[i]){ return false; } } return true; }; // Оператор тождественно не равно MyString_stat // bool MyString_stat::operator != (MyString_stat &OtherStr) const { if(this->SIZE != OtherStr.SIZE){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] != OtherStr.str[i]){ return true; } } return false; }; // Оператор меньше MyString_stat // bool MyString_stat::operator < (MyString_stat &OtherStr) const { if(this->SIZE < OtherStr.SIZE){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] < OtherStr.str[i]){ return true; } } return false; }; // Оператор больше MyString_stat // bool MyString_stat::operator > (MyString_stat &OtherStr) const { if(strlen(this->str) > strlen(OtherStr.str)){ return true; } for(int i=0; i < this->SIZE; i++){ if(this->str[i] > OtherStr.str[i]){ return true; } } return false; }; // Функция проверки класса MyString_stat // void MyString_check(){ char buff[256]; cout << endl << "\tКласс MyString - динамическая строка char" << endl; cout << endl << red << "Warning!!!" << reset << " рекомендуемый язык для ввода: " << yellow << "English" << reset << endl << endl; cout << "Введите содержимое 1ой строки: "; cin.get(buff,256); cin.ignore(256, '\n'); MyString str1; str1 = buff; cout << "Введите содержимое 2ой строки: "; cin.get(buff,256); cin.ignore(256, '\n'); MyString str2; str2 = buff; cout << "1ая строка: " << endl << " " << str1 << endl << endl; cout << "2ая строка: " << endl << " " << str2 << endl << endl; cout << "Выберите оператор для проверки: " << std::endl; cout << "\t1 - \"==\"" << std::endl; cout << "\t2 - \"!=\"" << std::endl; cout << "\t3 - \">\"" << std::endl; cout << "\t4 - \"<\"" << std::endl; cout << "\t5 - \"+\"" << std::endl; cout << "\t6 - \"at()\"" << std::endl; cout << "\t7 - \"[]\"" << std::endl; cout << "Ваш выбор: "; int answer; std::cin >> answer; switch(answer){ case 1:{ if(str1 == str2){ std::cout <<" строка №1 равна строке №2" << std::endl; } else{ std::cout <<" строка №1 не равна строке №2" << std::endl; } break; } case 2:{ if(str1 != str2){ std::cout <<" строка №1 не равна строке №2" << std::endl; } else{ std::cout <<" строка №1 равна строке №2" << std::endl; } break; } case 3:{ if(str1 > str2){ std::cout <<" строка №1 больше строки №2" << std::endl; } else{ std::cout <<" строка №1 не больше строки №2" << std::endl; } break; } case 4:{ if(str1 < str2){ std::cout <<" строка №1 меньше строки №2" << std::endl; } else{ std::cout <<" строка №1 не меньше строки №2" << std::endl; } break; } case 5:{ MyString str3; str3 = str1 + str2; std::cout << " Результирующая строка:" << std::endl; std::cout << str3 << std::endl; break; } case 6:{ std::cout << " Выберите номер строки с которой хотите работать: "; int m; std::cin >> m; if(m < 1 || m > 2 ){ cerr << red << "Выбрана неверная строка!" << reset << endl; exit(0); } switch (m) { case 1:{ std::cout << " Введите номер элемента к которому хотите получить доступ(начало отсчета индексов с 1): " << std::endl; int n; std::cin >> n; n -= 1; std::cout << "Выбранный элемент: " << str1.at(n) << std::endl; break; } case 2:{ std::cout << " Введите номер элемента к которому хотите получить доступ(начало отсчета индексов с 1): " << std::endl; int n; std::cin >> n; n -= 1; std::cout << "Выбранный элемент: " << str2.at(n) << std::endl; break; } } break; } case 7:{ std::cout << " Выберите номер строки с которой хотите работать: "; int m; std::cin >> m; if(m < 1 || m > 2 ){ cerr << red << "Выбрана неверная строка!" << reset << endl; exit(0); } switch (m) { case 1:{ std::cout << " Введите номер элемента к которому хотите получить доступ(начало отсчета индексов с 1): " << std::endl; int n; std::cin >> n; n -= 1; std::cout << "Выбранный элемент: " << str1[n] << std::endl; break; } case 2:{ std::cout << " Введите номер элемента к которому хотите получить доступ(начало отсчета индексов с 1): " << std::endl; int n; std::cin >> n; n -= 1; std::cout << "Выбранный элемент: " << str2[n] << std::endl; break; } } break; } } } // статическая функция для выравнивания строк MyString_stat // std::string MyString_stat::alignLinesOfMyStr(MyString_stat &Mystr, int width){ std::string str = Mystr.str; int len = str.length(); if(len > width){return str;}; int diff = width -len; int pad1 = diff/2; int pad2 = diff - pad1; return std::string(pad1,' ') + str + std::string(pad2,' '); };<file_sep>#pragma once #include "mystr.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса Car (записи об автомобилях) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// class Car{ private: MyString_stat mark; //поле для указания марки - статическая строка библиотеки MyString_stat MyString_stat manufacturer; //поле изготовителя - статическая строка библиотеки MyString_stat int yearOfIssue; //поле для указания годы выпуска int mileage; //поле для пробега int price; //поле для цены unsigned int ID; //поле ID для различения одинаковых авто public: Car(); //конструктор по умолчанию //нет смысла описывать деструктор, т. к. все поля объекта класса статические static unsigned int descriptor; //объявим static переменную - дескриптор void SetInfo(); //метод для заполнения полей объекта void PrintInfoConsole(); /* метод для вывода информации об объекте в стандартный поток вывода. Данный метод не вызывается явно в данный метод включен в функции GetInfoFromFile(обе перегрузки), но сам по себе явно нигде не вызывается */ }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Определение функции не являющимися атрибутами, но работающих с объектами класса // void PrintInfoToFile(Car *car, size_t sizeOfarray, std::ofstream &file); //Определение функции для записи инфомарции массива объектов в файл. void GetInfoFromFile(Car &car, std::ifstream &file); //Определение функции для считывания инфомарции обо всех объектах из файла. void GetInfoFromFile(Car &car, std::ifstream &file, int numberOfObj); //Определение функции для определенного кол-ва объектов из файла. <file_sep>#pragma once //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Подключенные библиотеки // #include <iostream> //ввод/вывод #include <cstring> //strlen(),strcpy() #include <fstream> //работа с файловыми потоками #include <iomanip> //форматирование вывода #include <cstdlib> //exit(), atoi() #include <string> //строки string для функции выравнивания вывода в таблицу using std::cin; using std::cout; using std::endl; using std::cerr; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // переменные для смены цвета текста в консоли // const std::string red("\x1B[0;31m"); const std::string yellow("\x1B[1;33m"); const std::string cyan("\x1B[0;36m"); const std::string magenta("\x1B[0;35m"); const std::string reset("\x1B[0m"); const std::string flicker("\x1B[0;5m"); // Функция проверки массива char на содержание только цифр // int CheckInputNumbers(char *str); // Функции для получения кол-ва пунктов таблицы // int GetQuantityOfPoints(); int GetQuantityOfPoints(char *argv); // Функции для проверки открытия файлового потока // void CheckFile(std::ofstream &file); void CheckFile(std::ifstream &file); // Функции для оформления // void PrintLogotip(); //Функция вывода логотипа void PrintHat(const int jubNumber, const int optionNumber); //функция вывода шапки void PrintShortreferens(); //функция вывода краткой справки void PrintFullReferens(const double release, const double update); //функция вывода полной справки void PrintErrorFlag(); //функция для вывода предупреждения при задании неверного флага при запуске void PrintWarning(); //функция для вывода предупреждения во время записи <file_sep>#include "heading.h" ///////////////////////////// Функции для проверки открытия файловых потоков ////////////////////////// void CheckFile(std::ofstream &file){ if(!file.is_open()){ cout << red << endl << "\t\t\tПроизошла ошибка при открытие файлового потока для записи!" << endl << endl; cout << "\t\t\t\tУстраните проблему и перезапустите программу!" << reset << endl; cout << flicker << red << "============================\t\tДосрочное завершение программы... \t===========================" << reset << endl << endl; exit(1); } } void CheckFile(std::ifstream &file){ if(!file.is_open()){ cout << red << endl << "\t\t\tПроизошла ошибка при открытии файлового потока для чтения!" << endl; cout << "\t\t\t\tУстраните проблему и перезапустите программу!" << reset << endl; cout << flicker << red << "============================\t\tДосрочное завершение программы... \t===========================" << reset << endl << endl << endl; exit(1); } } /////////////////// функции проверяющая строку на содержание только цифр /////////////////////////// int CheckInputNumbers(char *str){ size_t len = strlen(str); for (int i = 0; i < len; i++){ if(str[i] < '0' || str[i] > '9'){ return 0; } } return 1; }; //////////////////////////// Получение кол-ва пунктов, если они не указаны во время запуска /////////////////////////////// int GetQuantityOfPoints(){ char numberOfLines[12]; int NumbLines; cout << "\tБыл выбран режим без указания кол-ва пунктов в таблице при запуске программы."; while(true){ cout << endl << flicker << "\t\tУкажите кол-во пунктов в таблице: " << reset; cin.unsetf(std::ios::skipws); std::cin >> numberOfLines; if(cin.good() && atoi(numberOfLines) > 0 && CheckInputNumbers(numberOfLines)){ if(atoi(numberOfLines) > 100){ cout << endl << red << "\t\t\t\t\tПревышен лимит записей!" << reset << endl; cout << "\t\t\t\tВряд ли вам надо так много пунктов :) " << endl; cout << "\t\tCкорее всего такое кол-во пунктов(или более) приведет к ошибке или зависанию системы." << endl << endl; cout << flicker << red << "================\tДосрочное завершение программы... \t================" << reset << endl << endl; exit(1); } NumbLines = atoi(numberOfLines); cin.ignore(10, '\n'); break; } cin.clear(); cout << red << endl << "\t\tНеправильный ввод! Введите корректное число пунктов таблицы." << reset; cin.ignore(10, '\n'); } cout << std::endl; return NumbLines; } /////////////// функция для получения кол-ва пунктов из аргументов при запуске ////////////////// int GetQuantityOfPoints(char *argv){ if(atoi(argv) < 1 || !CheckInputNumbers(argv)){ cout << red << endl << "\t\tБыло задано неверное кол-во пунктов при запуске!" << endl; cout << flicker << red << "================\tДосрочное завершение программы... \t================" << reset << endl << endl; exit(1); } int numberOfLines = std::atoi(argv); return numberOfLines; }; /////////////////// Функция для вывода сообщения о неправильном флаге при запуске /////////////////////// void PrintErrorFlag(){ cout << red << endl << "\t\t\tБыл введен неверный флаг при запуске!" << endl; cout << " Для получении справки о флагах запуска воспользуйтесь справкой: ./lab3 [-h || --help]" << endl; cout << "====================== Досрочное завершение программы... ======================"<< reset << endl << endl; }; //////////////////// Функция для вывода предупреждения при вводе информации о объекте /////////////////////////// void PrintWarning(){ cout << red << " Внимание!!! " << reset << "При вводе Марки/Изготовителя на русском языке, во время вывода таблицы в консоль она может " << magenta << "\"съехать\"" << reset << endl; cout << "\t\t\t\tРекомедуемый язык для ввода: " << cyan << "Английский" << reset << endl << endl; }; /////////////////////////////////// Функции с выводом логотипа, шапки, справок: ////////////////////////////////////// void PrintLogotip() { std::cout << std::endl << red <<"\t**************************************************************************************************"<< std::endl; std::cout << "\t*******" << yellow <<"*************" << red << "************" <<cyan<<"******" <<red << "************************************************************"<< std::endl; std::cout << "\t******" << yellow <<"* *" << red <<"**********" <<cyan<<"*********" <<red << "**********************************************************"<< std::endl; std::cout << "\t*******" << yellow <<"*************" << red << "*********" <<cyan<<"***"<< red<<"*****" <<cyan << "***" << red << "**********************************************************"<< std::endl; std::cout << "\t*******" << yellow <<"*" << cyan << "**********" << yellow <<"*" << red << "**********" <<cyan<<"***" << red << "******************************************************************"<< std::endl; std::cout << "\t*******" << yellow <<"***" << red << "sapog" << yellow <<"****" << red << "***********" <<cyan<<"***" << red << "*****************************************************************"<< std::endl; std::cout << "\t*******" << yellow <<"************" << red << "*************" <<cyan<<"*******" << red<< "********" <<cyan<<"**********"<<red <<"***"<<cyan<<"*******"<<red <<"*****" << cyan << "*********" <<red<<"***"<<cyan<<"*********"<<red<<"*****"<< std::endl; std::cout << "\t********" << yellow <<"**********" << red << "****************" <<cyan<<"*******" << red<< "*****" <<cyan<<"****"<<red<<"****"<<cyan<<"***"<<red <<"***"<<cyan<<"***"<<red <<"***"<<cyan<<"***" <<red <<"***" <<cyan<<"***" <<red << "***"<<cyan<<"***"<<red<<"***"<<cyan<<"***"<<red<<"***"<<cyan<<"***"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"************" << red << "****************" <<cyan<<"*******" << red<< "****" <<cyan<<"****"<<red<<"****"<<cyan<<"***"<<red <<"***"<<cyan<<"***"<<red <<"***"<<cyan<<"***"<<red <<"***" <<cyan<<"***" <<red << "***"<<cyan<<"***"<<red<<"***"<<cyan<<"***"<<red<<"***"<<cyan<<"***"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"************" << red <<"***********"<<cyan<< ""<<red <<"***" <<cyan<<"*******"<< red<< "******"<<cyan<<"****"<<red<<"****"<<cyan<<"***"<<red <<"***"<<cyan<<"*******"<<red <<"*****"<<cyan<<"***"<<red <<"***" <<cyan<<"***" <<red<<"***"<<cyan<<"*********"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"************" << red << "*********" <<cyan<<"**********"<< red<< "********"<<cyan<<"****"<<red<<"****"<<cyan<<"***"<<red <<"***"<<cyan<<"***"<<red <<"*********"<<cyan<<"***"<<red <<"***" <<cyan<<"***" <<red<<"*********"<<cyan<<"***"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"************" << red << "**********" <<cyan<<"********"<< red<< "**********" <<cyan<<"***********"<<red <<"**"<<cyan<<"***"<<red <<"*********" << cyan << "*********" <<red<<"*********"<<cyan<<"***"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"**************"<<red<<"*********"<<yellow<<"*" << red << "**************************************************"<<red<<"***"<<cyan<<"*********"<<red<<"*****"<< std::endl; std::cout << "\t*******" << yellow <<"***********************" << red <<"*******************"<<cyan<< "Программируй светлое будущее!"<<red<<"******"<<cyan<<"*********"<<red<<"*****"<< std::endl; std::cout << "\t********" << cyan <<"******"<< red <<"***"<<cyan<<"************" << red << "*********************************************************************" << std::endl; std::cout << "\t**************************************************************************************************"<< reset << std::endl << std::endl; }; void PrintHat(const int jubNumber, const int optionNumber) { cout << magenta << "\t\t**************************************************************\n" << reset; cout << magenta << "\t\t*" << reset << "************************************************************"<< magenta << "*\n"; cout <<"\t\t*" << reset << "*** Нижегородский государственный технический университет ***" << magenta << "*\n"; cout <<"\t\t*" << reset << "************* Лабораторная работа №"<< jubNumber << " Варинт №" << optionNumber << " ************" << magenta << "*\n"; cout <<"\t\t*" << reset << "************* Выполнил: студент группы 19-IVT-3 ************" << magenta << "*\n"; cout <<"\t\t*" << reset << "******************* <NAME> *******************" << magenta << "*\n"; cout << magenta << "\t\t*" << reset << "************************************************************"<< magenta << "*\n"; cout << magenta << "\t\t**************************************************************\n" << reset; cout << std::endl; }; void PrintShortreferens() { std::cout << red << "========================\tОшибка запуска! \t========================" << reset << std::endl << std::endl; std::cout << "\tРазрабатываемая программа предназначена для хранения массива объектов класса." << std::endl; std::cout << "\tСозданная электронная таблица, массив экземпляров класса сохраняется в бинарном файле." << std::endl; cout << "\tВ ходе выполнения работы был разработан пользовательский класс TCharArrar," << endl; cout << "\tиспользуемый для хранения элементов типа char. В данном классе реализованы" << endl; cout << "\tметод at() для доступа к элементу символьного массива с проверкой корректности" << endl; cout << "\tзначения индекса элемента массива. Кроме того, была перегружена операция[]." << endl; cout << "\tиспользуя класс TCharArray в качестве родительского было был создан производный класс" << endl; cout << "\tMyString, используемый для хранения символьных строк. Для данного класса были" << endl; cout << "\tследующие операции: +, ==, >, <, !=" << endl; std::cout << "\tПоддерживается управление на уровне аргументов командной строки (аргументов запуска)." << std::endl << std::endl; std::cout << "\tДля дополнительной информации введите: " << std::endl; std::cout << "\t ./main [-h || --help]" << std::endl << std::endl; std::cout << "\tДля запуска введите: " << std::endl; std::cout << "\t ./main (<флаг_режима>) ([кол-во_записей]) (путь_к_текстовому_файлу)" << std::endl << std::endl; std::cout << flicker << red << "================\tДосрочное завершение программы... \t================" << reset << std::endl << std::endl; } void PrintFullReferens(const double release, const double update) { std::cout << std::endl << "Разработчик: " << std::endl << std::endl; std::cout << "\tстудент группы 19-IVT-3" << std::endl; std::cout << "\tСапожников Владислав" << std::endl; std::cout << std::endl << "\tдата релиза:" << release <<".20" << std::endl; std::cout << "\tдата последнего обновления:" << update <<".20" << std::endl << std::endl; std::cout << "Функции программы: " << std::endl << std::endl; std::cout << "\tРазрабатываемая программа предназначена для хранения массива объектов класса." << std::endl; std::cout << "\tСозданная электронная таблица, массив экземпляров класса сохраняется в бинарном файле." << std::endl; cout << "\tВ ходе выполнения работы был разработан пользовательский класс TCharArrar," << endl; cout << "\tиспользуемый для хранения элементов типа char. В данном классе реализованы" << endl; cout << "\tметод at() для доступа к элементу символьного массива с проверкой корректности" << endl; cout << "\tзначения индекса элемента массива. Кроме того, была перегружена операция[]." << endl; cout << "\tиспользуя класс TCharArray в качестве родительского было был создан производный класс" << endl; cout << "\tMyString, используемый для хранения символьных строк. Для данного класса были" << endl; cout << "\tследующие операции: +, ==, >, <, !=" << endl; std::cout << "\tПоддерживается управление на уровне аргументов командной строки (аргументов запуска)." << std::endl << std::endl; std::cout << red << " Убедительная просьба запускать программу только в полноэкранном режиме консоли!!" << reset << std::endl; std::cout << red << " Если во время вывода таблица " << magenta << "\"съехала\"" << red << " перезаполните таблицу согласно её размерсноти." << reset << std::endl; std::cout << std::endl <<"Для запуска введите: " << std::endl << std::endl; std::cout << "\t ./main (<флаг_режима>) ([кол-во_записей]) (<путь_к_текстовому_файлу>)" << std::endl << std::endl; std::cout << std::endl << "Флаги:" << std::endl << std::endl; std::cout << "\t-с - запуск программы в режиме создания электронной таблицы записей" << std::endl; std::cout << "\t-r - запуск программы в режиме чтения содержимого текстового файла" << std::endl; std::cout << std::endl << "Системные требования: " <<std::endl << std::endl; std::cout <<"\tОперационная система: windows, linux, MacOS" << std::endl; std::cout <<"\tЦентральный процессор: Pentium 4 2.5 GHz (одноядерный) и выше" << std::endl; std::cout <<"\tОбъём RAM: 20Kб непрерывной свободной памяти и выше" << std::endl; std::cout << std::endl << "Контанктная информация: (указаны не существующие данные)" << std::endl << std::endl; std::cout << "\t телефон: 8-800-555-35-35 " << std::endl; std::cout << "\t e-male: <EMAIL>" << std::endl << std::endl; } <file_sep>НГТУ им Р.Е. Алексеева ИРИТ кафедра Вычислительные Системы и Технологии Дисциплина: Программирование Преподаватель: <NAME>. Лабораторная работа №4 Наследование, перегрузка операций Вариант №12 Текста задания: Согласно заданию, составить алгоритм и написать программу на языке С++. Программа компилируется и запускается под управлением ОС Linux. В случае если студент разрабатывает программу, работающую под управлением операционной системы MS Windows, необходимо обеспечить максимальную переносимость кода. То есть не использовать не стандартные Microsoft-расширения языка С++, привязанные к среде разработки MS Visual Studio. Разработанная программа должна содержать встроенную справочную информации, описывающую правила использования, цель назначения и информацию о разработчике. Аргументы запуска программа должна обрабатывать согласно рекомендациям POSIX. Создать пользовательский класс TCharArray (массив), используемый для хранения элементов типа char. В данном классе должен быть реализован метод at для доступа к элементу символьного массива с проверкой корректности значения индекса элемента массива. Кроме того, необходимо перегрузить операцию [ ] для доступа к элементам массива. Используя класс TCharArray в качестве родительского, создать производный от него пользовательский класс String, используемый для хранения символьных строк. Для данного класса перегрузить следующие операции: ‘+’, ‘==’, ‘>’, ‘<’, ‘!=’ Разрабатываемая программа предназначена для хранения массива экземпляров класса. Перечень атрибут класса (членов-данных) определяется исходя их задания во второй лабораторной работе. Созданная программа должна поддерживать управление на уровне аргументов командной строки (аргументов запуска). Поддерживаемые опции запуска: --help либо -h - запуск программы в режиме получения справки. После вывода справочной информации программа завершает работу. -с [N] [file_name] - запуск программы в режиме создания электронной таблицы записей, N – количество записей, file_name – имя бинарного файла, в котором будет сохранен массив (таблица) записей. -r [N] [file_name] - запуск программы в режиме чтения содержимого бинарного файла file_name, на экран должны быть выведены не более N записей. Следует учесть, что реальное количество записей в файле может не совпадать с заданным значением N. Если заданный файл окажется пуст, либо по какой-либо причине программа не сможет его открыть, должно быть выдано соответствующее сообщение. В случае, если программа будет запущена с неопределенными разработчиком аргументами, программа должна выдать соответствующее сообщение и вывести минимальную справку о корректных аргументах запуска. Это так же касается случая, когда программа запускается без аргументов. Иерархия классов, которую необходимо реализовать Родительский класс: Легковые автомобили Производные класы: Марка | Год выпуска | Пробег | Изготовитель | Цена <file_sep>#include "car.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Объявление методов и конструкторов класса Car (записи об автомобилях) // //////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int Car::descriptor = 0; //инициализация статической переменной // Реализация вынесенного конструктора по умолчанию // Car::Car(){ yearOfIssue = 0; mileage = 0; price = 0; descriptor++; //при создании объекта увеличиваем счетчик дескриптора ID = descriptor; //в поле ID записываем значение дескриптора } // Метод SetInfo для заполнения полей объекта класса // void Car::SetInfo(){ char Mark[256]; char Manufacturer[256]; char Year[11]; char Mileage[11]; char Price[10]; cout << "---------------------------------------------- Автомобиль №" << ID << " ----------------------------------------------" << endl; cout << " Введите марку: "; //ввод марки автомобиля cin.get(Mark,256); mark = Mark; cin.ignore(256, '\n'); cout << " Введите изготовителя: "; //ввод марки автомобиля cin.get(Manufacturer,256); manufacturer = Manufacturer; cin.ignore(256, '\n'); while(true){ cout << " Введите год выпуска: "; //ввод года выпуска с проверкой на корректность cin >> Year; if(cin.good() && CheckInputNumbers(Year) && (atoi(Year) > 1900 && atoi(Year) < 2021)){ yearOfIssue = atoi(Year); cin.ignore(10, '\n'); break; } cin.clear(); cerr << red << endl << "\t\tГод введен неверно!" << reset << endl; cin.ignore(10, '\n'); } while(true){ cout << " Введите пробег(только целое кол-во км): "; //ввод года выпуска с проверкой на корректность cin >> Mileage; if(cin.good() && CheckInputNumbers(Mileage) && atoi(Mileage) >= 0){ mileage = atoi(Mileage); cin.ignore(10, '\n'); break; } cin.clear(); cerr << red << endl << "\t\tПробег введен неверно!" << reset << endl; cin.ignore(10, '\n'); } while(true){ cout << " Введите цену (в рублях без копеек): "; //ввод стоимости автомобиля с проверкой на корректность cin >> Price; if(cin.good() && CheckInputNumbers(Price) && atoi(Price) > 0){ price = atoi(Price); cin.ignore(10, '\n'); break; } cin.clear(); cerr << red << endl << "\t\tЦена введена неверное!" << reset << endl; cin.ignore(10, '\n'); } } // Метод PrintInfoConsole для вывода инф-ии об объекта класса в консоль // void Car::PrintInfoConsole(){ cout << "-------------------------------------------------------- Автомобиль №" << ID << " ------------------------------------------------------------------------------------------" << std::endl; cout << "| \tМарка: " << MyString_stat::alignLinesOfMyStr(mark, 15); cout << "| \tГод выпуска: " << yearOfIssue << " "; cout << "| \tПробег(км): " << std::setw(8) << mileage <<" "; cout << "| \tИзготовитель: " << MyString_stat::alignLinesOfMyStr(manufacturer,15); cout << "| \tЦена: " << std::setw(8) << price; cout << "| \tID: " << std::setw(3) << ID << " | " << endl; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Функции которые не являются атрибутами класса, но работают с его объектами // // Функция для записи инф-ии об объекте класса в бинарный файл // void PrintInfoToFile(Car *car, size_t sizeOfarray, std::ofstream &file){ for(int i=0; i < sizeOfarray; i++){ file.write(reinterpret_cast<char*>(&car), sizeof(*car)); } }; // Функция чтения и вывода инф-ии обо всех объектах из бинарного файла // void GetInfoFromFile(Car &car, std::ifstream &file){ file.seekg(0, std::ios::end); int endposition = file.tellg(); int counter = endposition / sizeof(car); if(counter == 0){ cout << red << endl << "\t\t\t\tЧитаемый файл пуст!!!" << reset << endl; cout << red << "====================== Досрочное завершение программы... ======================" << reset << endl << endl; exit(1); } PrintLogotip(); PrintHat(4, 12); cout << " \tЕсли во время вывода таблица " << magenta << "\"съехала\"" << reset << ", то перезаполните таблицу согласно её размерам." << reset << endl << endl; cout << endl << "\t\t\tВсего автомобилей в таблице: " << magenta << counter << reset << endl << endl; int position; for(int i=0; i < counter; i++){ position = (i)*sizeof(car); file.seekg(position); file.read(reinterpret_cast<char*>(&car), sizeof(car)); car.PrintInfoConsole(); } cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl; } // Функция чтения и вывода инф-ии об определенном кол-ве объектов из бинарного файла // void GetInfoFromFile(Car &car, std::ifstream &file, int numberOfObj){ file.seekg(0, std::ios::end); int endposition = file.tellg(); int counter = endposition / sizeof(car); if(counter == 0){ cout << red << endl << "\t\t\t\tЧитаемый файл пуст!!!" << reset << endl; cout << red << "====================== Досрочное завершение программы... ======================" << reset << endl << endl; exit(1); } if(numberOfObj > counter){ cout << red << endl << "\t\t\tВ файле нет указанного кол-ва пунктов!" << reset << endl; cout << "\t\t\t Кол-во пунктов в файле: " << counter << endl; cout << red << "======================== Досрочное завершение программы... ========================" << reset << endl << endl; exit(2); } if(numberOfObj < 1){ cout << red << "\t\t\tВведено неверное кол-во пунктов для чтения!" << reset << endl << endl; cout << flicker << red << "======================== Досрочное завершение программы... ========================"<< reset << endl << endl; exit(2); } PrintLogotip(); PrintHat(4, 12); cout << " Если во время вывода таблица " << magenta << "\"съехала\"" << red << ", то перезаполните таблицу её размерсноти согласно размерам." << reset << endl << endl; cout << endl << "\t\t\tВсего автомобилей в таблице: " << magenta << counter << reset << endl << endl; int position; for(int i=0; i < numberOfObj; i++){ position = (i)*sizeof(car); file.seekg(position); file.read(reinterpret_cast<char*>(&car), sizeof(car)); car.PrintInfoConsole(); } cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
c4892d665f8df5a1782821f6c32d1a8d0ea910a7
[ "Markdown", "C++" ]
8
C++
MzNizh570/programming-1-course-2-semester-work-4
a80e3a119d8dec01d2a7f550889e30075842d5c6
56a340ab2c3f4618322986dd8bce9c8bdc17a736
refs/heads/master
<repo_name>dariogf/SeqtrimNext<file_sep>/lib/seqtrimnext/actions/action_user_contaminant.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute Plugin1 # Inherit: Plugin ######################################################## class ActionUserContaminant < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =false end def apply_decoration(char) return char.yellow end end <file_sep>/bin/join_ilumina_paired.rb #!/usr/bin/env ruby require 'scbi_fastq' VERBOSE=false if !(ARGV.count==3 or ARGV.count==5) puts "Usage: #{$0} paired1 paired2 output_base_name [paired1_tag paired2_tag]" exit end p1_path=ARGV[0] p2_path=ARGV[1] output_base_name=ARGV[2] paired1_tag='/1' paired2_tag='/2' if (ARGV.count==5) paired1_tag=ARGV[3] paired2_tag=ARGV[4] end PAIRED1_TAG_RE=/#{Regexp.quote(paired1_tag)}$/ PAIRED2_TAG_RE=/#{Regexp.quote(paired2_tag)}$/ if !File.exists?(p1_path) puts "File #{p1_path} doesn't exists" exit end if !File.exists?(p2_path) puts "File #{p2_path} doesn't exists" exit end def read_to_file(file) res ={} f_file = FastqFile.new(file,'r',:sanger, true) f_file.each do |n,f,q,c| res[n.gsub(PAIRED2_TAG_RE,'')]=[f,q,c] if ((f_file.num_seqs%10000) == 0) puts "Loading: #{f_file.num_seqs}" end end f_file.close return res end p1 = FastqFile.new(p1_path,'r',:sanger, true) # p2 = FastqFile.new(p2_path,'r',:sanger, true) p2 = read_to_file(p2_path) puts "Sequences from #{p2_path} loaded. Total: #{p2.count}" normal_out = FastqFile.new(output_base_name+'_normal.fastq','w',:sanger, true) paired_out = FastqFile.new(output_base_name+'_all_paired.fastq','w',:sanger, true) paired1_out = FastqFile.new(output_base_name+'_paired1.fastq','w',:sanger, true) paired2_out = FastqFile.new(output_base_name+'_paired2.fastq','w',:sanger, true) p1.each do |n1,f1,q1,c1| n1.gsub!(PAIRED1_TAG_RE,'') puts "Find #{n1}" if VERBOSE seq_in_p2=p2[n1] # p2.find{|e| e[0]==n1} if seq_in_p2 n2=n1 f2,q2,c2=seq_in_p2 puts " ===> PAIRED #{n2}" if VERBOSE paired_out.write_seq(n1+paired1_tag,f1,q1,c1) paired1_out.write_seq(n1+paired1_tag,f1,q1,c1) paired_out.write_seq(n2+paired2_tag,f2,q2,c2) paired2_out.write_seq(n2+paired2_tag,f2,q2,c2) p2.delete(n2) else puts " ===> NOT PAIRED #{n1}" if VERBOSE normal_out.write_seq(n1+paired1_tag,f1,q1,c1) end if ((p1.num_seqs%10000) == 0) puts p1.num_seqs end end # remaining at p2 goes to normal_out p2.each do |seq_in_p2,v| n2=seq_in_p2 f2,q2,c2=v normal_out.write_seq(n2+paired2_tag,f2,q2,c2) end p1.close # p2.close normal_out.close paired_out.close paired1_out.close paired2_out.close <file_sep>/lib/seqtrimnext/utils/extract_samples.rb require "fasta_reader.rb" ###################################### # Author:: <NAME> # Extract ramdom sequences until "num_seqs" # Inherit:: FastaReader ###################################### class ExtractSamples < FastaReader attr_accessor :num_seqs def initialize(file_name) @num_seqs = 0 super(file_name) end # override begin processing def on_begin_process() $LOG.info " Begin Extract Samples" @fich = File.open("results/Sample.txt",'w') @max = 1000 end # override processing sequence def on_process_sequence(seq_name,seq_fasta) ra_seq = Kernel.rand if ((@num_seqs < @max) and (ra_seq>0.5)) #if cond is successful then, choose a part from this sequence #calculate the part from the sequence width = (Kernel.rand * 50 ) + 300 ra_part1 = Kernel.rand * (seq_fasta.length-width) ra_part2 = ra_part1 + width sub_seq_fasta = seq_fasta.slice(ra_part1,ra_part2) @fich.puts "#{seq_name} " @fich.puts "#{sub_seq_fasta} " @num_seqs += 1 end end #override end processing def on_end_process() $LOG.info "All Samples have been extracted" @fich.close end end<file_sep>/lib/seqtrimnext/classes/list_db.rb #List all entries in a DB, by name # #list all DB names if db is ALL class ListDb def initialize(path,db) filename=File.join(path,'formatted',db) if File.exists?(filename) f = File.open(filename) f.grep(/^>(.*)$/) do |line| puts $1 end f.close else puts "File #{filename} doesn't exists" puts '' puts "Available databases:" puts '-'*20 d=Dir.glob(File.join(path,'formatted','*.fasta')) d.entries.map{|e| puts File.basename(e)} # cmd= "grep '^>' #{File.join(path,'formatted',db+'.fasta')}" # system(cmd) end end def self.list_databases(path) res = [] if File.exists?(path) d=Dir.glob(File.join(path,'formatted','*.fasta')) res = d.entries.map{|e| File.basename(e)} end return res end end <file_sep>/lib/seqtrimnext/plugins/plugin_short_insert.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginShortInserted # Inherit: Plugin ######################################################## class PluginShortInsert < Plugin def cut_by(items,sub_inserts) delete=false # puts " eee1 #{sub_inserts.inspect} item #{items.inspect}" # puts " eee1 #{sub_inserts.join('-')}" items.each do |item| sub_inserts.each do |sub_i| if ((item.start_pos<=sub_i[0]) && (item.end_pos>=sub_i[1])) # if not exists any subinsert delete=true elsif ((item.end_pos>=sub_i[0]) && (item.end_pos+1<=sub_i[1])) # if exists an subinsert between the item one and the end of subinsert sub_inserts.push [item.end_pos+1,sub_i[1]] # mark subinsert after the item delete=true # puts " !!!! 1 #{sub_inserts.inspect}" if ((item.start_pos-1>=sub_i[0])) # if exists an subinsert between the start of the subinsert and the item sub_inserts.push [sub_i[0],item.start_pos-1] # mark subinsert before the item delete=true # puts " !!!! 2-1 #{sub_inserts.inspect}" end elsif ((item.start_pos-1>=sub_i[0]) && (item.start_pos<=sub_i[1])) # if exists an subinsert between the start of the subinsert and the item sub_inserts.push [sub_i[0],item.start_pos-1,] # mark subinsert before the item delete=true # puts " !!!! 2-2 #{sub_inserts.inspect}" end # sub_inserts.delete [sub_i[0],sub_i[1]] and delete=false and puts " DELETEEE ___________ #{delete}" if delete if delete sub_inserts.delete [sub_i[0],sub_i[1]] delete=false # puts " DELETEEE ___________ #{delete} #{[sub_i[0] , sub_i[1]] }" end # puts " eee2 #{sub_inserts.join(',')}" end #each sub_insert end #each low_qual end #select the best subinsert, when there is not a linker def select_the_best(sub_inserts) insert_size = 0 insert = nil sub_inserts.each do |sub_i| if (insert_size<(sub_i[1]-sub_i[0]+1)) insert_size = (sub_i[1]-sub_i[0]+1) insert=sub_i end end sub_inserts=[] sub_inserts.push insert if !insert.nil? # puts " subinsert #{sub_inserts.join(' ')}" return sub_inserts end def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking if insert of sequence has enought size" # puts "inserto #{seq.insert_start}, #{seq.insert_end} size #{seq.seq_fasta.size}" if (seq.seq_fasta.size > 0) # para acciones que no tienen activado el cortar, se las corta aquí sub_inserts=[] sub_inserts.push [ seq.insert_start, seq.insert_end] low_quals=seq.get_actions(ActionLowQuality) # puts "low qual size #{low_quals.size}" cut_by(low_quals,sub_inserts) # puts '?' + sub_inserts.join('?') if sub_inserts.empty? p_beg,p_end = 0,-1 # position from an empty insert else sub_inserts=select_the_best(sub_inserts) #vemos el tamaño del inserto actual # puts " antes current_insert #{seq.seq_fasta.length}" # p_beg,p_end = seq.current_insert # p_beg,p_end = seq.insert_bounds p_beg,p_end = sub_inserts[0][0],sub_inserts[0][1] # insert positions # puts " p_beg p_end #{p_beg} #{p_end}" # puts " despues current_insert #{p_beg} #{p_end}" size_min_insert = @params.get_param('min_insert_size_trimmed').to_i end else p_beg,p_end = 0,-1 # position from an empty insert # puts " p_beg p_end #{p_beg} #{p_end} size= #{p_end-p_beg+1}" end # puts "INSERTO:"+seq.seq_fasta actions=[] # puts " in PLUGIN SHORT INSERT previous to add action #{p_beg} #{p_end}" if p_end-p_beg+1 <= 0 type = "ActionEmptyInsert" # puts " in PLUGIN EMPTY previous to add action #{p_beg} #{p_end}" # a = seq.add_action(p_beg,p_end,type) a=seq.new_action(0,0,type) actions.push a add_stats('short_inserts',0) # puts "1 p_beg p_end #{p_beg} #{p_end}" seq.seq_rejected=true seq.seq_rejected_by_message='empty insert' elsif ((p_end-p_beg+1)<size_min_insert) type = "ActionShortInsert" a_beg,a_end = p_beg-seq.insert_start, p_end-seq.insert_start # puts " in PLUGIN SHORT previous to add action" # a = seq.add_action(p_beg,p_end,type) a=seq.new_action(a_beg,a_end,type) actions.push a add_stats('short_inserts',a_end-a_beg+1) # puts "2 p_beg p_end #{p_beg} #{p_end}" seq.seq_rejected=true seq.seq_rejected_by_message='short insert' else type= "ActionInsert" # a=seq.add_action(p_beg,p_end,type) a_beg,a_end = sub_inserts[0][0]-seq.insert_start, sub_inserts[0][1]-seq.insert_start a=seq.new_action(a_beg,a_end,type) actions.push a add_stats('inserts',a_end-a_beg+1) # puts "3 p_beg p_end #{p_beg} #{p_end}" end seq.add_actions(actions) end #Begins the plugin1's execution to warn if the inserted is so short def execute_no_cut_quality(seq) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking if insert of sequence has enought size" #vemos el tamaño del inserto actual # puts " antes current_insert #{seq.seq_fasta.length}" # p_beg,p_end = seq.current_insert p_beg,p_end = seq.insert_bounds # puts " despues current_insert #{p_beg} #{p_end}" size_min_insert = @params.get_param('min_insert_size_trimmed').to_i # puts "INSERTO:"+seq.seq_fasta actions=[] # puts " in PLUGIN SHORT INSERT previous to add action #{p_beg} #{p_end}" if p_end-p_beg+1 <= 0 type = "ActionEmptyInsert" # puts " in PLUGIN EMPTY previous to add action #{p_beg} #{p_end}" # a = seq.add_action(p_beg,p_end,type) a=seq.new_action(0,0,type) actions.push a elsif ((p_end-p_beg+1)<size_min_insert) type = "ActionShortInsert" # puts " in PLUGIN SHORT previous to add action" # a = seq.add_action(p_beg,p_end,type) a=seq.new_action(0,p_end-p_beg,type) actions.push a else type= "ActionInsert" # a=seq.add_action(p_beg,p_end,type) a=seq.new_action(0,p_end-p_beg,type) actions.push a end seq.add_actions(actions) end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] self.check_param(errors,params,'min_insert_size_trimmed','Integer') # if !params.exists?('genus') # errors.push " The param genus doesn't exist " # end # if !params.exists?('p2') # errors.push " The param p2 doesn't exist" # end return errors end end <file_sep>/bin/create_graphs.rb #!/usr/bin/env ruby require 'stringio' # require 'test/unit' require 'seqtrimnext' require 'json' require 'gnuplot' # ROOT_PATH=File.dirname(File.dirname(__FILE__)) # $: << File.expand_path(File.join(ROOT_PATH,'test')) # $: << File.expand_path(File.join(ROOT_PATH,'classes')) # $: << File.expand_path(File.join(ROOT_PATH,'plugins')) # $: << File.expand_path(File.join(ROOT_PATH,'utils')) if ARGV.empty? puts "Usage: #{$0} stats.json initial_stats.json" exit end d=Dir.glob(File.expand_path(File.join(ROOT_PATH,'plugins','*.rb'))) # puts d.entries # puts "="*20 require 'plugin' # require 'params' d.entries.each do |plugin| require plugin # puts "Requiring #{plugin}" end require 'graph_stats' #load stats r=File.read(ARGV[0]) stats=JSON::parse(r) r2=File.read(ARGV[1]) init_stats=JSON::parse(r2) gs=GraphStats.new(stats,init_stats) puts "Graphs generated" <file_sep>/lib/seqtrimnext/plugins/plugin_indeterminations.rb ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginIndeterminations # Inherit: Plugin ######################################################## require "plugin" require "global_match" class PluginIndeterminations < Plugin def overlap(polys,mi_start,mi_end) # overlap = polys.find{|e| ( mi_start < e['end'])} overlap = polys.find{|e| ( overlapX?(mi_start,mi_end, e['begin'],e['end']) )} # puts " Overlap #{mi_start} #{mi_end} => #{overlap}" return overlap end MAX_RUBBISH = 3 # Begins the pluginFindPolyAt's execution whit the sequence "seq" # Uses the param poly_at_length to look for at least that number of contiguous A's def find_polys(ta,seq,actions) minn = 4 m2 = 1#(minn/2) m4 = (minn/4) r = [-1,0,0] re2 = /((#{ta}{#{m2},})(.{0,3})(#{ta}{#{1},}))/i type='ActionIndetermination' poly_base = 'N' matches = re2.global_match(seq.seq_fasta,3) matches2 = /[^N]N$/.match(seq.seq_fasta) # HASH polys = [] # crear una region poly nuevo poly = {} #i=0 matches.each do |pattern2| #puts pattern2.match[0] m_start = pattern2.match.begin(0)+pattern2.offset m_end = pattern2.match.end(0)+pattern2.offset-1 #puts "MATCH: #{m_start} #{m_end}" # does one exist in polys with overlap? # yes => group it, updated end # no => one new if (e=overlap(polys,m_start,m_end)) e['end'] = m_end e['found'] = seq.seq_fasta.slice(e['begin'],e['end']-e['begin']+1) else poly={} poly['begin'] = m_start poly['end'] = m_end # the next pos to pattern's end poly['found'] = seq.seq_fasta.slice(poly['begin'],poly['end']-poly['begin']+1) polys.push poly end end poly_size=0 polys.each do |poly| #puts "NEW POLY: #{poly.to_json}" if poly_near_end(poly['end'],seq.seq_fasta) # near right side #puts "near end" a = seq.new_action(poly['begin'],poly['end'],type) a.right_action=true actions.push a poly_size=poly['end']-poly['begin']+1 add_stats('size',poly_size) else #puts "far of end" if check_poly_length(poly['begin'],poly['end']) and (check_poly_percent(poly,poly_base)) #puts "ok" a = seq.new_action(poly['begin'],poly['end'],type) a.right_action=true actions.push a if @params.get_param('middle_indetermination_rejects').to_s=='true' seq.seq_rejected=true seq.seq_rejected_by_message='Indeterminations in middle of sequence' end poly_size=poly['end']-poly['begin']+1 add_stats('size',poly_size) end end end end def check_poly_length(poly_start,poly_end) #puts "poly_length: #{1+(poly_end-poly_start)} nt" return (1+(poly_end-poly_start)) >= @params.get_param('poly_n_length').to_i end def check_poly_percent(poly,poly_base) # count Ts en poly['found'] s=poly['found'] ta_count = s.count(poly_base.downcase+poly_base.upcase) #puts "poly_percent: #{(ta_count.to_f/s.size.to_f)*100}%" res=((ta_count.to_f/s.size.to_f)*100 >= @params.get_param('poly_n_percent').to_i) return res end def poly_near_end(pos,seq_fasta) max_to_end = @params.get_param('poly_n_max_to_end').to_i res = (pos>=(seq_fasta.length-max_to_end)) end def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: removing indeterminations N+" actions=[] # find simple indeterminations at the beginning of sequence match=seq.seq_fasta.match(/^[nN]+/) if !match.nil? found=match[0].length a = seq.new_action(0,found-1,'ActionIndetermination') actions.push a #Add actions seq.add_actions(actions) actions=[] add_stats('indetermination_size',found) end # find simple indeterminations at end of sequence match=seq.seq_fasta.match(/[nN]+$/) if !match.nil? found=match[0].length a = seq.new_action(seq.seq_fasta.length-found,seq.seq_fasta.length,'ActionIndetermination') a.right_action=true actions.push a #Add actions seq.add_actions(actions) actions=[] add_stats('indetermination_size',found) end find_polys('[N]',seq,actions) seq.add_actions(actions) end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Minimum number of Ns within the sequence to be rejected by having an internal segment of indeterminations. Indeterminations at the end of the sequence will be removed regardless of their size and without rejecting the sequence' default_value = 15 params.check_param(errors,'poly_n_length','Integer',default_value,comment) comment='Minimum percent of Ns in a segment to be considered a valid indetermination' default_value = 80 params.check_param(errors,'poly_n_percent','Integer',default_value,comment) comment='Maximum distance to the end of the sequence to be considered an internal segment' default_value = 15 params.check_param(errors,'poly_n_max_to_end','Integer',default_value,comment) comment='Rejects sequences with indeterminations in the middle' default_value = 'true' params.check_param(errors,'middle_indetermination_rejects','String',default_value,comment) return errors end end <file_sep>/bin/resume_clusters.rb #!/usr/bin/env ruby require 'json' if ARGV.count != 2 puts "#{$0} cluster.fasta.clstr COUNT" exit end path=ARGV.shift list_max=ARGV.shift.to_i # puts path h={} last_line = '' f=File.open(path) f.each do |line| if line =~ />Cluster/ if !last_line.empty? if last_line =~ /^([\d]+)\s[^>]*>([^\s]*)\.\.\.\s/ # puts $1 h[$2]=$1.to_i+1 end end end last_line=line end f.close # puts "30 most repeated sequences:" list_max.times do ma=h.max_by{|k,v| v} if ma puts ma.join(' => ') h.delete(ma[0]) end end # puts h.sort.to_json<file_sep>/lib/seqtrimnext/classes/make_blast_db.rb class MakeBlastDb def initialize(dir) @db_folder = dir @status_folder = File.join(@db_folder,'status_info') @formatted_folder = File.join(@db_folder,'formatted') update_dbs end def catFasta(path_start,path_end) $LOG.debug("Cat of #{path_start}") # system("cat #{path_start} > #{path_end}") system("cat /dev/null > #{path_end}") system("for i in `find #{path_start} -type f ! -name '.*'`; do echo cat of $i; cat $i >> #{path_end}; echo \"\n\" >> #{path_end}; done") end def dirEmpty?(path_db) folder2=Dir.open("#{path_db}") ignore = ['.','..','.DS_Store'] res = folder2.entries - ignore return res.empty? end def merge_db_files(path_db, db_name, formatted_folder) if !dirEmpty?(path_db) #hay que hacer el cat solo cuando cambian los ficheros que hay en subfolder1 formatted_file = File.join(formatted_folder, db_name+'.fasta') catFasta(File.join(path_db),formatted_file) end end def self.format_db(path_db, db_name, formatted_folder) #hay que hacer el cat solo cuando cambian los ficheros que hay en subfolder1 formatted_file = File.join(formatted_folder, db_name+'.fasta') cmd = "makeblastdb -in #{formatted_file} -parse_seqids -dbtype nucl >> logs/formatdb.log" system(cmd) $LOG.info(cmd) end #--------------------------------------------------------------------------------------------------- # Check if files for DataBase have been updated, and only when that has happened, makeblastdb will run # Consideres the next directories structure: # # @dir is the main directory # @dir/folder0 is the directoy where will be storaged the DB created/updated # @dir/folder0/subfolder1 is where are storaged all the fasta files of the type subfolder1 # @dir/update is where register the log for each subfolder1, to check if DB has been updated #--------------------------------------------------------------------------------------------------- def update_dbs FileUtils.mkdir_p(@status_folder) FileUtils.mkdir_p(@formatted_folder) ignore_folders=['.','..','status_info','formatted'] $LOG.info("Checking Blast databases at #{@db_folder} for updates") dbs_folder=Dir.open(@db_folder) #if all file_update.entries is in folder1.entries then cat db/* > DB , make blast, guardar ls nuevo dbs_folder.entries.each do |db_name| db_folder=File.join(@db_folder,db_name) if (!ignore_folders.include?(db_name) and File.directory?(db_folder)) #puts "Checking #{db_name} in #{db_folder}" #path_db = File.join(@dir,db_folder) # set status files new_status_file = File.join(@status_folder,'new_'+db_name+'.txt') old_status_file = File.join(@status_folder,'old_'+db_name+'.txt') cmd = "ls -lR #{db_folder} > #{new_status_file}" $LOG.debug(cmd) # list new status tu new_status_file # system("ls -lR #{File.join(db_folder,'*')} > #{new_status_file}") system(cmd) # if new and old statuses files changed, then reformat if (!(File.exists?(old_status_file)) || !system("diff -q #{new_status_file} #{old_status_file} > /dev/null ") || !File.exists?(File.join(@formatted_folder,db_name+'.fasta'))) $LOG.info("Database #{db_name} modified. Merging and formatting") merge_db_files(db_folder,db_name,@formatted_folder) MakeBlastDb.format_db(db_folder,db_name,@formatted_folder) # rename new_status_file to replace the old one system("mv #{new_status_file} #{old_status_file}") end end end #end folder1.entries end end <file_sep>/lib/seqtrimnext/classes/extract_stats.rb ###################################### # Author:: <NAME> # Extract stats like mean of sequence's length ###################################### # $: << '/Users/dariogf/progs/ruby/gems/scbi_plot/lib' # $: << '/Users/dariogf/progs/ruby/gems/scbi_math/lib' require 'scbi_plot' require "scbi_math" class ExtractStats def initialize(sequence_readers,params) @sequence_lengths = [] #array of sequences lengths @length_frequency = [] #number of sequences of each size (frequency) @keys={} #found keys @params = params @use_qual=sequence_readers.first.with_qual? # @params.get_param('use_qual') @totalnt=0 @qv=[] @sequence_lengths_stats, @length_frequency_stats, @quality_stats = extract_stats_from_sequences(sequence_readers) set_params_and_results plot_lengths plot_qualities if @use_qual print_global_stats end def extract_stats_from_sequences(sequence_readers) sequence_readers.each do |sequence_reader| sequence_reader.each do |name_seq,fasta_seq,qual| l = fasta_seq.length @totalnt+=l #save all lengths @sequence_lengths.push l # add key value add_key(fasta_seq[0..3].upcase) # add fasta length @length_frequency[fasta_seq.length] = (@length_frequency[fasta_seq.length] || 1 ) + 1 #extract qv values extract_qv_from_sequence(qual) if @use_qual # print some progress info if (sequence_reader.num_seqs % 10000==0) puts "Calculating stats: #{sequence_reader.num_seqs}" end end end length_stats = ScbiNArray.to_na(@sequence_lengths) length_frequency_stats = ScbiNArray.to_na(@length_frequency.map{|e| e || 0}) quality_stats = ScbiNArray.to_na(@qv) if @use_qual return [length_stats, length_frequency_stats, quality_stats] end def plot_lengths ## PLOT RESULTS if !File.exists?('graphs') Dir.mkdir('graphs') end x = [] y = [] x =(0..@length_frequency.length-1).collect.to_a y = @length_frequency.map{|e| e || 0} file_name = 'graphs/size_stats.png' p=ScbiPlot::Lines.new(file_name,'Stats of sequence sizes') p.x_label= "Sequence length" p.y_label= "Number of sequences" p.add_x(x) p.add_series('sizes', y,'impulses',2) p.add_vertical_line('Mode',@length_frequency_stats.fat_mode[0]) p.add_vertical_line('L',@params.get_param('min_sequence_size_raw').to_i) p.add_vertical_line('H',@params.get_param('max_sequence_size_raw').to_i) p.do_graph end def plot_qualities if !File.exists?('graphs') Dir.mkdir('graphs') end minimum_qual_value = @params.get_param('min_quality').to_i # get qualities values x=[] y=[] min=[] max=[] qual_limit=[] @qv.each_with_index do |e,i| x << i y << (e[:tot]/e[:nseq]) min << (e[:min]) max << (e[:max]) qual_limit << minimum_qual_value # puts "#{i}: #{e[:tot]/e[:nseq]}" end # make plot of qualities file_name='graphs/qualities.png' p=ScbiPlot::Lines.new(file_name,'Stats of sequence qualities') p.x_label= "Nucleotide position" p.y_label= "Quality value" p.add_x(x) p.add_series('mean', y) p.add_series('min', min) p.add_series('max', max) p.add_series('qual limit',qual_limit) p.do_graph end def add_qv(q,i) if !@qv[i] @qv[i]={:max => 0, :min => 1000000, :nseq => 0, :tot => 0} end # set max @qv[i][:tot]+=q @qv[i][:nseq]+=1 @qv[i][:min]=[@qv[i][:min],q].min @qv[i][:max]=[@qv[i][:max],q].max end def extract_qv_from_sequence(qual) qual.each_with_index do |q,i| add_qv(q,i) end end def add_key(key) if @keys[key].nil? @keys[key]=1 else @keys[key]+=1 end end def get_max_key return @keys.keys.sort{|e1,e2| @keys[e1]<=>@keys[e2]}.last end def set_params_and_results if @sequence_lengths.empty? puts "No sequences has been sucessfully readed " return end # set limiting parameters @params.set_param('sequencing_key',get_max_key) @params.set_param('all_found_keys',@keys.to_json) # sequence min size, is taken directly from params file # max sequence limit is calculated here if (@sequence_lengths_stats.variance_coefficient<=10) or (@params.get_param('accept_very_long_sequences').to_s=='true') # high size limit is calculated with stats @params.set_param('max_sequence_size_raw',(@sequence_lengths_stats.max+10).to_i) else # > 10 % # high size limit is calculated with stats @params.set_param('max_sequence_size_raw',(@sequence_lengths_stats.mean+2*@sequence_lengths_stats.stddev).to_i) end end def print_global_stats if !@sequence_lengths_stats.nil? initial_stats={} initial_stats[:sequence_count] = @sequence_lengths_stats.size initial_stats[:smallest_sequence_size] = @sequence_lengths_stats.min initial_stats[:biggest_sequence_size] = @sequence_lengths_stats.max initial_stats[:min_sequence_size_raw]=@params.get_param('min_sequence_size_raw') initial_stats[:max_sequence_size_raw]=@params.get_param('max_sequence_size_raw') initial_stats[:coefficient_of_variance]=@sequence_lengths_stats.variance_coefficient initial_stats[:nucleotide_count]=@totalnt initial_stats[:mode_of_sizes]=@length_frequency_stats.fat_mode[0] initial_stats[:mean_of_sequence_sizes]=@sequence_lengths_stats.mean initial_stats[:qv]=@qv initial_stats[:used_key]=get_max_key initial_stats[:all_keys]=@keys File.open(File.join(OUTPUT_PATH,'initial_stats.json'),'w') do |f| f.puts JSON.pretty_generate(initial_stats) end puts "_"*10+ " STATISTICS "+"_"*10 puts "Total sequence count: #{@sequence_lengths_stats.size}" puts "Smallest sequence: #{initial_stats[:smallest_sequence_size]} nt" puts "Biggest sequence : #{initial_stats[:biggest_sequence_size]} nt" puts "Mean of sequence sizes : #{initial_stats[:mean_of_sequence_sizes]} nt" puts "Mode of sequence sizes : #{initial_stats[:mode_of_sizes]} nt" puts "Low size limit : #{initial_stats[:min_sequence_size_raw]} nt" puts "High size limit : #{initial_stats[:max_sequence_size_raw]} nt" puts "Coefficient of variation: #{initial_stats[:coefficient_of_variance]} %" puts "Total nucleotide count: #{initial_stats[:nucleotide_count]} nt" puts "_"*30 end end end <file_sep>/lib/seqtrimnext/actions/action_left_primer.rb require "seqtrim_action" class ActionLeftPrimer < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =true end def apply_decoration(char) return char.blue.underline end end <file_sep>/lib/seqtrimnext/plugins/plugin_mids.rb require "plugin" require 'recover_mid' include RecoverMid ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginMids # Inherit: Plugin ######################################################## class PluginMids < Plugin SIZE_SEARCH_MID=20 MAX_MID_ERRORS = 2 #MIN_MID_SIZE = 7 # very important, don't touch # DB_MID_SIZE = 10 # DONE read formatted db and save the mid sizes def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast = BatchBlast.new("-db #{@params.get_param('mids_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_mids')} -max_target_seqs 4 ") #get mids $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta[0..SIZE_SEARCH_MID] end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas) # puts blast_table_results.inspect return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for mids into the sequence" # blast_table_results = blast.do_blast(seq.seq_fasta[0..SIZE_SEARCH_MID]) # execute blast to find mids # blast_table_results.inspect actions=[] file_tag='no_MID' key_size=0 mid_size=0 key_already_found=!seq.get_actions(ActionKey).empty? mid_errors=[] #number of MIDs with 1 error, and number of MIDs with 2 errors mid_id=[] #number of MIDs from each type mid_found = false if !blast_query.hits.empty? # mid found # blast_query.hits.sort!{|h1,h2| h1.q_beg <=> h2.q_beg} # puts blast_query.count.to_s + "============== #{blast_query.hits[0].inspect}" # blast_table_results.inspect # select first sorted mid mid=blast_query.hits[0] # find a not reversed mid if mid.reversed blast_query.hits.each do |hit| if !hit.reversed # take the first non-reversed one mid = hit break end end end # puts "DOES THE MID HAVE ENOUGHT SIZE? #{mid.q_end-mid.q_beg+1} >= #{MIN_MID_SIZE}?" mid_size=mid.q_end-mid.q_beg+1 db_mid=@params.get_mid(mid.subject_id) db_mid_size = db_mid.size #get mid's size from DB mid_initial_pos=mid.q_beg-mid.s_beg has_full_key=false if !@params.get_param('sequencing_key').nil? && !@params.get_param('sequencing_key').empty? has_full_key = !seq.seq_fasta.index(@params.get_param('sequencing_key')).nil? end if mid.reversed # discard mid elsif (mid.gaps+mid.mismatches > MAX_MID_ERRORS) # number of ERRORS and GAPs is higher than MAX_MID_ERRORS, # discard mid elsif (mid.q_beg<3) # if found mid starts below 3, then discard it # discard mid elsif (has_full_key && (mid_initial_pos >=6)) # discard mid elsif (!has_full_key && (mid_initial_pos >=7)) # discard mid elsif (mid_size >= db_mid_size-1) # MID found and MID's size is enought, THEN create key and mid key_beg,key_end=[0,mid.q_beg-1] key_size=mid.q_beg # Create an ActionKey before the ActionMid if key_size>0 && !key_already_found a = seq.new_action(key_beg,key_end,"ActionKey") # adds the actionKey to the sequence actions.push a end #Create an ActionMid a = seq.new_action(mid.q_beg,mid.q_end,"ActionMid") # adds the ActionMids to the sequence a.message = mid.subject_id a.tag_id = mid.subject_id file_tag = mid.subject_id actions.push a mid_found = true elsif (mid_size >= db_mid_size-3) # To recover a MID it must start or end in one edge if (mid.s_beg==0) || (mid.s_end==mid_size) new_q_beg, new_q_end, recovered_size,recovered_mid = recover_mid(mid, db_mid, seq.seq_fasta[0..SIZE_SEARCH_MID]) $LOG.debug("Recover mid: #{recovered_mid} valid (#{recovered_size} >= #{10-1}) = #{recovered_size>=10-1}, #{seq.seq_fasta[new_q_beg..new_q_end]}") if recovered_size >= db_mid_size-1 mid_size = recovered_size # if MID found and MID's size is enought to recover a MID, THEN create an action key and mid key_beg,key_end=[0,new_q_beg-1] key_size=new_q_beg $LOG.debug "RECOVER OUTPUT: #{new_q_beg} #{new_q_end} #{recovered_size}" # if key_size > 4(or max_size_key) then seq.seq_rejected # Create an ActionKey before the ActionMid if key_size>0 && !key_already_found a = seq.new_action(key_beg,key_end,"ActionKey") # adds the actionKey to the sequence actions.push a end #Create an ActionMid to a recovered mid a = seq.new_action(new_q_beg,new_q_end,"ActionMid") # adds the ActionMids to the sequence a.message = "Recovered " + mid.subject_id a.tag_id = mid.subject_id file_tag = mid.subject_id actions.push a add_stats('recovered_mid_id',mid.subject_id) mid_found = true end end end end if !mid_found && !key_already_found # MID not found, take only the key mid_size=0 key_beg,key_end=[0,3] key_size=4 a = seq.new_action(key_beg,key_end,'ActionKey') # adds the actionKey to the sequence actions.push a end #Add actions seq.add_actions(actions) seq.add_file_tag(1, file_tag, :both) # seq.add_file_tag(2,'sequence') if (mid_found) # MID without errors add_stats('mid_id',mid.subject_id) add_stats('mid_id','total') #save MID count by ID add_stats(mid.subject_id,mid_size) if (mid.gaps+mid.mismatches > 0) add_stats('mid_with_errors',mid.gaps+mid.mismatches) end end if !key_already_found add_stats('key_size',key_size) add_stats('mid_size',mid_size) end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for MIDs' default_value = 1e-10 params.check_param(errors,'blast_evalue_mids','Float',default_value,comment) comment='Minimum required identity (%) for a reliable MID' default_value = 95 params.check_param(errors,'blast_percent_mids','Integer',default_value,comment) comment='Path for MID database' default_value = File.join($FORMATTED_DB_PATH,'mids.fasta') params.check_param(errors,'mids_db','DB',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/plugins/plugin_linker.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLinker # Inherit: Plugin ######################################################## class PluginLinker < Plugin MAX_LINKER_ERRORS=2 #------------------------------------------------------------------------- #It's created an ActionInsert or ActionShortInsert before the ActionLinker #Used: in class PluginLinker and PluginMid #------------------------------------------------------------------------- # def add_action_before_linker(p_q_beg,size_insert,actions,seq) # # size_min_insert = @params.get_param('size_min_insert').to_i # if ((p_q_beg>0) && (size_insert>=size_min_insert)) #if linker's positions are right # #It's created an ActionInsert or ActionShortInsert before the ActionLinker # a = seq.new_action(0,p_q_beg-1,"ActionInsert") # adds the ActionInsert to the sequence before adding the actionMid # actions.push a # elsif (p_q_beg>0) #if linker's positions are right and insert's size is short # #It's created an ActionShortInsert before the ActionLinker # a = seq.new_action(0,p_q_beg-1,"ActionShortInsert") # adds the ActionInsert to the sequence before adding the actionMid # actions.push a # end # # end #------------------------------------------------------------------------- #It's created an ActionInsert or ActionShortInsert after the ActionLinker #------------------------------------------------------------------------- # def add_action_after_linker(p_q_end,size_insert,actions,seq) # # size_min_insert = @params.get_param('size_min_insert').to_i # # if ((p_q_end<seq.seq_fasta.size-1) && (size_insert>=size_min_insert) ) #if linker's positions are right # #It's created an ActionInsert after the ActionLinker # a = seq.new_action(p_q_end+1,seq.seq_fasta.size-1,"ActionInsert") # adds the ActionInsert to the sequence before adding the actionMid # # actions.push a # # elsif (p_q_end<seq.seq_fasta.size-1) #if linker's positions are right and insert's size is short # #It's created an ActionInsert after the ActionLinker # a = seq.new_action(p_q_end+1,seq.seq_fasta.size-1,"ActionShortInsert") # adds the ActionInsert to the sequence before adding the actionMid # # actions.push a # end # # end # def sum_quals(a) res = 0 a.map{|e| res+=e} return res end def merge_hits_with_same_qbeg_and_qend(hits) res =[] hits.each do |hit| if !res.find{|h| (h.q_beg==hit.q_beg) && (h.q_end==hit.q_end)} res.push hit end end return res end def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast = BatchBlast.new("-db #{@params.get_param('linkers_db')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_linkers')} -perc_identity #{@params.get_param('blast_percent_linkers')}") #get linkers $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas) # puts blast_table_results.inspect return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for linker into the sequence" # key_beg,key_end=search_key(seq,0,3) if false # blast = BatchBlast.new("-subject #{File.join($FORMATTED_DB_PATH,'linkers.fasta')}",'blastn'," -task blastn -evalue #{@params.get_param('blast_evalue_linkers')} -perc_identity #{@params.get_param('blast_percent_linkers')}") #get linkers # blast = BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'linkers.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_linkers')} -perc_identity #{@params.get_param('blast_percent_linkers')}") #get linkers # # blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to linkers executing over blast #blast_table_results = BlastTableResult.new(res) actions=[] linker_size=0 if (!blast_query.hits.empty?) #linker found linkers = merge_hits_with_same_qbeg_and_qend(blast_query.hits) if linkers.count ==1 linker=linkers.first linker_size=linker.q_end-linker.q_beg+1 if (linker.gaps+linker.mismatches>MAX_LINKER_ERRORS) # number of ERRORS and GAPs is higher than MAX_LINKER_ERRORS, seq.seq_rejected=true seq.seq_rejected_by_message='linker with mismatches' # @stats[:rejected_seqs]={'rejected_seqs_by_errors' => 1} add_stats('rejected','by_linker_errors') add_stats('linker_errors',linker.gaps+linker.mismatches) else #Create an ActionLinker a = seq.new_action(linker.q_beg,linker.q_end,'ActionLinker') # adds the ActionLinker to the sequence a.message = linker.subject_id a.tag_id = linker.subject_id actions.push a # seq.add_file_tag(0, 'paired', :file) add_stats('linker_id',linker.subject_id) add_stats('linker_id','total') end else # multiple linkers found q_begs=[] q_ends=[] linker_count=linkers.count linkers.each do |linker| #puts "*MULTILINKER* #{linker.subject_id[0..40].ljust(40)} #{linker.q_beg.to_s.rjust(6)} #{linker.q_end.to_s.rjust(6)} #{linker.s_beg.to_s.rjust(6)} #{linker.s_end.to_s.rjust(6)}" q_begs.push linker.q_beg q_ends.push linker.q_end end first_linker = linkers.first last_linker = linkers.last a = seq.new_action(q_begs.min,q_ends.max,'ActionMultipleLinker') # adds the ActionLinker to the sequence a.message = "#{linker_count} x #{first_linker.subject_id}" a.tag_id = first_linker.subject_id #determine with part (left or right) has the best quality left_quals = seq.seq_qual[0,q_begs.min] sum_left=sum_quals(left_quals) right_quals = seq.seq_qual[q_ends.max+1..seq.seq_qual.length] sum_right=sum_quals(right_quals) if sum_left>=sum_right a.right_action=true else a.left_action=true end #puts "SUM QUAL LEFT:#{sum_left} count:#{left_quals.length}" #puts "SUM QUAL RIGHT:#{sum_right} count:#{right_quals.length}" actions.push a add_stats('multiple_linker_id',first_linker.subject_id) add_stats('multiple_linker_id','total') add_stats('multiple_linker_count',linker_count) # puts "=== > seq_qual: #{seq.seq_qual.count}" # seq.get_qual_inserts.each do |qi| # puts "==> #{qi.join(' ')}" # end end else # no linker found add_stats('without_linker',linker_size) end if !actions.empty? #Add actions seq.add_actions(actions) end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for linkers in paired-ends' default_value = 1e-10 params.check_param(errors,'blast_evalue_linkers','Float',default_value,comment) comment='Minimum required identity (%) for a reliable linker' default_value = 95 params.check_param(errors,'blast_percent_linkers','Integer',default_value,comment) comment='Path for 454 linkers database' default_value = File.join($FORMATTED_DB_PATH,'linkers.fasta') params.check_param(errors,'linkers_db','DB',default_value,comment) return errors end end <file_sep>/bin/join_big_illumina_paired.sh #!/usr/bin/env bash # Sort two big illumina files corresponding to paired-end experiment and then join common sequences on different files. Sequences not in common goes to a separate file. # cat $1 | awk '{split($0, a, " "); n++; if (n%1==0){printf("%s\t",a[1]);}; printf("%s",$0); if(n%4==0) { printf("\n");} else { printf("\t");} }' # # exit if [ "$#" < 4 ]; then echo "" echo "Use: $0 file1.fastq file2.fastq base_output_name tmp_dir" echo "" exit fi base_name=$3 if [[ -z "$base_name" ]]; then echo "$base_name doesn't exists" exit -1 fi tmp_dir=$4 if [[ -z "$4" ]]; then tmp_dir=`pwd` fi if [[ ! -e "$tmp_dir" ]]; then echo "Tmp dir: $4 doesn't exists" exit -1 fi echo "Using TMPDIR $tmp_dir" f1_path=$1 f2_path=$2 f1_name=`basename $1` f2_name=`basename $2` f1_tmp="$tmp_dir/${f1_name}" f2_tmp="$tmp_dir/${f2_name}" common_names="$tmp_dir/comm.names" only_in_1="$tmp_dir/only_in_1.txt" only_in_2="$tmp_dir/only_in_2.txt" in_both="$tmp_dir/in_both.txt" echo "Starting sorting" if [[ ! -e "$f1_tmp.sorted" ]]; then echo "Sorting $f1_name" cat $f1_path | awk '{split($0, a, " "); sub(/\/1$/,"\t", a[1]); n++; if (n%4==1){printf("%s",a[1]);}; printf("%s",$0); if(n%4==0) { printf("\n");} else { printf("\t");} }' | sort -T $tmp_dir -k1,1 -t $'\t' > $f1_tmp.sorted & fi if [[ ! -e "$f2_tmp.sorted" ]]; then echo "Sorting $f2_name" cat $f2_path | awk '{split($0, a, " "); sub(/\/2$/,"\t", a[1]); n++; if (n%4==1){printf("%s",a[1]);}; printf("%s",$0); if(n%4==0) { printf("\n");} else { printf("\t");} }' | sort -T $tmp_dir -k1,1 -t $'\t' > $f2_tmp.sorted & fi wait echo "Starting name extraction" if [[ ! -e "$f1_tmp.names" ]]; then echo "Extracting names from $f1_tmp.sorted" # cat $1.sorted | cut -f1 | sed 's/\(.*\)\/1$/\1/' > $1.names & cat $f1_tmp.sorted | cut -f1 > $f1_tmp.names & fi if [[ ! -e "$f2_tmp.names" ]]; then echo "Extracting names from $f2_tmp.sorted" cat $f2_tmp.sorted | cut -f1 > $f2_tmp.names & fi wait echo "Starting names comparison" if [[ ! -e "$common_names" ]]; then echo "Making comm file" # diff $1.names $2.names > names.diff comm $f1_tmp.names $f2_tmp.names > $common_names fi echo "Starting names extraction" # grep '^>' names.diff | cut -d ' ' -f2 | awk '{ printf("%s/2\n",$0) }' > only_in_2.txt & # grep '^<' names.diff | cut -d ' ' -f2 | awk '{ printf("%s/1\n",$0) }' > only_in_1.txt & grep -P '^[^\t]' $common_names > $only_in_1 & grep -P '^\t[^\t]' $common_names |tr -d "\t" > $only_in_2 & grep -P '^\t\t[^\t]' $common_names |tr -d "\t" > $in_both & wait echo "Num seqs only in 1) $f1_name" wc -l $only_in_1 echo "Num seqs only in 2) $f2_name" wc -l $only_in_2 echo "Num seqs in both $f1_name and $f2_name" wc -l $in_both echo "Starting extracting seqs" join -t $'\t' -1 1 -2 1 $only_in_1 $f1_tmp.sorted |cut -f 2,3,4,5| tr "\t" "\n" > ${base_name}_normal1.fastq & join -t $'\t' -1 1 -2 1 $only_in_2 $f2_tmp.sorted |cut -f 2,3,4,5| tr "\t" "\n" > ${base_name}_normal2.fastq & join -t $'\t' -1 1 -2 1 $in_both $f1_tmp.sorted |cut -f 2,3,4,5| tr "\t" "\n" > ${base_name}_paired1.fastq & join -t $'\t' -1 1 -2 1 $in_both $f2_tmp.sorted |cut -f 2,3,4,5| tr "\t" "\n" > ${base_name}_paired2.fastq & wait rm $f1_tmp.names rm $f2_tmp.names rm $f1_tmp.sorted rm $f2_tmp.sorted rm $only_in_2 rm $only_in_1 rm $in_both rm $common_names<file_sep>/lib/seqtrimnext/plugins/plugin_extract_inserts.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLinker # Inherit: Plugin ######################################################## class PluginExtractInserts < Plugin #------------------------------------------------------ # check if part of a vector is in a linker #------------------------------------------------------ def part_left_overlap?(r1_start,r1_end,r2_start,r2_end) return ((r1_start<r2_start) and (r1_end<=r2_end) and (r1_end>=r2_start) ) #overlap on the left of r2 end def part_right_overlap?(r1_start,r1_end,r2_start,r2_end) return ((r1_end>r2_end) and (r1_start<=r2_end) and (r1_start>=r2_start) ) #overlap on the right of r2 end # crea una action insert controlado si el inserto es corto o no y actualiza las stats según sea inserto izquierdo o derecho def add_action_inserts(insert,linker,actions,seq) insert_size = insert[1]-insert[0]+1 min_insert_size = @params.get_param('min_insert_size_paired').to_i if (insert_size >= min_insert_size) if (insert[0]<linker.start_pos) #insert is on the left from the linker add_stats('left_insert_size',insert_size) elsif (insert[0]>linker.end_pos) #insert is on the right from the linker add_stats('right_insert_size',insert_size) end a = seq.new_action(insert[0]-seq.insert_start,insert[1]-seq.insert_start,"ActionInsert") # adds the ActionInsert to the sequence actions.push a else if (insert[0]<linker.start_pos) #insert is on the left from the linker # @stats[:short_left_insert_size]={insert_size => 1} add_stats('short_left_insert_size',insert_size) elsif (insert[0]>linker.end_pos) #insert is on the right from the linker # @stats[:short_right_insert_size]={insert_size => 1} add_stats('short_right_insert_size',insert_size) end #create an ActionShortInsert before the ActionLinker # adds the ActionInsert to the sequence a = seq.new_action(insert[0]-seq.insert_start,insert[1]-seq.insert_start,"ActionShortInsert") # adds the ActionInsert to the sequence actions.push a end end #------------------------------------------------------------------------- #It's created an ActionInsert or ActionShortInsert before the ActionLinker #Used: in class PluginLinker and PluginMid #------------------------------------------------------------------------- def add_action_before_linker(overlap,actions,seq) # puts "INSERT1: [#{seq.insert_start},#{overlap.start_pos}]" insert_size = overlap.start_pos - seq.insert_start min_insert_size = @params.get_param('min_insert_size_trimmed').to_i # puts "INSERT1: [#{overlap.start_pos},#{seq.insert_start} #{seq.insert_end} seqsize #{seq.seq_fasta.size} insert_size #{insert_size} #{min_insert_size}]" if ((overlap.start_pos>seq.insert_start) && (insert_size >= min_insert_size))#if overlap's positions are right #It's created an ActionInsert or ActionShortInsert before the Actionoverlap # a = seq.new_action(seq.insert_start_last,overlap.start_pos-1-seq.insert_start,"ActionInsert") # adds the ActionInsert to the sequence a = seq.new_action(0,overlap.start_pos-1-seq.insert_start,"ActionInsert") # adds the ActionInsert to the sequence actions.push a # puts " 1---------- Inserto antes del linker en pos #{a.start_pos} #{a.end_pos}" elsif (overlap.start_pos>seq.insert_start) #if overlap's positions are right and insert's size is short # puts " 2---------- #{seq.insert_start},#{overlap.start_pos}-1-#{seq.insert_start}" #It's created an ActionShortInsert before the ActionLinker # a = seq.new_action(seq.insert_start_last-seq.insert_start,overlap.start_pos-1-seq.insert_start,"ActionShortInsert") # adds the ActionInsert to the sequence a = seq.new_action(0,overlap.start_pos-1-seq.insert_start,"ActionShortInsert") # adds the ActionInsert to the sequence actions.push a # puts " 2---------- Inserto corto antes del linker en pos #{a.start_pos} #{a.end_pos}" end @stats[:insert_size_left]={insert_size => 1} end #------------------------------------------------------------------------- #It's created an ActionInsert or ActionShortInsert after the ActionLinker #------------------------------------------------------------------------- def add_action_after_linker(overlap,actions,seq) # puts "INSERT2: [#{overlap.end_pos},#{seq.insert_end}]" insert_size = seq.insert_end-overlap.end_pos min_insert_size = @params.get_param('min_insert_size_trimmed').to_i # puts "INSERT_SIZE2 #{insert_size} > #{min_insert_size}" # puts "INSERT2: [#{overlap.end_pos},#{seq.insert_start} #{seq.insert_end} #{seq.seq_fasta.size} #{seq.seq_fasta_orig.size}]" if ((overlap.end_pos-seq.insert_start < seq.seq_fasta_orig.size-1) && (insert_size>=min_insert_size) ) #if overlap's positions are left #It's created an ActionInsert after the Actionoverlap a = seq.new_action(overlap.end_pos-seq.insert_start+1,seq.seq_fasta.size-1,"ActionInsert") # adds the ActionInsert to the sequence # puts " new after action #{overlap.end_pos} - #{seq.insert_start}" # puts " 1---new insert despues del linker #{a.start_pos} #{a.end_pos} " actions.push a elsif (overlap.end_pos-seq.insert_start<seq.seq_fasta_orig.size-1) #if overlap's positions are right and insert's size is short #It's created an ActionInsert after the ActionLinker a = seq.new_action(overlap.end_pos-seq.insert_start+1,seq.seq_fasta.size-1,"ActionShortInsert") # adds the ActionInsert to the sequence # puts " new after action #{overlap.end_pos} - #{seq.insert_start} +1" # puts "2---new insert short despues del linker #{a.start_pos} #{a.end_pos} " actions.push a end # puts "#{a.start_pos} #{a.end_pos}" if !a.nil? @stats[:insert_size_right]={insert_size => 1} end def split_by(actions,sub_inserts) delete=false # puts " split #{sub_inserts.each{|i| i.join(',')}}" if !sub_inserts.empty? actions.each do |action| sub_inserts.reverse_each do |sub_i| # puts "A: [#{action.start_pos},#{action.end_pos}] cuts [#{sub_i[0]},#{sub_i[1]}] " if ((action.start_pos<=sub_i[0]) && (action.end_pos>=sub_i[1])) # if not exists any subinsert delete=true elsif ((action.end_pos>=sub_i[0]) && (action.end_pos+1<=sub_i[1])) # if exists an subinsert between the action one and the end of subinsert sub_inserts.push [action.end_pos+1,sub_i[1]] # mark subinsert after the action delete=true # puts " !!!! 1" if ((action.start_pos-1>=sub_i[0])) # if exists an subinsert between the start of the subinsert and the action sub_inserts.push [sub_i[0],action.start_pos-1] # mark subinsert before the action delete=true # puts " !!!! 2-1" end elsif ((action.start_pos-1>=sub_i[0]) && (action.start_pos<=sub_i[1])) # if exists an subinsert between the start of the subinsert and the action sub_inserts.push [sub_i[0],action.start_pos-1,] # mark subinsert before the action delete=true # puts " !!!! 2-2" end # sub_inserts.delete [sub_i[0],sub_i[1]] and delete=false and puts " DELETEEE ___________ #{delete}" if delete if delete sub_inserts.delete [sub_i[0],sub_i[1]] delete=false # puts " DELETEEE ___________ #{delete} #{[sub_i[0] , sub_i[1]] }" end # puts " eee #{sub_inserts.join(',')}" end #each sub_insert end #each action end end #select the best subinsert, when there is not a linker def select_the_best(sub_inserts) insert_size = 0 insert = nil sub_inserts.each do |sub_i| if (insert_size<(sub_i[1]-sub_i[0]+1)) insert_size = (sub_i[1]-sub_i[0]+1) insert=sub_i end end sub_inserts=[] sub_inserts.push insert if !insert.nil? # puts " subinsert #{sub_inserts.join(' ')}" return sub_inserts end #select the best subinsert when there is a linker def select_the_best_with_linker(sub_inserts,linker) left_insert_size = 0 right_insert_size = 0 left_insert = nil right_insert = nil sub_inserts.each do |sub_i| #puts "*SBI: "+sub_i.join(',') if (sub_i[0]<linker.start_pos) #if the subinsert is on the left from the linker if (left_insert_size<(sub_i[1]-sub_i[0]+1)) left_insert_size = (sub_i[1]-sub_i[0]+1) left_insert=sub_i # puts " left" end elsif (sub_i[0]>linker.end_pos) #if the subinsert is on the right from the linker if (right_insert_size<(sub_i[1]-sub_i[0]+1)) right_insert_size = (sub_i[1]-sub_i[0]+1) right_insert=sub_i end # puts " right" end end # puts " left #{left_insert} #{left_insert_size} right #{right_insert} #{right_insert_size}" sub_inserts=[] sub_inserts.push left_insert if !left_insert.nil? sub_inserts.push right_insert if !right_insert.nil? # puts " subinsert #{sub_inserts.join(' ')}" #puts "SELECTED SUBINSERTS" # sub_inserts.each do |sub_i| # puts "*SBI: "+sub_i.join(',') # end # return sub_inserts end def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: extract inserts" # puts "INSERTO ANTES LINKER INSERT:"+seq.seq_fasta #look for ActionLinker into the sequence's actions linkers=seq.get_actions(ActionLinker) #look for ActionVectors into the sequence's actions vectors=seq.get_actions(ActionVectors) #look for ActionLowQuality into the sequence's actions low_quals=seq.get_actions(ActionLowQuality) insert_size=0 actions=[] sub_inserts=[] if (linkers.count==1) #linker found linker=linkers[0] # get left insert if linker.start_pos>seq.insert_start sub_inserts.push [ seq.insert_start,linker.start_pos-1 ] end #get right insert if linker.end_pos<seq.insert_end sub_inserts.push [ linker.end_pos+1, seq.insert_end] end # puts '1ST SUBS:' # puts sub_inserts.join("\n") #split sub_inserts by vectors split_by(vectors,sub_inserts) # puts 'SUBS:' # puts sub_inserts.join("\n") #sub_inserts=select_the_best_with_linker(sub_inserts,linker) if not sub_inserts.empty? # split by low qual actions split_by(low_quals,sub_inserts) # puts 'SUBS:' # puts sub_inserts.join("\n") sub_inserts=select_the_best_with_linker(sub_inserts,linker) if not sub_inserts.empty? if sub_inserts.empty? # if is an empty insert a=seq.new_action(0,0,'ActionEmptyInsert') seq.seq_rejected=true seq.seq_rejected_by_message='empty insert' actions.push a end sub_inserts.each do |sub_i| add_action_inserts(sub_i,linker,actions,seq) # ponerlo también abajo para que controle si la accion es de inserto corto o no end else # no linker found => add whole insert sub_inserts.push [ seq.insert_start, seq.insert_end ] split_by(vectors,sub_inserts) #sub_inserts=select_the_best(sub_inserts) if not sub_inserts.empty? split_by(low_quals,sub_inserts) sub_inserts=select_the_best(sub_inserts) if not sub_inserts.empty? # ordena los subinsertos por tamaño # sub_inserts.sort!{|i,j| j[1]-j[0]<=>i[1]-i[0]} if sub_inserts.empty? found_insert_size = 0 # position from an empty insert a=seq.new_action(0,0,'ActionEmptyInsert') # refactorizando codigo seq.seq_rejected=true seq.seq_rejected_by_message='empty insert' else found_insert_size =(sub_inserts[0][1]-sub_inserts[0][0]+1) end if (found_insert_size >= (@params.get_param('min_insert_size_trimmed').to_i)) add_stats('insert_size',found_insert_size) a = seq.new_action(sub_inserts[0][0]-seq.insert_start, sub_inserts[0][1]-seq.insert_start,"ActionInsert") # adds the ActionInsert to the sequence before adding the actionMid elsif (found_insert_size!=0) # if is a short insert add_stats('short_insert_size',found_insert_size) a = seq.new_action(sub_inserts[0][0]-seq.insert_start, sub_inserts[0][1]-seq.insert_start,"ActionShortInsert") # adds the ActionInsert to the sequence before adding the actionMid seq.seq_rejected=true seq.seq_rejected_by_message='short insert' end actions.push a end seq.add_actions(actions) # find inserts to see if it is necessary to reject it if ! seq.seq_rejected inserts=seq.get_actions(ActionInsert) if inserts.empty? seq.seq_rejected=true if seq.get_actions(ActionShortInsert).empty? seq.seq_rejected_by_message='empty insert' else seq.seq_rejected_by_message='short insert' end end end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] # self.check_param(errors,params,'min_insert_size_trimmed','Integer') return errors end def self.plot_setup(stats_value,stats_name,x,y,init_stats,plot) # puts "============== #{stats_name}" # puts stats_name case stats_name when 'insert_size' plot.x_label= "Length" plot.y_label= "Count" plot.x_range="[0:#{init_stats['biggest_sequence_size'].to_i}]" # plot.x_range="[0:200]" plot.add_x(x) plot.add_y(y) plot.do_graph return true else return false end end end <file_sep>/lib/seqtrimnext/plugins/plugin_contaminants.rb require "plugin" require "make_blast_db" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginContaminants # Inherit: Plugin ######################################################## class PluginContaminants < Plugin MAX_TARGETS_SEQS=4 #MAXIMUM NUMBER OF DIFFERENT ALIGNED SEQUENCES TO KEEP FROM BLAST DATABASE def near_to_extrem(c,seq,min_cont_size) max_to_extreme=(min_cont_size/2).to_i return ((c.q_beg-max_to_extreme<0) || (( c.q_end+max_to_extreme)>=seq.seq_fasta.size-1) ) #return if vector is very near to the extremes of insert) end def do_blasts(seqs) # find MIDS with less results than max_target_seqs value # blast = BatchBlast.new("-db #{@params.get_param('contaminants_db')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_contaminants')} -perc_identity #{@params.get_param('blast_percent_contaminants')} -culling_limit 1") #get contaminants -max_target_seqs #{MAX_TARGETS_SEQS} # This message is due to short sequences #Warning: Could not calculate ungapped Karlin-Altschul parameters due to an invalid query sequence or its translation. Please verify the query sequence(s) and/or filtering options # TODO - Culling limit = 2 porque el blast falla con este comando cuando se le pasa cl=1 y dust=no # y una secuencia de baja complejidad como entrada task_template=@params.get_param('blast_task_template_contaminants') extra_params=@params.get_param('blast_extra_params_contaminants') extra_params=extra_params.gsub(/^\"|\"?$/, '') #blast = BatchBlast.new("-db #{@params.get_param('contaminants_db')}",'blastn'," -task blastn -evalue #{@params.get_param('blast_evalue_contaminants')} -perc_identity #{@params.get_param('blast_percent_contaminants')} -culling_limit 1") #get contaminants -max_target_seqs #{MAX_TARGETS_SEQS} blast = BatchBlast.new("-db #{@params.get_param('contaminants_db')}",'blastn'," -task #{task_template} #{extra_params} -evalue #{@params.get_param('blast_evalue_contaminants')} -perc_identity #{@params.get_param('blast_percent_contaminants')} -culling_limit 1") #get contaminants -max_target_seqs #{MAX_TARGETS_SEQS} $LOG.debug('BLAST:'+blast.get_blast_cmd(:table)) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") # $LOG.info('doing blast to:') # $LOG.info('-'*20) # $LOG.info(fastas) # $LOG.info('-'*20) #blast_table_results = blast.do_blast(fastas,:xml) t1=Time.now #blast_table_results = blast.do_blast(fastas,:xml,false) blast_table_results = blast.do_blast(fastas,:table,false) add_plugin_stats('execution_time','blast',Time.now-t1) t1=Time.now #blast_table_results = BlastStreamxmlResult.new(blast_table_results) blast_table_results = BlastTableResult.new(blast_table_results) add_plugin_stats('execution_time','parse',Time.now-t1) # $LOG.info(blast_table_results.inspect) return blast_table_results end # TODO - Contaminants databases grouped by folders # TODO - User can select a set of contaminants folders def exec_seq(seq,blast_query) user_conts=seq.get_actions(ActionUserContaminant) if (!user_conts.nil?) && (!user_conts.empty?) return end #if blast_query.query_def != seq.seq_name if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for contaminants into the sequence" #add_plugin_stats('hsp_count',seq.seq_name,blast_query.hits.count) #blast = BatchBlast.new('-db DB/formatted/contaminants.fasta','blastn',' -task blastn -evalue 1e-10 -perc_identity 95') #get contaminants # blast = BatchBlast.new("-db #{@params.get_param('contaminants_db')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_contaminants')} -perc_identity #{@params.get_param('blast_percent_contaminants')} -culling_limit 1") #get contaminants -max_target_seqs #{MAX_TARGETS_SEQS} # blast_table_results = blast.do_blast(seq.seq_fasta,:xml) #rise seq to contaminants executing over blast #blast_table_results = BlastTableResult.new(res) type = "ActionIsContaminated" contaminants=[] contaminants_ids=[] # blast_table_results.querys.each do |query| #first round to save contaminants without overlap # contaminants_ids.push query.hits.definition if (not contaminants_ids.include?(query.hits.definition)) merge_hits(blast_query.hits,contaminants,contaminants_ids) # end begin contaminants2=contaminants contaminants = [] #second round to save contaminants without overlap merge_hits(contaminants2,contaminants) # DONE describir cada ID contaminante encontradomerge_hits(contaminants2,contaminants,ids_contaminants) end until (contaminants2.count == contaminants.count) actions=[] contaminants_size=0 # @stats[:contaminants_size]={} # @stats['contaminants_size']={} # @stats['rejected_seqs']={} min_cont_size=@params.get_param('min_contam_seq_presence').to_i contaminants.each do |c| contaminants_size=c.q_end - c.q_beg + 1 #if ( (@params.get_param('genus')!=c.subject_id.split('_')[1]) && valid_genus=@params.get_param('genus').empty? || !c.definition.upcase.index(@params.get_param('genus').upcase) if (valid_genus) && (contaminants_size>=min_cont_size) #( (min_cont_size<=contaminants_size) || (near_to_extrem(c,seq,min_cont_size)) ) ) if !seq.range_inside_action_type?(c.q_beg,c.q_end,ActionVectors) # puts "DIFFERENT SPECIE #{specie} ,#{hit.subject_id.split('_')[1].to_s}" a = seq.new_action(c.q_beg,c.q_end,type) # adds the correspondent action to the sequence a.message = c.definition a.found_definition = contaminants_ids # save the contaminants definitions, each separately actions.push a contaminants_size=c.q_end-c.q_beg+1 # if @stats[:contaminants_size][contaminants_size].nil? # @stats[:contaminants_size][contaminants_size] = 0 # end # # @stats[:contaminants_size][contaminants_size] += 1 add_stats('contaminants_size',contaminants_size) contaminants_ids.each do |c| add_stats('contaminants_ids',c) end end else $LOG.debug('Contaminant ignored due to genus match: '+c.definition) end end reject=@params.get_param('contaminants_reject') # cond_if=false # cond_if=true if (not actions.empty? ) && (reject=='true') # # puts "Before check SEQ_REJECTED= TRUE (reject= .#{reject}. #{reject.class}&& not actions empty= #{not actions.empty?} ) == #{cond_if} >>> " if ((not actions.empty? ) && (reject.to_s=='true')) #reject sequence # puts "SEQ_REJECTED= TRUE >>> " seq.seq_rejected=true seq.seq_rejected_by_message='contaminated' # @stats[:rejected_seqs]={'rejected_seqs_by_contaminants' => 1} add_stats('rejected','contaminated') end seq.add_actions(actions) end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for contaminations' default_value = 1e-10 params.check_param(errors,'blast_evalue_contaminants','Float',default_value,comment) comment='Minimum required identity (%) for a reliable contamination' default_value = 85 params.check_param(errors,'blast_percent_contaminants','Integer',default_value,comment) comment='Minimum hit size (nt) for considering a true contamination' default_value = 40 params.check_param(errors,'min_contam_seq_presence','Integer',default_value,comment) comment='Genus of input data: contaminations belonging to this genus will be ignored' default_value = '' params.check_param(errors,'genus','String',default_value,comment) comment='Is a contamination considered a source of sequence rejection? (setting to false will only trim contaminated sequences instead of rejecting the complete read)' default_value = 'true' params.check_param(errors,'contaminants_reject','String',default_value,comment) comment='Path for contaminants database' default_value = File.join($FORMATTED_DB_PATH,'contaminants.fasta') params.check_param(errors,'contaminants_db','DB',default_value,comment) comment='Blast task template for contaminations' #default_value = 'blastn' default_value = 'megablast' params.check_param(errors,'blast_task_template_contaminants','String',default_value,comment) comment='Blast extra params for contaminations' #default_value = '' default_value = '"-word_size=22"' params.check_param(errors,'blast_extra_params_contaminants','String',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/plugins/plugin_user_contaminants.rb require "plugin" require "make_blast_db" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute Pluginclassify # Inherit: Plugin ######################################################## class PluginUserContaminants < Plugin MAX_TARGETS_SEQS=4 #MAXIMUM NUMBER OF DIFFERENT ALIGNED SEQUENCES TO KEEP FROM BLAST DATABASE def near_to_extrem(c,seq,min_cont_size) max_to_extreme=(min_cont_size/2).to_i return ((c.q_beg-max_to_extreme<0) || (( c.q_end+max_to_extreme)>=seq.seq_fasta.size-1) ) #return if vector is very near to the extremes of insert) end def sum_hits_by_id(hits) res={} hits.each do |c| hit_size=c.q_end - c.q_beg + 1 res[c.definition] = (res[c.definition]||0)+hit_size end puts res.to_json return res end def can_execute? return !@params.get_param('user_contaminant_db').empty? end def do_blasts(seqs) # TODO - Culling limit = 2 porque el blast falla con este comando cuando se le pasa cl=1 y dust=no # y una secuencia de baja complejidad como entrada task_template=@params.get_param('blast_task_template_user_contaminants') extra_params=@params.get_param('blast_extra_params_user_contaminants') extra_params=extra_params.gsub(/^\"|\"?$/, '') blast = BatchBlast.new("-db #{@params.get_param('user_contaminant_db')}",'blastn'," -task #{task_template} #{extra_params} -evalue #{@params.get_param('blast_evalue_user_contaminant')} -perc_identity #{@params.get_param('blast_percent_user_contaminant')} -culling_limit 1") #get classify -max_target_seqs #{MAX_TARGETS_SEQS} $LOG.debug('BLAST:'+blast.get_blast_cmd(:table)) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end #blast_table_results = blast.do_blast(fastas,:xml) t1=Time.now blast_table_results = blast.do_blast(fastas,:table,false) add_plugin_stats('execution_time','blast',Time.now-t1) t1=Time.now #blast_table_results = BlastStreamxmlResult.new(blast_table_results) blast_table_results = BlastTableResult.new(blast_table_results) add_plugin_stats('execution_time','parse',Time.now-t1) return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for classify into the sequence" type = "ActionUserContaminant" classify={} contaminants=[] merge_hits(blast_query.hits,contaminants,nil,false) begin contaminants2=contaminants contaminants = [] #second round to save contaminants without overlap merge_hits(contaminants2,contaminants,nil,false) end until (contaminants2.count == contaminants.count) contaminants.sort {|c1,c2| (c1.q_end - c1.q_beg + 1)<=>(c2.q_end - c2.q_beg + 1)} # classify=sum_hits_by_id(contaminants.hits) actions=[] # classify_size=0 min_cont_size=@params.get_param('min_user_contaminant_size').to_i # biggest_classify = contaminants.sort {|c1,c2| c1[1]<=>c2[1]} if !contaminants.empty? # definition,classify_size = biggest_classify.last biggest_contaminant=contaminants.last hit_size=(biggest_contaminant.q_end - biggest_contaminant.q_beg + 1) a = seq.new_action(biggest_contaminant.q_beg,biggest_contaminant.q_end,type) # adds the correspondent action to the sequence a.message = biggest_contaminant.definition seq.add_comment("Contaminated: #{biggest_contaminant.definition}") a.tag_id = biggest_contaminant.definition.gsub(' ','_') # a.found_definition = c.definition # save the classify definitions, each separately #save to this file seq.add_file_tag(0, 'with_user_contaminant', :both, 10) actions.push a add_stats('user_contaminant_size',hit_size) add_stats('user_contaminant_ids',biggest_contaminant.definition) seq.add_actions(actions) end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for contaminations' default_value = 1e-10 params.check_param(errors,'blast_evalue_user_contaminant','Float',default_value,comment) comment='Minimum required identity (%) for a reliable user contaminant match' default_value = 85 params.check_param(errors,'blast_percent_user_contaminant','Integer',default_value,comment) comment='Minimum hit size (nt) for considering for user contaminant' default_value = 30 # era 40 params.check_param(errors,'min_user_contaminant_size','Integer',default_value,comment) comment='Path for user contaminant database' default_value = "" #File.join($FORMATTED_DB_PATH,'user_contaminant.fasta') params.check_param(errors,'user_contaminant_db','DB',default_value,comment) comment='Blast task template for user contaminations' #default_value = 'blastn' default_value = 'megablast' params.check_param(errors,'blast_task_template_user_contaminants','String',default_value,comment) comment='Blast extra params for user contaminations' #default_value = '' default_value = '"-word_size=22"' params.check_param(errors,'blast_extra_params_user_contaminants','String',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/plugins/plugin_size_trim.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginSizeTrim # Inherit: Plugin # Trims the output sequences to a fixed size ######################################################## class PluginSizeTrim < Plugin def exec_seq(seq,blast_query) #$LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking if insert of sequence has enought size" # puts "inserto #{seq.insert_start}, #{seq.insert_end} size #{seq.seq_fasta.size}" tr_size = @params.get_param('trim_size_file_'+(seq.order_in_tuple+1).to_s) trim_size=-1 if tr_size trim_size=tr_size.to_i end # $WORKER_LOG.info "TRIM_SIZE=#{trim_size}, #{seq.order_in_tuple+1}" if trim_size>0 if (seq.seq_fasta.size > trim_size) a_beg,a_end = trim_size, seq.seq_fasta.size # position from an empty insert actions=[] type = "ActionTrim" a=seq.new_action(a_beg,a_end,type) actions.push a add_stats('trim_sizes',a_end-a_beg+1) seq.add_actions(actions) end end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] self.check_param(errors,params,'trim_size_file_1','Integer',-1) self.check_param(errors,params,'trim_size_file_2','Integer',-1) return errors end end <file_sep>/lib/seqtrimnext/actions/action_is_contaminated.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute Plugin1 # Inherit: Plugin ######################################################## class ActionIsContaminated < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =true end # def apply_to(seq) # # # seq.seq_fasta = seq.seq_fasta.slice(start_pos,end_pos) # $LOG.debug " Applying #{self.class} to seq #{seq.seq_name} . BEGIN: #{@start_pos} END: #{@end_pos} " # # end def apply_decoration(char) return char.red end end <file_sep>/lib/seqtrimnext/plugins/plugin_low_high_size.rb ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLowHighSize # # Inherit: Plugin ######################################################## require "plugin" class PluginLowHighSize < Plugin # Begins the plugin_low_high_size's execution with the sequence "seq" def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking low or high size of the sequence" min_size = @params.get_param('min_sequence_size_raw').to_i #min_size is: mean - 2dev max_size = @params.get_param('max_sequence_size_raw').to_i #max_size is: mean + 2dev #add_stats('rejected_seqs',seq.seq_fasta.length) actions=[] if ((max_size>0 && (seq.seq_fasta.length>max_size)) || (seq.seq_fasta.length<min_size)) #if length of sequence is out of (-2dev,2dev) $LOG.debug "#{seq.seq_name} rejected by size #{seq.seq_fasta.length} " type='ActionLowHighSize' # seq.add_action(0,seq.seq_fasta.length,type) a = seq.new_action(0,seq.seq_fasta.length,type) a.message = 'low or high size' seq.seq_rejected = true seq.seq_rejected_by_message= 'size out of limits' add_stats('rejected_seqs',seq.seq_fasta.length) actions.push a seq.add_actions(actions) end end ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Minimum size for a raw input sequence to be analysed (shorter reads are directly rejected without further analysis)' default_value = 40 params.check_param(errors,'min_sequence_size_raw','Integer',default_value,comment) #self.check_param(errors,params,'max_sequence_size_raw','Integer') return errors end end <file_sep>/lib/seqtrimnext/classes/sequence_with_action.rb require "action_manager.rb" require "sequence" require 'term/ansicolor' include Term::ANSIColor ###################################### # Author:: <NAME> # This class create the structure to storage the actions associated to a sequence. # It allows to add action, and to write at file the actions for every sequence # Inherit:: Sequence ###################################### class SequenceWithAction < Sequence SHOW_QUAL = false SHOW_FINAL_INSERTS=true attr_accessor :actions,:seq_fasta_orig, :seq_qual_orig ,:insert_start , :insert_end, :stats , :insert_start_last , :insert_end_last, :order_in_tuple, :tuple_id, :tuple_size # Creates an instance with the structure to storage the actions associated to a sequence def initialize(seq_name,seq_fasta,seq_qual, seq_comment = '') super @actions = [] @seq_fasta_orig = seq_fasta @seq_fasta = seq_fasta @seq_qual_orig = seq_qual @seq_qual = seq_qual @insert_start = 0 @insert_end = seq_fasta.length-1 @stats={} @comments=[] @file_tags=[] # for paired ends @order_in_tuple=0 @tuple_id=0 @tuple_size=0 @file_tag_tuple_priority=0 end def add_comment(comment) @comments.push comment end def get_comment_line return ([@seq_rejected_by_message]+@comments).compact.join(';') end # add a file tag to sequence def add_file_tag(tag_level, tag_value, tag_type, priority=0) @file_tags<< {:level => tag_level, :name => tag_value, :type=> tag_type} @file_tag_tuple_priority=priority end # join file tags into a path def get_file_tag_path levels=@file_tags.map{|e| e[:level]}.uniq dirpath = [] levels.sort.each do |level| # select names from all that are not files level_path = @file_tags.select{|e| ((e[:level]==level) && (e[:type]!=:file))}.map{|tag| tag[:name]} dirpath << level_path.join('_') if !level_path.empty? end filepath = [] levels.sort.each do |level| # select names from all that are not files level_path = @file_tags.select{|e| ((e[:level]==level) && (e[:type]!=:dir))}.map{|tag| tag[:name]} filepath << level_path.join('_') if !level_path.empty? end filename=filepath.join('_') dirname=File.join(dirpath) # puts "#{dirname}, #{filename}" return [dirname,filename,@file_tag_tuple_priority] end # Adds a new action to the sequence def add_action(a) $LOG.debug("Adding action #{a.type} to #{seq_name}") @actions.push a a.apply_to(self) return a end # Adds a new action to the sequence def new_action(start_pos,end_pos,action_type) a = ActionManager.new_action(start_pos,end_pos,action_type) return a end # def left_action(seq_fasta,start_pos,end_pos) # return ((start_pos - 0 ) < (seq_fasta.length - end_pos)) # end # # def right_action(seq_fasta,start_pos,end_pos) # return !left_action(seq_fasta,start_pos,end_pos) # end # Adds a set of actions to the sequence, update the positon of the cut sequence. # # Version with the parameters left_action and rigth action # # TODO - Nuevo algoritmo de corte de seqs. # 1 - Ordenar seqs con cut=true en izq y der y por posición de ends o begs # 2 - Obtener izq.ends.max y der.begs.min # 3 - El corte lo definen esos min y max def add_actions(actions) if !actions.empty? start_pos=0 end_pos = 0 cut = false max_end_pos = 0 p_beg = @insert_start p_end = @seq_fasta.length-1+@insert_start # p_end = @seq_fasta.length-1 # puts "ADDING ACTIONS" # puts "=" * 50 # puts 'actions ' + actions.inspect # para cada accion ordenada por start_pos actions.sort{|e,f| e.start_pos<=>f.start_pos}.each do |action| # puts ' current ' + action.inspect # puts " UUUUUUUUUU1 " # puts "vect in pos #{action.start_pos} #{action.end_pos}" if (action.type=='ActionVectors') # puts " UUUUUUUUUU2 " # puts "ADD ACTION:",action.to_json # añadir el inicio del inserto si es necesario if action.start_pos !=0 or action.end_pos != 0 action.start_pos+=@insert_start action.end_pos+=@insert_start end # guardar accion a = add_action(action) start_pos= a.start_pos end_pos=a.end_pos # si hay que cortar y es accion izquierda # if (a.cut && ( left_action(@seq_fasta,start_pos-p_beg,end_pos) || # action is left in insert if (a.cut && a.left_action?(@seq_fasta.length)) # if (a.cut && ( a.left_action==true || # ( a.right_action==false && (left_action(@seq_fasta,start_pos-p_beg,end_pos-p_beg) || # action is left in insert # (start_pos==p_beg)) ))) # action is right in insert but it's continous to the before action # # puts "in seq w action left act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" # puts "Cut left: #{a.inspect}" if (end_pos+1) > p_beg p_beg=end_pos+1 end a.left_action=true cut=true # puts "in seq w action left act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" # elsif (a.cut && right_action(@seq_fasta,start_pos-p_beg,end_pos)) # action is rigth in insert elsif (a.cut && a.right_action?(@seq_fasta.length)) # puts "Cut right: #{a.inspect}" # elsif (a.cut && (a.right_action==true || right_action(@seq_fasta,start_pos-p_beg,end_pos-p_beg))) # action is rigth in insert # puts "in seq w action right act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" if (start_pos-1) < p_end p_end = start_pos-1 end a.right_action=true cut=true # puts "in seq w action right act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" elsif !a.cut # puts "NO cut action" if a.right_action?(@seq_fasta.length) a.right_action=true else a.left_action = true end end # puts "p_beg: #{p_beg} , p_end: #{p_end}" end if cut then @seq_fasta = @seq_fasta_orig[p_beg..p_end] # puts @seq_fasta @seq_qual = @seq_qual_orig[p_beg..p_end] if !@seq_qual_orig.nil? # puts "in seq w action1 #{@insert_start} #{@insert_end}" @insert_start = p_beg size_cut_right = @insert_end - p_end @insert_end -= size_cut_right # puts "in seq w action2 #{@insert_start} #{@insert_end}" end end end # Adds a set of actions to the sequence, update the positon of the cut sequence. # # Version without the parameters left_action and rigth action # def add_actions_no_left_rigth_parameters(actions) if !actions.empty? start_pos=0 end_pos = 0 cut = false max_end_pos = 0 p_beg = @insert_start p_end = @seq_fasta.length-1+@insert_start # p_end = @seq_fasta.length-1 # puts 'actions ' + actions.inspect # para cada accion ordenada por start_pos actions.sort!{|e,f| e.start_pos<=>f.start_pos}.each do |action| # puts ' current ' + action.inspect # puts " UUUUUUUUUU1 " # puts "vect in pos #{action.start_pos} #{action.end_pos}" if (action.type=='ActionVectors') # puts " UUUUUUUUUU2 " # puts "ADD ACTION:",action.to_json # añadir el inicio del inserto si es necesario if action.start_pos !=0 or action.end_pos != 0 action.start_pos+=@insert_start action.end_pos+=@insert_start end # guardar accion a = add_action(action) start_pos= a.start_pos end_pos=a.end_pos # si hay que cortar y es accion izquierda # if (a.cut && ( left_action(@seq_fasta,start_pos-p_beg,end_pos) || # action is left in insert if (a.cut && ( left_action(@seq_fasta,start_pos-p_beg,end_pos-p_beg) || # action is left in insert (start_pos==p_beg)) ) # action is right in insert but it's continous to the before action puts "in seq w action left act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" p_beg=end_pos+1 cut=true a.left_action=true # puts "in seq w action left act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" # elsif (a.cut && right_action(@seq_fasta,start_pos-p_beg,end_pos)) # action is rigth in insert elsif (a.cut && right_action(@seq_fasta,start_pos-p_beg,end_pos-p_beg)) # action is rigth in insert puts "in seq w action right act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" p_end = start_pos-1 a.right_action=true cut=true # puts "in seq w action right act #{start_pos} #{end_pos} pbeg #{p_beg} p_end #{p_end}" elsif !a.cut puts "NO cut action" if right_action(@seq_fasta,start_pos-p_beg,end_pos-p_beg) a.right_action=true end end end if cut then @seq_fasta = @seq_fasta_orig[p_beg..p_end] @seq_qual = @seq_qual_orig[p_beg..p_end] if !@seq_qual_orig.nil? # puts "in seq w action1 #{@insert_start} #{@insert_end}" @insert_start = p_beg size_cut_right = @insert_end - p_end @insert_end -= size_cut_right # puts "in seq w action2 #{@insert_start} #{@insert_end}" end end end # check if range defined by q_beg and q_end is inside some action of the type indicated by action_type def range_inside_action_type?(q_beg,q_end,action_type) res = false action_list = get_actions(action_type) action_list.each do |action| if action.contains_action?(q_beg+@insert_start,q_end+@insert_start,10) res = true break end end return res end # Prints a sequence with its actions to a file def to_text output_res=[] if @seq_rejected output_res<< "[#{@tuple_id},#{@order_in_tuple}] Sequence #{seq_name} had the next actions: ".bold.underline + " REJECTED: #{@seq_rejected_by_message}".red # puts @seq_name.bold + bold + ' REJECTED BECAUSE ' +@seq_rejected_by_message.bold if @seq_rejected else output_res<< "[#{@tuple_id},#{@order_in_tuple}] Sequence #{seq_name} had the next actions: ".bold.underline end n=1 withMessage = ["ActionIsContaminated","ActionVectors","ActionBadAdapter","ActionLeftAdapter","ActionRightAdapter"] color = red @actions.sort!{|e,f| e.start_pos<=>f.start_pos}.each do |a| a_type=a.action_type color = a.apply_decoration(" EXAMPLE ") color2 =a.apply_decoration(" #{a_type.center(8)} ") reversed_str = '' if a.reversed reversed_str = " REVERSED ".bold end output_res<< " [#{n}] ".bold + color2+ " #{a.title} ".ljust(24).reset + " [ " + " #{a.start_pos+1}".center(6) + " , " + "#{a.end_pos+1}".center(6) + " ]" + clear.to_s + "#{a.message}".rjust(a.message.size+8) + reversed_str n +=1 end pos = 0 res = '' @seq_fasta_orig.each_char do |c| @actions.each do |a| c= a.decorate(c,pos) end res += c pos += 1 end output_res<< res if SHOW_QUAL and @seq_qual_orig res = '' pos=0 output_res<< '' @seq_fasta_orig.each_char do |c2| c=@seq_qual_orig[pos].to_s+' ' @actions.each do |a| c= a.decorate(c,pos) end res += c pos += 1 end output_res<< res end if SHOW_FINAL_INSERTS output_res<< "INSERT ==>"+get_inserts.join("\nINSERT ==>") output_res<< "="*80 end # puts @seq_name.bold + bold + ' rejected because ' +@seq_rejected_by_message.bold if @seq_rejected return output_res end def to_text_seq_fasta return " "*@insert_start +@seq_fasta end # Saves a sequence with its actions to a file def save_to_file File.open("results/#{seq_name}"+".txt", 'w') { |file| n=1 @actions.each do |a| file.puts a.description n +=1 end } end def action_right(a,p_beg,p_end) # $LOG.debug " is right action" if ((a.start_pos-p_beg)>(p_end-a.end_pos-1)) # $LOG.debug " is left action " if !((a.start_pos-p_beg)>(p_end-a.end_pos-1)) return ((a.start_pos-p_beg)>(p_end-a.end_pos-1)) end # def is_first_action(p_beg,p_end,seq_end) # return ((p_beg==0) && (p_end==seq_end)) # end #Receive a type of action. Be carefull, type is not a string . #Return an array of actions of this type def get_actions(type=nil) res = [] @actions.each do |a| if a.is_a?(type) or type.nil? res.push a end end return res end def get_inserts inserts = get_actions(ActionInsert) res =[] inserts.each do |insert| res.push @seq_fasta_orig[insert.start_pos..insert.end_pos] end return res end def get_qual_inserts inserts = get_actions(ActionInsert) res =[] if @seq_qual_orig inserts.each do |insert| res.push @seq_qual_orig[insert.start_pos..insert.end_pos] end end return res end def insert_bounds return [@insert_start,@insert_end] end def to_json s={} s[:seq_name]=@seq_name s[:seq_fasta]=@seq_fasta_orig s[:seq_qual]='' if @seq_qual_orig s[:seq_qual]=@seq_qual_orig.join(' ') end s[:rejected]=@rejected s[:fasta_inserts]= get_inserts s[:qual_inserts]=get_qual_inserts.map { |e| e.join(' ') } s[:actions]=[] @actions.each { |a| s[:actions].push a.to_hash } # puts "YAML",s.to_yaml return JSON.pretty_generate(s) end # private :to_text end <file_sep>/lib/seqtrimnext/classes/params.rb ######################################### # Author:: <NAME> # This class provided the methods to read the parameter's file and to create the structure where will be storaged the param's name and the param's numeric-value ######################################### require 'scbi_fasta' class Params #Creates the structure and start the reading of parameter's file def initialize(path) @params = {} @comments = {} # @param_order={} @mids = {} @ab_adapters={} @adapters={} @linkers = {} @clusters = {} @plugin_comments = {} read_file(path) end # Reads param's file def read_file(path_file) if path_file && File.exists?(path_file) comments= [] File.open(path_file).each_line do |line| line.chomp! # delete end of line if !line.empty? if !(line =~ /^\s*#/) # if line is not a comment # extract the parameter's name in params[0] and the parameter's value in params[1] #params = line.split(/\s*=\s*/) # store in the hash the pair key/value, in our case will be name/numeric-value , # that are save in params[0] and params[1], respectively #if (!params[0].nil?) && (!params[1].nil?) # set_param(params[0].strip,params[1].strip,comments) # comments=[] #end line =~ /^\s*([^=]*)\s*=\s*(.*)\s*$/ params=[$1,$2] # store in the hash the pair key/value, in our case will be name/numeric-value , # that are save in params[0] and params[1], respectively if (!params[0].nil?) && (!params[1].nil?) set_param(params[0].strip,params[1].strip,comments) comments=[] end $LOG.debug "read: #{params[0]}=#{params[1]}" if !$LOG.nil? else comments << line.gsub(/^\s*#/,'') end # end if comentario end #end if line end #end each if @params.empty? puts "INVALID PARAMETER FILE: #{path_file}. No parameters defined" exit end end end# end def def load_db_fastas(input_paths) res={} if (!input_paths.nil?) & (input_paths!='') # remove quotes paths=input_paths.gsub(/\A['"]+|['"]+\Z/, "") # split paths by spaces # puts "PATHS:" # puts paths.split(' ') paths.split(' ').each do |path_file| if File.exists?(path_file) ff = FastaFile.new(path_file) ff.each {|n,f| res[n]=f } ff.close end end end # puts "LOADED_DB #{paths}:" # res.each do |k,v| # puts k # end return res end # Load mid's file def load_mids(path_file) @mids=load_db_fastas(path_file) # puts @mids end # Load ab_adapters file def load_ab_adapters(path_file) @ab_adapters=load_db_fastas(path_file) # puts @ab_adapters end # load normal adapters def load_adapters(path_file) @adapters=load_db_fastas(path_file) end # Load mid's file def load_linkers(path_file) @linkers=load_db_fastas(path_file) # puts @linkers end def load_repeated_seqs(file_path) @clusters={} if File.exists?(file_path) # File.open(ARGV[0]).each_line do |line| $LOG.debug("Repeated file path:"+file_path) File.open(file_path).each_line do |line| #puts line,line[0] # en ruby19 line[0] da el caracter, no el chr #if (line[0]!=62) && (line[0]!=48) # if (line[0]!='>'[0]) && (line[0]!='0'[0]) # line doesn't finish in * if (line[0]!='>'[0]) && (!(line =~ /\*$/)) #puts line # puts line,line[0] if line =~ />([^\.]+)\.\.\.\s/ #puts 'ok' # puts $1 @clusters[$1]=1 end end end $LOG.info("Repeated sequence count: #{@clusters.count}") else $LOG.error("Clustering file's doesn't exists: #{@clusters.count}") end end def repeated_seq?(name) return !@clusters[name].nil? end # Reads param's file def save_file(path_file) f=File.open(path_file,'w') @plugin_comments.keys.sort.reverse.each do |plugin_name| f.puts "#"*50 f.puts "# " + plugin_name f.puts "#"*50 f.puts '' @plugin_comments[plugin_name].keys.each do |param| comment=get_comment(plugin_name,param) if !comment.nil? && !comment.empty? && comment!='' f.puts comment.map{|c| '# '+c if c!=''} end f.puts '' f.puts "#{param} = #{@params[param]}" f.puts '' end end f.close end# end def # Prints the pair name/numeric-value for every parameter def print_parameters() @params.each do |clave, valor| #$LOG.debug "The Parameter #{clave} have the value " +valor.to_s puts "#{clave} = #{valor} " end end # Return the parameter's list in an array def get_param(param) #$LOG.debug "Get Param: #{@params[param]}" return @params[param] end def get_fasta(list,name,type) res = list[name] if res.nil? $LOG.error("Error. The #{type}: #{name} was not correctly loaded") raise "Error. The #{type}: #{name} was not found in loaded #{name}s: #{list.map{|k,v| k}}." end return res end # Return the mid's size of param def get_mid(mid) # return @mids[mid] return get_fasta(@mids,mid,"mid") end # Return the linker of param def get_linker(linker) # return @linkers[linker] return get_fasta(@linkers,linker,"linker") end # Return the ab of param def get_ab_adapter(adapter) # return @ab_adapters[adapter] return get_fasta(@ab_adapters,adapter,"ab_adapter") end def get_adapter(adapter) # return @adapters[adapter] return get_fasta(@adapters,adapter,"adapter") end def get_plugin plugin='General' # puts caller(2)[1] at = caller(2)[1] if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at file = Regexp.last_match[1] line = Regexp.last_match[2].to_i method = Regexp.last_match[3] plugin=File.basename(file,File.extname(file)) end end def set_param(param,value,comment = nil) plugin=get_plugin @params[param] = value if get_comment(plugin,param).nil? set_comment(plugin,param,comment) end end def get_comment(plugin,param) res = nil if @plugin_comments[plugin] res =@plugin_comments[plugin][param] end return res end def set_comment(plugin,param,comment) if !comment.is_a?(Array) && !comment.nil? comment=comment.split("\n").compact.map{|l| l.strip} end if @plugin_comments[plugin].nil? @plugin_comments[plugin]={} end old_comment='' # remove from other plugins @plugin_comments.each do |plugin_name,comments| if comments.keys.include?(param) && plugin_name!=plugin old_comment=comments[param] comments.delete(param) end end if comment.nil? comment=old_comment end # @comments[param]=(comment || ['']) @plugin_comments[plugin][param]=(comment || ['']) # puts @plugin_comments.keys.to_json # remove empty comments @plugin_comments.reverse_each do |plugin_name,comments| if comments.empty? @plugin_comments.delete(plugin_name) end end end def set_mid(param,value) @mids[param] = value end # Returns true if exists the parameter and nil if don't def exists?(param_name) return !@params[param_name].nil? end def check_plugin_list_param(errors,param_name) # get plugin list pl_list=get_param(param_name) # puts pl_list,param_name list=pl_list.split(',') list.map!{|e| e.strip} # puts "Lista:",list.join(',') # always the pluginExtractInserts at the end list.delete('PluginExtractInserts') list << 'PluginExtractInserts' set_param(param_name,list.join(',')) # if !list.include?('PluginExtractInserts') # raise "PluginExtractInserts do not exists" # # end end # def split_databases(db_param_name) def check_db_param(errors,db_param_name) if !get_param(db_param_name).empty? # expand database paths dbs= get_param(db_param_name).gsub('"','').split(/\s+/) # puts "ALGO"*20 # puts "INPUT DATABASES:\n"+dbs.join(',') procesed_dbs=[] # # TODO - chequear aqui que la db no esta vacia y que esta formateada. dbs.reverse_each {|db_p| db=File.expand_path(db_p) if !File.exists?(db) path=File.join($FORMATTED_DB_PATH,db_p) else path=db end if Dir.glob(path+'*.n*').entries.empty? puts "DB file #{path} not formatted" if File.writable_real?(path) cmd = "makeblastdb -in #{path} -parse_seqids -dbtype nucl" system(cmd) else raise "Can't format database. We don't have write permissions in: #{path}" end end procesed_dbs << path if !File.exists?(path) raise "DB File #{path} does not exists" # exit end } db_paths = '"'+procesed_dbs.join(' ')+'"' set_param(db_param_name,db_paths) puts "USED DATABASES\n"+db_paths end end def self.generate_sample_params filename = 'sample_params.txt' x=1 while File.exists?(filename) filename = "sample_params#{x}.txt" x+=1 end f=File.open(filename,'w') f.puts "SAMPLE_PARAMS" f.close puts "Sample params file generated: #{filename}" end def check_param(errors,param,param_class,default_value=nil, comment=nil) if !exists?(param) if default_value.nil? #|| (default_value.is_a?(String) && default_value.empty?) errors.push "The param #{param} is required and no default value is available" else set_param(param,default_value,comment) end end s = get_param(param) set_comment(get_plugin,param,comment) # check_class=Object.const_get(param_class) begin case param_class when 'Integer' r = Integer(s) when 'Float' r = Float(s) when 'String' r = String(s) when 'DB' # it is a string r = String(s) # and must be a valid db r = check_db_param(errors,param) when 'PluginList' r=String(s) r= check_plugin_list_param(errors,param) end rescue Exception => e message="Current value is ##{s}#. " if param_class=='DB' message += e.message end errors.push "Param #{param} is not a valid #{param_class}. #{message}" end # end end end <file_sep>/lib/seqtrimnext/classes/scan_for_restr_site.rb #!/usr/bin/env ruby ######################################### # Author:: <NAME> # This class provided the methods to read the parameter's file and to create the structure where will be storaged the param's name and the param's numeric-value ######################################### class ScanForRestrSite #Creates the structure and start the reading of parameter's file def initialize(sequence,rest) @seq_fasta=sequence @rest=rest puts "#{@seq_fasta} , #{@rest}" res = execute res.each do |e| puts "#{e.join(',')}" end # selects from res,the max good hit puts "--- MAX: --- " max = res.max{|e1,e2| e1[1]<=> e2[1]} puts max.join(' ; ') # checks if the max one has the size of restriction with a margen error margen = (@rest.size <= 4)? 0 : 1; # <- don't change if ((max[1] != @rest.size) && (max[1] != @rest.size-margen)) puts "-the max good hit hasn't the size minimum: #{@rest.size} or #{@rest.size-margen} " max=[] end #read_file(path) end def execute r=[] # # for (my $p=0; $p < $sL-$srfL; $p++){ # $os = $ns = $xs = 0; # for ( my $i=0; $i < $srfL; $i++ ) { # my $c = substr($s, $i+$p, 1); # ver si decrementar antes pos # my $cc = substr($restrSite, $i, 1); # if ($c eq $cc) { # ++$os; # } elsif ($c eq "N"){ # ++$ns; # } else { # ++$xs; # } # } # $r[$p] = [$p, $os, $ns, $xs]; # print "$p, $os, $ns, $xs\n"; # } for p in 0..@seq_fasta.size-@rest.size os = 0; ns = 0; xs = 0; puts "-------[#{p}]-#{@seq_fasta[p,@seq_fasta.size-p]} , #{@rest}" i=0 @rest.each_char do |cc| c = @seq_fasta[i+p].chr puts "(#{c}==#{cc})=>#{c==cc}" if (c == cc) os += 1 elsif (c == 'N') ns += 1 else xs += 1 end i+=1 end r[p]=[p,os,ns,xs] puts r[p].join(',') end return r end # Reads param's file def read_file(path_fichero) File.open(path_fichero).each_line do |line| line.chomp! # delete end of line if !line.empty? if !(line =~ /^#/) # if line is not a comment # extract the parameter's name in params[0] and the parameter's value in params[1] params = line.split(/\s*=\s*/) # storage in the hash the pair key/value, in our case will be name/numeric-value , # that are save in params[0] and params[1], respectively @h[params[0]] = params[1] $LOG.debug "read: #{params[1]}" end # end if comentario end #end if line end #end each $LOG.info "File Params have been readed" end# end def # Prints the pair name/numeric-value for every parameter def print_parameters() @h.each do |clave, valor| $LOG.debug "The Parameter #{clave} have the value " +valor.to_s end end # Return the parameter's list in an array def get_param(param) #$LOG.debug "Get Param: #{@h[param]}" return @h[param] end def set_param(param,value) @h[param] = value end #attr_accessor :h # to accede to the atribute 'h' from out of this class # Returns true if exists the parameter and nil if don't def exists?(param_name) return !@h[param_name].nil? end end scan = ScanForRestrSite.new("AaaaACGTACGT", "AGTAC") # scan = ScanForRestrSite.new("AaaaACGTAeCGT", "AGTAC") <file_sep>/lib/seqtrimnext/plugins/plugin_vectors.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginVectors # Inherit: Plugin ######################################################## class PluginVectors < Plugin # MIN_VECTOR_SIZE=30 # MAX_TO_EXTREME=(MIN_VECTOR_SIZE/2).to_i MAX_TARGETS_SEQS=20 #MAXIMUM NUMBER OF DIFFERENT ALIGNED SEQUENCES TO KEEP FROM BLAST DATABASE def near_to_extrem(c,seq,min_vector_size) max_to_extreme=(min_vector_size/2).to_i return ((c.q_beg-max_to_extreme<0) || (( c.q_end+max_to_extreme)>=seq.seq_fasta.size-1) ) #return if vector is very near to the extremes of insert) end def all_vector_in_linker(vector_beg,vector_end,seq) linkers=seq.get_actions(ActionLinker) # res=((linkers.count>=1) && (vector_beg>=linkers[0].start_pos) && (vector_end<=linkers[0].end_pos)) # puts " RES #{res} insert-start #{seq.insert_start} #{linkers.count}>=1 #{vector_beg+seq.insert_start}>=#{linkers[0].start_pos}) && #{vector_end+seq.insert_start}<=#{linkers[0].end_pos})) " return ((linkers.count>=1) && (vector_beg+seq.insert_start>=linkers[0].start_pos) && (vector_end+seq.insert_start<=linkers[0].end_pos)) end def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast = BatchBlast.new("-db #{@params.get_param('vectors_db')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_vectors')} -perc_identity #{@params.get_param('blast_percent_vectors')} -culling_limit 1") #get vectors $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") #blast_table_results = blast.do_blast(fastas,:xml) t1=Time.now blast_table_results = blast.do_blast(fastas,:table,false) add_plugin_stats('execution_time','blast',Time.now-t1) t1=Time.now #blast_table_results = BlastStreamxmlResult.new(blast_table_results) blast_table_results = BlastTableResult.new(blast_table_results) add_plugin_stats('execution_time','parse',Time.now-t1) # puts blast_table_results.inspect return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for vectors into the sequence " #blast contra contaminantes # blast = BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'vectors.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_vectors')} -perc_identity #{@params.get_param('blast_percent_vectors')} -culling_limit 1") #get vectors # blast_table_results = blast.do_blast(seq.seq_fasta,:xml) #rise seq to contaminants executing over blast type = "ActionVectors" # puts res # blast_table_results.inspect # blast_table_results.querys.each do |query| # adds the correspondent action to the sequence # query.hits.each do |hit| # seq.add_action(hit.q_beg,hit.q_end,type) # end # end vectors=[] vectors_ids=[] # blast_table_results.querys.each do |query| # first round to save vectors without overlap # vectors_ids.push query.hits.subject_id if (not vectors_ids.include?(query.hits.subject_id)) merge_hits(blast_query.hits,vectors,vectors_ids) # end begin vectors2=vectors # second round to save vectors without overlap vectors = [] merge_hits(vectors2,vectors) end until (vectors2.count == vectors.count) actions = [] vectors_size=0 min_vector_size=@params.get_param('min_vector_seq_presence').to_i vectors.each do |v| # adds the correspondent action to the sequence #puts "*VECTOR* #{v.subject_id[0..40].ljust(40)} #{v.q_beg.to_s.rjust(6)} #{v.q_end.to_s.rjust(6)} #{v.s_beg.to_s.rjust(6)} #{v.s_end.to_s.rjust(6)}" vector_size=v.q_end-v.q_beg+1 # puts " in PLUGIN VECTOR previous to add action #{seq.insert_start} #{seq.insert_end}" # if ((vector_size>=MIN_VECTOR_SIZE) || ((vector_size<MIN_VECTOR_SIZE) && near_to_extrem(v,seq))) if (near_to_extrem(v,seq,10) || (vector_size>=min_vector_size) ) # puts " near #{near_to_extrem(v,seq,min_vector_size)} #{vector_size}>=#{min_vector_size}" #c.q_end+seq.insert_start+max_to_end)>=seq.seq_fasta_orig.size-1) #if ab adapter is very near to the end of original sequence piro_on=@params.get_param('next_generation_sequences').to_s if (((piro_on=='true') && (!seq.range_inside_action_type?(v.q_beg,v.q_end,ActionLinker)) && (!seq.range_inside_action_type?(v.q_beg,v.q_end,ActionMultipleLinker))) || # if vectors DB not is contained inside detected linkers (piro_on=='false')) # if vector is too big, and it isn't in an extreme, then it is an unexpected vector if !near_to_extrem(v,seq,min_vector_size) type = 'ActionUnexpectedVector' if @params.get_param('middle_vector_rejects').to_s=='true' seq.seq_rejected=true seq.seq_rejected_by_message='unexpected vector' end add_stats('rejected','unexpected_vector') end a = seq.new_action(v.q_beg,v.q_end,type) a.message = v.definition # a.found_definition.push v.subject_id # save the vectors definitions, each separately a.found_definition=vectors_ids # save the vectors definitions, each separately a.reversed = v.reversed a.cut=false if (piro_on=='true') # vectors don't cut when piro is on # puts "piro on #{piro_on} vector cut #{a.cut} ________________|||||||||| " # puts " no piro" if (piro_on=='false') actions.push a # @stats[:vector_size]={vector_size => 1} add_stats('vector_size',vector_size) vectors_ids.each do |v| add_stats('vectors_ids',v) end end end end seq.add_actions(actions) # end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for vector fragments' default_value = 1e-1 params.check_param(errors,'blast_evalue_vectors','Float',default_value,comment) comment='Minimum required identity (%) for a reliable vector fragment' default_value = 90 params.check_param(errors,'blast_percent_vectors','Integer',default_value,comment) comment='Correct sequences could contain vectors only close to the read end (not within the sequence). The following variable indicates the number of nucleotides from the 5\' or 3\' end that are allowed for considering a vector fragment located at the end. Otherwise, the vector fragment will be qualified as internal and the sequence will be rejected' default_value = 8 params.check_param(errors,'max_vector_to_end','Integer',default_value,comment) comment='If a vector fragment is qualified as internal, the fragment should be long enough to be sure that it is a true vector fragment. This is the minimum length of a vector fragment that enables sequence rejection by an internal, unexpected vector' default_value = 50 params.check_param(errors,'min_vector_seq_presence','Integer',default_value,comment) comment='Vectors database path' default_value = File.join($FORMATTED_DB_PATH,'vectors.fasta') params.check_param(errors,'vectors_db','DB',default_value,comment) comment='Rejects sequences with vectors in the middle' default_value = 'true' params.check_param(errors,'middle_vector_rejects','String',default_value,comment) # params.split_databases('vectors_db') return errors end end <file_sep>/bin/fasta2fastq.rb #!/usr/bin/env ruby require 'scbi_fasta' require 'scbi_fastq' if ARGV.count < 3 puts "#{$0} FASTA QUAL OUTPUT_NAME" exit end fasta = ARGV.shift qual = ARGV.shift output_name = ARGV.shift default_qual = nil if !File.exists?(qual) fqr=FastaFile.new(fasta) puts "Quality file doesn't exists. Using default qual value = 40" default_qual = [40] else fqr=FastaQualFile.new(fasta,qual) end output=FastqFile.new(output_name+'.fastq','w') fqr.each do |seq_name,seq_fasta,seq_qual| if default_qual seq_qual = default_qual * seq_fasta.length end output.write_seq(seq_name,seq_fasta,seq_qual) end output.close fqr.close <file_sep>/lib/seqtrimnext.rb require "seqtrimnext/version" ROOT_PATH=File.join(File.dirname(__FILE__),'seqtrimnext') $: << File.expand_path(File.join(ROOT_PATH, 'classes')) #finds the classes that were in the folder 'plugins' $: << File.expand_path(File.join(ROOT_PATH, 'plugins')) #finds the classes that were in the folder 'plugins' $: << File.expand_path(File.join(ROOT_PATH, 'actions')) #finds the classes that were in the folder 'utils' $: << File.expand_path(File.join(ROOT_PATH, 'utils')) $: << File.expand_path(File.join(ROOT_PATH, 'classes','em_classes')) $: << File.expand_path(File.join(ROOT_PATH, 'latex','classes')) module Seqtrimnext # Your code goes here... end <file_sep>/lib/seqtrimnext/classes/em_classes/seqtrim_worker.rb #finds the classes that were in the folder 'classes' # ROOT_PATH=File.dirname(File.dirname(File.dirname(__FILE__))) # # $: << File.expand_path(File.join(ROOT_PATH, 'classes')) # $: << File.expand_path(File.join(ROOT_PATH, 'classes','blast')) # # #finds the classes that were in the folder 'plugins' # $: << File.expand_path(File.join(ROOT_PATH, 'plugins')) # # #finds the classes that were in the folder 'plugins' # $: << File.expand_path(File.join(ROOT_PATH, 'actions')) # # #finds the classes that were in the folder 'utils' # $: << File.expand_path(File.join(ROOT_PATH, 'utils')) # # $: << File.expand_path(File.join(ROOT_PATH, 'classes','em_classes')) # # $: << File.expand_path(ROOT_PATH) # $: << File.expand_path('~/progs/ruby/gems/seqtrimnext/lib/') # $: << File.expand_path('~/progs/ruby/gems/scbi_mapreduce/lib') require 'seqtrimnext' $SEQTRIM_PATH = ROOT_PATH if ENV['BLASTDB']# && Dir.exists?(ENV['BLASTDB']) $FORMATTED_DB_PATH = ENV['BLASTDB'] $DB_PATH = File.dirname($FORMATTED_DB_PATH) else $FORMATTED_DB_PATH = File.expand_path(File.join(ROOT_PATH, "DB",'formatted')) $DB_PATH = File.expand_path(File.join(ROOT_PATH, "DB")) end ENV['BLASTDB']=$FORMATTED_DB_PATH OUTPUT_PATH='output_files_tmp' puts "FORMATTED_DB_BLAST in workers: #{$FORMATTED_DB_PATH}" require 'scbi_mapreduce' require 'params' require 'action_manager' require 'plugin_manager' # require 'sequence_with_action' # require 'scbi_fastq' require 'sequence_group' class SeqtrimWorker < ScbiMapreduce::Worker def process_object(obj) running_seqs=SequenceGroup.new(obj.flatten) # execute plugins @plugin_manager.execute_plugins(running_seqs) # add output data add_output_data(running_seqs) return running_seqs end def receive_initial_config(obj) # Reads the parameters $WORKER_LOG.info "Params received" # @params = Params.new(params_path) @params = obj @tuple_size=@params.get_param('tuple_size') @use_qual=@params.get_param('use_qual') @use_json=@params.get_param('use_json') end def starting_worker # $WORKER_LOG.level = Logger::ERROR #$WORKER_LOG.level = Logger::WARN $WORKER_LOG.level = Logger::INFO $WORKER_LOG.info "Loading actions" @action_manager = ActionManager.new $WORKER_LOG.info "Loading plugins" @plugin_list = @params.get_param('plugin_list') # puts in plugin_list the plugins's array $WORKER_LOG.info "PLUGIN LIST:" + @plugin_list @plugin_manager = PluginManager.new(@plugin_list,@params) # creates an instance from PluginManager. This must storage the plugins and load it rescue Exception => e puts (e.message+ e.backtrace.join("\n")) end def closing_worker end def add_output_data(obj) obj.output_text=[] if @tuple_size>1 obj.each_slice(@tuple_size) do |seqs| write_seq_to_files_tuple(obj.output_files,seqs, obj.stats) seqs.each do |seq| obj.output_text << seq.to_text end end else obj.each do |seq| write_seq_to_files_normal(obj.output_files,seq, obj.stats) obj.output_text << seq.to_text end end # @remove seqs since they are not needed anymore to write output files obj.remove_all_seqs end def add_stat(stats,key,subkey,value,count=1) stats[key]={} if !stats[key] stats[key][subkey]={} if !stats[key][subkey] stats[key][subkey][value]=0 if !stats[key][subkey][value] stats[key][subkey][value]+=count end def write_seq_to_files_tuple(files,seqs, stats) seq1=seqs[0] seq2=seqs[1] dir_name,file_name,priority=seq1.get_file_tag_path dir_name2,file_name2,priority2=seq2.get_file_tag_path # both paired sequences must go in same file, there are priorities if (dir_name!=dir_name2) || (file_name!=file_name2) if priority2>priority dir_name=dir_name2 file_name=file_name2 end end # get current inserts inserts1 = seq1.get_inserts inserts2 = seq2.get_inserts # qualities are optional if @use_qual qual_inserts1 = seq1.get_qual_inserts qual_inserts2 = seq2.get_qual_inserts end # save json if necessary if @use_json json_file(files)<< seq1.to_json json_file(files)<< seq2.to_json end # find mids mid1 = seq1.get_actions(ActionMid).first mid2 = seq2.get_actions(ActionMid).first if !inserts1.empty? && !inserts2.empty? # both have inserts # save_two_inserts(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) save_two_inserts_tuple(files,seq1,seq2, stats,inserts1,inserts2,qual_inserts1,qual_inserts2,mid1,dir_name,file_name) else save_rejected_empty_or_single(files,seq1, stats,inserts1,qual_inserts1,mid1,dir_name,file_name) save_rejected_empty_or_single(files,seq2, stats,inserts2,qual_inserts2,mid2,dir_name,file_name) end end def save_two_inserts_tuple(files,seq1,seq2, stats,inserts1,inserts2,qual_inserts1,qual_inserts2,mid,dir_name,file_name) add_stat(stats,'sequences','count','output_seqs_paired') add_stat(stats,'sequences','count','output_seqs_paired') mid_id,mid_message=get_mid_message(mid) # save left read n="#{seq1.seq_name}" c=seq1.get_comment_line # "template=#{seq1.seq_name} dir=R library=#{mid_id}" f=inserts1[0]#.reverse.tr('actgACTG','tgacTGAC') q=[] if @use_qual q=qual_inserts1[0] #.reverse end paired_file_ilu1(files,dir_name,file_name)<<FastqFile.to_fastq(n,f,q,c) # save right read n="#{seq2.seq_name}" c=seq2.get_comment_line # "template=#{seq2.seq_name} dir=F library=#{mid_id}" f=inserts2[0] q=[] if @use_qual q=qual_inserts2[0] end paired_file_ilu2(files,dir_name,file_name)<<FastqFile.to_fastq(n,f,q,c) end def save_rejected_empty_or_single(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) if (seq.seq_rejected) # save to rejected sequences save_rejected_seq(files,seq, stats) elsif (inserts.empty?) #sequence with no inserts save_empty_insert(files,seq, stats) elsif (inserts.count == 1) # sequence with one insert save_one_insert(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) end end # SAVE NORMAL =============================== def save_rejected_seq(files,seq, stats) # message = seq.seq_rejected_by_message message= seq.get_comment_line rejected_output_file(files)<<('>'+seq.seq_name+ ' ' + message) add_stat(stats,'sequences','rejected',seq.seq_rejected_by_message) add_stat(stats,'sequences','count','rejected') end def save_empty_insert(files,seq, stats) seq.seq_rejected=true seq.seq_rejected_by_message='short insert' message = 'No valid inserts found' rejected_output_file(files)<<('>'+seq.seq_name+ ' ' + message) add_stat(stats,'sequences','rejected',message) add_stat(stats,'sequences','count','rejected') end def get_mid_message(mid) if (mid.nil? || (mid.message=='no_MID') ) # without mid mid_id = 'no_MID' mid_message = ' No MID found' else mid_id = mid.tag_id mid_message='' if mid_id != mid_message mid_message = ' '+mid.message end end return mid_id,mid_message end def save_two_inserts(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) add_stat(stats,'sequences','count','output_seqs_paired') mid_id,mid_message=get_mid_message(mid) # save left read n="#{seq.seq_name}_left" c="template=#{seq.seq_name} dir=R library=#{mid_id} #{seq.get_comment_line}" f=inserts[0].reverse.tr('actgACTG','tgacTGAC') q=[] if @use_qual q=qual_inserts[0].reverse end paired_file(files,dir_name,file_name)<<FastqFile.to_fastq(n,f,q,c) # save right read n="#{seq.seq_name}_right" c="template=#{seq.seq_name} dir=F library=#{mid_id} #{seq.get_comment_line}" f=inserts[1] q=[] if @use_qual q=qual_inserts[1] end paired_file(files,dir_name,file_name)<<FastqFile.to_fastq(n,f,q,c) end def save_one_insert(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) mid_id,mid_message=get_mid_message(mid) # save fasta and qual in no MID file has_low_complexity = seq.get_actions(ActionLowComplexity) if has_low_complexity.empty? add_stat(stats,'sequences','count','output_seqs') fasta_file=sequence_file(files,dir_name,file_name) sff_file=sffinfo_file(files,dir_name,file_name) else add_stat(stats,'sequences','count','output_seqs_low_complexity') fasta_file=low_complexity_file(files,dir_name,file_name) sff_file=low_sffinfo_file(files,dir_name,file_name) end q=[] if @use_qual q=qual_inserts[0] end n=seq.seq_name c=mid_message seq_comments=seq.get_comment_line if !seq_comments.strip.empty? c=seq_comments + c end f=inserts[0] fasta_file << FastqFile.to_fastq(n,f,q,c) inserts_pos = seq.get_actions(ActionInsert) sff_file<< "#{n} #{inserts_pos[0].start_pos+1} #{inserts_pos[0].end_pos+1}" end def write_seq_to_files_normal(files,seq, stats) # puts stats.to_json dir_name,file_name,priority=seq.get_file_tag_path # puts File.join(dir_name,'sequences_'+file_name) # get current inserts inserts = seq.get_inserts # qualities are optional if @use_qual qual_inserts = seq.get_qual_inserts end # save json if necessary if @use_json json_file(files)<< seq.to_json end # find mids mid = seq.get_actions(ActionMid).first if (seq.seq_rejected) # save to rejected sequences save_rejected_seq(files,seq, stats) elsif (inserts.empty?) #sequence with no inserts save_empty_insert(files,seq, stats) elsif (inserts.count == 2) # sequence with two inserts = PAIRED SEQUENCES save_two_inserts(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) elsif (inserts.count == 1) # sequence with one insert save_one_insert(files,seq, stats,inserts,qual_inserts,mid,dir_name,file_name) end end # ACCESS TO FILES def json_file(files) return get_file(files,File.join(OUTPUT_PATH,'results.json')) end def rejected_output_file(files) return get_file(files,File.join(OUTPUT_PATH,'rejected.txt')) end def sequence_file(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'sequences_'+file_name+'.fastq')) end def paired_file(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'paired_'+file_name+'.fastq')) end def paired_file_ilu1(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'paired_1_'+file_name+'.fastq')) end def paired_file_ilu2(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'paired_2_'+file_name+'.fastq')) end def low_complexity_file(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'low_complexity_'+file_name+'.fastq')) end def sffinfo_file(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'sff_info_'+file_name+'.txt')) end def low_sffinfo_file(files, dir_name, file_name) return get_file(files,File.join(OUTPUT_PATH,dir_name,'low_complexity_sff_info_'+file_name+'.txt')) end def get_file(files,fn) res=files[fn] if !res files[fn]=[] res=files[fn] end return res end end <file_sep>/lib/seqtrimnext/classes/install_database.rb require 'open-uri' class InstallDatabase def initialize(type,db_path) types=['core','cont_bacteria','cont_fungi','cont_mitochondrias','cont_plastids','cont_ribosome','cont_viruses','adapters_illumina'] if types.include?(type) if !File.exists?(db_path) FileUtils.mkdir_p(db_path) end remote_db_url="http://www.scbi.uma.es/downloads/#{type}_db.zip" local_path=File.join(db_path,'core_db.zip') puts "Install databases: #{type}" download_and_unzip(remote_db_url,local_path) else puts "Unknown database #{type}" puts "Available databases:" puts types.join("\n") end end def download_and_unzip(from_url,to_file) puts "Downloading databases from #{from_url} to #{to_file}" open(to_file, "w+") { |f| f.write(open(from_url).read)} puts "Unzipping #{to_file}" # unzip and remove # `cd #{File.dirname(to_file)};unzip #{to_file}; rm #{to_file}` `cd #{File.dirname(to_file)};unzip #{to_file}; rm #{to_file}` end end<file_sep>/lib/seqtrimnext/plugins_old/plugin_low_quality_old.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLowQuality. See the main method called execute. # # Inherit: Plugin ######################################################## class PluginLowQuality < Plugin def create_sum_window(qual,ini,index_window_end) # puts "--------index w #{index_window_end}" sum=[] i=ini # puts "#{i} #{index_window_end}" while (i<=index_window_end) # initialize sum sum[i]=0 i += 1 end # puts " contenido de sum" + sum.join.to_s + " i index_window_end window #{i} #{index_window_end} #{@window}" i=ini while (i<ini+@window) sum[ini] += qual[i] i+=1 end i=ini+1 while (i<=index_window_end) sum[i]=sum[i-1]-qual[i-1]+qual[i+@window-1] i+=1 end # puts '2____' + sum.join(',') + 'pos sum' + ini.to_s return sum end def find_bounds_high_quality(sum,ini,index_window_end) new_start = -1 new_end = -1 # puts " ini #{ini} iwe #{index_window_end}" # puts "ini #{ini} index_window_end #{index_window_end} sum[ini] #{sum[ini]} cut_off #{@cut_off} suma #{sum.size} " if (ini>index_window_end) temp_start= ini # new_start, new_end = temp_start, index_window_end new_end = index_window_end # para que no crea que no hay alta calidad, sino que hemos sobrepasado el indice final de la ventana # new_start, new_end = index_window_end, index_window_end end # puts " temp_start #{temp_start}" if (ini>index_window_end) temp_start=((ini<=index_window_end) && (sum[ini]>=@cut_off))? ini : -1 i=ini+1 while (i<=index_window_end) if (sum[i]>=@cut_off) if (temp_start<0) temp_start=i #just in! # puts "just in ---- #{sum[i]}>= cut off #{@cut_off} pos #{temp_start}" end else # puts "sum #{sum[i]} < cut off " if(temp_start>=0) #just out! # puts "update #{sum[i]}< cut off #{@cut_off} pos #{i}.if #{i-1} - #{temp_start} > #{new_end} - #{new_start}" if (((i-1-temp_start)>=(new_end-new_start))) new_start,new_end=temp_start,i-1 # puts "just out ---- new start,new_end = #{temp_start}, #{i-1} index_window_end = #{index_window_end}" end temp_start= -1 end end i+=1 end # puts "4 temp_start #{temp_start} new_start #{new_start} new-end #{new_end}" if (temp_start != -1) # finished while ok # puts "4 #{index_window_end} - #{temp_start} > #{new_end} - #{new_start}" if ((index_window_end- temp_start) >= (new_end-new_start)) #put the end of the window at the end of sequence new_start, new_end = temp_start, index_window_end #-1 end end # puts "5 temp_start #{temp_start} new_start #{new_start} new-end #{new_end}" # puts " newstart #{new_start} newend #{new_end}" return new_start,new_end end def cut_fine_bounds_short(qual,new_start,new_end) i=0 # puts " qual[new_start+i] new_start #{new_start} i #{i} = #{new_start+i} qual.size #{qual.size}" while (i<@window) if (qual[new_start+i]>=@low) break end i+=1 end new_start +=i # puts "#{new_start} ***********" i=@window -1 while (i>=0) if (qual[new_end+i]>=@low) break end i-=1 end new_end += i # puts "6a new_start #{new_start} new-end #{new_end}" # puts " #{new_start} #{new_end} .o.o.o.o.o.o.o.o2 short" return new_start, new_end end # cuts fine the high quality bounds def cut_fine_bounds(qual,new_start,new_end) # puts " ççççççççççççççç #{new_start+@window} >= #{new_end} " # puts " #{new_start} #{new_end} .o.o.o.o.o.o.o.o1" # cut it fine one_ok = 0 i=@window-1 # puts " qual[new_start+i] new_start #{new_start} i #{i} = #{new_start+i} qual.size #{qual.size}" while (i>=0) if (qual[new_start+i] < @low) break if one_ok else one_ok = 1 end i-=1 end new_start += i+1 oneOk = 0 i=0 while (i<@window) if (qual[new_end+i] < @low) break if oneOk else oneOk = 1 end i+=1 end new_end += i-1 # puts "6b new_start #{new_start} new-end #{new_end}" # puts " #{new_start} #{new_end} .o.o.o.o.o.o.o.o2" return new_start, new_end end def find_high_quality(qual,ini=0) # puts qual.class.to_s + qual.size.to_s + 'size,' + @window.to_s + ' window, '+ qual.join(',') + 'size' + qual.size.to_s update=false # if @window>qual.length-ini #search in the last window although has a low size # @window=qual.length-ini # # puts ' UPDATE WINDOW Y CUT OFF ' + @window.to_s # @cut_off=@window*@low # update=true # end if (ini==0 or update) #index_window_start = ini @index_window_end = qual.size- @window #don't sub 1, or will lost the last nucleotide of the sequence -1; #TODO En seqtrim de <NAME>, que en nuestro seqtrim se llama index_window_end, está perdiendo 2 nucleótidos de la última ventana calculada @sum = create_sum_window(qual,ini,@index_window_end) # puts "SUMA #{@sum.join(' ')}" end new_start, new_end = find_bounds_high_quality(@sum,ini,@index_window_end) # puts " #{new_start} #{new_end} .o.o.o.o.o.o.o.o1" if (new_start>=0) if (new_start+@window >= new_end) # puts "cfs" new_start, new_end = cut_fine_bounds_short(qual,new_start,new_end) # puts "cfs" else # puts "cf" new_start, new_end = cut_fine_bounds(qual,new_start,new_end) # puts "cf" end end # puts " #{new_start} #{new_end} .o.o.o.o.o.o.o.o2" return new_start,new_end #+1 end def add_action_before_high_qual(p_begin,p_end,actions,seq,start) action_size = p_begin-1 if action_size>=(@window/2) # puts "action_SIZE1 #{action_size} > #{@window/2}" if ( (p_begin>0) && (action_size>0) ) #if there is action before the high qual part # it's created an action before of the high quality part a = seq.new_action(start ,p_begin-1,"ActionLowQuality") # adds the ActionInsert to the sequence before adding the actionMid # puts " new low qual start: #{start} = #{a.start_pos} end: #{p_begin} -1 = #{a.end_pos}" actions.push a end end end def add_action_after_high_qual(p_begin,p_end,actions,seq) action_size = seq.insert_end-p_end if action_size>=(@window/2) # puts "action_SIZE2 #{action_size} > #{@window/2}" if ((p_end<seq.seq_fasta.size-1) && (action_size>0) ) #if there is action before the high qual part # it's created an action before of the high quality part a = seq.new_action(p_end-seq.insert_start+1,seq.seq_fasta.size-1,"ActionLowQuality") # adds the ActionInsert to the sequence before adding the actionMid actions.push a end end end ###################################################################### #--------------------------------------------------------------------- # Begins the plugin1's execution whit the sequence "seq" # Creates an action by each subsequence with low quality to eliminate it # A subsequence has low quality if (the add of all its qualitis < subsequence_size*20) # Creates the qualities windows from the sequence, looks for the subsequence with high quality # and mark, with an action, the before part to the High Quality Subsequence like a low quality part # Finally mark, with an action, the after part to the High Quality Subsequence like a low quality part #----------------------------------------------------------------- def exec_seq(seq,blast_query) if ((self.class.to_s=='PluginLowQuality') && seq.seq_qual.nil? ) $LOG.error " Quality File haven't been provided. It's impossible to execute " + self.class.to_s elsif (seq.seq_qual.size>0) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking low quality of the sequence" @low=@params.get_param('min_quality').to_i if @params.get_param('window_width').to_i>seq.seq_fasta.length @window=seq.seq_fasta.length else @window=@params.get_param('window_width').to_i end @cut_off=@window*@low type='ActionLowQuality' low_qual=0 actions=[] p_begin,p_end =0,-1 # positions from high quality bounds while ((p_begin>=0) && (p_end + 1 < seq.seq_qual.size) ) p_begin_old,p_end_old= p_begin, p_end p_begin,p_end = find_high_quality(seq.seq_qual,p_end+1) if ((p_begin>0) && (p_begin-p_end_old-1>=@window/2)) #if we have found the high quality part, and the low quality part has enough size # it's created an action before of the high quality part add_action_before_high_qual(p_begin,p_end,actions,seq,p_end_old+1) # puts "low1 ini fin #{p_end_old+1} #{p_begin-1} = #{p_begin-1-p_end_old-1+1}" low_qual = p_begin-1-p_end_old-1 + 1 add_stats('low_qual',low_qual) # @stats[:low_qual]={low_qual => 1} end # puts "-----ññññ----- high quality #{p_begin} #{p_end}+#{seq.insert_start} seq size #{seq.seq_fasta.size}" end # puts "high [#{p_begin}, #{p_end}] old [#{p_begin_old}, #{p_end_old}] size #{seq.seq_qual.size}" if ((p_begin>=0) && (p_end+1<seq.seq_qual.size)) #if we have found the high quality part # it's created an action after of the high quality part add_action_after_high_qual(p_begin,p_end,actions,seq) # puts "low2 ini fin #{p_end+1} #{seq.seq_fasta.size-1} = #{seq.seq_fasta.size-1-p_end-1+1}" low_qual = seq.seq_fasta.size-1 - p_end-seq.insert_start-1 + 1 # if @stats[:low_qual][low_qual].nil? # @stats[:low_qual][low_qual] = 0 # end # @stats[:low_qual][low_qual] += 1 add_stats('low_qual',low_qual) # @stats[:low_qual]={low_qual => 1} end # puts "-----ññññ----- high quality #{p_begin} #{p_end}" if p_end<0 and p_end_old #add action low qual to all the part a = seq.new_action(p_end_old+1 ,seq.seq_fasta.size-1,"ActionLowQuality") # adds the ActionInsert to the sequence before adding the actionMid # puts "new low qual start: #{p_end_old+1} end: #{seq.seq_fasta.size-1} = #{seq.seq_fasta.size-1 - p_end_old-1 + 1}" low_qual = seq.seq_fasta.size-1 - p_end_old-1 + 1 # if @stats[:low_qual][low_qual].nil? # @stats[:low_qual][low_qual] = 0 # end # @stats[:low_qual][low_qual] += 1 add_stats('low_qual',low_qual) # @stats[:low_qual]={'low_qual' => 1} actions.push a end # puts "------- ADDING ACTIONs LOW QUAL #{actions.size}" seq.add_actions(actions) end end #----------------------------------------------------------------- ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Minimum quality value for every nucleotide' default_value = 20 params.check_param(errors,'min_quality','Integer',default_value,comment) comment='Quality window for scanning low quality segments' default_value = 15 params.check_param(errors,'window_width','Integer',default_value,comment) return errors end private :find_high_quality end <file_sep>/lib/seqtrimnext/utils/hash_stats.rb class Hash #increments a hash with the stats defined in h_stats # three levels: # STATS->plugin_name->Property->count def add_stats(h_stats) h=self h_stats.each do |plugin_hash,add_stats| h[plugin_hash]={} if h[plugin_hash].nil? add_stats.each do |property,hash_value| h[plugin_hash][property]={} if h[plugin_hash][property].nil? # values need to be in string format because of later loading from json file hash_value.each do |value, count| h[plugin_hash][property][value.to_s]=(h[plugin_hash][property][value.to_s]||0) + count end end end end end <file_sep>/bin/get_seq.rb #!/usr/bin/env ruby require 'scbi_fasta' GOOD_QUAL=50 BAD_QUAL=10 DOWN_CASE=('a'..'z') class Array def count self.length end end if ARGV.count < 3 puts "#{$0} FASTA QUAL SEQ_NAME [f|q|fq]" exit else fqr=FastaQualFile.new(ARGV[0],ARGV[1]) get_type = 'fq' if ARGV.count == 4 get_type=ARGV[3] end fqr.each do |seq_name,seq_fasta,seq_qual| if seq_name == ARGV[2] if get_type.index('f') puts ">#{seq_name}" puts seq_fasta end if get_type.index('q') puts ">#{seq_name}" puts seq_qual end break end end fqr.close end <file_sep>/bin/resume_stn_contaminants.rb #!/usr/bin/env ruby require 'json' if ARGV.count<1 puts "Usage: #{$0} stats1.json [stats2.json stats3.json,...]" exit -1 end # print header if ARGV[0]=='-t' #heads=['sample_name','input_count','sequence_count_paired','sequence_count_single','rejected','rejected_percent'] #puts heads.join("\t") ARGV.shift end contaminants={} ARGV.each do |file_path| sample_name = File.basename(File.expand_path(File.join(file_path,'..','..'))) stats=JSON::parse(File.read(file_path)) res=[] cont=stats['PluginContaminants']['contaminants_ids'] limit=60 cont.keys.sort{|c1,c2| cont[c2].to_i <=> cont[c1].to_i}.each do |k| #puts "#{k} => #{cont[k]}" contaminants[k]=(contaminants[k] || 0 ) + cont[k] limit = limit -1 break if limit==0 end end puts JSON::pretty_generate(contaminants) <file_sep>/lib/seqtrimnext/utils/string_utils.rb class String def integer? res = true begin r=Integer(self) rescue res=false end return res end def decamelize self.to_s. gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'). gsub(/([a-z]+)([A-Z\d])/, '\1_\2'). gsub(/([A-Z]{2,})(\d+)/i, '\1_\2'). gsub(/(\d+)([a-z])/i, '\1_\2'). gsub(/(.+?)\&(.+?)/, '\1_&_\2'). gsub(/\s/, '_').downcase end end class File def self.is_zip?(file_path) res=false begin f=File.open(file_path,'rb') head=f.read(4) f.close res=(head=="PK\x03\x04") rescue res=false end return res end def self.unzip(file_path) unzipped=`unzip "#{file_path}"` file_list = unzipped.split("\n") list=[] # select only the files, not folders list=file_list.select{|e| e=~/inflating/}.map{|e| e.gsub('inflating:','').strip} return list end end<file_sep>/bin/group_by_range.rb #!/usr/bin/env ruby if ARGV.count != 1 puts "#{$0} FASTA " exit end file = ARGV.shift f=File.open(file) f.each_line do |line| puts line end <file_sep>/lib/seqtrimnext/classes/em_classes/seqtrim_work_manager.rb require 'scbi_fasta' require 'scbi_fastq' # require 'work_manager' require 'graph_stats' require 'sequence_with_action' require 'sequence_group' # OUTPUT_PATH='output_files' STATS_PATH=File.join(OUTPUT_PATH,'stats.json') # TODO - Pasar secuencias en grupos, y hacer blast en grupos de secuencias. class SeqtrimWorkManager < ScbiMapreduce::WorkManager def self.init_work_manager(sequence_readers, params, chunk_size = 100, use_json=false, skip_output=false, write_in_gzip=true) @@full_stats={} @@params= params @@exit = false @@exit_status=0 @@ongoing_stats={} @@ongoing_stats[:sequence_count] = 0 @@ongoing_stats[:smallest_sequence_size] = 900000000000000 @@ongoing_stats[:biggest_sequence_size] = 0 @@skip_output=skip_output @@write_in_gzip=write_in_gzip @@chunk_size = chunk_size checkpoint_exists=File.exists?(ScbiMapreduce::CHECKPOINT_FILE) # @@use_qual = !qual_path.nil? and File.exists?(qual_path) @@open_mode='w' if checkpoint_exists @@open_mode = 'a' end #open input file @@sequence_readers=sequence_readers # @@use_qual = @@fqr.with_qual? # @@use_json = use_json @@params.set_param('use_qual',@@sequence_readers.first.with_qual?) @@params.set_param('use_json',use_json) @@params.set_param('tuple_size',@@sequence_readers.count) @@use_json=use_json @@sequence_readers.each do |sequence_reader| sequence_reader.rewind end # open output files if !Dir.exists?(OUTPUT_PATH) Dir.mkdir(OUTPUT_PATH) end @@files={} # @@rejected_output_file=File.open(File.join(OUTPUT_PATH,'rejected.txt'),@@open_mode) # seqs_with_errors @@errors_file=File.open('errors.txt',@@open_mode) if @@use_json @@json_output=File.open('results.json',@@open_mode) end @@json_separator='' @@paired_output_files={} @@sequences_output_files={} @@low_complexity_output_files={} @@sffinfo_files={} @@low_sffinfo_files={} @@tuple_id=0 end def self.exit_status return @@exit_status end def self.end_work_manager # if initial files doesn't exists, create it if !File.exists?(File.join(OUTPUT_PATH,'initial_stats.json')) File.open(File.join(OUTPUT_PATH,'initial_stats.json'),'w') do |f| f.puts JSON.pretty_generate(@@ongoing_stats) end end # load stats #r=File.read(STATS_PATH) #stats=JSON::parse(r) stats=@@full_stats # make graphs gs=GraphStats.new(stats) #close all files if @@use_json @@json_output.close end @@errors_file.close @@files.each do |k,file| file.close end end def self.global_error_received(error_exception) $LOG.error "Global error:\n" + error_exception.message + ":\n" +error_exception.backtrace.join("\n") @@errors_file.puts "Global error:\n" + error_exception.message + ":\n" +error_exception.backtrace.join("\n") @@errors_file.puts "="*60 @@exit_status=-1 SeqtrimWorkManager.controlled_exit end def self.work_manager_finished @@full_stats['scbi_mapreduce']=@@stats puts "FULL STATS:\n" +JSON.pretty_generate(@@full_stats) # create stats file f = File.open(STATS_PATH,'w') f.puts JSON.pretty_generate(@@full_stats) f.close end def error_received(worker_error, obj) @@errors_file.puts "Error while processing object #{obj.inspect}\n" + worker_error.original_exception.message + ":\n" +worker_error.original_exception.backtrace.join("\n") @@errors_file.puts "="*60 @@exit_status=-1 SeqtrimWorkManager.controlled_exit end def too_many_errors_received $LOG.error "Too many errors: #{@@error_count} errors on #{@@count} executed sequences, exiting before finishing" @@exit_status=-1 end def worker_initial_config return @@params end def load_user_checkpoint(checkpoint) # load full_stats from file !!!!!!!!!!!!! if File.exists?(STATS_PATH) # load stats text = File.read(STATS_PATH) # wipe text # text=text.grep(/^\s*[^#]/).to_s # decode json @@full_stats = JSON.parse(text) end # reset count stats since they are repeated by checkpointing # { # "sequences": { # "count": { # "input_count": 1600, # "output_seqs": 933, # "rejected": 67 # }, # "rejected": { # "short insert": 39, # "contaminated": 26, # "unexpected vector": 2 # } # } # } if @@full_stats['sequences'] if @@full_stats['sequences']['count'] # set input count to 0 @@full_stats['sequences']['count']['input_count']=0 # do not remove outputseqs # @@full_stats['sequences']['count']['output_seqs']=0 end # remove rejected due to repetitions from rejected count if @@full_stats['sequences']['rejected'] # it there are repeated if (@@full_stats['sequences']['rejected']['repeated']) # if repeated count > 0 and there count exists if (@@full_stats['sequences']['rejected']['repeated'] > 0) and @@full_stats['sequences']['count'] # discount repeated from rejected, since they are going to be added again by checkout process @@full_stats['sequences']['count']['rejected'] -= @@full_stats['sequences']['rejected']['repeated'] end # set repeated to 0 @@full_stats['sequences']['rejected']['repeated']=0 end end end # puts "Loaded Stats" # puts "FULL STATS:\n" +JSON.pretty_generate(@@full_stats) # TODO - remove sequences from rejected file that were added by cloned super # return checkpoint end def save_user_checkpoint f = File.open(STATS_PATH,'w') f.puts JSON.pretty_generate(@@full_stats) f.close end # read a work that will not be processed, only to skip until checkpoint def trash_checkpointed_work warn "Deprecated: trash_checkpointed_work was deprecated, it is automatic now" end def get_next_seq_from_file(file) # find a valid and no repeated sequence in file begin n,f,q,c = file.next_seq if !n.nil? && @@params.repeated_seq?(n) @@full_stats.add_stats({'sequences' => {'count' => {'rejected' => 1}}}) @@full_stats.add_stats({'sequences' => {'rejected' => {'repeated' => 1}}}) get_file(File.join(OUTPUT_PATH,'rejected.txt')).puts('>'+n+ ' repeated') end if !n.nil? @@ongoing_stats[:sequence_count] += 1 @@ongoing_stats[:smallest_sequence_size] = [f.size, @@ongoing_stats[:smallest_sequence_size]].min @@ongoing_stats[:biggest_sequence_size] = [f.size, @@ongoing_stats[:smallest_sequence_size]].max @@full_stats.add_stats({'sequences' => {'count' => {'input_count' => 1}}}) end end while (!n.nil? && @@params.repeated_seq?(n)) return n,f,q,c end def next_work if @@exit return nil end tuple=[] order_in_tuple=0 @@tuple_id += 1 tuple_size=@@sequence_readers.count @@sequence_readers.each do |sequence_reader| n,f,q,c = get_next_seq_from_file(sequence_reader) if !n.nil? seq=SequenceWithAction.new(n,f.upcase,q,c) seq.tuple_id=@@tuple_id seq.order_in_tuple=order_in_tuple seq.tuple_size=tuple_size tuple << seq order_in_tuple+=1 end end if tuple_size>1 # check duplicated names names = tuple.map{|s| s.seq_name} if names.uniq.count!=tuple_size # puts "NAMES EQUAL IN TUPLE" tuple.each_with_index do |seq,i| # puts seq.class # seq_name seq.seq_name = "#{seq.seq_name}/#{i+1}" end end end # tuple is complete if tuple.count==tuple_size return tuple else return nil end end def work_received(obj) res = obj # collect stats @@full_stats.add_stats(obj.stats) # print output in screen if !@@skip_output puts obj.output_text end # save results to files save_files(obj) end def save_files(obj) files=obj.output_files files.each do |file_name,content| f=get_file(file_name) f.puts content end end def get_file(file_name) res_file = @@files[file_name] # if file is not already open, create it if res_file.nil? # create dir if necessary dir = File.dirname(file_name) if !File.exists?(dir) FileUtils.mkdir_p(dir) end # open file if @@write_in_gzip && file_name.upcase.index('.FASTQ') file=File.open(file_name+'.gz',@@open_mode) res_file=Zlib::GzipWriter.new(file) else res_file=File.open(file_name,@@open_mode) end # save it in hash for next use @@files[file_name]=res_file end return res_file end end <file_sep>/lib/seqtrimnext/classes/sequence.rb ######################################################## # Author: <NAME> # # Defines the class Sequence's attribute # ######################################################## class Sequence #storages the name and the contains from fasta sequence def initialize(seq_name,seq_fasta,seq_qual, seq_comment = '') @seq_fasta=seq_fasta @seq_name=seq_name @seq_qual=seq_qual @seq_comment = seq_comment @seq_rejected=false @seq_repeated=false @seq_reversed=false @seq_rejected_by_message='' @ns_present = ns_present? @xs_present = xs_present? # puts "INIT SEQ >>>> #{seq_name} #{seq_specie}" end attr_accessor :seq_name, :seq_fasta, :seq_qual, :seq_comment , :seq_rejected, :seq_repeated , :seq_reversed attr_accessor :seq_rejected_by_message def ns_present? return (@seq_fasta.index('N') != nil) end def xs_present? return (@seq_fasta.index('X') != nil) end def seq_is_long_enough(seq_min_length) return (@seq_fasta.length>=seq_min_length) end def to_fasta return ">"+@seq_name.to_s+"\n"+@seq_fasta end def to_qual return ">"+@seq_name.to_s+"\n"+"#{@seq_qual}" end end <file_sep>/lib/seqtrimnext/classes/plugin_manager.rb ######################################### # Author:: <NAME> # This class provided the methods to manage the execution of the plugins ######################################### require 'json' require 'sequence_with_action' require 'sequence_group' class PluginManager attr_accessor :plugin_names #Storages the necessary plugins specified in 'plugin_list' and start the loading of plugins def initialize(plugin_list,params) @plugin_names = plugin_list.strip.split(',').map{|p| p.strip}.reject{|p| ['',nil].include?(p)} @params = params # puts plugin_list load_plugins_from_files end # Receives the plugin's list , and create an instance from its respective class (it's that have the same name) def execute_plugins(running_seqs) # $LOG.info " Begin process: Execute plugins " if !@plugin_names.empty? # keeps a list of rejected sequences rejected_seqs = [] @plugin_names.each do |plugin_name| # remove rejected or empty seqs from execution list running_seqs.reverse_each do |seq| if seq.seq_rejected || seq.seq_fasta.empty? # remove from running running_seqs.delete(seq) # save in rejecteds rejected_seqs.push seq end end if running_seqs.empty? break end # Creates an instance of the respective plugin stored in "plugin_name",and asociate it to the sequence 'seq' plugin_class = Object.const_get(plugin_name) plugin_execution=plugin_class.new(running_seqs,@params) running_seqs.stats[plugin_name] = plugin_execution.stats # puts running_seqs.stats.to_json plugin_execution=nil end #end each running_seqs.add(rejected_seqs) else raise "Plugin list not found" end #end if lista-param end # Checks if the parameters are right for all plugins's execution. Finally return true if all is right or false if isn't def check_plugins_params(params) res = true if !@plugin_names.empty? #$LOG.debug " Check params values #{plugin_list} " @plugin_names.each do |plugin_name| #Call to the respective plugin storaged in 'plugin_name' plugin_class = Object.const_get(plugin_name) # DONE - chequear si es un plugin de verdad u otra clase # puts plugin_class,plugin_class.ancestors.map {|e| puts e,e.class} if plugin_class.ancestors.include?(Plugin) errors=plugin_class.check_params(params) else errors= [plugin_name + ' is not a valid plugin'] end if !errors.empty? $LOG.error plugin_name+ ' found following errors:' errors.each do |error| $LOG.error ' -' + error res = false end #end each end #end if end #end each else $LOG.error "No plugin list provided" res = false end #end if plugin-list return res end # Iterates by the files from the folder 'plugins', and load it def load_plugins_from_files # DONE - CARGAR los plugins que hay en @plugin_names en vez de todos # the plugin_name changes to file using plugin_name.decamelize @plugin_names.each do |plugin_name| plugin_file = plugin_name.decamelize require plugin_file end end # end def # Iterates by the files from the folder 'plugins', and load it def load_plugins_from_files_old # DONE - CARGAR los plugins que hay en @plugin_names en vez de todos ignore = ['.','..','plugin.rb'] #carpeta=Dir.open("progs/ruby/seqtrimii/plugins") plugins_path = File.expand_path(File.join(File.dirname(__FILE__), "../plugins")) if !File.exists?(plugins_path) raise "Plugin folder does not exists" end # carpeta=Dir.open(plugins_path) entries = Dir.glob(File.join(plugins_path,'*.rb')) # carpeta. entries.each do |plugin| if !ignore.include?(plugin) require plugin end # end if end # end each end # end def end <file_sep>/lib/seqtrimnext/plugins/plugin_key.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginKey # Inherit: Plugin ######################################################## class PluginKey < Plugin #Begins the pluginKey's execution to warn where is a key in the sequence "seq" def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: marking key into the sequence" # blast_table_results.inspect actions=[] key_size=0 # mid_size=0 key_beg,key_end=[0,3] key_size=4 key=seq.seq_fasta[0..3].upcase a = seq.new_action(key_beg,key_end,'ActionKey') # adds the actionKey to the sequence actions.push a #Add actions seq.add_actions(actions) if @group_by_key seq.add_file_tag(0,'key_' + key, :dir) add_stats('key_tag',key) end add_stats('key_size',key_size) # add_stats('mid_size',mid_size) end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] # self.check_param(errors,params,'blast_evalue_mids','Float') # self.check_param(errors,params,'blast_percent_mids','Integer') comment='sequences containing with diferent keys (barcodes) are saved to separate folders' default_value='false' params.check_param(errors,'use_independent_folder_for_each_key','String',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/plugins/plugin_amplicons.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginAdapters # Inherit: Plugin ######################################################## class PluginAmplicons < Plugin def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast=BatchBlast.new("-db #{@params.get_param('primers_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_primers')}") $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas) # puts blast_table_results.inspect return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for primers into the sequence" # puts blast_query.inspect # merge hits # primers=blast_query.merged_hits! # do not merge hits, since id is important primers=blast_query.hits min_primer_size=@params.get_param('min_primer_size').to_i # puts "MERGED:" # puts primers.inspect # type = 'ActionAbAdapter' actions=[] adapter_size=0 # filter primers by size primers = primers.select{|primer| (primer.size >= min_primer_size)}.sort{|p1,p2| p1.size<=>p2.size}.reverse # puts "FILTERED:" # puts primers.inspect # reject sequences with less than two primers if primers.count < 2 seq.seq_rejected=true seq.seq_rejected_by_message='Primer pair not found' # @stats[:rejected_seqs]={'rejected_seqs_by_contaminants' => 1} add_stats('rejected','primers_not_found') else # has two primers, or more if seq.seq_fasta.index('N') seq.seq_rejected=true seq.seq_rejected_by_message='At least one N found' # @stats[:rejected_seqs]={'rejected_seqs_by_contaminants' => 1} add_stats('rejected','one_n_found') else # puts "<NAME>" # take first two primers and order them by qbeg left_primer = primers[0..1].sort{|p1,p2| p1.q_beg<=>p2.q_beg}.first right_primer = primers[0..1].sort{|p1,p2| p1.q_beg<=>p2.q_beg}.last # puts "LEFT_PRIMER:" # puts left_primer.inspect # puts "RIGHT_PRIMER:" # puts right_primer.inspect # if (left_primer.size>= min_primer_size) && (right_primer.size>= min_primer_size) a = seq.new_action(left_primer.q_beg,left_primer.q_end,'ActionLeftPrimer') a.message = left_primer.subject_id a.tag_id = left_primer.subject_id a.reversed = left_primer.reversed a.left_action = true actions.push a add_stats('primer_size',left_primer.size) add_stats('primer_id',left_primer.subject_id) a = seq.new_action(right_primer.q_beg,right_primer.q_end,'ActionRightPrimer') a.message = right_primer.subject_id a.reversed = right_primer.reversed a.tag_id = right_primer.subject_id a.right_action = true actions.push a add_stats('primer_size',right_primer.size) add_stats('primer_id',right_primer.subject_id) seq.add_file_tag(2, left_primer.subject_id, :file) seq.add_file_tag(2, right_primer.subject_id, :file) # end if !actions.empty? seq.add_actions(actions) add_stats('sequences_with_primers','count') # add_stats('sequences',seq.seq_fasta) end end # end end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for primers' # default_value = 1e-6 default_value = 1 params.check_param(errors,'blast_evalue_primers','Float',default_value,comment) comment='Minimum required identity (%) for a reliable primer' default_value = 95 params.check_param(errors,'blast_percent_primers','Integer',default_value,comment) comment='Minimun primer size' default_value = 15 params.check_param(errors,'min_primer_size','Integer',default_value,comment) comment='Path for primers database' # default_value = File.join($FORMATTED_DB_PATH,'adapters_ab.fasta') default_value=nil params.check_param(errors,'primers_db','DB',default_value,comment) return errors end # def self.get_graph_title(plugin_name,stats_name) # case stats_name # when 'adapter_type' # 'AB adapters by type' # when 'adapter_size' # 'AB adapters by size' # end # end # # def self.get_graph_filename(plugin_name,stats_name) # return stats_name # # # case stats_name # # when 'adapter_type' # # 'AB adapters by type' # # when 'adapter_size' # # 'AB adapters by size' # # end # end # # def self.valid_graphs # return ['adapter_type'] # end # def self.plot_setup(stats_value,stats_name,x,y,init_stats,plot) # # # puts "============== #{stats_name}" # # # puts stats_name # case stats_name # # when 'primer_size' # plot.x_label= "Length" # plot.y_label= "Count" # # plot.x_range="[0:#{init_stats['biggest_sequence_size'].to_i}]" # plot.x_range="[0:200]" # puts x.class # plot.add_x(x) # plot.add_y(y) # # plot.do_graph # # return true # else # return false # end # # end end <file_sep>/bin/extract_seqs_from_fastq.rb #!/usr/bin/env ruby require 'scbi_fastq' class Array def count self.length end end if ARGV.count != 3 puts "#{$0} FASTQ OUTPUT_NAME SEQ_NAMES_FILE" exit else fasta = ARGV.shift output_name = ARGV.shift seqs_file=ARGV.shift seqs=[] f=File.open(seqs_file).each_line do |line| seqs.push line.strip.chomp end puts seqs.join(';') fqr=FastqFile.new(fasta) output_fastq=FastqFile.new(output_name+'.fastq','w') fqr.each do |seq_name,seq_fasta,seq_qual| if seqs.index(seq_name) output_fastq.write_seq(seq_name,seq_fasta,seq_qual) seqs.delete(seq_name) if seqs.empty? break end end end output_fastq.close fqr.close end <file_sep>/lib/seqtrimnext/actions/action_paired_reads.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginPairedReads # Inherit: Plugin ######################################################## class ActionPairedReads < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =true end def apply_to(seq) $LOG.debug "Applying #{self.class}" #Storage the first and second subsequences subseq1 = seq.seq_fasta[0,@start_pos-1] subseq2 = seq.seq_fasta[@end_pos+1,seq.seq_fasta.length-1] #$LOG.debug "\nSubsequence left: #{subseq1} \n Subsequence right: #{subseq2}}" end end <file_sep>/lib/seqtrimnext/utils/fasta2xml.rb #!/usr/bin/env ruby command_info=" #================================================ # Author: <NAME> # # # Usage: fasta2xml.rb <fasta_file> [> <out_file.xml>] # # Converts a fasta file to xml format (used for cabog) # # Prints to stdout, can be redirected to file with > # #================================================ \n"; #require "utils/fasta_utils" require File.dirname(__FILE__) + "/utils/fasta_utils" #receive one argument or fail if ARGV.length != 1 puts command_info; Process.exit(-1); end #get file name file_name=ARGV[0]; #check if file exists if !File.exist?(file_name) puts "File #{file_name} not found.\n"; puts command_info; Process.exit(-1); end ###################################### # Define a subclass to override events ###################################### class FastaProcessor< FastaUtils::FastaReader #override begin processing def on_begin_process() # print XML header puts "<?xml version=\"1.0\"?>\n<trace_volume>\n"; end #override sequence processing def on_process_sequence(seq_name,seq_fasta) # prints the xml tags puts "<trace>\n\t<trace_name>#{seq_name}</trace_name>\n\t<clip_vector_left>1</clip_vector_left>\n\t<clip_vector_right>#{seq_fasta.length.to_s}</clip_vector_right>\n</trace>\n"; end #override end processing def on_end_process() #print foot puts "</trace_volume>\n"; end end #Create a new instance to process the file f=FastaProcessor.new(file_name); <file_sep>/lib/seqtrimnext/plugins/plugin_sanger_adapters.rb require "plugin" ######################################################## # Author: <NAME> ABR # # Defines the main methods that are necessary to execute PluginAdapters # Inherit: Plugin ######################################################## class PluginSangerAdapters < Plugin # adapters found at end of sequence are even 2 nt wide, cut in 5 because of statistics MIN_ADAPTER_SIZE = 5 MIN_FAR_ADAPTER_SIZE = 13 MIN_LEFT_ADAPTER_SIZE = 9 def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast=BatchBlast.new("-db #{@params.get_param('adapters_sanger_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_sanger')} -word_size #{MIN_ADAPTER_SIZE}") $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas) # puts blast_table_results.inspect return blast_table_results end # filter hits that are far the extreme and do not have a valid length def filter_hits(hits,end_pos) # hits.reverse_each do |hit| # # if (hit.q_end < (end_pos-40)) && ((hit.q_end-hit.q_beg+1)<(@params.get_sanger_adapter(hit.subject_id).length*0.80).to_i) # if ((hit.q_end-hit.q_beg+1)<(@params.get_sanger_adapter(hit.subject_id).length*0.80).to_i) # hits.delete(hit) # end # end end def filter_adapters(adapters) min_size=@params.get_param('min_sanger_adapter_size').to_i adapters.reverse_each do |c| adapter_size=c.q_end-c.q_beg+1 if adapter_size < min_size adapters.delete(c) end end end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for adapters into the sequence" # blast=BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'adapters_ab.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_ab')} -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE}") # blast with only one sequence, no with many sequences from a database #--------------------------------------------------------------------- # blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to adapterss executing over blast #BlastTableResult.new(res) # puts blast_query.inspect # puts blast_table_results.inspect # filter_hits(blast_query.hits, seq.seq_fasta.length) adapters=[] # blast_table_results.querys.each do |query| # first round to save adapters without overlap merge_hits(blast_query.hits,adapters) # end begin adapters2=adapters # second round to save adapters without overlap adapters = [] merge_hits(adapters2,adapters) end until (adapters2.count == adapters.count) # type = 'ActionAbAdapter' actions=[] adapter_size=0 filter_adapters(adapters) if adapters.count==1 # only one adapter c=adapters.first adapter_size=c.q_end-c.q_beg+1 message = c.subject_id type = 'ActionSangerLeftAdapter' stat_type='left' add_stats('adapter_type',stat_type) a = seq.new_action(c.q_beg,c.q_end,type) a.message = message a.reversed = c.reversed a.left_action = true actions.push a add_stats('adapter_size',adapter_size) add_stats('adapter_id',message) elsif adapters.count >=2 type = 'ActionSangerLeftAdapter' stat_type='left' left_action=true right_action=false adapters.sort!{|a1,a2| a1.q_beg <=> a2.q_beg} old_qend=adapters.first.q_end max_slice_size=[] # left_qend=adapters.first.q_end adapters.each do |c| # adds the correspondent action to the sequence # check if it is a right adapter if c.q_beg > (old_qend+50) type=type = 'ActionSangerRightAdapter' stat_type='right' left_action=false right_action=true end adapter_size=c.q_end-c.q_beg+1 message = c.subject_id add_stats('adapter_type',stat_type) a = seq.new_action(c.q_beg,c.q_end,type) a.message = message a.reversed = c.reversed a.left_action = left_action a.right_action = right_action # if action.last.q_end - a.start_pos > max_slice_size.last[:size] # end actions.push a add_stats('adapter_size',adapter_size) add_stats('adapter_id',message) old_qend=adapters.first.q_end end end if !actions.empty? seq.add_actions(actions) add_stats('sequences_with_adapter','count') end # end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for Sanger adapters' # default_value = 1e-6 default_value = 1 params.check_param(errors,'blast_evalue_sanger','Float',default_value,comment) comment='Minimum required identity (%) for a reliable Sanger adapter' default_value = 95 params.check_param(errors,'blast_percent_sanger','Integer',default_value,comment) comment='Minimum required adapter size for a valid Sanger adapter' default_value = 10 params.check_param(errors,'min_sanger_adapter_size','Integer',default_value,comment) comment='Path for Sanger adapters database' default_value = File.join($FORMATTED_DB_PATH,'adapters_sanger.fasta') params.check_param(errors,'adapters_sanger_db','DB',default_value,comment) return errors end def self.get_graph_title(plugin_name,stats_name) case stats_name when 'adapter_type' 'Sanger adapters by type' when 'adapter_size' 'Sanger adapters by size' end end def self.get_graph_filename(plugin_name,stats_name) return stats_name # case stats_name # when 'adapter_type' # 'AB adapters by type' # when 'adapter_size' # 'AB adapters by size' # end end def self.valid_graphs return ['adapter_type'] end end <file_sep>/bin/split_fastq.rb #!/usr/bin/env ruby require 'scbi_fastq' if ARGV.count < 3 puts "#{$0} FASTQ OUTPUT_NAME SPLIT_BY [-gz]" exit end fastq = ARGV.shift output_name = ARGV.shift split_by = ARGV.shift.to_i gz_arg=ARGV.shift gz='' if !gz_arg.nil? and gz_arg.index('-gz') gz='.gz' end file_index=1 out=FastqFile.new("#{output_name}#{file_index}.fastq#{gz}","w#{gz}") fqr=FastqFile.new(fastq) count = 0 fqr.each do |seq_name,seq_fasta,seq_qual,comments| out.write_seq(seq_name,seq_fasta,seq_qual,comments) count +=1 if (count % split_by) == 0 file_index +=1 out.close out=FastqFile.new("#{output_name}#{file_index}.fastq#{gz}","w#{gz}") end end out.close fqr.close <file_sep>/bin/extract_seqs_from_fasta.rb #!/usr/bin/env ruby require 'scbi_fasta' # GOOD_QUAL=50 # BAD_QUAL=10 # DOWN_CASE=('a'..'z') class Array def count self.length end end if ARGV.count < 4 puts "#{$0} FASTA QUAL OUTPUT_NAME SEQ_NAMES_FILE" exit else fasta = ARGV.shift qual = ARGV.shift output_name = ARGV.shift seqs_file=ARGV.shift seqs=[] f=File.open(seqs_file).each_line do |line| seqs.push line.strip.chomp end # puts seqs.join(';') fqr=FastaQualFile.new(fasta,qual) output_fasta=File.new(output_name+'.fasta','a') output_qual=File.new(output_name+'.fasta.qual','a') fqr.each do |seq_name,seq_fasta,seq_qual| if seqs.index(seq_name) output_fasta.puts ">#{seq_name}" output_fasta.puts seq_fasta output_qual.puts ">#{seq_name}" output_qual.puts seq_qual seqs.delete(seq_name) if seqs.empty? break end end end output_qual.close output_fasta.close fqr.close end <file_sep>/bin/filter_database.rb #!/usr/bin/env ruby require 'scbi_fasta' if ARGV.count!=3 puts "Usage: #{File.basename($0)} database min_size name_list" exit end min_size = ARGV[1].to_i # read keywords keywords=File.read(ARGV[2]).split("\n") # convert all to upcase keywords.map { |keyword| keyword.upcase!} # puts "Search keywords" # keywords.each { |keyword| puts keyword} fqr=FastaQualFile.new(ARGV[0]) all=[] fqr.each do |n,s,c| keywords.each do |keyword| if s.length<=min_size # all+=c.split(" ") if c.upcase.index(keyword) # puts "[#{s.length.to_s}] - #{n} - #{c}" puts ">#{n} #{c}\n#{s}" break end end end end # puts all.sort.uniq.reject{|e| e=~/\d/} fqr.close <file_sep>/lib/seqtrimnext/classes/sequence_group.rb class SequenceGroup attr_accessor :stats,:output_text,:output_files def initialize(seqs) @stats={} @seqs=seqs @output_text={} @output_files={} end def push(seq) @seqs.push seq end def delete(seq) @seqs.delete(seq) end def empty? return @seqs.empty? end def each @seqs.each do |seq| yield seq end end def each_slice(n) @seqs.each_slice(n) do |seqs| yield seqs end end def each_with_index @seqs.each_with_index do |seq,i| yield seq,i end end def reverse_each @seqs.reverse_each do |seq| yield seq end end def add(array) @seqs = @seqs + array # sort by tuple_id and order in tuple @seqs.sort! do |a,b| comp = (a.tuple_id <=> b.tuple_id) comp.zero? ? (a.order_in_tuple <=> b.order_in_tuple) : comp end # print # @seqs.each do |s| # puts "TID:#{s.tuple_id}, OIT: #{s.order_in_tuple}" # end end def count return @seqs.count end def include?(s) return @seqs.include?(s) end def remove_all_seqs @seqs=[] end # def job_identifier # return @seqs[0].seq_name # end def inspect return "Group with #{@seqs.count} sequences" end end<file_sep>/lib/seqtrimnext/utils/recover_mid.rb module RecoverMid #receives hit of mid from blast, complete db_mid from DB and SEQ_fasta def recover_mid(hit, db_mid, seq) mid_in_seq = seq[hit.q_beg..hit.q_end] mid_in_mid = db_mid[hit.s_beg..hit.s_end] if hit.s_beg==0 # look right parts mid_part=db_mid[hit.s_end+1..db_mid.length] seq_part=seq[hit.q_end+1,mid_part.length+1] common=mid_part.lcs(seq_part) in_seq_pos=seq_part.index(common) # puts "seq right part: #{seq_part}, mid right part #{mid_part} => Match: #{common}" if in_seq_pos>1 # # puts "NO VALE, comienza en #{in_seq_pos}" in_seq_pos=0 common='' end new_q_beg=hit.q_beg new_q_end=hit.q_end+in_seq_pos+common.length recovered_mid=seq[new_q_beg..new_q_end] recovered_size=hit.q_end-hit.q_beg+1+common.length else hit.s_end == db_mid.length-1#look left parts mid_part=db_mid[0..hit.s_beg-1] seq_part=seq[hit.q_beg-mid_part.length-1..hit.q_beg-1] common=mid_part.lcs(seq_part) in_seq_pos=hit.q_beg-mid_part.length-1+seq_part.index(common) # puts "seq left part: #{seq_part}, mid right part #{mid_part} => Match: #{common} at #{in_seq_pos}" if in_seq_pos+common.length<hit.q_beg-1 # puts "NO VALE, comienza en #{in_seq_pos+common.length} < #{hit.q_beg}" in_seq_pos=hit.q_beg common='' end new_q_beg=in_seq_pos new_q_end=hit.q_end recovered_mid=seq[new_q_beg..new_q_end] recovered_size=hit.q_end-hit.q_beg+1+common.length end return [new_q_beg, new_q_end, recovered_size,recovered_mid] end end class String def lcs(s2) s1=self res="" num=Array.new(s1.size){Array.new(s2.size)} len,ans=0 lastsub=0 s1.scan(/./).each_with_index do |l1,i | s2.scan(/./).each_with_index do |l2,j | unless l1==l2 num[i][j]=0 else (i==0 || j==0)? num[i][j]=1 : num[i][j]=1 + num[i-1][j-1] if num[i][j] > len len = ans = num[i][j] thissub = i thissub -= num[i-1][j-1] unless num[i-1][j-1].nil? if lastsub==thissub res+=s1[i,1] else lastsub=thissub res=s1[lastsub, (i+1)-lastsub] end end end end end res end end <file_sep>/bin/gen_qual.rb #!/usr/bin/env ruby require 'scbi_fasta' GOOD_QUAL=50 BAD_QUAL=10 DOWN_CASE=('a'..'z') class Array def count self.length end end if ARGV.count != 2 puts "Programa ENTRADA SALIDA" exit else puts ARGV[0] puts ARGV[1] fqr=FastaQualFile.new(ARGV[0]) f = File.new(ARGV[1],'w+') fqr.each do |seq_name,seq_fasta,seq_qual| f.puts ">#{seq_name}" res =[] seq_fasta.each_char do |c| if DOWN_CASE.include?(c) res << BAD_QUAL else res << GOOD_QUAL end end f.puts res.join(' ') #f.puts "50 "*seq_fasta.length end f.close fqr.close end <file_sep>/bin/resume_rejected.rb #!/usr/bin/env ruby if ARGV.count!=1 puts "You must specify a file with seqtrim's rejected sequences" puts "Usage $0 rejected_seqtrim_file"; exit(-1); end rejected_file=ARGV.shift if !File.exists?(rejected_file) puts "File #{rejected_file} doesn't exists" puts "Usage $0 rejected_seqtrim_file"; exit(-1); end res={} File.open(rejected_file).each do |line| cols=line.split(' ') cols.shift res[cols.join(' ')] = 0 if !res[cols.join(' ')] res[cols.join(' ')] += 1 end res.each do |k,v| puts "#{v} #{k}" end <file_sep>/lib/seqtrimnext/classes/scbi_stats.rb #!/usr/bin/env ruby require 'json' class Array def sum r=0 each do |e| r+=e end return r end end class ScbiStats def initialize(values) @values=values end def get_window_value(i,window_size=10) start_pos=[0,i-window_size].max end_pos=[@values.length,i+window_size].min # puts "#{@values[start_pos..end_pos]} => #{@values[start_pos..end_pos].sum}" return @values[start_pos..end_pos].sum end def fat_mode(window_size=10) fat_modes=[] max_fat=0 @values.length.times do |i| fat=get_window_value(i) fat_modes << fat if fat_modes[max_fat] < fat max_fat=i end end # puts fat_modes return max_fat # puts @values.length, @fat_modes.length end end # istat=JSON.parse(File.read('initial_stats.json')) # # x=[] # istat['qv'].each do |qv| # x<< qv['tot'].to_i # # end # # Usage: # # s=ScbiStats.new(x) # # puts s.fat_mode <file_sep>/lib/seqtrimnext/actions/action_insert.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute ActionInserted # Inherit: Plugin ######################################################## class ActionInsert < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =false @informative = true end # #this method is launched when the size of inserted is enough # def apply_to(seq) # # # seq.seq_fasta = seq.seq_fasta.slice(start_pos,end_pos) # $LOG.debug " Applying #{self.class}. ------Inserted has enough size ------ . BEGIN: #{@start_pos} END: #{@end_pos} " # # # end def apply_decoration(char) return char end end <file_sep>/lib/seqtrimnext/classes/gnu_plot_graph.rb require 'gnuplot' class GnuPlotGraph def initialize(file_name,x,y,title=nil) $VERBOSE=true Gnuplot.open do |gp| # histogram Gnuplot::Plot.new( gp ) do |plot| # plot.space= 5 # it's the free space between the first/last value and the begin/end of axis X #plot.set("xrange [#{xr_min}: #{xr_max}]") if !title title=file_name end plot.title "#{title}" plot.xlabel "length" plot.ylabel "Number of sequences" plot.set "key off" #leyend # plot.set "style fill solid 1.00 border -1" # #plot.set "style histogram clustered gap 0 title offset character 0, 0, 0" # plot.set "style data histograms" # plot.set "boxwidth 0.2 absolute" # For this next line, lw is linewidth (2-4)? #plot [XMIN:XMAX] 'myHistogramData' with boxes lw VALUE contains_strings=false x.each do |v| begin r=Integer(v) rescue contains_strings=true break end end if !contains_strings # plot.set "xrange [*:*]" # puts "INTEGER GRAPH" plot.style "fill pattern 22 border -1" plot.set "boxwidth 0.2" # Probably 3-5. plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds| #ds.with= " boxes lw 1" # ds.using="" ds.with= " imp lw 4" end else #graph with strings in X axis # puts "STRING GRAPH" plot.xlabel "" plot.set "style fill solid 1.00 border -1" plot.set "style histogram clustered gap 1 title offset character 0, 0, 0" plot.set "style data histogram" plot.set "boxwidth 0.2 absolute" if x.count>4 then plot.set "xtics offset 0,graph 0 rotate 90" end # $VERBOSE=true # plot.set "style data linespoints" # plot.set "xtics border in scale 1,0.5 nomirror rotate by -45 offset character 0, 0, 0" # s = [] # # i=0 # x.each_with_index do |v,i| # #s.push "\"#{v}\"" # s.push "#{v} #{i}" # # # i+=1 # end # # # plot.set "xtics (#{s.join(',')})" # puts "XTICKS: (#{s.join(',')})" # puts "X:" # puts x.join(';') # puts "Y:" # puts y.join(';') # if more than 20 strings, then keep greater ones if x.count>20 # puts "original X:#{x.count}" $VERBOSE=true h = {} x.each_with_index do |x1,i| h[x1]=y[i] end # puts h.to_json x=[] y=[] 10.times do ma=h.max_by{|k,v| v} if ma puts "MAX:",ma.join(' * '),"of",h.values.sort.join(',') x.push ma[0] y.push ma[1] h.delete(ma[0]) end end # puts "MAX 20 #{x.length}:#{x.join(';')}" # set key below # plot.set "label 3 below" end plot.data << Gnuplot::DataSet.new( [x,y] ) do |ds| ds.using = "2:xticlabels(1)" #show the graph and use labels at x # ds.using="2" #ds.with= " boxes lw 1" # ds.using = "2 t 'Sequences' " #show the legend in the graph end end if !file_name.nil? plot.terminal "png size 800,600" plot.output "#{file_name}" end end end end end <file_sep>/lib/seqtrimnext/utils/load_qual_in_hash.rb #================================================ # SCBI - dariogf <<EMAIL>> #------------------------------------------------ # # Version: 0.1 - 04/2009 # # Usage: require "utils/fasta_utils" # # Fasta utilities # # # #================================================ require File.dirname(__FILE__) +"/qual_reader.rb" ###################################### # Define a subclass to override events ###################################### class LoadQualInHash< QualReader attr_reader :quals #override begin processing def on_begin_process() @quals = {} end def on_process_sequence(seq_name,seq_qual) @quals[seq_name]=seq_qual end #override end processing def on_end_process() end end <file_sep>/lib/seqtrimnext/classes/action_manager.rb ######################################### # Author:: <NAME> # This class provided the methods to apply actions to sequences ######################################### require 'seqtrim_action' class ActionManager #Storages the necessary plugins specified in 'plugin_list' and start the loading of plugins def initialize load_actions_from_files end def self.new_action(start_pos,end_pos,action_type) action_class = Object.const_get(action_type) # DONE mirar si la action_class es de verdad una action existente res = nil if !action_class.nil? && action_class.ancestors.include?(SeqtrimAction) res= action_class.new(start_pos,end_pos) else #$LOG.error ' Error. Don´t exist the action: ' + action_class.to_s puts ' Error. The action : ' + action_class.to_s+ ' does not exists' end return res end # Iterates by the files from the folder 'actions', and load it def load_actions_from_files ignore = ['.','..','seqtrim_action.rb'] #carpeta=Dir.open("progs/ruby/seqtrimii/actions") actions_path = File.expand_path(File.join(File.dirname(__FILE__), "..","actions")) if !File.exists?(actions_path) raise "Action folder does not exists" end carpeta=Dir.open(actions_path) carpeta.entries.each do |action| if !ignore.include?(action) require action end # end if end # end each end # end def end <file_sep>/bin/reverse_paired.rb #!/usr/bin/env ruby require 'scbi_fasta' if ARGV.count!=3 puts "Usage: #{$0} fasta qual output_base_name" exit end fasta_path = ARGV[0] qual_path = ARGV[1] name = ARGV[2] out_fasta = name+'.fasta' out_qual = name+'.fasta.qual' puts "Opening #{fasta_path}, #{qual_path}" fqr=FastaQualFile.new(fasta_path,qual_path,true) out_f=File.new(out_fasta,'w+') out_q=File.new(out_qual,'w+') c=0 fqr.each do |n,f,q| out_f.puts ">#{n}" out_q.puts ">#{n}" if n.index('dir=F') out_f.puts f.reverse.tr('actgACTG','tgacTGAC') out_q.puts q.reverse.join(' ') else out_f.puts f out_q.puts q.join(' ') end c=c+1 end puts c fqr.close out_f.close out_q.close <file_sep>/lib/seqtrimnext/plugins_old/plugin_rem_adit_artifacts.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginRemAditArtifacts # # Inherit: Plugin ######################################################## class PluginRemAditArtifacts < Plugin def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: removing artifacts into the sequence" seq2 = seq.seq_fasta first = 0 last = seq2.size-1 old_first=first old_last=last while (seq2 =~ /^(GCGGGG|CCCCGC)/i) first += 6 seq2.slice!(0..5) end while (seq2 =~ /(GCGGGG|CCCCGC)$/i) last -= 6 seq2.slice!(seq2.size-1-5..seq2.size-1) end #is_forward, is_cDNA, #TrimExtremeNXs(first,last) is_forward = @params.get_param('is_forward')=='true' is_cDNA = @params.get_param('is_cDNA')=='true' previous_first,previous_last =0,0 until ((previous_first == first) && (previous_last == last)) previous_first,previous_last = first, last if (is_cDNA) if (is_forward) nTs = 0 nTs = $1.length if (seq2 =~ /^(T+)/i) if (nTs > 3) seq2.slice!(0..nTs -1) first += nTs #-1 end nAs = 0 nAs = $1.length if (seq2 =~ /(A+)$/i) if (nAs > 3) seq2.slice!(seq2.size - nAs..seq2.size - 1) last -= nAs end else #si es backward nTs = 0 nTs = $1.length if (seq2 =~ /(T+)$/i) if (nTs > 3) seq2.slice!(seq2.size-nTs..seq2.size-1) last -= nTs end nAs = 0 nAs = $1.length if (seq2 =~ /^(A+)/i) if (nAs > 3) seq2.slice!(0..nAs -1) first += nAs end end end end if (((first>=0) && (first>old_first)) || ((last>=0) && (last<old_last))) type='ActionRemAditArtifacts' actions = [] # seq.add_action(first,last,type) a=seq.new_action(first,last,type) actions.push a seq.add_actions(actions) end end ###################################################################### #--------------------------------------------------------------------- def execute_old(seq) seq2 = seq.seq_fasta #seq2 = 'dGCGGGG' first = 0 last = seq2.size-1 old_first=first old_last=last # puts '1 '+seq2 # puts 'POS '+first.to_s # puts 'POS '+last.to_s while (seq2 =~ /^(GCGGGG|CCCCGC)/i) first += 6 seq2.slice!(0..5) # puts '2 '+seq2 # already = true end while (seq2 =~ /(GCGGGG|CCCCGC)$/i) last -= 6 seq2.slice!(seq2.size-1-5..seq2.size-1) # puts '3 '+seq2 # already = true end #is_forward, is_cDNA, #TrimExtremeNXs(first,last) is_forward = @params.get_param('is_forward') is_cDNA = @params.get_param('is_cDNA') # puts '4 '+seq2 previous_first,previous_last =0,0 until ((previous_first == first) && (previous_last == last)) previous_first,previous_last = first, last # puts 'POS5-F '+first.to_s # puts 'POS5-L '+last.to_s if (is_cDNA) if (is_forward) # puts '5 '+seq2 nTs = 0 nTs = $1.length if (seq2 =~ /^(T+)/i) if (nTs > 3) seq2.slice!(0..nTs -1) # puts '6 '+seq2 first += nTs #-1 # puts 'POS6-F '+first.to_s end nAs = 0 nAs = $1.length if (seq2 =~ /(A+)$/i) # puts '6-7 '+seq2 + nAs.to_s if (nAs > 3) # puts '7 '+seq2 seq2.slice!(seq2.size - nAs..seq2.size - 1) last -= nAs#seq2.size-nAs-2 # puts 'POS7-L '+last.to_s end else #si es backward # puts '5b '+seq2 nTs = 0 nTs = $1.length if (seq2 =~ /(T+)$/i) if (nTs > 3) # puts '6b '+seq2 seq2.slice!(seq2.size-nTs..seq2.size-1) last -= nTs#seq2.size-nTs -2 # puts 'POS6b-L '+last.to_s end nAs = 0 nAs = $1.length if (seq2 =~ /^(A+)/i) if (nAs > 3) # puts '7b '+seq2 seq2.slice!(0..nAs -1) first += nAs#nAs -1 # puts 'POS7b-f '+first.to_s end end end end #first -= 1 if (old_first!= first) #last += 1 if (old_last!= last) # puts 'POS7-8 '+first.to_s # puts 'POS7-8 '+last.to_s if (((first>=0) && (first>old_first)) || ((last>=0) && (last<old_last))) type='ActionRemAditArtifacts' # puts '8 '+seq2 seq.add_action(first,last,type) end # puts '9 '+seq2 end ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] # if !params.exists?('ta') # errors.push " The param <ta> doesn't exist" # end # if !params.exists?('poly_at_length') # errors.push " The param <poly_at_length> doesn't exist" # end return errors end end <file_sep>/lib/seqtrimnext/plugins/plugin_ab_adapters.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginAdapters # Inherit: Plugin ######################################################## class PluginAbAdapters < Plugin # adapters found at end of sequence are even 2 nt wide, cut in 5 because of statistics MIN_ADAPTER_SIZE = 5 MIN_FAR_ADAPTER_SIZE = 13 MIN_LEFT_ADAPTER_SIZE = 9 def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast=BatchBlast.new("-db #{@params.get_param('adapters_ab_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE}") # con culling limit hay situaciones en las que un hit largo con 1 mismatch es ignorado porque hay otro más corto que no tiene ningun error, no es aceptable. #blast=BatchBlast.new("-db #{@params.get_param('adapters_ab_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE} -culling_limit=1") $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") #blast_table_results = blast.do_blast(fastas) #blast_table_results = BlastTableResult.new(blast_table_results) t1=Time.now blast_table_results = blast.do_blast(fastas,:table,false) add_plugin_stats('execution_time','blast',Time.now-t1) #f=File.new("/tmp/salida_#{fastas.first.gsub('>','').gsub('/','_')}.blast",'w+') #f.puts blast.get_blast_cmd #f.puts blast_table_results #f.close t1=Time.now blast_table_results = BlastTableResult.new(blast_table_results) add_plugin_stats('execution_time','parse',Time.now-t1) # t1=Time.now # blast_table_results = blast.do_blast(fastas,:xml,false) # add_plugin_stats('execution_time','blast',Time.now-t1) # t1=Time.now # blast_table_results = BlastStreamxmlResult.new(blast_table_results) # add_plugin_stats('execution_time','parse',Time.now-t1) # puts blast_table_results.inspect return blast_table_results end # filter hits that are far the extreme and do not have a valid length def filter_hits(hits,end_pos) hits.reverse_each do |hit| if (hit.q_end < (end_pos-40)) && ((hit.q_end-hit.q_beg+1)<(@params.get_ab_adapter(hit.subject_id).length*0.80).to_i) hits.delete(hit) # puts "DELETE #{hit.inspect}" # else # puts "ACCEPTED #{hit.inspect}, >= #{(@params.get_ab_adapter(hit.subject_id).length*0.2).to_i}" end end end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for adapters into the sequence" # blast=BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'adapters_ab.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_ab')} -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE}") # blast with only one sequence, no with many sequences from a database #--------------------------------------------------------------------- # blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to adapterss executing over blast #BlastTableResult.new(res) # puts blast_query.inspect # puts blast_table_results.inspect filter_hits(blast_query.hits, seq.seq_fasta.length) adapters=[] # blast_table_results.querys.each do |query| # first round to save adapters without overlap merge_hits(blast_query.hits,adapters) # end begin adapters2=adapters # second round to save adapters without overlap adapters = [] merge_hits(adapters2,adapters) end until (adapters2.count == adapters.count) # puts "MERGED" # puts "="*50 # adapters.each {|a| puts a.inspect} max_to_end=@params.get_param('max_ab_to_end').to_i # type = 'ActionAbAdapter' actions=[] adapter_size=0 #@stats['adapter_size']={} adapters.each do |c| # adds the correspondent action to the sequence # puts "is the adapter near to the end of sequence ? #{c.q_end+seq.insert_start+max_to_end} >= ? #{seq.seq_fasta_orig.size-1}" adapter_size=c.q_end-c.q_beg+1 #if ((c.q_end+seq.insert_start+max_to_end)>=seq.seq_fasta_orig.size-1) right_action = true #if ab adapter is very near to the end of original sequence if c.q_end>=seq.seq_fasta.length-max_to_end message = c.subject_id type = 'ActionAbAdapter' ignore=false add_stats('adapter_type','normal') elsif (c.q_beg <= 4) && (adapter_size>=MIN_LEFT_ADAPTER_SIZE) #left adapter message = c.subject_id type = 'ActionAbLeftAdapter' ignore = false right_action = false add_stats('adapter_type','left') elsif (adapter_size>=MIN_FAR_ADAPTER_SIZE) message = c.subject_id type = 'ActionAbFarAdapter' ignore = false add_stats('adapter_type','far') else ignore=true end if !ignore a = seq.new_action(c.q_beg,c.q_end,type) a.message = message a.reversed = c.reversed if right_action a.right_action = true #mark as rigth action to get the left insert else a.left_action = true end actions.push a # puts "adapter_size #{adapter_size}" #@stats[:adapter_size]={adapter_size => 1} add_stats('adapter_size',adapter_size) add_stats('adapter_id',message) end end if !actions.empty? seq.add_actions(actions) add_stats('sequences_with_adapter','count') end # end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for 454 AB adapters' # default_value = 1e-6 default_value = 1 params.check_param(errors,'blast_evalue_ab','Float',default_value,comment) comment='Minimum required identity (%) for a reliable 454 AB adapter' default_value = 95 params.check_param(errors,'blast_percent_ab','Integer',default_value,comment) comment='454 AB adapters can be found only at the read end (not within it). The following variable indicates the number of nucleotides that are allowed for considering the AB adapters to be located at the end' default_value = 9 params.check_param(errors,'max_ab_to_end','Integer',default_value,comment) comment='Path for 454 AB adapters database' default_value = File.join($FORMATTED_DB_PATH,'adapters_ab.fasta') params.check_param(errors,'adapters_ab_db','DB',default_value,comment) return errors end def self.get_graph_title(plugin_name,stats_name) case stats_name when 'adapter_type' 'AB adapters by type' when 'adapter_size' 'AB adapters by size' end end def self.get_graph_filename(plugin_name,stats_name) return stats_name # case stats_name # when 'adapter_type' # 'AB adapters by type' # when 'adapter_size' # 'AB adapters by size' # end end def self.valid_graphs return ['adapter_type'] end end <file_sep>/bin/split_fasta.rb #!/usr/bin/env ruby require 'scbi_fasta' if ARGV.count < 3 puts "#{$0} FASTA_FILE OUTPUT_NAME SEQS_PER_FILE_COUNT" exit end fastq = ARGV.shift output_name = ARGV.shift split_by = ARGV.shift.to_i file_index=1 out=File.new("#{output_name}#{file_index}.fasta",'w') fqr=FastaQualFile.new(fastq) count = 0 fqr.each do |seq_name,seq_fasta,comments| if (count >= split_by) count=0 file_index +=1 out.close out=File.new("#{output_name}#{file_index}.fasta",'w') end out.puts(">#{seq_name} #{comments}") out.puts(seq_fasta) count +=1 end out.close if out fqr.close<file_sep>/bin/extract_seqs.rb #!/usr/bin/env ruby require 'scbi_fastq' class Array def count self.length end end if ARGV.count < 3 puts "#{$0} FASTA OUTPUT_NAME SEQ_NAME_FILE [MORE_SEQ_NAMES]" exit else fasta = ARGV.shift qual = ARGV.shift output_name = ARGV.shift seqs=ARGV puts seqs.join(';') fqr=FastaQualFile.new(fasta,qual) output_fasta=File.new(output_name+'.fasta','a') output_qual=File.new(output_name+'.fasta.qual','a') fqr.each do |seq_name,seq_fasta,seq_qual| if seqs.index(seq_name) output_fasta.puts ">#{seq_name}" output_fasta.puts seq_fasta output_qual.puts ">#{seq_name}" output_qual.puts seq_qual seqs.delete(seq_name) if seqs.empty? break end end end output_qual.close output_fasta.close fqr.close end <file_sep>/bin/resume_execution_times.rb #!/usr/bin/env ruby require 'json' if ARGV.count<1 puts "Usage: #{$0} [-t] [-j] [-h] stats1.json" exit -1 end # print header if ARGV[0]=='-t' heads=['Plugin name','execution_time (s)'] puts heads.join("\t") ARGV.shift end puts_json=false if ARGV[0]=='-j' puts_json=true ARGV.shift end time_divider=1 # print header if ARGV[0]=='-h' time_divider=3600 puts "Times are in hours" ARGV.shift end ARGV.each do |file_path| sample_name = File.basename(File.expand_path(File.join(file_path,'..','..'))) stats=JSON::parse(File.read(file_path)) res={} total=0 begin stats.keys.each do |k| if stats[k]['execution_time'] res[k]=stats[k]['execution_time']['total_seconds'].to_f/time_divider total+=res[k] end end res["TOTAL_plugins"]=total rescue Excepcion => e puts "Error reading #{file_path}" end if stats['scbi_mapreduce'] res['TOTAL_workers']=stats['scbi_mapreduce']['connected_workers'] res['TOTAL_read']=stats['scbi_mapreduce']['total_read_time']/time_divider res['TOTAL_write']=stats['scbi_mapreduce']['total_write_time']/time_divider res['TOTAL_manager_idle']=stats['scbi_mapreduce']['total_manager_idle_time']/time_divider res['TOTAL_execution']=stats['scbi_mapreduce']['total_seconds']/time_divider end if puts_json puts JSON::pretty_generate(res) else res.keys.sort.each do |k| puts "#{k}\t#{res[k]}" end end end <file_sep>/lib/seqtrimnext/actions/action_empty_insert.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute ActionShortInserted # Inherit: Plugin ######################################################## class ActionEmptyInsert < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =false @informative = true end def apply_decoration(char) return char end end <file_sep>/lib/seqtrimnext/classes/graph_stats.rb # $: << '/Users/dariogf/progs/ruby/gems/scbi_plot/lib' require 'scbi_plot' # require 'gnu_plot_graph' class GraphStats def initialize(stats,initial_stats=nil) #load stats init_stats=initial_stats if init_stats.nil? if File.exists?(File.join(OUTPUT_PATH,'initial_stats.json')) r=File.read(File.join(OUTPUT_PATH,'initial_stats.json')) init_stats= JSON::parse(r) else init_stats=[] end end # puts init_stats.to_json #r=File.read(File.join(File.dirname(__FILE__),'stats.json')) if !File.exists?('graphs') Dir.mkdir('graphs') end @stats=stats @stats.each do |plugin_name,plugin_value| # get plugin class begin plugin_class = Object.const_get(plugin_name) rescue Exception => e # puts "RESCUE",e.message,e.backtrace plugin_class = Plugin end plugin_value.keys.each do |stats_name| puts "Plotting #{stats_name} from #{plugin_name}" # if graph is not ignored if !plugin_class.graph_ignored?(stats_name) x=[] y=[] # get filename file_name=File.join('graphs',plugin_class.get_graph_filename(plugin_name,stats_name)+'.png') # create new graph object plot=ScbiPlot::Histogram.new(file_name,plugin_class.get_graph_title(plugin_name,stats_name)) plugin_class.auto_setup(plugin_value[stats_name],stats_name,x,y) # puts plugin_class.name.to_s # plot_setup returns true if it has already handled the setup of the plot, if not, handle here if !plugin_class.plot_setup(plugin_value[stats_name],stats_name,x,y,init_stats,plot) if !x.empty? && !y.empty? && (x.length==y.length) plot.x_label= "Length" plot.y_label= "Count" plot.add_x(x) plot.add_y(y) plot.do_graph end end # if !x.empty? && !y.empty? && (x.length==y.length) # # end end end end end end <file_sep>/lib/seqtrimnext/utils/global_match.rb class GMatch attr_accessor :offset attr_accessor :match end class Regexp def global_match(input_str,overlap_group_no = 0) res = [] str=input_str last_end = 0 loop do str = input_str.slice(last_end,input_str.length-last_end) if str.nil? or str.empty? break end m = self.match(str) # puts "find in: #{str}" if !m.nil? # puts m.inspect new_match=GMatch.new() new_match.offset = last_end new_match.match = m res.push new_match if overlap_group_no == 0 last_end += m.end(overlap_group_no) else last_end += m.begin(overlap_group_no) end else break end end return res end # def global_match(str, &proc) # retval = nil # loop do # res = str.sub(self) do |m| # proc.call($~) # pass MatchData obj # '' # end # break retval if res == str # str = res # retval ||= true # end # end end <file_sep>/bin/parse_amplicons.rb #!/usr/bin/env ruby require 'json' require 'scbi_fastq' if ARGV.count != 2 end # >Cluster 0 # 0 216aa, >E9LAHD006DQKVK... * # >Cluster 1 # 0 203aa, >E9LAHD006DODWR... * # >Cluster 2 # 0 198aa, >E9LAHD006DQCDS... * # >Cluster 3 # 0 195aa, >E9LAHD006DQURO... * # 1 172aa, >E9LAHD006DOSHR... at 93.02% # 2 172aa, >E9LAHD006DSV4P... at 93.02% # 3 172aa, >E9LAHD006DI00Q... at 93.02% # 4 172aa, >E9LAHD006DR7MR... at 93.02% # 5 175aa, >E9LAHD006DTDA7... at 90.86% # 6 172aa, >E9LAHD006DVCR3... at 93.02% # 7 172aa, >E9LAHD006DHY3H... at 93.02% # 8 177aa, >E9LAHD006DI52X... at 90.96% def load_repeated_seqs(file_path,min_repetitions) clusters=[] # count=0 current_cluster=[] if File.exists?(file_path) # File.open(ARGV[0]).each_line do |line| # $LOG.debug("Repeated file path:"+file_path) File.open(file_path).each_line do |line| if line =~ /^>Cluster/ if !current_cluster.empty? && (current_cluster.count <= min_repetitions) clusters += current_cluster end # count=0 current_cluster=[] elsif line =~ />([^\.]+)\.\.\.\s/ current_cluster << $1 end end if !current_cluster.empty? && (current_cluster.count <= min_repetitions) clusters += current_cluster end # $LOG.info("Repeated sequence count: #{@clusters.count}") else # $LOG.error("Clustering file's doesn't exists: #{@clusters.count}") end return clusters end def remove_singletons_from_file(input_file_path,singletons) fqr=FastqFile.new(input_file_path) out=FastqFile.new(input_file_path+'_without_singletons','w+') fqr.each do |n,f,q,c| if !singletons.include?(n) out.write_seq(n,f,q,c) end end out.close fqr.close end input_file_path=ARGV.shift min_repetitions = ARGV.shift.to_i `cd-hit -i #{input_file_path} -o clusters` singletons = load_repeated_seqs('clusters.clrs',min_repetitions) remove_singletons_from_file(input_file_path,singletons) # puts singletons.to_json <file_sep>/lib/seqtrimnext/classes/install_requirements.rb ######################################### # Author:: <NAME> # This class provided the methods to check if the necesary software is installed in the user system ######################################### class InstallRequirements def initialize @external_requirements = {} @ruby_requirements = {} load_requirements end def check_install_requirements res = true errors = check_system_requirements if !errors.empty? $stderr.puts ' Unable to find these external requeriments:' errors.each do |error| $stderr.puts ' -' + error res = false end #end each end #end if errors = check_ruby_requirements if !errors.empty? $stderr.puts ' Unable to find these Ruby requeriments:' errors.each do |error| $stderr.puts ' -' + error res = false end #end each end #end if return res end private def check_system_requirements errors=[] @external_requirements.each do |cmd,msg| if !system("which #{cmd} > /dev/null ") errors.push "It's necessary to install #{cmd}. " + msg end end return errors end def check_ruby_requirements(install=true) errors=[] @ruby_requirements.each do |cmd,msg| if !system("gem list #{cmd} | grep #{cmd} > /dev/null") if install puts "Are you sure you wan't to install #{cmd} gem? ([Y/n]):" res=stdin.readline if res.chomp.upcase!='N' system("echo gem install #{cmd}") end else errors.push "It's necessary to install #{cmd}. Issue a: gem install #{cmd} " + msg end end end return errors end # seqtrim's requirements are specified here def load_requirements @external_requirements['blastn']= "You need to install Blast+ 2.2.24 or greater and make sure it is available in your path (export PATH=$PATH:path_to_blast).\nYou can download it from ftp://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/LATEST/" @external_requirements['cd-hit-454']= "Download from http://code.google.com/p/cdhit/downloads/list" # @external_requirements['gnuplot']= "Download from http://www.gnuplot.info/download.html" # @external_requirements['pepe']= "" # @ruby_requirements = { 'n2array' => "" , @ruby_requirements['narray'] = '' # @ruby_requirements['gnuplot'] = '' @ruby_requirements['term-ansicolor'] = '' @ruby_requirements['xml-simple'] = '' @ruby_requirements['scbi_blast'] = '' @ruby_requirements['scbi_mapreduce'] = '' @ruby_requirements['scbi_fasta'] = '' @ruby_requirements['scbi_fastq'] = '' @ruby_requirements['scbi_plot'] = '' @ruby_requirements['scbi_math'] = '' # @ruby_requirements['scbi_fastq2'] = '' end # end def def install # gem install gnuplot # gem install narray # gem install scbi_blast # gem install scbi_drb # gem install scbi_fasta # gem install scbi_fastq # gem install term-ansicolor # gem install xml-simple end end <file_sep>/lib/seqtrimnext/plugins/plugin_low_complexity.rb ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLowComplexity # # Inherit: Plugin ######################################################## require "plugin" MIN_DUST_SIZE = 30 class PluginLowComplexity < Plugin # do the dust masker instead of blast def do_blasts(seqs) dust_masker=DustMasker.new() fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") found_dust = dust_masker.do_dust(fastas) # puts found_dust # puts blast_table_results.inspect return found_dust end def exec_seq(seq,blast_query) dust_query=blast_query if dust_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end actions=[] # puts "Checking for dust: #{seq.seq_fasta}" # puts found_dust.to_json total_dust=0 if !dust_query.nil? # low_quals=seq.get_actions(ActionLowQuality) dust_query.dust.each do |dust| start=dust[0] stop=dust[1] dust_size=dust[1]-dust[0]+1 if (dust_size)>=MIN_DUST_SIZE # check if low complexity is inside a lowqual region if !seq.range_inside_action_type?(start,stop,ActionLowQuality) total_dust+=dust_size a = seq.new_action(start,stop,'ActionLowComplexity') # a.left_action=true actions.push a end # break end end end if !actions.empty? add_stats('low_complexity',total_dust) seq.add_file_tag(0, 'low_complexity', :both, 100) seq.add_actions(actions) end end ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] # # comment='Minimum percent of T bases in poly_a to be accepted' # default_value = 80 # params.check_param(errors,'poly_t_percent','Integer',default_value,comment) # return errors end end <file_sep>/README.md = seqtrimnext * http://www.scbi.uma.es/downloads == DESCRIPTION: SeqtrimNEXT is a customizable and distributed pre-processing software for NGS (Next Generation Sequencing) biological data. It makes use of scbi_mapreduce gem to be able to run in parallel and distributed environments. It is specially suited for Roche 454 (normal and paired-end) & Ilumina datasets, although it could be easyly adapted to any other situation. == FEATURES: * SeqtrimNEXT is very flexible since it's architecture is based on plugins. * You can add new plugins if needed. * SeqtrimNEXT uses scbi_mapreduce and thus is able to exploit all the benefits of a cluster environment. It also works in multi-core machines big shared-memory servers. == Default templates for genomics & transcriptomics are provided <b>genomics_454.txt</b>:: cleans genomics data from Roche 454 sequencer. <b>genomics_454_with_paired.txt</b>:: cleans genomic data from a paired-end experiment sequenced with a Roche 454 sequencer. <b>low_quality.txt</b>:: trims low quality. <b>low_quality_and_low_complexity.txt</b>:: trims low quality and low complexity. <b>transcriptomics_454.txt</b>:: cleans transcriptomics data from a Roche 454 sequencer. <b>transcriptomics_plants.txt</b>:: cleans transcriptomics data from a Roche 454 sequencer with extra databases for plants. <b>amplicons.txt</b>:: filters amplicons. == You can define your own templates using a combination of available plugins: <b>PluginKey</b>:: to remove sequencing keys from 454 input sequences. <b>PluginMids</b>:: to remove MIDS (barcodes) from 454 sequences. <b>PluginLinker</b>:: splits sequences into two inserts when a valid linker is found (paired-end experiments only) <b>PluginAbAdapters</b>:: removes AB adapters from sequences using a predefined DB or one provided by the user. <b>PluginFindPolyAt</b>:: removes polyA and polyT from sequences. <b>PluginLowComplexity</b>:: filters sequences with low complexity regions <b>PluginAdapters</b>:: removes Adapters from sequences using a predefined DB or one provided by the user. <b>PluginLowHighSize</b>:: removes sequences too small or too big. <b>PluginVectors</b>:: remove vectors from sequences using a predefined database or one provided by the user. <b>PluginAmplicons</b>:: filters amplicons using user predefined primers. <b>PluginIndeterminations</b>:: removes indeterminations (N) from the sequence. <b>PluginLowQuality</b>:: eliminate low quality regions from sequences. <b>PluginContaminants</b>:: remove contaminants from sequences or rejects contaminated ones. It uses a core database, but it can be expanded with user provided ones. == SYNOPSIS: Once installed, SeqtrimNEXT is very easy to use: To install core databases (it should be done at installation time): $> seqtrimnext -i core Databases will be installed nearby SeqtrimNEXT by default, but you can override this location by setting the environment variable +BLASTDB+. Eg.: If you with your database installed at /var: $> export BLASTDB=/var/DB/formatted Be sure that this environment variable is always loaded before SeqtrimNEXT execution (Eg.: add it to /etc/profile.local). There are aditional databases. To list them: $> seqtrimnext -i LIST To perform an analisys using a predefined template with a FASTQ file format using 4 cpus: $> seqtrimnext -t genomics_454.txt -Q input_file_in_FASTQ -w 4 To perform an analisys using a predefined template with a FASTQ file format: $> seqtrimnext -t genomics_454.txt -f input_file_in_FASTA -q input_file_in_QUAL To clean illumina fastq files, with paired-ends and qualities encoded in illumina 1.5 format, using 4 cpus and disabling verbose output: $> seqtrimnext -t genomics_short_reads.txt -F illumina15 -Q p1.fastq,p2.fastq -w 4 -K To clean illumina fastq files, with paired-ends and qualities encoded in standard phred format, using 4 cpus and disabling verbose output: $> seqtrimnext -t genomics_short_reads.txt -Q p1.fastq,p2.fastq -w 4 -K To get additional help and list available templates and databases: $> seqtrimnext -h === CLUSTERED EXECUTION: To take full advantage of a clustered installation, you can launch SeqtrimNEXT in distributed mode. You only need to provide it a list of machine names (or IPs) where workers will be launched. Setup a workers file like this: machine1 machine1 machine2 machine2 machine2 And launch SeqtrimNEXT this way: $> seqtrimnext -t genomics_454.txt -Q input_file_in_FASTQ -w workers_file -s 10.0.0 This will launch 2 workers on machine1 and 3 workers on machine2 using the network whose ip starts with 10.0.0 to communicate. == TEMPLATE MODIFICATIONS You can modify any template to fit your workflow. To do this, you only need to copy one of the templates and edit it with a text editor, or simply modify a used_params.txt file that was produced by a previous SeqtrimNEXT execution. Eg.: If you want to disable repetition removal, do this: 1-Copy the template file you wish to customize and name it params.txt. 2-Edit params.txt with a text editor 3-Find a line like this: remove_clonality = true 4-Replace this line with: remove_clonality = false 5- Launch SeqtrimNEXT with params.txt file instead of a default template: $> seqtrimnext -t params.txt -f input_file_in_FASTA -q input_file_in_QUAL The same way you can modify any of the parameters. You can find all parameters and their description in any used_params.txt file generated by a previous SeqtrimNEXT execution. Parameters not especified in a template are automatically set to their default value at execution time. <b>NOTE</b>: The only mandatory parameter is the plugin_list one. == REQUIREMENTS: * Ruby 1.9.2 or greater * CD-HIT 4.5.3 or greater * Blast plus 2.24 or greater (prior versions have bugs that produces bad results) * [Optional] - GnuPlot version 4.4.2 or greater (prior versions may produce wrong graphs) * [Optional] - pdflatex - Optional, to produce a detailed report with results == INSTALL: === Installing CD-HIT *Download the latest version from http://code.google.com/p/cdhit/downloads/list *You can also use a precompiled version if you like *To install from source, decompress the downloaded file, cd to the decompressed folder, and issue the following commands: make sudo make install === Installing Blast *Download the latest version of Blast+ from ftp://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/LATEST/ *You can also use a precompiled version if you like *To install from source, decompress the downloaded file, cd to the decompressed folder, and issue the following commands: ./configure make sudo make install === Installing Ruby 1.9 *You can use RVM to install ruby: Download latest certificates (maybe you don't need them): $ curl -O http://curl.haxx.se/ca/cacert.pem $ export CURL_CA_BUNDLE=`pwd`/cacert.pem # add this to your .bashrc or equivalent Install RVM following the directions from this web: https://rvm.io/rvm/install Install ruby 1.9.2 (this can take a while): $ rvm install 1.9.2 Set it as the default: $ rvm use 1.9.2 --default === Install SeqtrimNEXT SeqtrimNEXT is very easy to install. It is distributed as a ruby gem: gem install seqtrimnext This will install seqtrimnext and all the required gems. === Install and rebuild SeqtrimNext's core databases SeqtrimNEXT needs some core databases to work. To install them: seqtrimnext -i core You can change default database location by setting the environment variable +BLASTDB+. Refer to SYNOPSIS for an example. There are aditional databases that can be listed with: seqtrimnext -i LIST === Database modifications Included databases will be usefull for a lot of people, but if you prefer, you can modify them, or add more elements to be search against your sequences. You only need to drop new fasta files to each respective directory, or even create new directories with new fasta files inside. Each directory with fasta files will be used as a database: DB/vectors to add more vectors DB/contaminants to add more contaminants etc... Once the databases has been modified, you will need to reformat them by issuing the following command: seqtrimnext -c Modified databases will be rebuilt. == CLUSTERED INSTALLATION To install SeqtrimNEXT into a cluster, you need to have the software available on all machines. By installing it on a shared location, or installing it on each cluster node. Once installed, you need to create a init_file where your environment is correctly setup (paths, BLASTDB, etc): export PATH=/apps/blast+/bin:/apps/cd-hit/bin export BLASTDB=/var/DB/formatted export SEQTRIMNEXT_INIT=path_to_init_file And initialize the SEQTRIMNEXT_INIT environment variable on your main node (from where SeqtrimNEXT will be initially launched): export SEQTRIMNEXT_INIT=path_to_init_file If you use any queue system like PBS Pro or Moab/Slurm, be sure to initialize the variables on each submission script. <b>NOTE</b>: all nodes on the cluster should use ssh keys to allow SeqtrimNEXT to launch workers without asking for a password. == SAMPLE INIT FILES FOR CLUSTERED INSTALLATION: === Init file $> cat stn_init_env source ~latex/init_env source ~ruby19/init_env source ~blast_plus/init_env source ~gnuplot/init_env source ~cdhit/init_env export BLASTDB=~seqtrimnext/DB/formatted/ export SEQTRIMNEXT_INIT=~seqtrimnext/stn_init_env === PBS Submission script $> cat sample_work.sh # 40 distributed workers and 1 GB memory per worker: #PBS -l select=40:ncpus=1:mpiprocs=1:mem=1gb # request 10 hours of walltime: #PBS -l walltime=10:00:00 # cd to working directory (from where job was submitted) cd $PBS_O_WORKDIR # create workers file with assigned node names cat ${PBS_NODEFILE} > workers # init seqtrimnext source ~seqtrimnext/init_env time seqtrimnext -t paired_ends.txt -Q fastq -w workers -s 10.0.0 Once this submission script is created, you only need to launch it with: qsub sample_work.sh === MOAB/SLURM submission script $> cat sample_work_moab.sh #!/bin/bash # @ job_name = STN # @ initialdir = . # @ output = STN_%j.out # @ error = STN_%j.err # @ total_tasks = 40 # @ wall_clock_limit = 10:00:00 # guardar lista de workers sl_get_machine_list > workers # init seqtrimnext source ~seqtrimnext/init_env time seqtrimnext -t paired_ends.txt -Q fastq -w workers -s 10.0.0 Then you only need to submit your job with mnsubmit mnsubmit sample_work_moab.sh == LICENSE: (The MIT License) Copyright (c) 2011 <NAME> & <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.<file_sep>/lib/seqtrimnext/classes/piro.rb # require '../utils/fasta_qual_reader' #descomentar en test_extracts require 'fasta_qual_reader' #descomentar en seqtrimii require 'make_blast_db' require 'scbi_blast' ###################################### # Author:: <NAME> # Extract stats like mean of sequence's length # Inherit:: FastaReader ###################################### class Piro < FastaQualReader #attr_accessor :na def initialize(path_fasta,path_qual) @path_fasta=path_fasta super(path_fasta,path_qual) MakeBlastDb.execute('../sequences/gemini.fasta') end def on_process_sequence(name_seq,fasta_seq,qual_seq) puts "in piro, in on process sequence, #{name_seq}" blast = BatchBlast.new('-db '+ @path_fasta ,'blastn',' -task blastn -evalue 1e-10 -perc_identity 95') #get contaminants #blast = BatchBlast.new('DB/vectors.fasta','blastn',' -task blastn ') #get vectors $LOG.debug "-------OK----" # puts seq.seq_fasta res = blast.do_blast(fasta_seq) #rise seq to contaminants executing over blast # # blast_table_results = BlastTableResult.new(res,nil) # vectors=[] # blast_table_results.querys.each do |query| # first round to save contaminants without overlap # merge_hits(query.hits,vectors) # end # # begin # vectors2=vectors # second round to save contaminants without overlap # vectors = [] # merge_hits(vectors2,vectors) # end until (vectors2.count == vectors.count) # # # vectors.each do |c| # adds the correspondent action to the sequence # #if @seq_specie!=seq_specie-contaminant # # if (@params.get_param('genus')!=c.subject_id.split('_')[1]) # # puts "DIFFERENT SPECIE #{specie} ,#{hit.subject_id.split('_')[1].to_s}" # a = seq.add_action(c.q_beg,c.q_end,type) # a.message = c.subject_id # end # end end def on_end_process() end end <file_sep>/bin/split_ilumina_paired.rb #!/usr/bin/env ruby # Splits a FastQ file with ilumina paired data into two separate files. require 'scbi_fastq' VERBOSE=false if !(ARGV.count==2 or ARGV.count==4) puts "Usage: #{$0} paired.fastq output_name [pared1_tag paired2_tag]" exit end p1_path=ARGV[0] output_base_name=ARGV[1] paired1_tag='/1' paired2_tag='/2' if (ARGV.count==4) paired1_tag=ARGV[2] paired2_tag=ARGV[3] end PAIRED1_TAG_RE=/#{Regexp.quote(paired1_tag)}$/ PAIRED2_TAG_RE=/#{Regexp.quote(paired2_tag)}$/ if !File.exists?(p1_path) puts "File #{p1_path} doesn't exists" exit end paired1_out = FastqFile.new(output_base_name+'_paired1.fastq','w',:sanger, true) paired2_out = FastqFile.new(output_base_name+'_paired2.fastq','w',:sanger, true) f_file = FastqFile.new(p1_path,'r',:sanger, true) f_file.each do |n,f,q,c| if n=~ PAIRED1_TAG_RE paired1_out.write_seq(n,f,q,c) elsif n=~ PAIRED2_TAG_RE paired2_out.write_seq(n,f,q,c) else STDERR.puts "Aborting due to ERROR in file: #{n} doens't match neither left (#{paired1_tag}) nor right (#{paired2_tag}) tags" exit end if ((f_file.num_seqs%10000) == 0) puts "Count: #{f_file.num_seqs}" end end f_file.close paired1_out.close paired2_out.close <file_sep>/lib/seqtrimnext/actions/action_trim.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute Plugin1 # Inherit: Plugin ######################################################## class ActionTrim < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =true end def apply_decoration(char) return char.red.italic end end <file_sep>/lib/seqtrimnext/version.rb module Seqtrimnext VERSION = "2.0.68" SEQTRIM_VERSION = VERSION end <file_sep>/lib/seqtrimnext/plugins/plugin_find_poly_at.rb ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginFindPolyATs # # Inherit: Plugin ######################################################## require "plugin" require "global_match" def overlap(polys,mi_start,mi_end) # overlap = polys.find{|e| ( mi_start < e['end'])} overlap = polys.find{|e| ( overlapX?(mi_start,mi_end, e['begin'],e['end']) )} # puts " Overlap #{mi_start} #{mi_end} => #{overlap}" return overlap end # MAX_RUBBISH = 3 MAX_POLY_T_FROM_LEFT = 4 MIN_TN_COUNT=15 MAX_POLY_A_FROM_RIGHT = 10 MIN_MIDDLE_POLY_A_SIZE = 35 MIN_MIDDLE_POLY_T_SIZE = 35 MAX_DUST_DISTANCE_FROM_POLYT=30 class PluginFindPolyAt < Plugin # Uses the param poly_at_length to look for at least that number of contiguous A's def find_polys(ta,seq) #minn = poly_at_length # puts "="*20 + seq.seq_name + "="*20 minn = 4 m2 = (minn/2) m4 = (minn/4) r = [-1,0,0] re2 = /(([#{ta}]{#{m2},})(.{0,2})([#{ta}]{#{m2},}))/i # re2 = /(([#{ta}]{#{m2},})(.{0,3})([#{ta}]{#{m2},}))/i # if ta =~/A/ # type='ActionPolyA' # else # type='ActionPolyT' # poly_base = 'T' # end matches = re2.global_match(seq.seq_fasta,3) # HASH polys = [] # crear una region poly nuevo poly = {} #i=0 matches.each do |pattern2| #puts pattern2.match[0] m_start = pattern2.match.begin(0)+pattern2.offset m_end = pattern2.match.end(0)+pattern2.offset-1 # does one exist in polys with overlap? # yes => group it, updated end # no => one new if (e=overlap(polys,m_start,m_end)) # puts "OVERLAPS #{e}" # found=seq.seq_fasta.slice(e['begin'],m_end-e['begin']+1) # if base_percent(poly,ta)>= 60 e['end'] = m_end e['found'] = seq.seq_fasta.slice(e['begin'],e['end']-e['begin']+1) # else # puts "Ignored because lowers the base percent of poly" # end else poly={} poly['begin'] = m_start poly['end'] = m_end # the next pos to pattern's end poly['found'] = seq.seq_fasta.slice(poly['begin'],poly['end']-poly['begin']+1) polys.push poly # puts " NEW POLY#{ta}: #{poly}" end end # polys.each do |p| # puts "P#{ta}: #{p}, bp: #{base_percent(p['found'],ta)}" # end return polys end def find_polyA(seq) actions=[] polys=find_polys('AN',seq) poly_base = 'AN' type='ActionPolyA' poly_size=0 # for each poly found cut it, from right to left (reverse order) polys.reverse_each do |poly| poly_size=poly['end'] - poly['begin'] +1 # if polya is near right and is big enought and has a base percent # check if poly lenth and percent are above limits if (poly['end']>=seq.seq_fasta.length-MAX_POLY_A_FROM_RIGHT) && (poly_size>= @params.get_param('poly_a_length').to_i) && (base_percent(poly,poly_base)>= @params.get_param('poly_a_percent').to_i) a = seq.new_action(poly['begin'],poly['end'],type) a.right_action=true #mark as rigth action to get the left insert actions.push a add_stats('poly_a_size',poly_size) # if poly a is not near right but is bigger, then cut elsif (poly['end']<<seq.seq_fasta.length-MAX_POLY_A_FROM_RIGHT) && (poly_size>=MIN_MIDDLE_POLY_A_SIZE) && (base_percent(poly,poly_base)>= @params.get_param('poly_a_percent').to_i) a = seq.new_action(poly['begin'],poly['end'],type) a.right_action=true #mark as rigth action to get the left insert actions.push a add_stats('in_middle_poly_a_size',poly_size) # else # puts "REJECTED: #{poly}" end if poly['found'].length > @params.get_param('poly_a_length').to_i add_stats("poly_#{poly_base}_base_percents","#{poly['found'].length} #{base_percent(poly,poly_base)}") end end if !actions.empty? add_stats('seqs_with_polyA',1) seq.add_actions(actions) actions=[] end end def find_polyT(seq) actions=[] poly_base = 'TN' type='ActionPolyT' polys=find_polys('TN',seq) poly_size=0 check_for_dust=nil # for each poly found process it polys.each do |poly| poly_size=poly['end'] - poly['begin'] + 1 # puts "#{poly}, size: #{poly['found'].length}, bcount:#{base_percent(poly,poly_base)}" # check if poly lenth and percent are above limits if (poly_size>= @params.get_param('poly_t_length').to_i) && (base_percent(poly,poly_base) >= @params.get_param('poly_t_percent').to_i) if (actions.empty?) # first poly, check if polyT is on the left of sequence #if is polyT and is near left, then the sequence is reversed if (poly['begin']==0) seq.seq_reversed=true a = seq.new_action(poly['begin'],poly['end'],type) a.left_action=true actions.push a check_for_dust=poly elsif (poly['begin']<=MAX_POLY_T_FROM_LEFT && base_count(poly,'TN')>=MIN_TN_COUNT) seq.seq_reversed=true a = seq.new_action(poly['begin'],poly['end'],type) a.left_action=true actions.push a check_for_dust=poly elsif (poly['begin']>MAX_POLY_T_FROM_LEFT && base_count(poly,'TN')>=MIN_MIDDLE_POLY_T_SIZE) seq.seq_reversed=true # seq.seq_rejected=true # seq.seq_rejected_by_message='unexpected polyT' check_for_dust=poly a = seq.new_action(poly['begin'],poly['end'],'ActionUnexpectedPolyT') a.left_action=true actions.push a add_stats('unexpected_poly_t_count',poly_size) end else # there are multiple polyTs if (poly['begin']>MAX_POLY_T_FROM_LEFT && base_count(poly,'TN')>=MIN_MIDDLE_POLY_T_SIZE) seq.seq_reversed=true # seq.seq_rejected=true # seq.seq_rejected_by_message='unexpected polyT' check_for_dust=poly a = seq.new_action(poly['begin'],poly['end'],'ActionUnexpectedPolyT') a.left_action=true actions.push a add_stats('unexpected_poly_t_count',poly_size) end end # if (poly['begin']<=MAX_POLY_T_FROM_LEFT*2) # seq.seq_rejected=true # seq.seq_rejected_by_message='polyT found' # end # @stats[:poly_t_size]={poly_size => 1} add_stats('poly_t_size',poly_size) end end if !actions.empty? add_stats('seqs_with_polyT',1) seq.add_actions(actions) actions=[] if check_for_dust && !seq.seq_fasta.nil? && !seq.seq_fasta.empty? dust_masker=DustMasker.new() dust_poly_size=check_for_dust['end']-check_for_dust['begin']+1 found_dust = dust_masker.do_dust([">"+seq.seq_name,seq.seq_fasta]) # puts "Checking for dust: #{seq.seq_fasta}" # puts found_dust.to_json total_dust=0 last_dust_start=0 if !found_dust.empty? found_dust[0].dust.each do |dust| start=dust[0] stop=dust[1] dust_size=dust[1]-dust[0]+1 total_dust+=dust_size # dust must be big enought and be near the polyt to be a induced one if (dust_size)>10 && (start<last_dust_start+MAX_DUST_DISTANCE_FROM_POLYT) last_dust_start=stop a = seq.new_action(start,stop,'ActionInducedLowComplexity') # a.left_action=true actions.push a elsif dust_size>10 a = seq.new_action(start,stop,'ActionLowComplexity') # a.left_action=true actions.push a end end end if !actions.empty? add_stats('poly_t_dust',dust_poly_size) seq.add_actions(actions) else add_stats('poly_t_no_dust',dust_poly_size) end # reject sequences if total dust is greater than 30 if total_dust>30 # if seq.seq_fasta.length<50 seq.seq_rejected=true seq.seq_rejected_by_message='low complexity by polyt' # end add_stats('induced_low_complexity',total_dust) end end end end def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for strings of polyAT's into the sequence with a length indicated by the param <poly_at_length>" find_polyT(seq) find_polyA(seq) end ###################################################################### #--------------------------------------------------------------------- def base_percent(poly,poly_base) # count Ts en poly['found'] s=poly['found'] ta_count = s.count(poly_base.downcase+poly_base.upcase) res=(ta_count.to_f/s.size.to_f)*100 # puts "poly #{s} base percent #{res}" return res end def base_count(poly,poly_base) # count bases en poly['found'] s=poly['found'] res = s.count(poly_base.downcase+poly_base.upcase) # puts "poly #{s} base count #{res}" return res end ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Minimum length of a poly-A' default_value = 6 params.check_param(errors,'poly_a_length','Integer',default_value,comment) comment='Minimum percent of As in a sequence segment to be considered a poly-A' # default_value = 80 default_value = 75 params.check_param(errors,'poly_a_percent','Integer',default_value,comment) comment='Minimum length of a poly-T' default_value = 15 params.check_param(errors,'poly_t_length','Integer',default_value,comment) comment='Minimum percent of Ts in a sequence segment to be considered a poly-T' # default_value = 80 default_value = 75 params.check_param(errors,'poly_t_percent','Integer',default_value,comment) return errors end private :overlap end <file_sep>/lib/seqtrimnext/actions/action_rem_adit_artifacts.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginActionLowHighSize # Inherit: Plugin ######################################################## class ActionRemAditArtifacts < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) @cut =true end # def apply_to(seq) # # # seq.seq_fasta = seq.seq_fasta.slice(start_pos,end_pos) # $LOG.debug " Applying #{self.class} to #{seq.seq_name} " # #delete sequence if it was created # # # end def apply_decoration(char) return char.yellow.negative end end <file_sep>/lib/seqtrimnext/classes/one_blast.rb #!/usr/bin/env ruby class OneBlast def initialize(database, blast_type = 'blastp') @blast_type = blast_type @database = database @c=0 end def do_blast(seq_fasta) @f = File.new('one_blast_aux.fasta','w+') @f.puts ">SEQNAME_"+@c.to_s @f.puts seq_fasta @c = @c+1 @f.close cmd = '~blast/programs/x86_64/bin/blastall -p '+@blast_type+' -d '+@database + ' -i one_blast_aux.fasta -o one_blast_aux.out' #puts cmd system(cmd) res ='' File.open('one_blast_aux.out').each_line { |line| res = line } end def close end end <file_sep>/lib/seqtrimnext/plugins/plugin_ignore_repeated.rb require "plugin" require "make_blast_db" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginIgnoreRepeated # Inherit: Plugin ######################################################## class PluginIgnoreRepeated < Plugin SIZE_SEARCH_IN_IGNORE=15 #Begins the plugin1's execution to warn that there are repeated sequences, and disables all but one" def exec_seq(seq,blast_query) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: searching sequence repeated at input file" fasta_input=@params.get_param('truncated_input_file') blast = BatchBlast.new("-db #{fasta_input}" ,'blastn'," -task blastn-short -searchsp #{SIZE_SEARCH_IN_IGNORE} -evalue #{@params.get_param('blast_evalue_ignore_repeated')} -perc_identity #{@params.get_param('blast_percent_ignore_repeated')}") #get contaminants p_start = @params.get_param('piro_repeated_start').to_i p_length = @params.get_param('piro_repeated_length').to_i blast_table_results = blast.do_blast(seq.seq_fasta[p_start,p_length]) #rise seq to contaminants executing over blast #blast_table_results = BlastTableResult.new(res) type = "ActionIgnoreRepeated" # @stats[:rejected_seqs]={} actions=[] blast_table_results.querys.each do |query| # puts "BLAST IGUALES:" # puts res.join("\n") if query.size>1 names = query.hits.collect{ |h| if h.align_len > (p_length-2) h.subject_id end } names.compact! # puts "IGUALES:" + names.size.to_s # puts names.join(',') if !names.empty? names.sort! if (names[0] != seq.seq_name) # Add action when the sequence is repeated # if true a = seq.new_action(0,0,type) a.message = seq.seq_name + ' equal to ' + names[0] actions.push a seq.seq_rejected=true seq.seq_rejected_by_message='repeated' seq.seq_repeated=true # @stats[:rejected_seqs]={'rejected_seqs_by_repe' => 1} add_stats('rejected_seqs','rejected_seqs_by_repe') # puts "#{names[0]} != #{seq.seq_name} >>>>>>" end end end end seq.add_actions(actions) end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] # self.check_param(errors,params,'fasta_file_input','String') self.check_param(errors,params,'blast_evalue_ignore_repeated','Float') self.check_param(errors,params,'blast_percent_ignore_repeated','Integer') self.check_param(errors,params,'piro_repeated_start','Integer') self.check_param(errors,params,'piro_repeated_length','Integer') return errors end end <file_sep>/seqtrimnext.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'seqtrimnext/version' Gem::Specification.new do |spec| spec.name = "seqtrimnext" spec.version = Seqtrimnext::VERSION spec.authors = ["<NAME>", "<NAME>"] spec.email = ["<EMAIL>", "<EMAIL> t"] spec.summary = %q{Sequences preprocessing and cleaning software} spec.description = %q{Seqtrimnext is a plugin based system to preprocess and clean sequences from multiple NGS sequencing platforms} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_runtime_dependency 'narray','>=0' spec.add_runtime_dependency 'gnuplot','>=0' spec.add_runtime_dependency 'term-ansicolor','>=1.0.5' spec.add_runtime_dependency 'xml-simple','>=1.0.12' spec.add_runtime_dependency 'scbi_blast','>=0.0.34' spec.add_runtime_dependency 'scbi_mapreduce','>=0.0.38' spec.add_runtime_dependency 'scbi_fasta','>=0.1.7' spec.add_runtime_dependency 'scbi_fastq','>=0.0.18' spec.add_runtime_dependency 'scbi_plot','>=0.0.6' spec.add_runtime_dependency 'scbi_math','>=0.0.1' spec.add_runtime_dependency 'scbi_headers','>=0.0.2' end <file_sep>/lib/seqtrimnext/plugins_old/plugin_adapters_old.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginAdapters # Inherit: Plugin ######################################################## class PluginAdaptersOld < Plugin def get_type_adapter(p_start,p_end,seq) #if q_beg is nearer the left, add adapter action by the left, #if q_end esta is nearer the right , add adapter action by the right #NOTE: If the adapter is very near from left and rigth, #then the sequence isn't valid, because almost sequence is adapter. v1= p_end.to_i v2= p_start.to_i # puts " startadapter #{v2} endadapter #{v1} insert_start #{seq.insert_start} insert_end #{seq.insert_end}" # puts " #{v2+seq.insert_start} <? #{seq.seq_fasta.length - v1 - 1 + seq.seq_fasta_orig.length - seq.insert_end-1}" if (v2+seq.insert_start < (seq.seq_fasta.length - v1 - 1+ seq.seq_fasta_orig.length - seq.insert_end-1)) #IF THE NEAREST ONE IS THE LEFT type = "ActionLeftAdapter" else type = "ActionRightAdapter" end return type end def cut_by_right(adapter,seq) left_size = adapter.q_beg-seq.insert_start+1 right_size = seq.insert_end-adapter.q_end+1 left_size=0 if (left_size<0) right_size=0 if (right_size<0) return (left_size>(right_size/2).to_i) end def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast=BatchBlast.new("-db #{@params.get_param('adapters_db')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_adapters')} -perc_identity #{@params.get_param('blast_percent_adapters')}") $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas) # puts blast_table_results.inspect return blast_table_results end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for adapters into the sequence" # blast=BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'adapters.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_adapters')} -perc_identity #{@params.get_param('blast_percent_adapters')}") # blast with only one sequence, no with many sequences from a database #--------------------------------------------------------------------- # blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to adapterss executing over blast #blast_table_results = BlastTableResult.new(res) # blast_table_results.inspect adapters=[] # blast_table_results.querys.each do |query| # first round to save adapters without overlap merge_hits(blast_query,adapters) # end begin adapters2=adapters # second round to save adapters without overlap adapters = [] merge_hits(adapters2,adapters) end until (adapters2.count == adapters.count) actions=[] adapter_size=0 # @stats['adapter_size']={} adapters.each do |ad| # adds the correspondent action to the sequence type = get_type_adapter(ad.q_beg,ad.q_end,seq) a = seq.new_action(ad.q_beg,ad.q_end,type) # puts " state left_action #{a.left_action} right_action #{a.right_action}" adapter_size=ad.q_end-ad.q_beg+1 if cut_by_right(ad,seq) # puts "action right end1 #{seq.insert_end}" a.right_action=true #mark rigth action to get the left insert else # puts " cut1 by left #{seq.insert_start} ad #{ad.q_beg+seq.insert_start} #{ad.q_end+seq.insert_start}" a.left_action = true #mark left action to get the right insert end a.message = ad.subject_id a.reversed = ad.reversed actions.push a # @stats[:adapter_size]={adapter_size => 1} add_stats('adapter_size',adapter_size) end seq.add_actions(actions) # end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for adapters or primers' default_value = 1e-6 params.check_param(errors,'blast_evalue_adapters','Float',default_value,comment) comment='Minimum required identity (%) for a reliable adapter' default_value = 95 params.check_param(errors,'blast_percent_adapters','Integer',default_value,comment) comment='Path for adapter database' default_value = File.join($FORMATTED_DB_PATH,'adapters.fasta') params.check_param(errors,'adapters_db','DB',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/actions/seqtrim_action.rb ###################################### # Author:: <NAME> # This class creates the structures that storage the necessary values from an action ###################################### require 'term/ansicolor' include Term::ANSIColor class SeqtrimAction attr_accessor :start_pos , :end_pos, :message, :cut , :reversed , :left_action , :right_action , :found_definition, :tag_id, :informative # Creates the nexts values from an action: start_position, end_position, type def initialize(start_pos,end_pos) # puts " #{start_pos} #{end_pos} #{self.class.to_s}" @start_pos = start_pos.to_i @end_pos = end_pos.to_i #@notes = '' @left_action = false @right_action = false @message = '' @found_definition=[] #array when contaminant or vectors definitions are saved, each separately @cut = false @informative = false @reversed = false # puts " #{@start_pos} #{@end_pos} #{self.class.to_s}" @tag_id ='' end def apply_to(seq) $LOG.debug " Applying #{self.class} to seq #{seq.seq_name} . BEGIN: #{@start_pos} END: #{@end_pos} " end def description return "Action Type: #{self.class} Begin: #{start_pos} End: #{end_pos}" end def inspect description end def contains?(pos) return ((pos>=@start_pos) && (pos<=@end_pos)) end def contains_action?(start_pos,end_pos,margin=10) #puts "#{start_pos}>=#{@start_pos-margin} && #{end_pos}<=#{@end_pos+margin} " return ((start_pos>=@start_pos-margin) && (end_pos<=@end_pos+margin)) end def apply_decoration(char) return char end def decorate(char,pos) if contains?(pos) return apply_decoration(char) else return char end end def type return self.class.to_s end def action_type a_type='INFO' if !@informative a_type = 'LEFT' if right_action a_type = 'RIGHT' end end return a_type end def to_human(camel_cased_word) word = camel_cased_word.to_s.dup word.gsub!(/::/, '/') word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1 \2') word.gsub!(/([a-z\d])([A-Z])/,'\1 \2') word.tr!("-", " ") word.downcase! word.capitalize! word end def title return to_human(type.gsub('Action','')) end def near_left?(seq_fasta_size) return ((@start_pos - 0 ) < (seq_fasta_size - @end_pos)) end def left_action?(seq_fasta_size) res = (@left_action || (!@right_action && near_left?(seq_fasta_size))) # @left_action = res return res end def right_action?(seq_fasta_size) res= (@right_action || !left_action?(seq_fasta_size)) # @right_action = res return res end def to_hash a = {} a[:type]=type a[:start_pos]=@start_pos a[:end_pos]=@end_pos a[:message]=@message return a end end <file_sep>/lib/seqtrimnext/actions/action_low_quality.rb require "seqtrim_action" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginActionLowHighSize # Inherit: Plugin ######################################################## class ActionLowQuality < SeqtrimAction def initialize(start_pos,end_pos) super(start_pos,end_pos) # esto es cut=false porque al principio el plugin lowqual estaba al inicio del pipeline y habia que dejar # la secuencia larga para que se encontrasen los contaminantes y vectores # Tambien esta por si un linker tiene baja calidad que pueda encontrarlo @cut =false end # def apply_to(seq) # # # seq.seq_fasta = seq.seq_fasta.slice(start_pos,end_pos) # $LOG.debug " Applying #{self.class} to #{seq.seq_name} . This sequence will be ignored due to low quality " # #delete sequence if it was created # # # end def apply_decoration(char) return char.downcase.on_white end end <file_sep>/lib/seqtrimnext/plugins/plugin_low_quality.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginLowQuality. See the main method called execute. # # Inherit: Plugin ######################################################## class PluginLowQuality < Plugin def next_low_qual_region(quals,from_pos,min_value,max_good_quals=2) rstart=nil rend=nil i=from_pos good_q=0 # skip good values while (i< quals.length) && (quals[i]>=min_value) i +=1 end # now we have found a bad quality, or end of sequence if i < quals.length rstart=i len=0 # puts " - [#{rstart},#{len}]" # continue growing while region of lowqual until more than 2 bases of good qual are found begin q=quals[i] if q<min_value len += 1 # puts "BAD #{q}<#{min_value}" len += good_q good_q=0 else good_q+=1 end # puts "#{q} - q[#{rstart},#{rend}], #{good_q}" i+=1 end while (i < quals.length) && (good_q <= max_good_quals) rend = rstart + len -1 # puts "#{q} - q[#{rstart},#{rend}], #{good_q}" end return [rstart,rend] end # A region is valid if it starts in 0, ends in seq.length or is big enought def valid_low_qual_region?(quals,rstart,rend,min_region_size) # puts [rstart,rend,0,quals.length,(rend-rstart+1)].join(';') # res =((rstart==0) || (rend==quals.length-1) || ((rend-rstart+1)>=min_region_size)) # if res # puts "VALID" # end return ((rstart==0) || (rend==quals.length-1) || ((rend-rstart+1)>=min_region_size)) end def get_low_qual_regions(quals,min_value, min_region_size,max_good_quals=2) # the initial region is the whole array left=0 right=quals.length-1 # puts quals.map{|e| ("%2d" % e.to_s)}.join(' ') # puts "[#{left},#{right}]" i = 0 from_pos=0 regions =[] # get all new regions begin rstart, rend = next_low_qual_region(quals,from_pos,min_value,max_good_quals) if !rstart.nil? from_pos= rend+1 if valid_low_qual_region?(quals,rstart,rend,min_region_size) regions << [rstart,rend] end end end while !rstart.nil? return regions end ###################################################################### #--------------------------------------------------------------------- # Begins the plugin1's execution whit the sequence "seq" # Creates an action by each subsequence with low quality to eliminate it # A subsequence has low quality if (the add of all its qualitis < subsequence_size*20) # Creates the qualities windows from the sequence, looks for the subsequence with high quality # and mark, with an action, the before part to the High Quality Subsequence like a low quality part # Finally mark, with an action, the after part to the High Quality Subsequence like a low quality part #----------------------------------------------------------------- def exec_seq(seq,blast_query) if ((self.class.to_s=='PluginLowQuality') && seq.seq_qual.nil? ) $LOG.debug " Quality File haven't been provided. It's impossible to execute " + self.class.to_s elsif ((seq.seq_qual.size>0) && (@params.get_param('use_qual').to_s=='true')) $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: checking low quality of the sequence" min_quality=@params.get_param('min_quality').to_i min_length_inside_seq=@params.get_param('min_length_inside_seq').to_i max_consecutive_good_bases=@params.get_param('max_consecutive_good_bases').to_i type='ActionLowQuality' actions=[] regions=get_low_qual_regions(seq.seq_qual,min_quality,min_length_inside_seq,max_consecutive_good_bases) regions.each do |r| low_qual_size=r.last-r.first+1 # puts "(#{low_qual_size}) = [#{r.first},#{r.last}]: #{a[r.first..r.last].map{|e| ("%2d" % e.to_s)}.join(' ')}" add_stats('low_qual',low_qual_size) # create action a = seq.new_action(r.first,r.last,type) # adds the correspondent action to the sequence actions.push a end # add quals seq.add_actions(actions) end end #----------------------------------------------------------------- ###################################################################### #--------------------------------------------------------------------- #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Minimum quality value for every nucleotide' default_value = 20 params.check_param(errors,'min_quality','Integer',default_value,comment) #comment='Quality window for scanning low quality segments' #default_value = 15 #params.check_param(errors,'window_width','Integer',default_value,comment) comment='Minimum length of a bad quality segment inside the sequence' default_value = 8 params.check_param(errors,'min_length_inside_seq','Integer',default_value,comment) comment='Maximum consecutive good-quality bases between two bad quality regions' default_value = 2 params.check_param(errors,'max_consecutive_good_bases','Integer',default_value,comment) return errors end end <file_sep>/lib/seqtrimnext/classes/seqtrim.rb ###################################### # Author: <NAME> # This is the main class. ###################################### require 'extract_stats' require 'scbi_mapreduce' require 'seqtrim_work_manager' require 'action_manager' # SEQTRIM_VERSION_REVISION=27 # SEQTRIM_VERSION_STAGE = 'b' # $SEQTRIM_VERSION = "2.0.0#{SEQTRIM_VERSION_STAGE}#{SEQTRIM_VERSION_REVISION}" class Seqtrim def self.exit_status return SeqtrimWorkManager.exit_status end # First of all, reads the file's parameters, where are the values of all parameters and the 'plugin_list' that specifies the order of execution from the plugins. # # Secondly, loads the plugins in a folder . # # Thirdly, checks if parameter's file have the number of parameters necessary for every plugin that is going to be executed. # # After that, creates a thread's pool of a determinate number of workers, e.g. 10 threads, # reads the sequences from files 'fasta' , until now without qualities, # and executes the plugins over the sequences in the pool of threads def get_custom_cdhit(cd_hit_input_file,params) cmd='' begin cdhit_custom_parameters=params.get_param('cdhit_custom_parameters').strip if !cdhit_custom_parameters.nil? and !cdhit_custom_parameters.empty? cmd = "cd-hit-454 -i #{cd_hit_input_file} -o clusters.fasta #{cdhit_custom_parameters} > cd-hit-454.out" end rescue Exception => exception #not an integer, send via ssh to other machine cmd='' end return cmd end def get_cd_hit_cmd(cd_hit_input_file,workers,init_file_path) num_cpus_cdhit=1 cmd='' # if workers is an integer, reduce it by one in the server begin Integer(workers) num_cpus_cdhit = workers cmd = "cd-hit-454 -i #{cd_hit_input_file} -o clusters.fasta -M #{num_cpus_cdhit*1000} -T #{num_cpus_cdhit} > cd-hit-454.out" rescue Exception => exception #not an integer, send via ssh to other machine # puts exception worker_hash={};workers.map{|e| worker_hash[e] = (worker_hash[e]||0) +1} max_worker = worker_hash.sort_by{|k,v| -v}.first puts "Found these workers: #{worker_hash.sort_by{|k,v| -v}}" num_cpus_cdhit=max_worker[1] init='' cd='' cmd = "cd-hit-454 -i #{cd_hit_input_file} -o clusters.fasta -M #{num_cpus_cdhit*1000} -T #{num_cpus_cdhit} > cd-hit-454.out" # worker is different to current machine, send over ssh if max_worker[0]!= workers[0] if File.exists?(init_file_path) init=". #{init_file_path}; " end pwd=`pwd`.chomp cd ='' if File.exists?(pwd) cd = "cd #{pwd}; " end cmd = "ssh #{max_worker[0]} \"#{init} #{cd} #{cmd}\"" end end return cmd end def check_global_params(params) errors=[] # check plugin list comment='Plugins applied to every sequence, separated by commas. Order is important' # default_value='PluginLowHighSize,PluginMids,PluginIndeterminations,PluginAbAdapters,PluginContaminants,PluginLinker,PluginVectors,PluginLowQuality' # params.check_param(errors,'plugin_list','String',default_value,comment) params.check_param(errors,'plugin_list','PluginList',nil,comment) comment='Should SeqTrimNext analysis be based on NGS? (if setting to false, a classic Sanger sequencing is considered)' default_value='true' params.check_param(errors,'next_generation_sequences','String',default_value,comment) comment='Remove duplicated (clonal) sequences (using CD-HIT 454)' default_value='true' params.check_param(errors,'remove_clonality','String',default_value,comment) comment='Custom parameters used by CD-HIT-454 (leave empty to let seqtrimnext decide). Execute "cd-hit-454 help" in command line to see a list of parameters' default_value='' params.check_param(errors,'cdhit_custom_parameters','String',default_value,comment) comment='Generate initial stats' default_value='true' params.check_param(errors,'generate_initial_stats','String',default_value,comment) comment='Minimum insert size for every trimmed sequence' default_value = 40 params.check_param(errors,'min_insert_size_trimmed','Integer',default_value,comment) comment='Minimum insert size for each end of paired-end reads; true paired-ends have both single-ends longer than this value' default_value = 40 params.check_param(errors,'min_insert_size_paired','Integer',default_value,comment) comment='Do not reject unexpectedly long sequences found in the raw data' default_value='true' params.check_param(errors,'accept_very_long_sequences','String',default_value,comment) comment='Seqtrim version' default_value=Seqtrimnext::SEQTRIM_VERSION params.check_param(errors,'seqtrim_version','String',default_value,comment) if !errors.empty? $LOG.error 'Please, define the following global parameters in params file:' errors.each do |error| $LOG.error ' -' + error end #end each end #end if return errors.empty? end def initialize(options) # ,options[:fasta],options[:qual],,,, params_path=options[:template] ip=options[:server_ip] port=options[:port] workers=options[:workers] only_workers=options[:only_workers] chunk_size = options[:chunk_size] use_json = options[:json] # check for checkpoint if File.exists?(ScbiMapreduce::CHECKPOINT_FILE) if !options[:use_checkpoint] STDERR.puts "ERROR: A checkpoint file exists, either delete it or provide -C flag to use it" exit(-1) end end # it is the server part if !only_workers then cd_hit_input_file = nil # TODO - FIX seqtrim to not iterate two times over input, so STDIN can be used sequence_readers=[] # open sequence reader and expand input files paths if options[:fastq] # choose fastq quality format format=:sanger case options[:format] when 'sanger' format = :sanger when 'illumina15' format = :ilumina when 'illumina18' format = :sanger end seqs_path='' $LOG.info("Used FastQ format for input files: #{format}") # iterate files options[:fastq].each do |fastq_file| if fastq_file=='-' seqs_path = STDIN else seqs_path = File.expand_path(fastq_file) end sequence_readers << FastqFile.new(seqs_path,'r',format, true) end cd_hit_input_file = seqs_path else seqs_path = File.expand_path(options[:fasta]) cd_hit_input_file = seqs_path qual_path = File.expand_path(options[:qual]) if qual_path sequence_readers << FastaQualFile.new(options[:fasta],options[:qual],true) end $LOG.info "Loading params" # Reads the parameter's file params = Params.new(params_path) $LOG.info "Checking global params" if !check_global_params(params) exit(-1) end # Load actions $LOG.info "Loading actions" action_manager = ActionManager.new() # load plugins plugin_list = params.get_param('plugin_list') # puts in plugin_list the plugins's array $LOG.info "Loading plugins [#{plugin_list}]" plugin_manager = PluginManager.new(plugin_list,params) # creates an instance from PluginManager. This must storage the plugins and load it # load plugin params $LOG.info "Check plugin params" if !plugin_manager.check_plugins_params(params) then $LOG.error "Plugin check failed" # save used params to file params.save_file('used_params.txt') exit(-1) end if !Dir.exists?(OUTPUT_PATH) Dir.mkdir(OUTPUT_PATH) end # Extract global stats if params.get_param('generate_initial_stats').to_s=='true' $LOG.info "Calculatings stats" ExtractStats.new(sequence_readers,params) else $LOG.info "Skipping calculatings stats phase." end # save used params to file params.save_file(File.join(OUTPUT_PATH,'used_params.txt')) piro_on = (params.get_param('next_generation_sequences').to_s=='true') params.load_mids(params.get_param('mids_db')) params.load_ab_adapters(params.get_param('adapters_ab_db')) params.load_adapters(params.get_param('adapters_db')) params.load_linkers(params.get_param('linkers_db')) #execute cd-hit if params.get_param('remove_clonality').to_s=='true' cmd=get_custom_cdhit(cd_hit_input_file,params) if cmd.empty? cmd=get_cd_hit_cmd(cd_hit_input_file,workers,$SEQTRIMNEXT_INIT) end $LOG.info "Executing cd-hit-454: #{cmd}" if !File.exists?('clusters.fasta.clstr') system(cmd) end if File.exists?('clusters.fasta.clstr') params.load_repeated_seqs('clusters.fasta.clstr') else $LOG.error("Exiting due to not found clusters.fasta.clstr. Maybe cd-hit failed. Check cd-hit.out") exit(-1) end end ############ SCBI DRB ########### # port = 50000 # ip = "10.250.255.6" # port = 50000 # ip = "localhost" # # workers=20 # only_workers=false # launch work manager end # end only_workers custom_worker_file = File.join(File.dirname(__FILE__), 'em_classes','seqtrim_worker.rb') $LOG.info "Workers:\n#{workers}" if only_workers then worker_launcher = ScbiMapreduce::WorkerLauncher.new(ip,port, workers, custom_worker_file, STDOUT) worker_launcher.launch_workers_and_wait else $LOG.info 'Starting server' SeqtrimWorkManager.init_work_manager(sequence_readers, params,chunk_size,use_json,options[:skip_output],options[:write_in_gzip]) begin cpus=1 if RUBY_PLATFORM.downcase.include?("darwin") cpus=`hwprefs -cpu_count`.chomp.to_i else cpus=`grep processor /proc/cpuinfo |wc -l`.chomp.to_i end rescue cpus=1 end # if workers is an integer, reduce it by one (because of the server) begin Integer(workers) if workers>1 && workers<cpus workers-=1 end rescue if workers.count>1 && workers.count<cpus workers.shift end end # launch processor server passing the ip, port and all required params # server = Server.new(ip,port, workers, SeqtrimWorkManager,custom_worker_file, STDOUT,File.join($SEQTRIM_PATH,'init_env')) # server = ScbiMapreduce::Manager.new(ip,port, workers, SeqtrimWorkManager,custom_worker_file, STDOUT,'~/.seqtrimnext') server = ScbiMapreduce::Manager.new(ip,port, workers, SeqtrimWorkManager,custom_worker_file, STDOUT,$SEQTRIMNEXT_INIT) server.chunk_size=chunk_size server.checkpointing=true server.keep_order=true server.retry_stuck_jobs=true server.start_server # close sequence reader sequence_readers.each do |file| file.close end if SeqtrimWorkManager.exit_status>=0 $LOG.info "Exit status: #{SeqtrimWorkManager.exit_status}" else $LOG.error "Exit status: #{SeqtrimWorkManager.exit_status}" end $LOG.info 'Closing server' end ############ SCBI DRB ########### end end # Seqtrim class <file_sep>/bin/split_paired.rb #!/usr/bin/env ruby require 'scbi_fasta' if ARGV.count!=3 puts "Usage: #{$0} fasta qual output_base_name" exit end fasta_path = ARGV[0] qual_path = ARGV[1] name = ARGV[2] out_fasta = name+'.fasta' out_qual = name+'.fasta.qual' puts "Opening #{fasta_path}, #{qual_path}" fqr=FastaQualFile.new(fasta_path,qual_path,true) out_f=File.new(out_fasta,'w+') out_q=File.new(out_qual,'w+') c=0 linker = 'TCGTATAACTTCGTATAATGTATGCTATACGAAGTTATTACG' fqr.each do |n,f,q| l_start= 0 l_end=f.index(linker) if l_end r_start=l_end+linker.length r_end =f.length forward=f[l_start..l_end-1] reverse=f[r_start..r_end] forward_q = q[l_start..l_end-1] reverse_q = q[r_start..r_end] if (forward.length!=forward_q.length) || (reverse.length!=reverse_q.length) puts [forward.length,forward_q.length,reverse.length,reverse_q.length].join(',') end out_f.puts ">#{n}F template=#{n} dir=F library=unadeellas" out_f.puts forward out_f.puts ">#{n}R template=#{n} dir=R library=unadeellas" out_f.puts reverse out_q.puts ">#{n}F template=#{n} dir=F library=unadeellas" out_q.puts forward_q.join(' ') out_q.puts ">#{n}R template=#{n} dir=R library=unadeellas" out_q.puts reverse_q.join(' ') end c=c+1 end puts c fqr.close out_f.close out_q.close <file_sep>/bin/seqtrimnext #!/usr/bin/env ruby # encoding: utf-8 # SeqTrimNext: Next generation sequencing preprocessor # Copyright (C) <2011> # Authors: <NAME>, <NAME>, # <NAME>, <NAME> & <NAME> # email: <EMAIL> - http://www.scbi.uma.es # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #= SEQTRIM II # #== Running # # Seqtrim can be run locally or in a parallel/distributted environment. # #=== Running locally #* list # #=== Running in a distributted environment # #== SEC 2 # #=== SUB 2.1 # # #finds the classes that were in the folder 'classes' # ROOT_PATH=File.dirname(__FILE__) # $: << File.expand_path(File.join(ROOT_PATH, 'classes')) # # #finds the classes that were in the folder 'plugins' # $: << File.expand_path(File.join(ROOT_PATH, 'plugins')) # # # #finds the classes that were in the folder 'plugins' # $: << File.expand_path(File.join(ROOT_PATH, 'actions')) # # #finds the classes that were in the folder 'utils' # $: << File.expand_path(File.join(ROOT_PATH, 'utils')) # # $: << File.expand_path(File.join(ROOT_PATH, 'classes','em_classes')) # to test scbi_drb gem locally # $: << File.expand_path('~/progs/ruby/gems/scbi_drb/lib/') # $: << File.expand_path(ROOT_PATH) $: << File.expand_path('~/progs/ruby/gems/seqtrimnext/lib/') # $: << File.expand_path('~/progs/ruby/gems/scbi_mapreduce/lib/') require 'seqtrimnext' require 'scbi_headers' def put_header header = ScbiHeader.new('SeqTrimNEXT',Seqtrimnext::SEQTRIM_VERSION) header.description="SeqtrimNEXT is a customizable and distributed pre-processing software for NGS (Next Generation Sequencing) biological data. It makes use of scbi_mapreduce gem to be able to run in parallel and distributed environments. It is specially suited for Roche 454 (normal and paired-end) & Ilumina datasets, although it could be easyly adapted to any other situation." header.copyright='2011' header.authors<< "<NAME>" header.authors<< "<NAME>" header.authors<< "<NAME>" header.authors<< "<NAME>" header.authors<< "<NAME>" header.authors<< "<NAME>" # header.articles<< "Article one: with one description line" # header.articles<< "Article two: with one description line" # To output the header puts header end put_header ############ PATHS ####################### $SEQTRIM_PATH = ROOT_PATH if ENV['SEQTRIMNEXT_INIT'] && File.exists?(ENV['SEQTRIMNEXT_INIT']) $SEQTRIMNEXT_INIT=File.expand_path(ENV['SEQTRIMNEXT_INIT']) else $SEQTRIMNEXT_INIT=File.join($SEQTRIM_PATH,'init_env') end # if there is a BLASTDB environment var, then use it if ENV['BLASTDB']# && Dir.exists?(ENV['BLASTDB']) $FORMATTED_DB_PATH = ENV['BLASTDB'] $DB_PATH = File.dirname($FORMATTED_DB_PATH) else # otherwise use ROOTPATH + DB $FORMATTED_DB_PATH = File.expand_path(File.join(ROOT_PATH, "DB",'formatted')) $DB_PATH = File.expand_path(File.join(ROOT_PATH, "DB")) end ENV['BLASTDB']=$FORMATTED_DB_PATH OUTPUT_PATH='output_files_tmp' DEFAULT_FINAL_OUTPUT_PATH='output_files' # TODO - COMENTAR todas las clases y metodos para que salga la descripcion cuando hagas rdoc en el terminal #Checks install requeriments require 'install_requirements' ins = InstallRequirements.new if (!ins.check_install_requirements) exit(-1) end require "logger" require 'optparse' require "global_match" require "seqtrim" require "params.rb" require "plugin.rb" require "sequence.rb" require "plugin_manager.rb" require "make_blast_db" require 'hash_stats' require 'list_db' require 'install_database' require 'socket' def show_additional_help puts "\n"*3 puts "E.g.: processing a fastq sequences file" puts "#{File.basename($0)} -t genomics_454.txt -Q sequences.fastq" puts "\n"*2 puts "E.g.: processing a fasta file with qual" puts "#{File.basename($0)} -t genomics_454.txt -f sequences.fasta -q sequences.qual" templates = Dir.glob(File.join($SEQTRIM_PATH,'templates','*.txt')).map{|t| File.basename(t)} puts "\n\n ========================================================================================================" puts " Available templates to use with -t option (you can also use your own template):" puts " Templates at: #{File.join($SEQTRIM_PATH,'templates')}" puts " ========================================================================================================\n\n" templates.map{|e| puts " "+e} puts "\n\n ========================================================================================================" puts " Available databases to use in custom template files (you can also use your own database):" puts " Databases at: #{$DB_PATH}" puts " ========================================================================================================\n\n" ListDb.list_databases($DB_PATH).map{|e| puts " "+e} # # ip_list = Socket.ip_address_list.select{|e| e.ipv4?}.map{|e| e.ip_address} # # puts ip_list exit end # Reads the parameters from console. For this is used ARGV, that is an array. options = {} optparse = OptionParser.new do |opts| # Set a banner, displayed at the top # of the help screen. opts.banner = "Usage: #{$0} -t template_file \{-Q fastaQ_file | -f fasta_file -q qual_file\} [options]" # Define the options, and what they do #options[:server_ip] = '127.0.0.1' options[:server_ip] = '0.0.0.0' opts.on( '-s', '--server IP', 'Server ip. Can use a partial ip to select the apropriate interface' ) do |server_ip| # get list of available ips ip_list = Socket.ip_address_list.select{|e| e.ipv4?}.map{|e| e.ip_address} ip=ip_list.select{|ip| ip.index(server_ip)==0}.first if !ip ip='0.0.0.0' # $LOG.info("No available ip matching #{server_ip}") end # $ .info("Using ip #{ip}") options[:server_ip] = ip end options[:port] = 0 #50000 opts.on( '-p', '--port PORT', 'Server port. If set to 0, an arbitrary empty port will be used') do |port| options[:port] = port.to_i end options[:workers] = 2 opts.on( '-w', '--workers COUNT', 'Number of workers, or file containing machine names to launch workers with ssh' ) do |workers| if File.exists?(workers) # use workers file options[:workers] = File.read(workers).split("\n").map{|w| w.chomp} else begin options[:workers] = Integer(workers) rescue STDERR.puts "ERROR:Invalid workers parameter #{options[:workers]}" exit -1 end end end options[:only_workers] = false opts.on( '-o', '--only_workers', 'Only launch workers' ) do options[:only_workers] = true end options[:check_db] = false opts.on( '-c', '--check_databases', 'Check Blast databases and reformat if necessary' ) do options[:check_db] = true end options[:use_checkpoint] = false opts.on( '-C', '--use_checkpoint', 'Restore at checkpoint if scbi_mapreduce_checkpoint file is available' ) do options[:use_checkpoint] = true end # options[:skip_initial_stats] = false # opts.on( '-k', '--skip_initial_stats', 'Skip initial stats' ) do # options[:skip_initial_stats] = true # end options[:install_db] = nil opts.on( '-i', '--install_databases TYPE', 'Install base databases and reformat them if necessary') do |db_type| options[:install_db] = db_type end options[:logfile] = STDOUT opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do |file| options[:logfile] = file end options[:fastq] = nil opts.on( '-Q', '--fastq FILE1,FILE2',Array, 'Fastq input file. Use - for <STDIN>' ) do |file| options[:fastq] = file puts "FILES:",file,file.class end options[:format] = nil opts.on( '-F', '--fastq_quality_format FORMAT', 'Fastq input quality format use sanger or illumina18 for phred+33 based scores. Use illumina15 for phred+64 based scores (default is sanger) file. Use - for <STDIN>' ) do |value| options[:format] = value if !['sanger','illumina15', 'illumina18'].include?(value) STDERR.puts "ERROR: Invalid FASTQ format parameter #{value}" exit -1 end end options[:fasta] = nil opts.on( '-f', '--fasta FILE', 'Fasta input file' ) do |file| options[:fasta] = file end options[:qual] = nil opts.on( '-q', '--qual FILE', 'Qual input file' ) do |file| options[:qual] = file end options[:list_db] = nil options[:list_db_name] = 'ALL' opts.on( '-L', '--list_db [DB_NAME]', 'List entries IDs in DB_NAME. Use "-L all" to view all available databases' ) do |value| options[:list_db] = true options[:list_db_name] = value if value end options[:gen_params] = false opts.on( '-G', '--generate_template', 'Generates a sample template file with default parameters' ) do options[:gen_params] = true end options[:template] = nil opts.on( '-t', '--template TEMPLATE_FILE', 'Use TEMPLATE_FILE instead of default parameters' ) do |file| options[:template] = file end options[:chunk_size] = 5000 opts.on( '-g', '--group_size chunk_size', 'Group sequences in chunks of size <chunk_size>' ) do |cs| options[:chunk_size] = cs.to_i end options[:json] = nil opts.on( '-j', '--json', 'Save results in json file' ) do options[:json] = true end options[:skip_output] = false opts.on( '-K', '--no-verbose', 'Change to no verbose mode. Every sequence will not be written to output log' ) do options[:skip_output] = true end options[:skip_report] = false opts.on( '-R', '--no-report', 'Do not generate final PDF report (gem scbi_seqtrimnext_report required if you want to generate PDF report).' ) do options[:skip_report] = true end options[:write_in_gzip] = false opts.on( '-z', '--gzip', 'Generate output files in gzip format.' ) do options[:write_in_gzip] = true end options[:final_output_path] = DEFAULT_FINAL_OUTPUT_PATH opts.on( '-O', '--ouput output_files', 'Output folder. It should not exists. output_files by default') do |folder| options[:final_output_path] = folder end # This displays the help screen, all programs are # assumed to have this option. opts.on_tail( '-h', '--help', 'Display this screen' ) do puts opts show_additional_help exit -1 end end # parse options and remove from ARGV optparse.parse! if options[:list_db] then # List database entries in a database ListDb.new($DB_PATH,options[:list_db_name]) exit -1 end if options[:gen_params] then # Generates a sample params file in current directory Params.generate_sample_params exit -1 end #set logger # system('rm logs/*') FileUtils.mkdir('logs') if !File.exists?('logs') $LOG = Logger.new(options[:logfile]) $LOG.datetime_format = "%Y-%m-%d %H:%M:%S" #logger.level = Logger::INFO #DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN $LOG.info("SeqTrimNext version #{Seqtrimnext::SEQTRIM_VERSION}") $LOG.info("STN command: #{$0}") $LOG.info("Using BLASTDB: "+ $FORMATTED_DB_PATH) $LOG.info("Using options: "+ options.to_json) if options[:install_db] then #install databases InstallDatabase.new(options[:install_db],$DB_PATH) # reformat databases MakeBlastDb.new($DB_PATH) exit end if !File.exists?($FORMATTED_DB_PATH) STDERR.puts "Database path not found: #{$FORMATTED_DB_PATH}. \n\n\nInstall databases to this path or set your BLASTDB environment variable (eg.: export BLASTDB=new_path)" exit(-1) end if options[:check_db] then # check and format blast databases MakeBlastDb.new($DB_PATH) exit end required_options = options[:template] && (options[:fastq] || (options[:fasta])) # if ((ARGV.count != 2) && (ARGV.count != 3)) # con esto vemos si hay argumentos, if (ARGV.count != 0) || (!required_options) # con esto vemos si hay argumentos, puts "You must provide all required options" puts "" puts optparse.help exit(-1) end if File.exists?(options[:final_output_path]) $LOG.error "Output folder #{options[:final_output_path]} already exists.\n Remove it if you want to launch STN again." exit(-1) end # check for template if (!File.exists?(options[:template])) if File.exists?(File.join($SEQTRIM_PATH,'templates',options[:template])) options[:template] = File.join($SEQTRIM_PATH,'templates',options[:template]) else $LOG.error "Params file: #{options[:template]} doesn't exists. \n\nYou can use your own template or specify one from this list:\n=============================" puts Dir.glob(File.join($SEQTRIM_PATH,'templates','*.txt')).map{|t| File.basename(t)} exit(-1) end end $LOG.info "Using init file: #{$SEQTRIMNEXT_INIT}" $LOG.info "Using params file: #{options[:template]}" # check file existence if options[:fastq] options[:fastq].each do |fastq_file| # fastq file if (!fastq_file.nil? && fastq_file!='-' && !File.exists?(File.expand_path(fastq_file))) $LOG.error "Input file: #{fastq_file} doesn't exists" exit(-1) end end end # fasta file if (!options[:fasta].nil? && !File.exists?(options[:fasta])) $LOG.error "Input file: #{options[:fasta]} doesn't exists" exit(-1) end # qual file if ((!options[:qual].nil?)&&(!File.exists?(options[:qual]))) $LOG.error "Input file: #{options[:qual]} doesn't exists" exit(-1) end s = Seqtrim.new(options) #generate report if !options[:skip_report] && system("which generate_report.rb > /dev/null ") cmd="generate_report.rb #{OUTPUT_PATH} 2> report_generation_errors.log" $LOG.info "Generating report #{cmd}" `#{cmd}` else skip_text='.' if options[:skip_report] skip_text=' and remove the -R option from the command line.' end $LOG.info "If you want a detailed report in PDF format, be sure you have installed the optional seqtrimnext_report gem (gem install seqtrimnext_report)#{skip_text}" end if (Seqtrim.exit_status>=0) FileUtils.mv OUTPUT_PATH, options[:final_output_path] end exit(Seqtrim.exit_status) <file_sep>/lib/seqtrimnext/plugins/plugin_adapters.rb require "plugin" ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute PluginAdapters # Inherit: Plugin ######################################################## class PluginAdapters < Plugin # adapters found at end of sequence are even 2 nt wide, cut in 5 because of statistics MIN_ADAPTER_SIZE = 5 MIN_FAR_ADAPTER_SIZE = 13 def do_blasts(seqs) # find MIDS with less results than max_target_seqs value blast=BatchBlast.new("-db #{@params.get_param('adapters_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_adapters')} -word_size #{MIN_ADAPTER_SIZE}") $LOG.debug('BLAST:'+blast.get_blast_cmd) fastas=[] seqs.each do |seq| fastas.push ">"+seq.seq_name fastas.push seq.seq_fasta end # fastas=fastas.join("\n") blast_table_results = blast.do_blast(fastas,:table) # puts blast_table_results.inspect return blast_table_results end # filter hits that are in the middle and do not have a valid length def filter_hits(hits,end_pos) hits.reverse_each do |hit| if (hit.q_beg>10) && (hit.q_end < (end_pos-10)) && ((hit.q_end-hit.q_beg+1)<(@params.get_adapter(hit.subject_id).length*0.85).to_i) hits.delete(hit) # puts "- DELETE #{hit.subject_id} #{(hit.q_end-hit.q_beg+1)}, < #{(@params.get_adapter(hit.subject_id).length*0.85).to_i} - R:#{hit.reversed}" # # else # puts " ** ACCEPTED #{hit.subject_id} #{hit.q_beg}>6 and #{hit.q_end}<#{end_pos}-10, #{(hit.q_end-hit.q_beg+1)}, >= #{(@params.get_adapter(hit.subject_id).length*0.85).to_i} - R:#{hit.reversed}" # puts " *** #{hit.inspect}" end end end def exec_seq(seq,blast_query) if blast_query.query_id != seq.seq_name # raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}" end $LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for adapters into the sequence" # blast=BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'adapters.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_adapters')} -perc_identity #{@params.get_param('blast_percent_adapters')} -word_size #{MIN_ADAPTER_SIZE}") # blast with only one sequence, no with many sequences from a database #--------------------------------------------------------------------- # blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to adapterss executing over blast #BlastTableResult.new(res) # puts blast_query.inspect # puts blast_table_results.inspect filter_hits(blast_query.hits, seq.seq_fasta.length) adapters=[] # blast_table_results.querys.each do |query| # first round to save adapters without overlap merge_hits(blast_query.hits,adapters) # end begin adapters2=adapters # second round to save adapters without overlap adapters = [] merge_hits(adapters2,adapters) end until (adapters2.count == adapters.count) # puts "MERGED" # puts "="*50 # adapters.each {|a| puts a.inspect} max_to_end=@params.get_param('max_adapters_to_end').to_i # type = 'ActionAbAdapter' actions=[] adapter_size=0 #@stats['adapter_size']={} adapters.each do |c| # adds the correspondent action to the sequence # puts "is the adapter near to the end of sequence ? #{c.q_end+seq.insert_start+max_to_end} >= ? #{seq.seq_fasta_orig.size-1}" adapter_size=c.q_end-c.q_beg+1 #if ((c.q_end+seq.insert_start+max_to_end)>=seq.seq_fasta_orig.size-1) right_action = true #if ab adapter is very near to the end of original sequence if c.q_end>=seq.seq_fasta.length-max_to_end # message = c.subject_id message = c.definition type = 'ActionRightAdapter' ignore=false add_stats('adapter_type','right') elsif (c.q_beg <= 6) #&& (adapter_size>=MIN_LEFT_ADAPTER_SIZE) #left adapter # message = c.subject_id message = c.definition type = 'ActionLeftAdapter' ignore = false right_action = false add_stats('adapter_type','left') elsif (adapter_size>=MIN_FAR_ADAPTER_SIZE) # message = c.subject_id message = c.definition type = 'ActionMiddleAdapter' ignore = false add_stats('adapter_type','middle') else ignore=true end if !ignore a = seq.new_action(c.q_beg,c.q_end,type) a.message = message a.reversed = c.reversed if right_action a.right_action = true #mark as rigth action to get the left insert else a.left_action = true end actions.push a # puts "adapter_size #{adapter_size}" #@stats[:adapter_size]={adapter_size => 1} add_stats('adapter_size',adapter_size) add_stats('adapter_id',message) end end if !actions.empty? seq.add_actions(actions) add_stats('sequences_with_adapter','count') end # end #Returns an array with the errors due to parameters are missing def self.check_params(params) errors=[] comment='Blast E-value used as cut-off when searching for adapters' # default_value = 1e-6 default_value = 1 params.check_param(errors,'blast_evalue_adapters','Float',default_value,comment) comment='Minimum required identity (%) for a reliable adapter' default_value = 95 params.check_param(errors,'blast_percent_adapters','Integer',default_value,comment) comment='Adapters can be found at both ends of the sequence. The following variable indicates the number of nucleotides that are allowed for considering the adapters to be located at the right end' default_value = 9 params.check_param(errors,'max_adapters_to_end','Integer',default_value,comment) comment='Path for adapters database' default_value = File.join($FORMATTED_DB_PATH,'adapters.fasta') params.check_param(errors,'adapters_db','DB',default_value,comment) return errors end def self.get_graph_title(plugin_name,stats_name) case stats_name when 'adapter_type' 'Adapters by type' when 'adapter_size' 'Adapters by size' end end def self.get_graph_filename(plugin_name,stats_name) return stats_name # case stats_name # when 'adapter_type' # 'AB adapters by type' # when 'adapter_size' # 'AB adapters by size' # end end def self.valid_graphs return ['adapter_type'] end end <file_sep>/bin/parse_json_results.rb #!/usr/bin/env ruby require 'yajl' require 'json' unless file = ARGV.shift puts "\nUsage: $0 results.json action1 [action] [action] [action] ...\n\n" exit(0) end actions = ARGV if actions.empty? puts "\nUsage: $0 results.json action1 [action] [action] [action] ...\n\n" exit(0) end json = File.new(file, 'r') puts "Counting sequences with these actions: #{actions.join(",")}" puts "" total = 0 count = 0 separate_count={} actions.each do |a| separate_count[a]=0 end all_actions =[] Yajl::Parser.parse(json) { |seq| total += 1 action_names=seq['actions'].map {|a| a['type']} if (action_names & actions).count == actions.count count +=1 end action_names.each do |a| if actions.include?(a) separate_count[a] += 1 end end all_actions = (all_actions + action_names).uniq } puts "="*20 + "Separate count" + "="*20 separate_count.each do |k,v| puts "#{k} = #{v}" end puts "="*20 + "Summarized" + "="*20 puts "Number of sequences with all actions: #{count}" puts "Total sequences: #{total}" puts "\n" puts "="*20 + "Other used actions" + "="*20 puts (all_actions-actions).join(',') <file_sep>/lib/seqtrimnext/utils/json_utils.rb #================================================ # SCBI - dariogf <<EMAIL>> #------------------------------------------------ # # Version: 0.1 - 04/2009 # # Usage: require "utils/json_utils" # # Fasta utilities # # # #================================================ module JsonUtils require 'json'; def to_pretty_json return JSON.pretty_generate(self) end def from_json return JSON.parse(self) end # =========================================== #------------------------------------ # get json data #------------------------------------ def self.get_json_data(file_path) file1 = File.open(file_path) text = file1.read file1.close # wipe text text=text.grep(/^\s*[^#]/).to_s # decode json data = JSON.parse(text) return data end end <file_sep>/lib/seqtrimnext/plugins/plugin.rb ######################################################## # Author: <NAME> # # Defines the main methods that are necessary to execute a plugin # ######################################################## require 'string_utils' # $: << '/Users/dariogf/progs/ruby/gems/scbi_blast/lib' require 'scbi_blast' class Plugin attr_accessor :stats #Loads the plugin's execution whit the sequence "seq" def initialize(seq, params) @params = params @stats ={} if can_execute? t1=Time.now execute(seq) t2=Time.now add_plugin_stats('execution_time','total_seconds',t2-t1) end end def add_plugin_stats(cat,item,elapsed_time) @stats[cat]={} if @stats[cat].nil? @stats[cat][item]=elapsed_time end def can_execute? return true end def exec_seq(seq,blast_query) end #Begins the plugin's execution whit the sequence "seq" def execute(seqs) t1=Time.now blasts=do_blasts(seqs) if !blasts.empty? if blasts.is_a?(Array) queries=blasts else queries = blasts.querys end add_plugin_stats('execution_time','blast_and_parse',Time.now-t1) t1=Time.now seqs.each_with_index do |s,i| exec_seq(s,queries[i]) end else # there is no blast t1=Time.now seqs.each do |s| exec_seq(s,nil) end end add_plugin_stats('execution_time','exec_seq',Time.now-t1) end def do_blasts(seqs) return [] end #Initializes the structure stats to the given key and value , only when it is neccesary, and increases its counter def add_stats(key,value) @stats[key]={} if @stats[key].nil? if @stats[key][value].nil? @stats[key][value] = 0 end @stats[key][value] += 1 # puts "@stats #{key} #{value}=#{ @stats[key][value]}" end #Initializes the structure stats to the given key and value , only when it is neccesary, and increases its counter def add_text_stats(key,value,text) @stats[key]={} if @stats[key].nil? if @stats[key][value].nil? @stats[key][value] = [] end @stats[key][value].push(text) end def overlapX?(r1_start,r1_end,r2_start,r2_end) # puts r1_start.class # puts r1_end.class # puts r2_start.class # puts r2_end.class # puts "-------" #puts "overlap? (#{r1_start}<=#{r2_end}) and (#{r1_end}>=#{r2_start})" return ((r1_start<=r2_end+1) and (r1_end>=r2_start-1) ) end def merge_hits(hits,merged_hits,merged_ids=nil, merge_different_ids=true) # puts " merging ============" # hits.each do |hit| hits.sort{|h1,h2| (h1.q_end-h1.q_beg+1)<=>(h2.q_end-h2.q_beg+1)}.reverse_each do |hit| merged_ids.push hit.definition if !merged_ids.nil? && (! merged_ids.include?(hit.definition)) # if new hit's position is already contained in hits, then ignore the new hit if merge_different_ids c=merged_hits.find{|c| overlapX?(hit.q_beg, hit.q_end,c.q_beg,c.q_end)} else # overlap with existent hit and same subject id c=merged_hits.find{|c| (overlapX?(hit.q_beg, hit.q_end,c.q_beg,c.q_end) && (hit.subject_id==c.subject_id))} end # puts " c #{c.inspect}" if (c.nil?) # add new contaminant #puts "NEW HIT #{hit.inspect}" merged_hits.push(hit.dup) #contaminants.push({:q_begin=>hit.q_beg,:q_end=>hit.q_end,:name=>hit.subject_id}) # else # one is inside each other, just ignore if ((hit.q_beg>=c.q_beg && hit.q_end <=c.q_end) || (c.q_beg>=hit.q_beg && c.q_end <= hit.q_end)) # puts "* #{hit.subject_id} inside #{c.subject_id}" else # merge with old contaminant # puts "#{hit.subject_id} NOT inside #{c.subject_id}" min=[c.q_beg,hit.q_beg].min max=[c.q_end,hit.q_end].max c.q_beg=min c.q_end=max # DONE para describir cada Id contaminante encontrado # puts "1 -#{c.subject_id}- -#{hit.subject_id}-" c.subject_id += ' ' + hit.subject_id if (not c.subject_id.include?(hit.subject_id)) # puts "2 -#{c.subject_id}- -#{hit.subject_id}-" # puts "MERGE HIT (#{c.inspect})" end # end end end # def check_length_inserted(p_start,p_end,seq_fasta_length) # min_insert_size = @params.get_param('min_insert_size ').to_i # v1= p_end.to_i # v2= p_start.to_i # v3= v1 - v2 # $LOG.debug "------ #{v3} ----" # # res = true # if ((v1 - v2 + 1) > (seq_fasta_length - min_insert_size )) # $LOG.debug "ERROR------ SEQUENCE IS NOT GOOD ----" # res = false # end # return res # end #------------------------------------------ # search a key into the sequence # Used: in class PluginLinker and PluginMid #------------------------------------------- # def search_key (seq,key_start,key_end) # p_q_beg=0 # p_q_end=0 # if (seq.seq_fasta[key_start..key_end]==@params.get_param('key')) # actions=[] # #Add ActionKey and apply it to cut the sequence # # type = "ActionKey" # # p_q_beg,p_q_end=key_start,key_end # a = seq.new_action(p_q_beg,p_q_end,type) # adds the actionKey/actionMid to the sequence # # actions.push a # # seq.add_actions(actions) #apply cut to the sequence with the actions # end # return [p_q_beg,p_q_end] # # end def self.check_param(errors,params,param,param_class,default_value=nil, comment=nil) if !params.exists?(param) if !default_value.nil? params.set_param(param,default_value,comment) else errors.push "The param #{param} is required and thre is no default value available" end else s = params.get_param(param) # check_class=Object.const_get(param_class) begin case param_class when 'Integer' r = Integer(s) when 'Float' r = Float(s) when 'String' r = String(s) end rescue errors.push " The param #{param} is not a valid #{param_class}: ##{s}#" end end end #Returns an array with the errors due to parameters are missing def self.check_params(params) return [] end def self.graph_ignored?(stats_name) res = true if !self.ignored_graphs.include?(stats_name) && (self.valid_graphs.empty? || self.valid_graphs.include?(stats_name)) res = false end return res end def self.plot_setup(stats_value,stats_name,x,y,init_stats,plot) return false end # automatically setup data def self.auto_setup(stats_value,stats_name,x,y) # res =false # # if !self.ignored_graphs.include?(stats_name) && (self.valid_graphs.empty? || self.valid_graphs.include?(stats_name)) # # res = true contains_strings=false stats_value.keys.each do |v| begin r=Integer(v) rescue contains_strings=true break end end # puts "#{stats_name} => #{contains_strings}" if !contains_strings stats_value.keys.each do |v| x.push v.to_i end x.sort! x.each do |v| y.push stats_value[v.to_s].to_i end else # there are strings in X x2=[] stats_value.keys.each do |v| x.push "\"#{v.gsub('\"','').gsub('\'','')}\"" x2.push v end # puts ".#{x}." x2.each do |v| # puts ".#{v}." y.push stats_value[v.to_s] end end # return res end def self.get_graph_title(plugin_name,stats_name) return plugin_name + '/' +stats_name end def self.get_graph_filename(plugin_name,stats_name) return (plugin_name+ '_' +stats_name) end def self.ignored_graphs return [] end def self.valid_graphs return [] end end <file_sep>/bin/parse_params.rb #!/usr/bin/env ruby require 'json' def get_json_data(file_path) file1 = File.open(file_path) text = file1.read file1.close # puts text # # wipe text # text=text.grep(/^\s*[^#]/).to_s # decode json data = JSON.parse(text) return data end # extract params loading to external file in ingebiol params={} params['vector_db_field']='vectors_db' params['primers_db_field']='primers_db' params['contaminants_db_field']='contaminants_db' params['user_contaminants_db_field']='user_contaminants_db' params['species_field']='genus' params['min_insert_size_field']='min_insert_size_trimmed' params['min_paired_insert_size_field']='min_insert_size_paired' params['min_quality_value_field']='min_quality' if ARGV.count!=2 puts "#{$0} ingebiol_params_file.json seqtrim_params_file" exit(-1) end input_file = ARGV[0] params_file=ARGV[1] if !File.exists?(input_file) puts "File #{input_file} doesn't exists" exit(-1) end if !File.exists?(params_file) puts "File #{params_file} doesn't exists" exit(-1) end sq_params=File.open(params_file,'r') data=get_json_data(input_file) # puts data.keys # puts data['vector_db_field'] # replace params # sq_params.each_line do |line| # line.chomp! # # if line =~ /^\s*(.+)\s*=\s*(.+)\s*/ # puts $1,$2 # end # # end sq_params=File.open(params_file,'a+') sq_params.puts "" data.each do |k,v| sq_name=params[k] # puts k,sq_name if sq_name && v && !v.empty? sq_params.puts "#{sq_name}=#{v}" end end sq_params.close<file_sep>/bin/fastq2fasta.rb #!/usr/bin/env ruby require 'scbi_fastq' if ARGV.count < 2 puts "#{$0} FASTQ OUTPUT_NAME" exit end fastq = ARGV.shift output_name = ARGV.shift fasta = File.open(output_name+'.fasta','w') qual = File.open(output_name+'.fasta.qual','w') fqr=FastqFile.new(fastq) fqr.each do |seq_name,seq_fasta,seq_qual,comments| fasta.puts ">#{seq_name} #{comments}" fasta.puts seq_fasta qual.puts ">#{seq_name} #{comments}" qual.puts seq_qual.join(' ') end fasta.close qual.close fqr.close <file_sep>/bin/resume_stn_stats.rb #!/usr/bin/env ruby require 'json' if ARGV.count<1 puts "Usage: #{$0} stats1.json [stats2.json stats3.json,...]" exit -1 end # print header if ARGV[0]=='-t' heads=['sample_name','input_count','sequence_count_paired','sequence_count_single','rejected','rejected_percent'] puts heads.join("\t") ARGV.shift end ARGV.each do |file_path| sample_name = File.basename(File.expand_path(File.join(file_path,'..','..'))) stats=JSON::parse(File.read(file_path)) res=[] begin res << sample_name res << stats['sequences']['count']['input_count'] res << stats['sequences']['count']['output_seqs_paired'] res << stats['sequences']['count']['output_seqs'] res << stats['sequences']['count']['rejected'] #res << sprintf('%.2f',(stats['sequences']['count']['rejected'].to_f/(stats['sequences']['count']['output_seqs_paired'].to_i+stats['sequences']['count']['output_seqs'].to_i).to_f)*100) res << sprintf('%.2f',(stats['sequences']['count']['rejected'].to_f/stats['sequences']['count']['input_count'].to_f)*100) rescue Excepcion => e puts "Error reading #{file_path}" end puts res.join("\t") end
ac70b94e2b54fd102a9da4ccc4256517e856ee5b
[ "Markdown", "Ruby", "Shell" ]
91
Ruby
dariogf/SeqtrimNext
8b434ed75011886c48b314f740edb9d4b090b900
948c92eff99cee18ecd194e0022ad10800e53e86
refs/heads/master
<file_sep> define(function(require, exports, module) { 'use strict'; // import dependencies var Surface = require('famous/core/Surface'); var Transform = require('famous/core/Transform'); var Utils = require('utils'); var Context = require('famous/core/Context'); var el = document.createElement("div"); el.classList.add("hide"); document.body.appendChild(el); var tmpContext = new Context(el); var usePrefix = document.body.style.webkitTransform !== undefined; var devicePixelRatio = window.devicePixelRatio || 1; function TextSurface() { Utils.transparentApply(Surface,this,arguments); tmpContext._node.set(this); this.commit(tmpContext._nodeContext); var i = 0; var target = this._currTarget; // this.eventHandler.emit('recall'); this.recall(target); target.style.display = 'none'; target.style.width = ''; target.style.height = ''; // this._size = null; _cleanupStyles.call(this, target); var classList = this.getClassList(); _cleanupClasses.call(this, target); for (i = 0; i < classList.length; i++) target.classList.remove(classList[i]); if (this.elementClass) { if (this.elementClass instanceof Array) { for (i = 0; i < this.elementClass.length; i++) { target.classList.remove(this.elementClass[i]); } } else { target.classList.remove(this.elementClass); } } _removeEventListeners.call(this, target); this._currTarget = null; tmpContext._allocator.deallocate(target); _setInvisible(target); } TextSurface.prototype = Object.create(Surface.prototype); TextSurface.prototype.constructor = TextSurface; // Attach Famous event handling to document events emanating from target // document element. This occurs just after deployment to the document. // Calling this enables methods like #on and #pipe. function _addEventListeners(target) { for (var i in this.eventHandler.listeners) { target.addEventListener(i, this.eventForwarder); } } // Detach Famous event handling from document events emanating from target // document element. This occurs just before recall from the document. function _removeEventListeners(target) { for (var i in this.eventHandler.listeners) { target.removeEventListener(i, this.eventForwarder); } } // Apply to document all changes from removeClass() since last setup(). function _cleanupClasses(target) { for (var i = 0; i < this._dirtyClasses.length; i++) target.classList.remove(this._dirtyClasses[i]); this._dirtyClasses = []; } // Apply values of all Famous-managed styles to the document element. // These will be deployed to the document on call to #setup(). function _applyStyles(target) { for (var n in this.properties) { target.style[n] = this.properties[n]; } } // Clear all Famous-managed styles from the document element. // These will be deployed to the document on call to #setup(). function _cleanupStyles(target) { for (var n in this.properties) { target.style[n] = ''; } } /** * Return a Matrix's webkit css representation to be used with the * CSS3 -webkit-transform style. * Example: -webkit-transform: matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,716,243,0,1) * * @method _formatCSSTransform * @private * @param {FamousMatrix} m matrix * @return {string} matrix3d CSS style representation of the transform */ function _formatCSSTransform(m) { m[12] = Math.round(m[12] * devicePixelRatio) / devicePixelRatio; m[13] = Math.round(m[13] * devicePixelRatio) / devicePixelRatio; var result = 'matrix3d('; for (var i = 0; i < 15; i++) { result += (m[i] < 0.000001 && m[i] > -0.000001) ? '0,' : m[i] + ','; } result += m[15] + ')'; return result; } /** * Directly apply given FamousMatrix to the document element as the * appropriate webkit CSS style. * * @method setMatrix * * @static * @private * @param {Element} element document element * @param {FamousMatrix} matrix */ var _setMatrix; if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { _setMatrix = function(element, matrix) { element.style.zIndex = (matrix[14] * 1000000) | 0; // fix for Firefox z-buffer issues element.style.transform = _formatCSSTransform(matrix); }; } else if (usePrefix) { _setMatrix = function(element, matrix) { element.style.webkitTransform = _formatCSSTransform(matrix); }; } else { _setMatrix = function(element, matrix) { element.style.transform = _formatCSSTransform(matrix); }; } // format origin as CSS percentage string function _formatCSSOrigin(origin) { return (100 * origin[0]).toFixed(6) + '% ' + (100 * origin[1]).toFixed(6) + '%'; } // Directly apply given origin coordinates to the document element as the // appropriate webkit CSS style. var _setOrigin = usePrefix ? function(element, origin) { element.style.webkitTransformOrigin = _formatCSSOrigin(origin); } : function(element, origin) { element.style.transformOrigin = _formatCSSOrigin(origin); }; // Shrink given document element until it is effectively invisible. var _setInvisible = usePrefix ? function(element) { element.style.webkitTransform = 'scale3d(0.0001,0.0001,1)'; element.style.opacity = 0; } : function(element) { element.style.transform = 'scale3d(0.0001,0.0001,1)'; element.style.opacity = 0; }; function _xyNotEquals(a, b) { return (a && b) ? (a[0] !== b[0] || a[1] !== b[1]) : a !== b; } function _hideTarget (target) { var oldVisibility = target.style.visibility; target.style.visibility = 'hidden'; return oldVisibility; } function _showTarget (target, visibilityVal) { target.style.visibility = visibilityVal; } TextSurface.prototype.getSize = function getSize (actual) { if(this._currTarget){ // this._currTarget.style.width = ''; // this._currTarget.style.height = ''; return [this._currTarget.clientWidth, this._currTarget.clientHeight]; } return actual ? this._size : (this.size || this._size || [0,0]); } TextSurface.prototype.setSize = function setSize () { if(this._currTarget){ // this._currTarget.style.width = ''; // this._currTarget.style.height = ''; this.size = [this._currTarget.clientWidth, this._currTarget.clientHeight]; // console.log(this.size) } this._sizeDirty = true; } TextSurface.prototype.commit = function commit(context) { if (!this._currTarget) this.setup(context.allocator); var target = this._currTarget; var matrix = context.transform; var opacity = context.opacity; var origin = context.origin; var size = context.size; var visibilityVal = _hideTarget(target); if (this._contentDirty) { // logSize(target); this.deploy(target); this.eventHandler.emit('deploy'); this._contentDirty = false; this.setSize(); // logSize(target); } if (this.size) { var origSize = size; size = [this.size[0], this.size[1]]; if (size[0] === undefined && origSize[0]) size[0] = origSize[0]; if (size[1] === undefined && origSize[1]) size[1] = origSize[1]; } if (_xyNotEquals(this._size, size)) { this._size = [size[0], size[1]]; this._sizeDirty = true; } if (!matrix && this._matrix) { this._matrix = null; this._opacity = 0; _setInvisible(target); return; } if (this._opacity !== opacity) { this._opacity = opacity; target.style.opacity = (opacity >= 1) ? '0.999999' : opacity; } if (_xyNotEquals(this._origin, origin) || Transform.notEquals(this._matrix, matrix) || this._sizeDirty) { // if (!matrix) matrix = Transform.identity; this._matrix = matrix; var aaMatrix = matrix; if (origin) { if (!this._origin) this._origin = [0, 0]; this._origin[0] = origin[0]; this._origin[1] = origin[1]; aaMatrix = Transform.moveThen([-this._size[0] * origin[0], -this._size[1] * origin[1], 0], matrix); } _setMatrix(target, aaMatrix); } if ((this._classesDirty || this._stylesDirty || this._sizeDirty || this._contentDirty)){ if (this._classesDirty) { _cleanupClasses.call(this, target); var classList = this.getClassList(); for (var i = 0; i < classList.length; i++) target.classList.add(classList[i]); this._classesDirty = false; } if (this._stylesDirty) { _applyStyles.call(this, target); this._stylesDirty = false; } if (this._sizeDirty) { if (this._size) { // target.style.width = (this._size[0] !== true) ? this._size[0] + 'px' : ''; // target.style.height = (this._size[1] !== true) ? this._size[1] + 'px' : ''; } this._sizeDirty = false; } } _showTarget(target, visibilityVal); }; module.exports = TextSurface; }) <file_sep>define(function(require, exports, module) { var Utils = require('utils'); var View = require('famous/core/View'); var StateModifier = require('famous/core/Modifier'); var TextNodeSurface = require('TextNodeSurface') function TextNodeView (textNodeOptions,stateModifierOptions,viewOptions) { View.call(this,viewOptions); this.stateModifier = new StateModifier(stateModifierOptions); this.textNode = new TextNodeSurface(textNodeOptions); this.add(this.stateModifier).add(this.textNode); } TextNodeView.prototype = Object.create(View.prototype); TextNodeView.prototype.constructor = TextNodeView; module.exports = TextNodeView; });
95e5e77a7e12c25bb1edb1545583d1249adcdbd0
[ "JavaScript" ]
2
JavaScript
HelveticaScenario/wiggle-words
de9b57cd51b6cbfaa06b4302535a00d9e0444b84
e5d35d958079bbb4abd552cc62b324e05dc1bd1f
refs/heads/master
<repo_name>Davasny/mech_pk_free_time_finder<file_sep>/finder/controller/__init__.py import finder.controller.Router <file_sep>/application.py from finder import application import optparse from finder.models.optivum_scraper import OptivumScraper from flask_apscheduler import APScheduler import os.path class Config(object): JOBS = [ { 'id': 'scraper_job', 'func': 'application:scraper_job', 'trigger': 'interval', 'seconds': 3600 } ] SCHEDULER_API_ENABLED = True def scraper_job(): OptivumScraper("http://aslan.mech.pk.edu.pl/~podzial/stacjonarne/html/") def flask_run(default_host="localhost", default_port="5000"): parser = optparse.OptionParser() parser.add_option("-H", "--host", help="Hostname/IP of system " + \ "[default %s]" % default_host, default=default_host) parser.add_option("-P", "--port", help="Port for the system " + \ "[default %s]" % default_port, default=default_port) parser.add_option("-d", "--debug", action="store_true", dest="debug", help=optparse.SUPPRESS_HELP) options, _ = parser.parse_args() application.config.from_object(Config()) scheduler = APScheduler() scheduler.init_app(application) scheduler.start() if not os.path.isfile("timetable.json"): scheduler.run_job("scraper_job") application.run( debug=options.debug, host=options.host, port=int(options.port), threaded=True, ) if __name__ == '__main__': flask_run() <file_sep>/finder/controller/APIHandler.py from flask import request from .BaseHandler import BaseView from finder.models import TimetableData import json class TimetableHours(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_hours(), ensure_ascii=False) class TimetableTeachers(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_teachers(), ensure_ascii=False) class TimetableGroups(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_groups(), ensure_ascii=False) class TimetableSubjects(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_subjects(), ensure_ascii=False) class TimetableClassrooms(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_classrooms(), ensure_ascii=False) class TimetableWeekDays(BaseView): def get(self, *args, **kwargs): timetable = TimetableData.TimetableData() return json.dumps(timetable.get_week_days(), ensure_ascii=False) <file_sep>/finder/models/TimetableData.py from finder import app, logger import re class TimetableData: def get_hours(self): if 'hours' not in app.timetable: logger.debug("Filling hours") app.timetable['hours'] = [] for lesson in app.timetable['lessons']: if lesson['hour'] not in app.timetable['hours']: app.timetable['hours'].append(lesson['hour']) sorted(app.timetable['hours']) return app.timetable['hours'] def get_teachers(self): if 'teachers' not in app.timetable: logger.debug("Filling teachers") app.timetable['teachers'] = [] for lesson in app.timetable['lessons']: if lesson['teacher'] is not None: teacher = re.sub("(-p.*)|(-n.*)", "", lesson['teacher']) # remove -n and -p from name if teacher not in app.timetable['teachers']: app.timetable['teachers'].append(teacher) return app.timetable['teachers'] def get_groups(self): if 'groups' not in app.timetable: logger.debug("Filling groups") app.timetable['groups'] = [] for lesson in app.timetable['lessons']: for group in lesson['group']: if group not in app.timetable['groups']: app.timetable['groups'].append(group) return app.timetable['groups'] def get_subjects(self): if 'subjects' not in app.timetable: logger.debug("Filling subjects") app.timetable['subjects'] = [] for lesson in app.timetable['lessons']: if lesson['subject'] not in app.timetable['subjects']: app.timetable['subjects'].append(lesson['subject']) return app.timetable['subjects'] def get_classrooms(self): if 'classrooms' not in app.timetable: logger.debug("Filling classrooms") app.timetable['classrooms'] = [] for lesson in app.timetable['lessons']: if lesson['classroom'] is not None: classroom = re.sub("(-p.*)|(-n.*)", "", lesson['classroom']) # remove -n and -p from name if classroom not in app.timetable['classrooms']: app.timetable['classrooms'].append(classroom) return app.timetable['classrooms'] def get_week_days(self): days = ["Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"] week = {} for x in range(1, 8): week[x] = days[x-1] return week <file_sep>/finder/templates/week_view.html {%- for week_type in timetable_by_weeks %} {%- if week_type == "-p" %} <h3>Parzysty</h3> <div id="week-p-box"> {%- else %} <h3>Nieparzysty</h3> <div id="week-n-box"> {%- endif %} <table id="table-week{{ week_type }}" class="table table-bordered table-condensed "> <thead> <tr> <th></th> {%- for day_num, val in days.items() %} <th>{{ val }}</th> {%- endfor %} </tr> </thead> <tbody> {%- for hour in hours %} <tr> <td>{{ hour }}</td> {%- for day_num, val in days.items() %} {%- if timetable_by_weeks[week_type][day_num][hour]|length > 0 %} <td class="taken"> {%- for lesson in timetable_by_weeks[week_type][day_num][hour] %} {{ lesson['subject'] }} - {{ lesson['classroom'] }} {%- endfor %} </td> {%- else %} <td></td> {%- endif %} {%- endfor %} {%- endfor %} </tbody> </table> </div> {%- endfor %}<file_sep>/finder/models/TimetableFinder.py from finder import app, logger from finder.models.TimetableData import TimetableData from mongoquery import Query, QueryError import json import re class TimetableFinder: def __init__(self, **kwargs): self.json_query = "{}" if "json_query" in kwargs: self.json_query = kwargs['json_query'] self.timetable = app.timetable def load_query(self): self.query = json.loads(self.json_query) def validate_query(self): return True def find_taken_time(self): if not self.validate_query(): return False else: self.load_query() query = Query(self.query) selected_lessons = filter( query.match, self.timetable['lessons'] ) return selected_lessons class TimetableParser: def __init__(self, filtered_timetable): self.filtered_timetable = [{k: v for k, v in item.items()} for item in filtered_timetable ] def timetable_by_weeks(self): week_list = ["-p", "-n"] taken_time_by_week = {} for week in week_list: taken_time_by_week[week] = self.generate_timetable_by_day(week) return taken_time_by_week def generate_timetable_by_day(self, week): timetable_data = TimetableData() days = timetable_data.get_week_days() hours = timetable_data.get_hours() timetable_by_day = {} for day_num, val in days.items(): timetable_by_day[day_num] = {} for hour in hours: query = Query( {"$and": [{"day": day_num}, {"hour": hour}]} ) lessons_to_append = filter( query.match, self.filtered_timetable ) timetable_by_day[day_num][hour] = [] add_to_timetable_by_day = False for lesson in lessons_to_append: if lesson['teacher'] is not None: if week in lesson['teacher']: lesson['teacher'] = re.sub("(-p.*)|(-n.*)", "", lesson['teacher']) add_to_timetable_by_day = True if lesson['classroom'] is not None: if week in lesson['classroom']: lesson['classroom'] = re.sub("(-p.*)|(-n.*)", "", lesson['classroom']) add_to_timetable_by_day = True if lesson['subject'] is not None: if week in lesson['subject']: lesson['subject'] = re.sub("(-p.*)|(-n.*)", "", lesson['subject']) add_to_timetable_by_day = True elif re.match("^(WF)", lesson['subject']): add_to_timetable_by_day = True if add_to_timetable_by_day: timetable_by_day[day_num][hour].append(lesson) return timetable_by_day <file_sep>/finder/controller/Router.py from finder import app, logger from . import MainHandler, APIHandler app.add_url_rule('/', endpoint="index") """ MainHandler """ app.add_url_rule('/index', view_func=MainHandler.IndexView.as_view('index')) app.add_url_rule('/filter', view_func=MainHandler.FilterView.as_view('filter')) """ API Handler """ app.add_url_rule('/api/timetable/hours', view_func=APIHandler.TimetableHours.as_view('api_timetable_hours')) app.add_url_rule('/api/timetable/teachers', view_func=APIHandler.TimetableTeachers.as_view('api_timetable_teachers')) app.add_url_rule('/api/timetable/groups', view_func=APIHandler.TimetableGroups.as_view('api_timetable_groups')) app.add_url_rule('/api/timetable/subjects', view_func=APIHandler.TimetableSubjects.as_view('api_timetable_subjects')) app.add_url_rule('/api/timetable/classrooms', view_func=APIHandler.TimetableClassrooms.as_view('api_timetable_classrooms')) app.add_url_rule('/api/timetable/weekdays', view_func=APIHandler.TimetableWeekDays.as_view('api_timetable_weekdays')) <file_sep>/finder/models/optivum_scraper.py """ Forked from not7cd Compatible with VULCAN using <div> and <p> instead of <ul> and <li> in lista.html """ import json import requests from bs4 import BeautifulSoup as bs from time import sleep import random import re from finder import app, logger class OptivumScraper: def __init__(self, base_url): logger.info("Updating timetable") self.s = requests.Session() self.base_url = base_url new_timetable = self.get_timetable() if len(new_timetable) > 0: app.timetable = new_timetable with open('timetable.json', 'w', encoding="utf-8") as file: json.dump(new_timetable, file, ensure_ascii=False) logger.info("Timetable updated") def get_soup(self, url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/64.0.3282.168 ' 'Safari/537.36 ' 'OPR/51.0.2830.40' } sleep(random.uniform(0, 0.2)) logger.debug("Getting:\t{}".format(url)) response = self.s.get(url, headers=headers) response.encoding = "utf-8" return bs(response.text, 'html.parser') def parse_sitemap(self, sitemap): return ( { link['href'].replace("plany/", ""): link.string for link in div.find_all('a') } for div in sitemap.find_all(("div", {"class": ["blk", "nblk"]})) ) def get_sitemap_date(self, first_classroom): td_right = self.get_soup("{}plany/{}".format(self.base_url, first_classroom)).findAll("td", {"align" : "right"}) for td in td_right: text = td.get_text().strip() if "wygenerowano" in text: return re.search("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d", text).group() return "01.01.1900" def get_lessons_from_table(self, table, classroom): rows = table.find_all('tr') classroom_lessons = [] for row in rows[1:]: hours = row.find(class_='g').get_text().strip().replace(" ", "") for weekday, cell in enumerate(row.find_all(class_='l')): teacher = cell.find_all('a', class_='n') # naucyciel if len(teacher) > 0: teacher = self.teachers[teacher[0]['href']] else: teacher = None subject = cell.find_all('span', class_='p') # przedmiot if len(subject) > 0: subject = subject[0].string else: subject = None groups = [] if cell.find_all('a', class_='o') is not None: groups = [group.string for group in cell.find_all('a', class_='o')] # oddział lesson_dict = { "day": weekday+1, "hour": hours, "teacher": teacher, "group": groups, "subject": subject, "classroom": classroom } if teacher is not None or len(groups) > 0 or subject is not None: classroom_lessons.append(lesson_dict) return classroom_lessons def get_lessons(self, objects): lessons = [] for key, val in objects.items(): table = self.get_soup("{}plany/{}".format(self.base_url, key)).find('table', class_='tabela') classroom_lessons = self.get_lessons_from_table(table, val) if len(classroom_lessons) > 0: lessons = lessons + classroom_lessons else: logger.debug("Empty class:\t{}\t{}".format(key, val)) return lessons def get_timetable(self): sitemap = self.get_soup(self.base_url + 'lista.html') units, self.teachers, classrooms = self.parse_sitemap(sitemap) date_valid = self.get_sitemap_date(list(classrooms.keys())[0]) return {'valid_from': date_valid, 'lessons': self.get_lessons(classrooms)} <file_sep>/finder/__init__.py from flask import Flask import time import hashlib import logging import json import os.path logger = logging.getLogger('werkzeug') logger.setLevel(logging.DEBUG) fh = logging.FileHandler('finder-access.log', mode='w') fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) sh = logging.StreamHandler() sh.setFormatter(formatter) sh.setLevel(logging.DEBUG) logger.addHandler(fh) logger.addHandler(sh) application = app = Flask('finder') app.config['SECRET_KEY'] = str(hashlib.sha256(str(time.time()).encode('utf-8')).hexdigest()) app.timetable = {} if os.path.isfile("timetable.json"): with open("timetable.json", encoding="utf-8") as f: app.timetable = json.load(f) import finder.models import finder.controller <file_sep>/README.md # Free time finder for mech.pk.edu.pl ### How to run: `python3 runserver.py` ### Used dependencies: ``` flask jinja2 mongoquery six APScheduler requests BeautifulSoup4 ```<file_sep>/finder/controller/BaseHandler.py from flask.views import MethodView from flask import render_template, redirect class BaseView(MethodView): def get(self, *args, **kwargs): return self.redirect("/") def post(self, *args, **kwargs): return self.redirect("/") @staticmethod def render(tpl, **render_data): return render_template(tpl, **render_data) @staticmethod def redirect(target): return redirect(target) <file_sep>/finder/controller/MainHandler.py from flask import request from .BaseHandler import BaseView from finder.models.TimetableFinder import TimetableFinder from finder.models.TimetableFinder import TimetableParser from finder.models.TimetableData import TimetableData import re class IndexView(BaseView): def get(self, *args, **kwargs): return BaseView.render('index.html') class FilterView(BaseView): def get(self, *args, **kwargs): if "filter" in request.args: if request.args['filter'] is not None: filter = request.args['filter'] selected_keywords = re.findall('"(.*?)"', filter) for x in range(len(selected_keywords)): if (selected_keywords[x] == "teacher" or selected_keywords[x] == "classroom" or selected_keywords[x] == "subject"): filter = filter.replace('"'+selected_keywords[x+1]+'"', '{"$regex": "/'+ selected_keywords[x+1] +'/"}') finder = TimetableFinder(json_query=filter) timetable_data = TimetableData() taken_time = finder.find_taken_time() timetable_parser = TimetableParser(taken_time) timetable_by_weeks = timetable_parser.timetable_by_weeks() return BaseView.render('week_view.html', taken_time=finder.find_taken_time(), hours=timetable_data.get_hours(), days=timetable_data.get_week_days(), timetable_by_weeks=timetable_by_weeks ) return BaseView.redirect("/")
ec0820287736eee99453f75003f151ddacd7e21b
[ "Markdown", "Python", "HTML" ]
12
Python
Davasny/mech_pk_free_time_finder
2ec4c278552b04b1535d52e0a222e5c4f7bd5324
e45013641848e8abcff3dcbf909a3f5e6b47febb
refs/heads/main
<file_sep>// Pizzeria Webbutveckling var i = 0; // start ställe var images = []; var time = 3000; //Image list images[0] = 'pizza3.jpg'; images[1] = 'pizza4.jpg'; images[2] = 'pizza5.jpg'; //Change Image function changeImg() { document.slide.src = images[i]; if (i < images.length - 1) { i++; } else { i = 0; } setTimeout("changeImg()", time); } window.onload = changeImg; /* var slideIndex = 1; showSlides(slideIndex); // Nästa/tidigare kontroller function plusSlides(n) { showSlides(slideIndex += n); } // Thumbnail bild kontroll function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n > slides.length) slideIndex = 1 } if (n < 1) { slideIndex = slides.length } for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex - 1].style.display = "block"; dots[slideIndex - 1].className += " active"; var slideIndex = 0; showSlides(); function showSlides() { var i; var slides = document.getElementsByClassName("mySlides"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slideIndex++; if (slideIndex > slides.length) { slideIndex = 1 } slides[slideIndex - 1].style.display = "block"; setTimeout(showSlides, 2000); // Change image every 2 seconds */
930089f46ebbee592175528414d7db3dc4c8f3a4
[ "JavaScript" ]
1
JavaScript
Carl-Brick/pizzeriawebbutveckling
bd6022b8a975271ef76a884b16998d31730b4fb2
220f1983d2a901066c3a916a303746d1aa46f171
refs/heads/master
<file_sep># Download densenet model import torch model = torch.hub.load('pytorch/vision:v0.6.0', 'densenet121', pretrained=True) model.eval()<file_sep># (2020 Fall) CS532 - Project 2 ## Contents **Source code** - server.py: backend server code - download_densenet.py: script for downloading Densenet-121 - imagenet_class_index.json: json file for mapping index to animal class **Config files** - config.json: server config file - Dockerfile: file for building Docker image **Script** - run.sh **Test files** - data/: please upload your custom test images under this folder **Documentation** - Design Report.pdf - README.md ---- ## Setup instructions Please make sure that below 3 variables in `run.sh` are properly set: - **IMG_NAME**: the name of the Docker image. By default, it is "cs532_project2:v1" - **CMD**: the path of Docker command. By default, it is "docker.exe" since my OS environment is Windows. You might need to change it to "docker" under Linux. - **SERVER_ADDR**: the URL of the backend server (default: http://localhost:5000). Make sure that this address and port number are available and the same as the values in `config.json`. In addition, if you are using "Docker Toolbox for Windows" for running docker service, you might need to set port forwarding rules on the default Docker virtual machine. Please follow the instructions in section **4. Running the program** of `Design Report.pdf` The `run.sh` script contains 3 parts: 1. Building a Docker image according to `Dockerfile` 2. Initiating a Docker container based on the previously built Docker image. 3. Sending test requests by looping over all images under folder `data/`. If you want to use your custom pictures for test, please upload them under this folder. You should be able to run the whole program by executing `./run.sh` command. If you want to skip some steps, simply comment out the corresponding lines. You can also download built Docker image of this project by executing: `docker pull tizzybird/cs532_project2:v1`. (Notice that the backend server URL in this image is http://localhost:5000)<file_sep>FROM python:3.7.9-buster COPY config.json / COPY imagenet_class_index.json / COPY server.py / COPY download_densenet.py / RUN pip install flask RUN pip install torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html RUN python download_densenet.py<file_sep>#!/bin/bash # 1. build docker image IMG_NAME="cs532_project2:v1" CMD=docker.exe SERVER_ADDR=http://localhost:5000/ echo "==================================================================" echo "================== 1. Building Docker Image ======================" echo "==================================================================" $CMD build -t $IMG_NAME . --no-cache # 2. initialize server container echo "==================================================================" echo "=============== 2. Initializing Server Container =================" echo "==================================================================" $CMD run --net=host -itd $IMG_NAME python server.py # 3. test echo "==================================================================" echo "=========================== 3. Test ==============================" echo "==================================================================" echo "Sleep 5 seconds before server is ready..." sleep 5 for filename in data/*; do echo "Sending $filename to $SERVER_ADDR" curl -i -X POST -F "image=@$filename" $SERVER_ADDR echo "==================================================================" done<file_sep>import torch import torchvision.transforms as transforms from flask import Flask, request, jsonify from PIL import Image import json, io with open('config.json') as f: CONFIG = json.load(f) # Used for mapping prediction to a corresponding class imagenet_class_index = json.load(open('imagenet_class_index.json')) model = torch.hub.load('pytorch/vision:v0.6.0', 'densenet121', pretrained=True) model.eval() app = Flask(__name__) # Function for classifying the input image # returns a class id and a name of animal def predict(image_bytes): image = Image.open(io.BytesIO(image_bytes)) transform_func = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) tensor = transform_func(image).unsqueeze(0) outputs = model.forward(tensor) _, y_hat = outputs.max(1) predicted_idx = str(y_hat.item()) return imagenet_class_index[predicted_idx] # Function for receiving HTTP requests # if receiving a GET request, it returns 'no input image' message # if receiving a POST request with an image appended in the 'image' field, # it returns a class_id and a class_name including the name of the animal # in the image @app.route('/', methods=['POST', 'GET']) def classify(): print('Request is received!') res = {'message': 'no input image'} if request.method == 'POST': image = request.files['image'] raw_image = image.read() class_id, class_name = predict(image_bytes=raw_image) res = {'class_id': class_id, 'class_name': class_name} return jsonify(res) if __name__ == '__main__': app.run(host=CONFIG['addr'], port=CONFIG['port'])
9fd8e5459725c7e7557a77ab13b6bba0b4e043ce
[ "Markdown", "Python", "Dockerfile", "Shell" ]
5
Python
tizzybird/CS532-Project2
f1ea0246904362dcb1f082fadc5a05616ef1f750
b04ebfdcb8262add851751fad365bac3c4c76474
refs/heads/master
<file_sep>class EmailsController < ApplicationController before_filter :authorize def index @user = current_user if current_user @emails = @user.emails @coworker = Coworker.first end def new #commented out stuff until I add sessions # @user = current_user @email = Email.new @user = User.find(current_user) # @projects = @user.projects.where(completed: false) @projects = Project.where(completed: false) end def create p params @email = Email.new(email_params) @recipient = Coworker.find_by(email: @email.addressee_email) @email.recipient_id = @recipient.id if @recipient @email.sender_id = current_user.id @user = User.find(@email.sender_id) @major_projects = @email.major_projects.split(",").map{|project| project.strip} @open_projects = @email.open_projects.split(",").map{|project| project.strip} if @email.save BossMailer.beginning_week_email(@email, @major_projects, @open_projects, @user).deliver_now redirect_to :action => :index else render 'new' end end private def email_params params.require(:email).permit(:addressee_name, :addressee_email, :subject_line_beginning_week, :sender_id, :recipient_id, :major_projects, :open_projects) end end<file_sep>class CoworkersController < ApplicationController before_filter :authorize def new @coworker = Coworker.new end def create @coworker = Coworker.new(coworker_params) current_user.coworkers << @coworker if @coworker.save redirect_to root_path else render 'new' end end def update end private def coworker_params params.require(:coworker).permit(:first_name, :email) end end<file_sep>class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :name t.string :status t.string :priority t.integer :user_id t.boolean :completed, default: false t.date :due_date, default: nil end end end <file_sep>class Coworker < ActiveRecord::Base has_many :emails, foreign_key: :recipient_id belongs_to :user end<file_sep>class User < ActiveRecord::Base has_many :emails, foreign_key: :sender_id has_many :coworkers has_many :projects has_secure_password end<file_sep>// EmailWidget = function(body, addressee_name){ // this.body = body; // this.addressee_name = addressee_name // } // EmailWidget.prototype.fillAddresseeNameOutput = function(input){ // this.addressee_name = input; // } // EmailWidget.prototype.fillAddresseeEmailOutput = function(input){ // this.addressee_email = input; // } // EmailWidget.prototype.fillAddresseeNameOutput = function(input){ // this.addressee_name = input; // } // function NewEmailWidgetView(element, model){ // this.element = element.; // this.model = model; // element.on("keyup", this.onBodyChange.bind(this)); // } // NewEmailWidgetView.prototype.onBodyChange = function(){ // var emailInput = $("#email").val(); // var nameInput = $("#name").val(); // this.model.fillAddresseeNameOutput(emailInput); // this.model.fillAddresseeEmailOutput(nameInput); // } function bossNameKeyPress() { var bossName = document.getElementById("boss-name"); var output = bossName.value; var bossNameOutput = document.getElementById("boss-name-output"); bossNameOutput.innerText = "Hi "+output+","; //var s = $("#edValue").val(); //$("#lblValue").text(s); } function bossEmailKeyPress() { var bossEmail = document.getElementById("boss-email"); var output = bossEmail.value; var bossEmailOutput = document.getElementById("boss-email-output"); bossEmailOutput.innerText = "(To: "+output+")"; //var s = $("#edValue").val(); //$("#lblValue").text(s); } function subjectLineKeyPress() { var subjectLine = document.getElementById("subject-line"); var output = subjectLine.value; var subjectLineOutput = document.getElementById("subject-line-output"); subjectLineOutput.innerText = "(Subject line: "+output+")"; //var s = $("#edValue").val(); //$("#lblValue").text(s); } MarkdownWidget = function(body){ this.body = body; } MarkdownWidget.prototype.fillOutput = function(input){ this.body = input } MarkdownWidget.prototype.checkStyle = function(input){ if (input.match(/[,]$/)){ return "<li>".concat(input.slice(0,-1)).concat("</li><br>"); // $(this).checkStyle(); } return input } function NewMarkdownWidgetView(element, model){ this.element = element; this.model = model; //should do this for distinct words element.on("keyup", this.onBodyChange.bind(this)); // element.checkIfWord//if keycode == space } NewMarkdownWidgetView.prototype.onBodyChange = function(){ console.log(this) var input = [] var inputArray = $(this.element).val().split(" "); inputArray.forEach(function(word){ input.push(this.model.checkStyle(word)); }.bind(this)); var output = input.join(" ") this.model.fillOutput(output) var currentModel = this.element if (currentModel.selector === "#text"){ $("#output").html(this.model.body) }else if (currentModel.selector === "#text2"){ $("#output2").html(this.model.body) } } $(document).on("ready", function(){ var widget = new MarkdownWidget("") var view = new NewMarkdownWidgetView($("#text"), widget) var widget2 = new MarkdownWidget("") var view2 = new NewMarkdownWidgetView($("#text2"), widget2) })<file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user def sat_through_wed Time.now.saturday? || Time.now.sunday? || Time.now.monday? || Time.now.tuesday? || Time.now.wednesday? end helper_method :sat_through_wed def thurs_through_sat Time.now.thursday? || Time.now.friday? || Time.now.saturday? end helper_method :thurs_through_sat def authorize redirect_to '/login' unless current_user end end <file_sep>class CreateEmails < ActiveRecord::Migration def change create_table :emails do |t| t.integer :sender_id t.integer :recipient_id t.string :subject_line_beginning_week t.string :subject_line_end_week t.string :addressee_name t.string :addressee_email t.string :major_projects t.string :open_projects t.timestamps end end end <file_sep>class ProjectsController < ApplicationController before_filter :authorize end<file_sep># Translucent ##A tool to be a better employee After reading [an article](https://www.linkedin.com/pulse/20140613164212-9522584-how-to-go-from-working-60-hours-a-week-to-40-by-sending-2-emails-a-week) on how a couple simple emails to one's boss could result in working fewer hours per week, I decided to implement the idea in a basic app. ##Functionality Built on Ruby/Rails with substantial use of javascript as well. Users input their boss's email and the tasks they plan to complete in the upcoming week; the app provides a template that creates a live-updating email template via javascript. The user can then actually send the email to his/her boss.<file_sep>class Project < ActiveRecord::Base has_many :emails, through: :users belongs_to :user end<file_sep>class Email < ActiveRecord::Base belongs_to :recipient, class_name: "Coworker" belongs_to :sender, class_name: "User" end<file_sep>class BossMailer < ApplicationMailer default from: "<EMAIL>" def beginning_week_email(email, major_projects, open_projects, user) @email = email @major_projects = major_projects @open_projects = open_projects @user = user mail(to: @email.addressee_email, subject: @email.subject_line_beginning_week, :cc => @user.email) end def end_week_email end end <file_sep>class CreateCoworkers < ActiveRecord::Migration def change create_table :coworkers do |t| t.string :first_name t.string :email t.string :coworker_type t.integer :user_id end end end
fd9588b52001e0ef97e12916f129df48d379b7d7
[ "JavaScript", "Ruby", "Markdown" ]
14
Ruby
cstavitsky/translucent-app
9c3625ed733f2cf5a712f2e066b1d0cf836d5a8f
e9698b80eb426ecc950f21cc8b19de0b4437aeb7
refs/heads/master
<repo_name>ck2e14/programming-univbasics-4-intro-to-hashes-lab-london-web-080519<file_sep>/intro_to_ruby_hashes_lab.rb def new_hash new_hash = { } end def my_hash my_hash = {:Arsenal => "Koscielny"} end def pioneer pioneer_hash = {:name => "<NAME>"} end def id_generator this_next_hash = {:id => 1} end def my_hash_creator(key, value) yet_another_lab_hash = {key => value} end #here you dont need : because it knows it is creating the key, you just refer it back to the paramter 'key' defined #in the method signature. Likewise => value doesn't need to be encolosed in quotation marks. def read_from_hash(hash, key) hash[key] end #Similarly no : needed in this lookup method unlike if you were writing the command outside of a method (function) #where it might look like hash[:key] def update_counting_hash(hash, key) if hash[key] hash[key] += 1 else hash[key] = 1 end return hash end #dont forget to return this hash otherwise Ruby treats the last line as the return value, which was failing the tests
84f30b6cf33c5ae16561c6fea81a1d8f9b6408a2
[ "Ruby" ]
1
Ruby
ck2e14/programming-univbasics-4-intro-to-hashes-lab-london-web-080519
97eb2f1fd0ebb3090c4d5e70aff26d31a93f389a
e268839880d035c5595d5d07be052c48bdad9c90
refs/heads/master
<repo_name>sharathgeorgem/react-redux-clone<file_sep>/DOM.js // Get an element by ID const domRoot = document.getElementById('root') // Create a new element by a tag name const domInput = document.createElement('input') // Set properties domInput['type'] = 'text' domInput['value'] = '<NAME>' domInput['className'] = 'my-class' // Listen to events domInput.addEventListener('change', e => { console.log(e.target.value) }) // Create a text node const domText = document.createTextNode('') domText['nodeValue'] = 'Foo' domRoot.appendChild(domInput) domRoot.appendChild(domText) <file_sep>/README.md # react-redux-clone An austere React - Redux clone.
fefcb75c54772bbe795685a5067e65525e74edfd
[ "JavaScript", "Markdown" ]
2
JavaScript
sharathgeorgem/react-redux-clone
48fa1cd028be3653860439eb05482420b27dfc8d
4d6dfbc70a064b8293939af80603958a0adb0470
refs/heads/master
<file_sep>const Eris = require("eris"); // botのトークンID var bot = new Eris("*******************************"); bot.on("ready", () => { // bot が準備できたら呼び出されるイベントです。 console.log("Ready!"); }); bot.on("voiceChannelJoin", (member, newChannel) => { // 入室処理 let ch = newChannel.guild.defaultChannel; console.log("%s が チャンネル %s に入室しました。", member.username, newChannel.name); bot.createMessage('510283280369582080', member.username + "が チャンネル[" + newChannel.name + "] に入室しました"); }); bot.on("voiceChannelLeave", (member, oldChannel) => { // 退室処理 let ch = oldChannel.guild.defaultChannel; console.log("%s が チャンネル %s を退室しました。", member.username, oldChannel.name); bot.createMessage('510283280369582080', member.username + "が チャンネル[" + oldChannel.name + "] を退室しました。"); }); // Discord に接続します。 bot.connect(); <file_sep># Discord.jsとErisを使った入退室通知BOT
3ad556f697a33e3b0ea6dca71c8755d60d122098
[ "JavaScript", "Markdown" ]
2
JavaScript
keichiro/DiscordBot
b97c57c71fff712e98cc27f0905b9b595cdb690b
747550fc78496f11351ef8fb275606b42a1352f5
refs/heads/main
<file_sep>using HopestoneApp.Data; using HopestoneApp.Models; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace HopestoneApp.Controllers { public class ProductController : Controller { private readonly AppDbContext _appDb; public ProductController(AppDbContext db) { _appDb = db; } public IActionResult Index() { IEnumerable<Product> objList = _appDb.Products; return View(objList); } //Get-Create public IActionResult Create() { return View(); } //Post-Create [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Product obj) { if (ModelState.IsValid) { _appDb.Products.Add(obj); _appDb.SaveChanges(); return RedirectToAction("Index"); } else { return View(obj); } } //Get-Update public IActionResult Update(int? id) { if (id == null || id == 0) { return NotFound(); } var obj = _appDb.Products.Find(id); if (obj == null) { return NotFound(); } else { return View(obj); } } //Post-Update [HttpPost] [ValidateAntiForgeryToken] public IActionResult Update(Product obj) { _appDb.Products.Update(obj); _appDb.SaveChanges(); return RedirectToAction("Index"); } //Get-Delete public IActionResult Delete(int? id) { if (id == null || id == 0) { return NotFound(); } var obj = _appDb.Products.Find(id); if (obj == null) { return NotFound(); } else { return View(obj); } } } }<file_sep>using HopestoneApp.Data; using HopestoneApp.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Diagnostics; namespace HopestoneApp.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly AppDbContext _appDb; public HomeController(ILogger<HomeController> logger, AppDbContext db) { _logger = logger; _appDb = db; } public IActionResult Index() { IEnumerable<Product> objList = _appDb.Products; return View(objList); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }<file_sep>using HopestoneApp.Models; using Microsoft.EntityFrameworkCore; namespace HopestoneApp.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Id); entity.Property(e => e.Title).HasMaxLength(150); entity.Property(e => e.Icon).HasMaxLength(150); entity.Property(e => e.Image).HasMaxLength(150); entity.Property(e => e.Description).HasMaxLength(250); entity.Property(e => e.Created); entity.Property(e => e.Updated); entity.Property(e => e.IsActive); }); } } }<file_sep>//Bootstrap Validation (function () { 'use strict' // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.querySelectorAll('.needs-validation') // Loop over them and prevent submission Array.prototype.slice.call(forms) .forEach(function (form) { form.addEventListener('submit', function (event) { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() //Bootstrap Tooltip var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')) var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl) }) //Main function showOverlay(id) { var serviceOverlay = document.getElementById("serviceBoxOverlay_" + id); if (serviceOverlay.classList.contains("show-serviceOverlay")) { serviceOverlay.classList.remove("show-serviceOverlay"); } else if (serviceOverlay.classList.contains("hide-serviceOverlay")) { serviceOverlay.classList.add("show-serviceOverlay"); serviceOverlay.classList.remove("hide-serviceOverlay"); } else { serviceOverlay.classList.add("show-serviceOverlay"); } } function hideOverlay(id) { var serviceOverlay = document.getElementById("serviceBoxOverlay_" + id); if (serviceOverlay.classList.contains("show-serviceOverlay")) { serviceOverlay.classList.remove("show-serviceOverlay"); serviceOverlay.classList.add("hide-serviceOverlay") } else { serviceOverlay.classList.add("hide-serviceOverlay"); } } function getServiceTitle(id) { var title = document.getElementById("service_" + id).innerHTML; document.getElementById("serviceForm_Modal").innerHTML = title; } function hideServiceTable() { var prodContainer = document.getElementById("productFormContainer"); var tableContainer = document.getElementById("tableContainer"); prodContainer.style.overflowY = "hidden"; tableContainer.classList.add("hide-table"); }<file_sep>using System; using System.ComponentModel.DataAnnotations; namespace HopestoneApp.Models { public class Product { [Key] public int Id { get; set; } [Required] public string Title { get; set; } [Required] public string Icon { get; set; } [Required] public string Image { get; set; } [Required] public string Description { get; set; } [Required] public DateTime Created { get; set; } [Required] public DateTime Updated { get; set; } [Display(Name = "Item Status")] [Required] public bool IsActive { get; set; } } }
02b5fb25d209e0351110370d564450f2e40cf17c
[ "JavaScript", "C#" ]
5
C#
onceacurious/HopestoneApp
378e9c1a247e1f8ea7dda75c877491e5dcc84c63
9eb8fddea28fe699987df396a7ba29c150724748
refs/heads/master
<repo_name>dpayonk/deployinator<file_sep>/stacks/xsellytics.rb module Deployinator module Stacks module Xsellytics def xsellytics_environments [ { :name => "qa", :method => deploy, :current_version => 'hi', :current_build => 'current_qa_build', :next_build => 'next_qa_build' }, { :name => "production", :method => "prod_rsync", :current_version => xsellytics_production_version, :current_build => 'current_prod_build', :next_build => 'next_prod_build' } ] end def deploy "HI" end def xsellytics_production_version # %x{curl http://my-app.com/version.txt} "cf44aab-20110729-230910-UTC" end def xsellytics_head_build # the build version you're about to push # %x{git ls-remote #{your_git_repo_url} HEAD | cut -c1-7}.chomp "11666e3" end def xsellytics_production(options={}) log_and_stream "Fill in the xsellytics_production method in stacks/xsellytics.rb!<br>" # log the deploy log_and_shout :old_build => environments[0][:current_build].call, :build => environments[0][:next_build].call end end end end
a161aad1c44ed84feb6154c755e0cb030bf8cb4e
[ "Ruby" ]
1
Ruby
dpayonk/deployinator
023440c83310676543f485fa48b9e853171b8d09
be51e779c23082ce363ce864950a190257ce0a07
refs/heads/master
<repo_name>siddmegadeth/facebook4-mongo<file_sep>/www/services/facebook-auth.js // Authenticate For Cordov ased FB Login Only. //There is a Web Based Login Also For Other Device app.provider('facebookAuth', [function() { var uri; return { config: function(options) { uri = options; log(uri); }, $get: ['$http', function($http) { return { login: function(accessToken, cb) { warn("Access Token :"); log(accessToken); $http({ method: 'POST', url: '/facebook/auth', params: { accessToken: accessToken } }).then(function(resp) { cb(resp); }); } } }] } }])<file_sep>/platforms/android/app/src/main/assets/www/services/nexmo-services.js app.provider('nexmo', [function() { var nexmoConfig; var nexmoState; return { config: function(config) { nexmoConfig = config; }, $get: ['$http', '$rootScope', function($http, $rootScope) { return { register: function(mobile, cb, err) { $http({ method: 'POST', url: nexmoConfig.register, params: { number: mobile } }) .then(function(resp) { log(resp.data); if (resp == undefined || resp.data.result == 'Your pre-pay account does not have sufficient credit to process this message') { warn("Nexmo Account balance has no credit left"); err(resp); } else if (resp.data.status == 10 || resp.data.status == 0) { var tuple = {}; tuple.requestId = resp.data.request_id; tuple.message = resp.data.error_text; tuple.status = parseInt(resp.data.status); cb(tuple); } }) }, validate: function(pin, mobile, cb, err) { var requestId = this.getRequestID(); if (requestId) { $http({ method: 'POST', url: nexmoConfig.validate, params: { requestId: requestId, pin: pin, mobile: mobile } }) .then(function(resp) { log(resp); cb(resp); }) } else { err({ message: "Request ID Is Empty.Cannot Validate OTP" }); } }, cancel: function(cb, err) { warn("Cancelling Previous Request"); var requestId = this.getRequestID(); log("RequestID :" + requestId); if (requestId) { $http({ method: 'POST', url: nexmoConfig.cancel, params: { requestId: requestId } }) .then(function(resp) { warn("Response From Cancel From Nexmo :"); log(resp); myToast.show(); $rootScope.toastMessage = resp.message; cb(resp); }) } else { err({ message: "Request ID Is Empty.Cannot Validate OTP" }); } }, getRequestID: function() { return window.localStorage.requestId; }, setRequestID: function(id) { requestId = id; window.localStorage.setItem("requestId", requestId); }, saveNexmoState: function(state) { localStorage.setItem("nexmoState", JSON.stringify(state)); }, getNexmoState: function() { return JSON.parse(localStorage.getItem("nexmoState")); } } }] } }]);<file_sep>/platforms/android/app/src/main/assets/www/services/http-interceptors.js app.service('httpInterceptors', ['$timeout', '$rootScope', function($timeout, $rootScope) { return { request: function(config) { log(config); warn("Request Received : " + Date()); return config; }, response: function(config) { log(config); warn("Response Received : " + Date()); if (config.status == 200) { myToast.show(); $timeout(function() { $rootScope.toastMessage = config.data.result || config.data.message; }, 1); } return config; }, requestError: function(config) { log(config); warn("Request Error : " + Date()); return config; }, responseError: function(config) { log(config); warn("Response Error : " + Date()); // if (config.status == 404) { // myToast.show(); // $timeout(function() { // $rootScope.toastMessage = config.data.result || config.data.message; // }, 1); // } else if (config.status == 401) { // myToast.show(); // $timeout(function() { // $rootScope.toastMessage = config.data.result || config.data.message; // }, 1); // } else if (config.status == 501) { // myToast.show(); // $timeout(function() { // $rootScope.toastMessage = "Servers Not Available"; // }, 1); // } else if (config.status == 500) { // myToast.show(); // $timeout(function() { // $rootScope.toastMessage = "Servers Not Available.Internal Error"; // }, 1); // } if (config.status == 500) { myToast.show(); $timeout(function() { $rootScope.toastMessage = "Servers Not Available.Internal Error"; }, 1); } return config; } } }]);<file_sep>/platforms/android/app/src/main/assets/www/services/geo-location-services.js app.service('geoLocationServices', [function() { var watchId; return { getCurrentPosition: function(options, onSuccess, onError) { navigator.geolocation.getCurrentPosition(onSuccess, onError, options); }, getUpdatedPosition: function(success, error) { log("Position Changed"); watchId = navigator.geolocation.watchPosition(success, error); }, stopGeoWatch: function() { navigator.geolocation.clearWatch(watchId); } } }])<file_sep>/platforms/android/app/src/main/assets/www/components/landing/landingCtrl.js app.controller('landingCtrl', ['$scope', '$rootScope', '$timeout', 'restServices', 'geoLocationServices', 'socket', '$http', 'userStateManager', function($scope, $rootScope, $timeout, restServices, geoLocationServices, socket, $http, userStateManager) { $scope.screenLoader = true; $scope.initiateSocketConnection = function() { $timeout(function() { var tempState = $scope.userProfileState(); log(tempState); var state = { mobile: tempState.mobile, fullName: tempState.fullName }; socket.emit("user:initialize", state); }, 1); }; $scope.calculateDistance = function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180 var radlat2 = Math.PI * lat2 / 180 var radlon1 = Math.PI * lon1 / 180 var radlon2 = Math.PI * lon2 / 180 var theta = lon1 - lon2 var radtheta = Math.PI * theta / 180 var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); dist = Math.acos(dist) dist = dist * 180 / Math.PI dist = dist * 60 * 1.1515 if (unit == "K") { dist = dist * 1.609344 } if (unit == "N") { dist = dist * 0.8684 } return dist } $scope.pageRefresh = function($done) { $scope.screenLoader = false; $scope.showIfUserFound = false; $timeout(function() { $scope.initializeGeoLocation(); $timeout(function() { $scope.screenLoader = true; $scope.showIfUserFound = true; $scope.showIfUserFoundMessage = "Refreshing.Trying Your Luck Again"; }) $done(); }.bind(this), 1000); }.bind(this); $scope.openChatWindow = function(userCurrentChat) { log(userCurrentChat); $scope.myNavigator.pushPage('chat-window.html', { animation: 'push' }).then(function(err) { localStorage.setItem("currentChat", JSON.stringify(userCurrentChat)); // $scope.map = new mapboxgl.Map(); }); } var geoSuccess = function(position) { warn("Geo Watch Position :"); log(position); //Initialize And Save User Lat/Lng var tempUser = userStateManager.getProfileState(); log(tempUser); var userLocation = {}; userLocation.latitude = position.coords.latitude; userLocation.longitude = position.coords.longitude; userLocation.profile = tempUser.profile; warn("Saving User Location :"); log(userLocation); //Get User Preference For Search Criteria var userPreference = {}; userPreference.preferAge = tempUser.preferAge; userPreference.preferDistance = tempUser.preferDistance; userPreference.preferGender = tempUser.preferGender; userPreference.gender = tempUser.gender; //intiate geoWatch // initMap(position); // geoLocationServices.getUpdatedPosition(geoWatch, geoError); $timeout(function() { restServices.saveUserLocation(userLocation, userPreference, function(resp) { $timeout(function() { warn("Retrievd Preferred Users NearBy Position And Updating Current Location :"); log(resp); if (resp.data.data) { $scope.screenLoader = false; $scope.preferredUser = resp.data.data; $scope.showIfUserFound = false; } else { myToast.show(); $timeout(function() { $scope.screenLoader = true; $scope.showIfUserFound = true; $scope.showIfUserFoundMessage = "There Are No People Around. Hard Luck. Try Again Later."; $rootScope.toastMessage = resp.data.message; }); } }); }); }); }; $scope.userProfileState = function() { //get ProfileState var profileState = JSON.parse(localStorage.profileState); return profileState; } var getPermission = function(type) { myToast.show(); $timeout(function() { $rootScope.toastMessage = type; }); $scope.ons.notification.confirm({ message: 'Enable GeoLocation Services' }) .then(function(resolve) { log("Running GeoLocation Services :"); log(resolve); if (resolve == 1) $scope.initializeGeoLocation(); else { $timeout(function() { $scope.showIfUserFound = true; $scope.showIfUserFoundMessage = "Geo Services Offline.Enable Geo Services To Continue"; }) } }); } var geoError = function(error) { // Call Cordova Based Servicies Here Incase Failure Happens //and then save lat/lng data switch (error.code) { case error.PERMISSION_DENIED: { errorMessage = "PERMISSION_DENIED" getPermission(errorMessage); break; } case error.POSITION_UNAVAILABLE: { errorMessage = "POSITION_UNAVAILABLE" getPermission(errorMessage); break; } case error.TIMEOUT: { errorMessage = "TIMEOUT" getPermission(errorMessage); break; } case error.UNKNOWN_ERROR: { errorMessage = "UNKNOWN_ERROR" getPermission(errorMessage); break; } default: { log(error); } } }; $scope.initializeGeoLocation = function() { warn("initializeGeoLocation Running"); geoLocationServices.getCurrentPosition({ highAccuracy: true, timeout: 15000 }, geoSuccess, geoError) } $timeout(function() { $scope.initiateSocketConnection(); $scope.initializeGeoLocation(); //Check if GeoLocation Is Enabled Or Not }); // mapBoxServices.addControls($scope.glControls); } ]);<file_sep>/platforms/browser/www/init.js "use strict"; var DI = [ "cordova.background", "cordova.notification", "cordova.localstorage", "cordova.diagnostics", "cordova.backgroundGeolocation", "onsen", "satellizer" ]; // mapboxgl.accessToken = '<KEY>'; var win = new winDevice("myApp", DI); //Bootstrap Cordova Or Browser Based App .no ng-app Required var app = win.device(); // init App win.enable(true); win.info(); ons.platform.select('android'); ons.ready(function() { log("Ready"); document.addEventListener("backbutton", function(e) { e.preventDefault(); }, false); }); app.config([ '$httpProvider', '$authProvider', function( $httpProvider, $authProvider) { $httpProvider.interceptors.push('httpInterceptors'); }]); app.run(['$rootScope', '$location', function($rootScope, $location) { // L.mapbox.accessToken = '<KEY>'; //mapboxgl.accessToken = "<KEY>";; // log(mapboxgl.accessToken); }]); // $ cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="283734742253744" --variable APP_NAME="facebook.com.app" // FB // 313314972731334 // 58aa27529273e13aa525cf68a0cd9b4d // $ cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="313314972731334" --variable APP_NAME="irover" <file_sep>/www/cordova-api/cordova-angular-diagnostics/cordova-angular-diagnostics.js "use strict"; (function() { var diag = angular.module("cordova.diagnostics", []); diag.provider('diagnostics', [function() { return { init: function() { }, $get: [function() { return { isLocationAuthorized: function(successCallback, errorCallback) { if (window.cordova) { cordova.plugins.diagnostic.isLocationAuthorized(function(resp) { successCallback(resp); }, function(err) { errorCallback(err); }); } else { warn("Diagnostics Cannot Run In Simulated Browser"); successCallback(false); } }, requestLocationAuthorization: function(successCallback, errorCallback) { cordova.plugins.diagnostic.requestLocationAuthorization(successCallback, errorCallback); }, isNetworkLocationEnabled: function(successCallback, errorCallback) { cordova.plugins.diagnostic.isNetworkLocationEnabled(successCallback, errorCallback); }, locationAccuracy: function(successCallback, errorCallback) { cordova.plugins.locationAccuracy.request(successCallback, errorCallback, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY) }, isLocationEnabled: function(successCallback, errorCallback) { if (window.cordova) cordova.plugins.diagnostic.isLocationEnabled(function(resp) { successCallback(resp); }, function(err) { errorCallback(err); }); else { warn("Diagnostics Cannot Run In Simulated Browser"); successCallback(false); } }, isLocationAvailable: function(successCallback, errorCallback) { if (window.cordova) { log("Codova Defined"); cordova.plugins.diagnostic.isLocationAvailable(successCallback, errorCallback) } else { warn("Diagnostics Cannot Run In Simulated Browser"); successCallback(false); } }, isGpsLocationEnabled: function(successCallback, errorCallback) { cordova.plugins.diagnostic.isGpsLocationEnabled(successCallback, errorCallback); }, isLocationAuthorized: function(successCallback, errorCallback) { if (window.cordova) { cordova.plugins.diagnostic.isLocationAuthorized(function(resp) { successCallback(resp); }, function(err) { errorCallback(err); }); } else { warn("Diagnostics Cannot Run In Simulated Browser"); successCallback(false); } } } }] //GET ENDS } }]); })()<file_sep>/platforms/android/app/src/main/assets/www/cordova-api/cordova-angular-geo-background/cordova-angular-geo-background.js (function() { var bg = angular.module("cordova.backgroundGeolocation", []); var options = { maximumAge: 30000, enableHighAccuracy: true }; bg.service('geoPosition', [function() { return { getCurrentPosition: function(options, cb, onError) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(resp) { warn("GeoLocation Run Once") }, function(error) { switch (error.code) { case error.PERMISSION_DENIED: errorMessage = "PERMISSION_DENIED"; break; case error.POSITION_UNAVAILABLE: errorMessage = "POSITION_UNAVAILABLE"; break; case error.TIMEOUT: errorMessage = "TIMEOUT"; break; case error.UNKNOWN_ERROR: errorMessage = "UNKNOWN_ERROR"; break; } geolocationStatus.type = errorMessage; geolocationStatus.status = false; onError(errorMessage); }, options); } else warn("No Gelocation Detected"); } } }]) })()<file_sep>/www/cordova-api/cordova-angular-camera-multiple/cordova-angular-camera-multiple.js (function() { var file = angular.module("cordova.camera.multiple", []); file.service('cameraMultiple', [function() { if (window.cordova) { var camera = { maximumImagesCount: 4, width: 800, quality: 100 } } else { warn("Running In A Browser. Cordova Camera Cannot Run"); } return { config: function(options) { }, getPicture: function(success, fail) { //get From Camera if (window.cordova) window.imagePicker.getPictures(success, fail); }, selectFromGallery: function(success, fail) { //Get From Album if (window.cordova) { //get From Camera if (window.cordova) window.imagePicker.getPictures(success, fail, camera); } } } }]) })()
e40afed416882939fc6886220b1b50864fdca44b
[ "JavaScript" ]
9
JavaScript
siddmegadeth/facebook4-mongo
69fdb5b96a6685bf697382a11056ad70fd7d4831
8b22dbf0f46cb87edcc4a3f58818511034869dc0
refs/heads/master
<repo_name>plcart/coursera-gameprogramming<file_sep>/week1/programming_assignment1/Scorched_Earth/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Scorched_Earth { class Program { const float G = 9.8F; static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Welcome new player!"); Console.WriteLine("This application will calculate the maximum height"+ "of the shell and the distance it will travel along the ground!"); Console.Write("Please provide the initial angle in degrees:"); // convet the value to float and turn into radiuns float theta = float.Parse(Console.ReadLine()) * 0.0174532925F; Console.Write("Please provide the initial speed:"); float speed = float.Parse(Console.ReadLine()); float vox = speed * (float)Math.Cos(theta); float voy = speed * (float)Math.Sin(theta); float t = voy / G; // time until shell reaches apex float h = voy * voy / (2 * G); // height of shell at apex float dx = vox * 2 * t; // distance shell travels horizontally (assuming launch and target elevations are equal) Console.WriteLine(string.Format("The height of shell at apex is {0:f3}", h)); Console.WriteLine(string.Format("The distance travalled by your shell is {0:f3}", dx)); Console.Read(); } } } <file_sep>/labs/week1/Lab2/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2 { class Program { const int MAX_SCORE = 100; static void Main(string[] args) { int age = 24; Console.WriteLine("My age is {0}", age); int score = 50; float percent = (float)score / MAX_SCORE; Console.WriteLine("Percentage: {0:p}", percent); Console.Read(); } } } <file_sep>/README.md # coursera-gameprogramming Material developed in the Course Beginning Game Programming with C# ofered by University of Colorado on Coursera <file_sep>/labs/week1/Lab1/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1 { class Program { static void Main(string[] args) { Console.WriteLine("My name is Arthur"); Console.WriteLine("My best friend is Livia"); Console.WriteLine("Favorite game 1: Mass Effect 2"); Console.WriteLine("Favorite game 2: Red Dead Redemption"); Console.WriteLine("Favorite game 3: Dark Souls"); Console.Read(); } } } <file_sep>/labs/week1/Lab3/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab3 { class Program { static void Main(string[] args) { Console.Write("Enter temperature (Fahrenheit): "); float originalFahrenheit = float.Parse(Console.ReadLine()); float toCelsius = ((originalFahrenheit - 32) / 9) * 5; float toFahrenheit = toCelsius * 9 / 5 + 32; Console.WriteLine("{0:f2} degrees Fahrenheit is {1:f2} degrees Celsius",originalFahrenheit,toCelsius); Console.WriteLine("{0:f2} degrees Celsius is {1:f2} degrees Fahrenheit", toCelsius, toFahrenheit); Console.Read(); } } } <file_sep>/labs/week2/Lab4/Lab4/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lab4 { /// <summary> /// Demonstrates classes and objects /// </summary> class Program { /// <summary> /// Demonstrates use of Deck and Card objects /// </summary> /// <param name="args">command-line args</param> static void Main(string[] args) { Deck objDesck = new Deck(); objDesck.Print(); objDesck.Shuffle(); objDesck.Print(); Card TopCard = objDesck.TakeTopCard(); Console.WriteLine("{0} of {1}", TopCard.Rank, TopCard.Suit); Console.Read(); } } }
cb073103eec8440fe54e044cde62a7a348fc0d7a
[ "Markdown", "C#" ]
6
C#
plcart/coursera-gameprogramming
bf92b3b80e76fe5840d8ba17d03bb447ef4b55cd
c1c2a5f8039b651e59fd8e416861204551d4f6af
refs/heads/master
<repo_name>coach9910/SpringCloud-Bus<file_sep>/Eureka-BUS/configclient/src/main/resources/application.properties spring.application.name=configclient spring.cloud.config.uri=http://localhost:2222/ spring.cloud.config.label=master spring.rabbitmq.host= 192.168.1.101 spring.rabbitmq.port=5672 spring.rabbitmq.username=rabbit spring.rabbitmq.password=<PASSWORD> <file_sep>/Eureka-BUS/consumer/src/main/resources/application.properties eureka.client.service-url.defaultZone= http://localhost:2222/eureka/ server.port=8000 spring.application.name=consumer <file_sep>/Eureka-BUS/configserver/src/main/resources/application.properties spring.application.name=configserver spring.cloud.config.server.git.uri=https://github.com/coach9910/config spring.rabbitmq.host= 192.168.1.101 spring.rabbitmq.port=5672 spring.rabbitmq.username=rabbit spring.rabbitmq.password=<PASSWORD><file_sep>/Eureka-BUS/consumer/src/main/java/consumer/consumer/HelloService.java package consumer.consumer; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * Created by lizheng on 2017/7/21. */ @Service public class HelloService { @Autowired RestTemplate restTemplate; //注解指定发生错误时的回调方法 @HystrixCommand(fallbackMethod = "helloFallBack") public String helloService() { //Get请求调用服务,restTemplate被@LoadBalanced注解标记,Get方法会自动进行负载均衡 return restTemplate.getForObject("http://localhost:2222/info", String.class); } public String helloFallBack() { return "Error occurred !"; } }<file_sep>/Eureka-BUS/producer/src/main/resources/application.properties eureka.client.service-url.defaultZone= http://localhost:2222/eureka/ server.port=8101 spring.application.name=producer <file_sep>/Eureka-BUS/zuul/target/classes/application.properties zuul.routes.customer.path=/** zuul.routes.customer.serviceId=springcloud-customer eureka.client.service-url.defaultZone= http://localhost:2222/eureka/ server.port=8101 spring.application.name=springcloud-gateway
214d655906fd91ad63c565699b29d14a1eebf056
[ "Java", "INI" ]
6
INI
coach9910/SpringCloud-Bus
c2d9479dd4468b7d3dfbf81d64cda2e1beea3172
e70a33825bb5daeef5de341de59b6a42f919e4f1
refs/heads/master
<file_sep>function Person(attr) { this.gender = attr.gender; this.age = attr.age; this.distance = attr.distance; }; Person.prototype.cooperResult = function(distance) { if (this.gender.toLowerCase() == 'male') { this.message = this.getCooperTestMale(distance); } else { this.message = this.getCooperTestFemale(distance); } }; Person.prototype.getCooperTestMale = function(distance) { //just testing for result for male distance //now adding age variable if(this.age>= 1 && this.age<= 14) { if(distance >= 2700){ return 'Excellent' } if(distance >= 2400 && distance <= 2699){ return 'Above Average' } if(distance >= 2200 && distance <=2399){ return 'Average' } if(distance >= 2100 && distance <=2199){ return 'Below Average' } if(distance < 2100){ return 'Poor' } } if(this.age>= 15 && this.age<= 16) { if(distance >= 2800){ return 'Excellent' } if(distance >= 2500 && distance <= 2799){ return 'Above Average' } if(distance >= 2300 && distance <=2499){ return 'Average' } if(distance >= 2200 && distance <=2299){ return 'Below Average' } if(distance < 2200){ return 'Poor' } } if(this.age>= 17 && this.age<= 19) { if(distance >= 3000){ return 'Excellent' } if(distance >= 2700 && distance <= 2999){ return 'Above Average' } if(distance >= 2500 && distance <=2699){ return 'Average' } if(distance >= 2300 && distance <=2499){ return 'Below Average' } if(distance < 2300){ return 'Poor' } } if(this.age>= 20 && this.age<= 29) { if(distance >= 2800){ return 'Excellent' } if(distance >= 2700 && distance <= 2999){ return 'Above Average' } if(distance >= 2500 && distance <=2699){ return 'Average' } if(distance >= 2300 && distance <=2499){ return 'Below Average' } if(distance < 2300){ return 'Poor' } } if(this.age>= 30 && this.age<= 39) { if(distance >= 2700){ return 'Excellent' } if(distance >= 2300 && distance <= 2699){ return 'Above Average' } if(distance >= 1900 && distance <=2299){ return 'Average' } if(distance >= 1500 && distance <=1999){ return 'Below Average' } if(distance < 1500){ return 'Poor' } } if(this.age>= 40 && this.age<= 49) { if(distance >= 2500){ return 'Excellent' } if(distance >= 2100 && distance <= 2499){ return 'Above Average' } if(distance >= 1700 && distance <=2099){ return 'Average' } if(distance >= 1400 && distance <=1699){ return 'Below Average' } if(distance < 1400){ return 'Poor' } } if(this.age>= 50) { if(distance >= 2400){ return 'Excellent' } if(distance >= 2000 && distance <= 2399){ return 'Above Average' } if(distance >= 1600 && distance <=1999){ return 'Average' } if(distance >= 1300 && distance <=1599){ return 'Below Average' } if(distance < 1300){ return 'Poor' } } }; Person.prototype.getCooperTestFemale = function(distance) { if(this.age>= 1 && this.age<= 14) { if(distance >= 2000){ return 'Excellent' } if(distance >= 1900 && distance <= 1999){ return 'Above Average' } if(distance >= 1600 && distance <=1899){ return 'Average' } if(distance >= 1500 && distance <=1599){ return 'Below Average' } if(distance < 1500){ return 'Poor' } } if(this.age>= 15 && this.age<= 16) { if(distance >= 2100){ return 'Excellent' } if(distance >= 2000 && distance <= 2099){ return 'Above Average' } if(distance >= 1700 && distance <=1999){ return 'Average' } if(distance >= 1600 && distance <=1699){ return 'Below Average' } if(distance < 1600){ return 'Poor' } } if(this.age>= 17 && this.age<= 19) { if(distance >= 2300){ return 'Excellent' } if(distance >= 2100 && distance <= 2299){ return 'Above Average' } if(distance >= 1800 && distance <=2099){ return 'Average' } if(distance >= 1700 && distance <=1799){ return 'Below Average' } if(distance < 1700){ return 'Poor' } } if(this.age>= 20 && this.age<= 29) { if(distance >= 2700){ return 'Excellent' } if(distance >= 2200 && distance <= 2699){ return 'Above Average' } if(distance >= 1800 && distance <=2199){ return 'Average' } if(distance >= 1500 && distance <=1799){ return 'Below Average' } if(distance < 1500){ return 'Poor' } } if(this.age>= 30 && this.age<= 39) { if(distance >= 2500){ return 'Excellent' } if(distance >= 2000 && distance <= 2499){ return 'Above Average' } if(distance >= 1700 && distance <=1999){ return 'Average' } if(distance >= 1400 && distance <=1699){ return 'Below Average' } if(distance < 1400){ return 'Poor' } } if(this.age>= 40 && this.age<= 49) { if(distance >= 2300){ return 'Excellent' } if(distance >= 1900 && distance <= 2299){ return 'Above Average' } if(distance >= 1500 && distance <=1899){ return 'Average' } if(distance >= 1200 && distance <=1499){ return 'Below Average' } if(distance < 1200){ return 'Poor' } } if(this.age>= 50) { if(distance >= 2200){ return 'Excellent' } if(distance >= 1700 && distance <= 2199){ return 'Above Average' } if(distance >= 1400 && distance <=1699){ return 'Average' } if(distance >= 1100 && distance <=1399){ return 'Below Average' } if(distance < 1100){ return 'Poor' } } }; <file_sep>angular.module('starter.services', []) .factory('performanceData', function ($resource, API_URL) { return $resource(API_URL + '/performance_data', {}, { 'query': { method: 'GET' }}); });
5741bbdbcbc63ead952b0f552960cca76f8a9286
[ "JavaScript" ]
2
JavaScript
thesuss/cooper-client
a9a2305b350360280839291610d1871371c93486
36a6e5ff76076b8fceb508da2b81a626be377029
refs/heads/master
<file_sep>import java.util.*; public class Max_2darray{ public static void main(String[] args) { Scanner scan= new Scanner(System.in); System.out.println("Please enter integers"); int n=scan.nextInt(); int max=0; int array[][]= new int[n][n]; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ array[i][j]= scan.nextInt(); if(max<array[i][j]){ max= array[i][j]; } } } System.out.println("Maximum number in the array is "+ max); } } <file_sep>import java.io.*; import java.lang.Math; import java.util.Scanner; class Prime{ public static void main(String[]args) { int a=0; Scanner scan=new Scanner(System.in); int z=scan.nextInt(); for(int y=2;y<=Math.ceil(Math.sqrt(z));y++) { if(z%y==0) { a=1; break; } } if(z<=1) { System.out.print(z+" is neither prime nor composite"); } else if(a==0 || z==2) { System.out.print(z+" is a prime"); } else { System.out.print(z+" is not a prime"); } } }
f8b94d08179c3d43954c317c2a46970a762637f0
[ "Java" ]
2
Java
170030930/SASANK_
582d39576164b8fbbe7285facfe883f62a971025
6c91b1480486c473d2419de9bc1ee67a682821cd
refs/heads/master
<repo_name>testpng356/finalProg3<file_sep>/src/app/app-routing.module.ts //import { ModalComponent } from './componentes/modal/modal.component'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; //import { ElementoComponent } from './componentes/elementos/elemento.component'; import {TableComponent} from './componentes/table/table.component' import { from } from 'rxjs'; const routes: Routes = [ //no se utilizaran //{path: '', component: TableComponent} //{path: 'persona/:id', component: TableComponent}, // {path: '**', pathMatch: 'full', redirectTo: ModalComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/componentes/table/table.component.ts import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Component, OnInit } from "@angular/core"; import { Persona } from "src/app/entidades/persona"; import { PersonaService } from "src/app/servicios/persona.service"; import { Router } from "@angular/router"; @Component({ selector: "app-table", templateUrl: "./table.component.html", styleUrls: ["./table.component.css"] }) export class TableComponent implements OnInit { personas: Persona[]=[]; id: number; update: false; formReact: FormGroup; constructor(private service: PersonaService, private router: Router, private formBuilder: FormBuilder) { } //Estructura de Persona , es igual a la entidad persona: Persona = { id: 0, nombre: '', apellido: '', dni: 0 }; ngOnInit() { this.getAll(); //console.log(getAll); //traza if(!this.update){this.validatorForm(); } } creationFormUpdate(persona: Persona){ this.update = false; //console.log(update);//traza this.formReact.setValue({nombre: persona.nombre, apellido: persona.apellido, dni: persona.dni});//datos que necesito para el form a editar this.id = persona.id; //llamo al id de persona // this.formReact.reset();//traza } validatorForm(){ this.formReact = this.formBuilder.group({nombre: ['', Validators.compose([Validators.required,Validators.pattern('/^[a-zA-Z]*$/')])], /*Para validar el nombre se necesita el formuReact(FormGroup) que depende del builder, dentro de este se arma el group o grupo de controles de estado para nombre - Ademas de validar que solo se ingresen letras, esta capacidad nos la entrega el pattern que más adelante se usará con numeros*/ apellido: ['', Validators.compose([Validators.required,Validators.pattern('/^[a-zA-Z]*$/')])], //Para apellido exijo lo mismo que para nombre, tambien se utiliza el pattern para letras dni: ['', Validators.compose([Validators.required, Validators.maxLength(8) ,Validators.minLength(8), Validators.pattern('/^[0-9]*$/')])] //Para el dni requiero un maximo de 8 digitos y un minimo de la misma cantidad (dni Argentina) y con el pattern (control de marcado) }); } getAll(){ this.service.getAll().subscribe((data)=>{ this.personas.length = 0; data.forEach((res)=>{ this.personas.push(res) console.log(this.personas);//traza }); }); } deletePers(id:number){ //Metodo delete reutilizado, siempre se elimina el registro por id const opcion = confirm('¿Esta seguro que desea eliminar el registro?'); if (opcion === true) { this.service.delete(id).subscribe((data)=> { console.log(data); alert('El registro ha sido eliminado'); //location.reload(); this.getAll(); }); } } agregarPers (){ //this.router.navigate(); //this.router.navigate(['persona/'+ id]); this.service.post(this.formReact.value).subscribe((data)=>{//post agrega a la persona this.persona = data; this.personas.push(this.persona); this.getAll(); this.formReact.reset(); //una vez agregada la persona se resetea el formulario }); } updatePers(){ // this.router.navigate(['persona/'+id]); this.service.put(this.id, this.formReact.value).subscribe((data)=>{ //Misma forma que la anterior solo que utiliza el id y put para poder editar this.persona = data; this.personas.push(this.persona);//inserto this.getAll(); this.formReact.reset(); //cuando se actualiza la persona se resetea el formulario como si se agregara }); } } <file_sep>/src/app/servicios/persona.service.ts import { Injectable } from "@angular/core"; import { HttpClient } from '@angular/common/http'; import { Persona } from '../entidades/persona'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class PersonaService { miUrl: string = 'http://localhost:9001/api/v1/persona/'; //rutaActiva: any; constructor(private http: HttpClient) { } getAll(): Observable<Persona[]> { try{ return this.http.get<Persona[]>(this.miUrl); }catch(excep){ alert("No hay datos para mostrar"); console.log(excep); } } getOne(id: number): Observable<Persona> { try{ return this.http.get<Persona>(this.miUrl + id); }catch(excep){ alert("No hay datos para mostrar"); console.log(excep); } } delete(id: number): Observable<any> { try{ return this.http.delete(this.miUrl + id); }catch(excep){ alert("El campo seleccionado ha sido removido"); console.log(excep); } } post(persona: Persona): Observable<Persona> { console.log("Servicio Post") try{ return this.http.post<Persona>(this.miUrl, persona); }catch(excep){ alert("Los datos ingresados no ha sido guardados"); console.log(excep); } } put(id: number, persona: Persona): Observable<Persona> { try{ return this.http.put<Persona>(this.miUrl + id, persona); }catch(excep){ alert("El campo seleccionado no se ha podido modificar"); console.log(excep); } } }<file_sep>/src/app/componentes/modal/modal.component.ts /*import { Component, OnInit, ElementRef, ViewChild, Input } from '@angular/core'; import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms'; import { Persona } from 'src/app/entidades/persona'; import { PersonaService } from 'src/app/servicios/persona.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { //Variables contacto: FormGroup; submitted = false; titulo = 'Crear Formulario'; constructor(private service: PersonaService, private rutaActiva: ActivatedRoute, private router: Router, private formBuilder: FormBuilder) { } @ViewChild('btnClose',{ static: true }) btnClose: ElementRef; @Input() userUid: string; formularioCreado: FormGroup; esNuevo: boolean= true; usuarios: Array<Persona> = new Array<Persona>(); posicionEditar: number = -1; ngOnInit() { this.crearFormulario(); } crearFormulario(){ this.formularioCreado= this.formBuilder.group({ nombre:['', Validators.required],//para que sea requerido apellido: ['', Validators.required],//Que el apellido sea valido dni: ['', Validators.compose([ Validators.required, Validators.minLength(8) //un ancho minimo de 8 caracteres ])] }) } agregar(){ this.usuarios.push(this.formularioCreado.value as Persona) this.formularioCreado.reset() } editar(){ this.usuarios[this.posicionEditar].nombre=this.formularioCreado.value.nombre; this.usuarios[this.posicionEditar].apellido=this.formularioCreado.value.apellido; this.usuarios[this.posicionEditar].dni=this.formularioCreado.value.dni; this.formularioCreado.reset(); this.esNuevo=true; this.posicionEditar=-1; } editarUsuario(posicion: number){ this.formularioCreado.setValue({ nombre: this.usuarios[posicion].nombre, apellido:this.usuarios[posicion].apellido, dni: this.usuarios[posicion].dni }) this.posicionEditar= posicion; this.esNuevo=false; } eliminarUsuario(posicion: number){ this.usuarios.splice(posicion,1) } // onSaveProf(profForm: FormGroup): void{ // //nuevo libro // // // console.log('profForm.value.id', profForm.value.id); // if(profForm.value.id === null){ // //nuevo libro // profForm.value.userUid = this.userUid; //cuando // this.service.post(profForm.value); // }else{ // //update // } // profForm.reset();//me permite limpiar el formulario // this.btnClose.nativeElement.click(); // } } */<file_sep>/README.md #Aprendiendo a trabajar con Fork ##Recursos de git ## Descripcion: Este trabajo ha sido realizado sobre la base de un proyecto anterior, se rescato parte del codigo y se mejoro para poder realizar un formulario reactivo, como no es necesario usar todas las secciones del codigo se han comentado he inutilizado algunas partes del como `component/modal.`, `component/elementos.` entre otros. El codigo base es en el que se ha practicado en las clases, es una base excelente para poder hacer pruebas y aprender nuevos metodos. Este proyecto pertenece al examen final de Programacion 3 UTN-FRM. ## PerDoAbm This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.17. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). <file_sep>/src/app/componentes/elementos/elemento.component.ts /*import { from } from 'rxjs'; import { Component, OnInit } from '@angular/core'; import { Persona } from 'src/app/entidades/persona'; import { PersonaService } from 'src/app/servicios/persona.service'; import { ActivatedRoute, Router } from '@angular/router'; //import { NumberFormatStyle } from '@angular/common'; @Component({ selector: 'app-elemento', templateUrl: './elemento.component.html', styleUrls: ['./elemento.component.css'] }) export class ElementoComponent implements OnInit { persona: Persona = { id: 0, nombre: '', apellido: '', dni: 0, } constructor(private service: PersonaService, private rutaActiva: ActivatedRoute, private router: Router) { } ngOnInit() { this.rutaActiva.params.subscribe(data => { if (data['id'] != '0') { this.getOne(data['id']); } }); } getOne(id: number){ this.service.getOne(id).subscribe(data => { this.persona = data; }) } save() { this.rutaActiva.params.subscribe(data => { if (data['id'] === '0') { this.add(); } else { this.update(data['id']); } }); } add() { this.service.post(this.persona).subscribe(data => { this.persona = data; // this.router.navigate(['']); }); } update(id:number){ this.service.put(id,this.persona).subscribe(data =>{ this.persona = data; // this.router.navigate(['']); }) } } */
93576a77af2167c2dd1c20915430de88ad609758
[ "Markdown", "TypeScript" ]
6
TypeScript
testpng356/finalProg3
11ca1a4010cc36320926ef59ef405f876aa61a41
32d5e74ebd0adacea00b176a80d500882c2dd313
refs/heads/master
<file_sep>require 'sinatra' get '/' do erb :form end # get '/:nombre' do # "<h1>Hola #{params[:nombre]}</h1>" # end post '/form' do if params[:frase] == params[:frase].upcase "<h1>Ahhh si, manzanas!</h1>" else "<h1>Habla más duro mijito</h1>" end end
99e5e762c2fe70bd97b68759a39a08521882df81
[ "Ruby" ]
1
Ruby
sanesco/grandma-deaf
23c9d313952a9dce20d31300682b0e30bf363b29
e30caf1c8449c05b289ed43a47f5704e75a34698
refs/heads/master
<file_sep>// @flow import assert from 'assert'; import Github from 'github'; import type {Uri, Options} from './index'; export default async function getGithubFile(uri: Uri, options: Options = {}) { assert(typeof uri === 'string', 'The uri parameter must be a string.'); const {client = new Github(), auth} = options; const [user, repo, ...pathParts] = uri.split('/'); assert(pathParts.length > 0, 'The uri must contain a file path'); const path = pathParts.join('/'); if (auth) { client.authenticate(auth); } const {default_branch: defaultBranch} = await client.repos.get({user, repo}); const {branch = defaultBranch} = options; const {content, encoding} = await client.repos.getContent({ user, repo, path, ref: branch }); return new Buffer(content, encoding); } <file_sep>#!/usr/bin/env bash declare exitCode; # -- [1] ------------------------------------------------------- $(npm bin)/travis-after-all exitCode=$? # -- [2] ------------------------------------------------------- if [ $exitCode -eq 0 ]; then git config --global user.email "<EMAIL>" git config --global user.name "<NAME>" npm version prerelease git push && git push --tags npm publish --tag=canary fi if [ $exitCode -eq 1 ]; then echo "One or more travis jobs for this build failed." fi
5e4477ffdcaf318923c7b8d6bf92d9b2dc07886b
[ "JavaScript", "Shell" ]
2
JavaScript
nerdlabs/get-github-file
b53dd2f5beb8295ff7b8b6b399402597f866c626
c5fd0aff243abcbadb73e71ded1e28816d022bb6
refs/heads/master
<repo_name>lc319641967/-<file_sep>/同余定理.cpp #include<stdio.h> void exGcd(int a,int b,int *x,int *y) //扩展欧几里得(求出x0,y0) { int t; if(b == 0) { *x = 1; *y = 0; return ; } exGcd(b,a%b,x,y); t = *x; *x = *y; *y = t-a/b*(*y); } int main() { int a,b; int x,y; scanf("%d%d",&a,&b); exGcd(a,b,&x,&y); while(x < 0) x += b; //根据通解公式进行累加,找到最小正整数 printf("%d\n",x); return 0; }<file_sep>/欧几里得算法求最大公约数.cpp #include<stdio.h> int main() { int a,b; int c=0,d=0; scanf("%d%d",&a,&b);(输入两个数) if(a<b)(比较大小,交换位置) { d=a; a=b; b=d; } while(a%b)(辗转相除法) { c=a%b; a=b; b=c; } printf("%d\n",b); } <file_sep>/筛法求素数.cpp #include<stdio.h> int main() { int i,j,m;//定义两个变量,i是从2到m的数字,j是用来被i除,检验i是否是素数的数,m是筛选范围 scanf("%d",&m); for(i=2;i<=m;i++)//i从2到m,挨个枚举,用下面的算法检验 { for(j=2;j<i;j++)//j从2到i-1,用i除以j { if(i%j==0)//如果i除以j的余数是0,即i不是素数 { break;//跳出循环 } if(j==i-1)//如果直到j=i-1时上面的判断一直没成立,即i不是素数,输出i { printf("%d ",i); } } } return 0; } <file_sep>/数组中重复的数字.cpp #include<stdio.h> #include<stdlib.h> int GetDuplication(int arr[], int len) { //处理异常情况 if (arr == NULL || len <= 0) { return -1; } //限定范围 for (int i=0;i<len;i++) { if (arr[i] < 0 || arr[i] >= len) { return -2; } } //查找 for (i = 0; i < len; i++)//遍历整个数组 { while (arr[i] != i)//当数组元素不等于下标时才执行循环 { if (arr[i] == arr[arr[i]])//找到重复数 { return arr[i]; } else { //交换 int tmp = arr[i]; arr[i] = arr[tmp]; arr[tmp] = tmp; } } } return -3; } int main() { int arr[] = { 1, 3, 2, 0, 2, 5, 3 }; int len = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < len; i++) { printf("% d", arr[i]); } printf("\n"); int ret = GetDuplication(arr, len); printf("% d\n", ret); system("pause"); return 0; }<file_sep>/数组中有一个数字出现的次数超过数组长度的一般.cpp #include<stdio.h> #include<stdlib.h> int Search(int A[],int len) { if(NULL==A || len<=0) { return -1; } int k, j=0; for(int i=0;i<len;++i) { if(j==0) { k=A[i]; } if(k==A[i]) { ++j; }else { --j; } } return k; } void main(){ int len=10; int a[10]={4,5,5,2,3,5,2,5,5,5}; int result=Search(a,len); printf("%d\n",result); }<file_sep>/二分查找.c /*实现?int sqrt(int x)?函数。 计算并返回?x?的平方根,其中?x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., ? 由于返回类型是整数,小数部分将被舍去。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sqrtx 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ int mySqrt(int x){ int left=1,right=x/2; int mid=(left+right)/2; while(left<right) { if(mid*mid==x) return mid; else if(mid*mid<x) left=mid+1; else right=mid+1; mid=(left+right)/2; } if(left*left>x) return left-1; return left; }
1de936a037b4b48542b514d92974df2f3efee906
[ "C", "C++" ]
6
C++
lc319641967/-
90253a4244631bafc002320189c3bce640b9177f
85970d73bed27da083a2f920ba912d22e7f2ced3
refs/heads/master
<file_sep>import { Action } from 'types'; import { CLEAN, INIT } from './constant'; const INITIAL_STATE = {}; export type ITemplateReducer = typeof INITIAL_STATE; export default function Template( state = INITIAL_STATE, action: Action ): ITemplateReducer { const { type, payload } = action; switch (type) { case INIT: return state; case CLEAN: return INITIAL_STATE; } return state; } <file_sep>import { NavigationScreenProp, NavigationState } from 'react-navigation'; declare global { const YouNavigator: NavigationScreenProp<NavigationState>; } <file_sep>package com.company.project.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Created by keith on 10/11/16. */ public class BaseController { @Autowired private MessageSource messageSource; /** * 获取国际化配置信息 * * @param code 国际化编码 * @return */ protected String getMessage(String code) { // 默认只用中文一种,如果有需要别的语言可以改 return messageSource.getMessage(code, null, "错误信息不明", Locale.CHINA); } /** * 返回默认的成功json数据 * * @return */ protected Map<String, Object> success() { Map<String, Object> result = new HashMap<>(); result.put("result", "ok"); result.put("data", ""); result.put("msg", getMessage("200")); return result; } /** * 返回成功json数据 * * @param data 返回的数据 * @param code 国际化编码 * @return */ protected Map<String, Object> success(Object data, String code) { Map<String, Object> result = new HashMap<>(); result.put("result", "ok"); result.put("data", data); result.put("msg", getMessage(code)); return result; } /** * 返回成功json数据 * * @param code 国际化编码 * @return */ protected Map<String, Object> failure(String code) { Map<String, Object> map = new HashMap<>(); map.put("result", "fail"); map.put("data", ""); map.put("msg", getMessage(code)); return map; } /** * 返回成功json数据 * * @param data 返回的数据 * @param code 国际化编码 * @return */ protected Map<String, Object> failure(Object data, String code) { Map<String, Object> result = new HashMap<>(); result.put("result", "fail"); result.put("data", data); result.put("msg", getMessage(code)); return result; } } <file_sep>package com.company.project.user.info; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> findAll() { Page<User> result = userRepository.findAll(new PageRequest(0, 10)); return result.getContent(); } } <file_sep>package com.company.project.user.info; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Entity @Data @Table(name="user") public class User implements Serializable { @Id @GeneratedValue private Long id; @Column(name = "name", nullable = false) private String name; } <file_sep>package com.company.project.user.address; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service public class AddressService { @Autowired private AddressRepository addressRepository; public Page<Address> findAll() { return addressRepository.findAll(new PageRequest(0, 10)); } } <file_sep>import _ from 'lodash'; export default { isLogin: () => window.userInfo.user, isMenuPerssion: (path: any, pathMap: any) => { return pathMap.indexOf(path) > -1; }, menuMap: (data: any) => { const resultMap: any = []; data.map((o: any) => { const children = _.get(o, 'children') || []; if (children.length <= 0) { resultMap.push({ key: o.id, value: o.path }); } children.map((item: any) => { resultMap.push({ key: o.id, value: item.path }); }); }); return resultMap; } }; <file_sep>package com.company.project.user.address; import com.company.project.user.info.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.Repository; public interface AddressRepository extends Repository<User, Long> { Page<Address> findAll(Pageable pageable); } <file_sep>import action from './action'; import { IGoodsListReducer } from './reducer'; export type IGoodsListProps = { goodsList: IGoodsListReducer; } & ReturnType<typeof action>; <file_sep>import GoodsList from '../pages/goods-list'; const routes = [ { path: '/goods-list', component: GoodsList } ]; export default routes; <file_sep>import Util from './util'; import Config from './config'; export { Util, Config }; <file_sep>import { CHANGE } from './constant'; export default (dispatch: any) => { const actions = { change() { return { type: CHANGE }; } }; return actions; }; <file_sep>import { combineReducers } from 'redux'; import template from './pages/template/reducer'; export default combineReducers({ template }); <file_sep>package com.company.project.controller; import com.company.project.service.HelloService; import com.company.project.user.info.User; import com.company.project.user.info.UserService; import com.company.project.user.xsite.TestConfig; import com.company.project.user.xsite.XSiteConfig; import com.company.project.user.xsite.XSiteService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by keith on 8/5/16. */ @RestController public class HelloController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(HelloController.class); @Autowired private HelloService helloService; @Autowired private UserService userService; @Autowired private XSiteService xsiteService; @RequestMapping("/") public String index() { logger.debug("HelloController index..."); User user = new User(); user.setId(Long.valueOf(1)); user.setName("keith"); return helloService.hello(); } @RequestMapping("/user") public String user() { logger.debug("HelloController index..."); User user = new User(); user.setId(Long.valueOf(1)); user.setName("keith"); return "info"; } @RequestMapping("/test") @ResponseBody public List<TestConfig> test() { return xsiteService.test(); } @RequestMapping("/test/all") @ResponseBody public List<TestConfig> testAll() { return xsiteService.testAll(); } @RequestMapping("/xsite/all") @ResponseBody public List<XSiteConfig> xSiteConfigs() { return xsiteService.xsiteAll(); } @RequestMapping("/xsite") @ResponseBody public XSiteConfig xSiteConfigByUserId() { return xsiteService.xsiteByUserId(); } @RequestMapping("/userList") @ResponseBody public List<User> userList() { return userService.findAll(); } } <file_sep>import YouTheme from './themes'; export type ThemeType = typeof YouTheme; const bindThemeToGlobal = (globalName: any) => { window[globalName] = YouTheme; }; bindThemeToGlobal('YouTheme'); <file_sep>const BASE = 'Template_'; export const INIT = BASE + 'INIT'; export const CLEAN = BASE + 'CLEAN'; <file_sep>import { NavigationScreenProp, NavigationState } from 'react-navigation'; import { ThemeType } from 'you-ui/styles'; declare const YouNavigator: NavigationScreenProp<NavigationState>; declare global { interface Window { [key: string]: any; } const YouTheme: ThemeType; } <file_sep>import { Dispatch } from 'types'; import { CLEAN, INIT } from './constant'; export default (dispatch: Dispatch) => { const actions = { /** * 初始化 */ async init() { dispatch({ type: INIT }); }, /** * 重置 */ async clean() { dispatch({ type: CLEAN }); } }; return { ...actions }; }; <file_sep>export default { Host: 'http://api.youdetan.com' }; <file_sep>import YouList from './list'; export { YouList }; <file_sep>import { connect } from 'react-redux'; import mapDispatchToProps from './action'; const mapStateToProps = ({ template }: any) => { return { template }; }; export default (component: any): any => { return connect( mapStateToProps, mapDispatchToProps )(component) as any; }; <file_sep>const INITIAL_STATE = { loading: false }; export type IGoodsListReducer = typeof INITIAL_STATE; export default function reducer(state = INITIAL_STATE, action: any) { const { type, payload } = action; switch (type) { default: return state; } } <file_sep>java版的后端项目模板 web 1.controller 项目对外接口 2.service 处理各个模块混合业务的service common 公共模块 user 用户业务领域,内部按业务划分模块 1.service 2.bean 3.dao 4.entity <file_sep>import RouterUtils from './router-utils'; export { RouterUtils }; <file_sep>import Actions from './action'; import { ITemplateReducer } from './reducer'; export type ITemplateProps = { template: ITemplateReducer; } & ReturnType<typeof Actions>; <file_sep>const BASE = 'GoodsList_'; export const CHANGE = BASE + 'CHANGE'; <file_sep>package com.company.project.controller; import com.company.project.user.info.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * Created by keith on 10/11/16. */ @RestController public class UserController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private UserService userService; @ResponseBody @RequestMapping("/login") public Map<String, Object> login() { return null; } @ResponseBody @RequestMapping("/logout") public Map<String, Object> logout() { return null; } @ResponseBody @RequestMapping("/register") public Map<String, Object> register() { return null; } } <file_sep>import { combineReducers } from 'redux'; import goodsList from '../pages/goods-list/reducer'; export default combineReducers({ goodsList }); <file_sep>declare interface Window { name: string; CHINA_REGION: any; } <file_sep>#### 使用 react 很久了,目前也有[create-react-app](https://github.com/facebook/create-react-app)这种脚手架项目,但总是和自己选择的技术搭配不太匹配,索性把自己用到的技术搭配方案所需要的全部配置都一一写一遍,保证项目每个模块都是我知晓的,都是我需要的 #### 目前主要模块版本是`react 16+`, `typescript 3+`, `webpack 4`, `babel 7`,后续会使用 react hook 重构 ##### _基础环境_ 确保已经安装了[nodejs](https://nodejs.org),安装完成后使用 npm 或者[yarn](https://yarnpkg.com/en/docs/install)初始化项目: `npm init`或者`yarn init` #### _基础依赖_ 1. 生产环境依赖 - react - react-dom 2. 开发环境依赖 - @babel/core - @babel/preset-env - @babel/preset-react - @babel/preset-typescript - webpack - webpack-cli - webpack-dev-server - babel-loader - less-loader - style-loader - css-loader - html-webpack-plugin - typescript - @types/react、@types/react-dom #### 配置 1. **babel** - @babel/core、@babel/preset-env、@babel/preset-react、@babel/preset-typescript - 这里有很多种配置方式,如.babelrc、.babelrc.js、babel.config.js,我们选择直接在根目录下使用 babel.config.js,既有编程能力,又支持各种场景(单仓库,配置覆盖等),官方就使用的这种配置 2. **typescript** - typescript - babel 7 开始只要使用@babel/preset-typescript 就支持直接转换 typescript - 根目录新建 tsconfig.json - 注意配置 baseUrl,为了拆分 ui、biz、kit 模块,拆分出来的模块都要包含 package.json 文件代表单独的模块 - 如果 ui、biz、kit 不在跟目录,要在 tscofnig.json 中配置 paths 属性,这样方便 ts 解析到,并能直接引用模块,如:`import { Header } from 'ui'` 3. **webpack** - webpack、webpack-cli、webpack-dev-server、babel-loader、less-loader、style-loader、css-loader、html-webpack-plugin - 根目录新建 webpack.config.js - tsconfig.json 只是为了类型检测不报错,如上所说的 ui、biz、kit 模块,真正能被直接引用到还需要配置 ```javascript resolve: { alias: { ui: path.resolve(__dirname, 'ui'); } } ``` <file_sep>const primary = '#4188FB'; const primary_tap = '#1C6AE8'; // 颜色 const color = { /** 文字色*/ text_base: '#383838', text_base_inverse: '#ffffff', text_disabled: '#cccccc', text_caption: '#999999', // 链接字体色 link: primary, /** 背景色 */ fill_base: '#f8f8f8', fill_grey: '#dddddd', fill_white: '#ffffff', fill_mask_base: 'rgba(0, 0, 0, .5)', fill_mask_tip: 'rgba(0, 0, 0, .7)', /** 品牌 */ brand_primary: primary, brand_primary_tap: primary_tap, brand_success: '##3dd77a', brand_warning: '#ffbd20', brand_error: '#ff5c33', // 边框 border: '#d9d9d9', // 分割线 split: '#f0f0f0' }; // 字体 const font = { head: 17, // 一级标题,按钮 caption: 15, // 辅助文字 subhead: 14, // 二级标题 base: 13, // 基础字号 caption_sm: 12, // 辅助文字小 icontext: 10 // 图标描述文字 }; // 圆角 const radius = { // 客服消息 sm: 8, // 图标 md: 12, // 按钮 lg: 22 }; // 间距 const spacing = { // 水平间距 h_spacing_sm: 4, h_spacing_md: 8, h_spacing_lg: 16, // 垂直间距 v_spacing_xs: 4, // v_spacing_sm: 6, v_spacing_md: 8, v_spacing_lg: 16 // v_spacing_xl: 20, }; // 图标大小 const icon = { lg: 24, md: 22, sm: 20, xs: 16 }; // 头像大小 const headIcon = { lg: 70, md: 50, sm: 20 }; // 图片大小 const image = { lg: 120, md: 80, sm: 60 }; // 按钮高度,宽度都是算出来的,不能定宽,但是高度要定高 const btn = { height_lg: 44, height_md: 36, height_sm: 28, height_xs: 22, height_xss: 18 }; export default { color, font, radius, spacing, icon, headIcon, image, btn }; <file_sep>import { ADD, MINUS } from './constant'; export default dispatch => { const actions = { asyncAdd() { setTimeout(() => { dispatch(this.add()); }, 2000); }, minus() { return { type: MINUS }; }, add() { return { type: ADD }; } }; return actions; }; <file_sep>package com.company.project.user.xsite; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * Created by keith on 8/31/16. */ @Document(collection = "test") @Data public class TestConfig { @Id private String id; private String name; private int age; } <file_sep>import action from './action'; import { IIndexReducer } from './reducer'; export type IIndexProps = { index: IIndexReducer; } & ReturnType<typeof action>; <file_sep>import './styles'; import YouHeader from './header'; import YouText from './text'; export { YouText, YouHeader }; <file_sep>package com.company.project.user.address; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @Entity @Data @Table(name = "address") public class Address implements Serializable { @Id @GeneratedValue private Long Id; /** * 省 */ private String province; /** * 市 */ private String City; /** * 区 */ private String region; } <file_sep>import { Dimensions, Platform } from 'react-native'; const { width, height } = Dimensions.get('window'); export default { screenWidth: width, screenHeight: height, get isAndroid(): boolean { return Platform.OS === 'android'; }, get isIOS(): boolean { return Platform.OS === 'ios'; }, noop: () => {} }; <file_sep>const menuList = [ { id: '2', name: '系统管理', type: 1, parentId: null, level: 1, menuList: [ { id: '201', name: '用户管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/user-manage' }, { id: '202', name: '角色管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/role-manage' }, { id: '203', name: '部门管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/department-manage' }, { id: '204', name: '门店管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/branch-manage' } ], functionList: null, icon: 'iconfont iconhx_shengchanqiyeguanli', path: '/auth', children: [ { id: '201', name: '用户管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/user-manage' }, { id: '202', name: '角色管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/role-manage' }, { id: '203', name: '部门管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/department-manage' }, { id: '204', name: '门店管理', type: 1, parentId: '2', level: 2, menuList: null, functionList: null, path: '/auth/branch-manage' } ] }, { id: '4', name: '商品中心', type: 1, parentId: null, level: 1, menuList: [ { id: '401', name: '类目管理', type: 1, parentId: '4', level: 2, menuList: null, functionList: null, path: '/shop/category-manage' }, { id: '402', name: '型号管理', type: 1, parentId: '4', level: 2, menuList: null, functionList: null, path: '/shop/model-manage' } ], functionList: null, children: [ { id: '401', name: '类目管理', type: 1, parentId: '4', level: 2, menuList: null, functionList: null, path: '/shop/category-manage' }, { id: '402', name: '型号管理', type: 1, parentId: '4', level: 2, menuList: null, functionList: null, path: '/shop/model-manage' } ], icon: 'iconfont iconshangpin', path: '/shop' }, { id: '5', name: '线索中心', type: 1, parentId: null, level: 1, menuList: [ { id: '501', name: '等级设置', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/lead-setup' }, { id: '502', name: '线索列表', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/lead-list' }, { id: '503', name: '新建线索', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/new-leads' } ], functionList: null, children: [ { id: '501', name: '等级设置', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/lead-setup' }, { id: '502', name: '线索列表', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/lead-list' }, { id: '503', name: '新建线索', type: 1, parentId: '5', level: 2, menuList: null, functionList: null, path: '/lead/new-leads' } ], icon: 'iconfont iconxiansuo', path: '/lead' }, { id: '6', name: '鉴定中心', type: 1, parentId: null, level: 1, menuList: [ { id: '601', name: '待鉴定列表', type: 1, parentId: '6', level: 2, menuList: null, functionList: null, path: '/appraisal/uncertainty-list' }, { id: '602', name: '鉴定历史', type: 1, parentId: '6', level: 2, menuList: null, functionList: null, path: '/appraisal/identified-list' } ], functionList: null, children: [ { id: '601', name: '待鉴定列表', type: 1, parentId: '6', level: 2, menuList: null, functionList: null, path: '/appraisal/uncertainty-list' }, { id: '602', name: '鉴定历史', type: 1, parentId: '6', level: 2, menuList: null, functionList: null, path: '/appraisal/identified-list' } ], icon: 'iconfont iconjianding', path: '/appraisal' }, { id: '7', name: '采购中心', type: 1, parentId: null, level: 1, menuList: [ { id: '702', name: '采购待审核', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/purchase-uncheck-list' }, { id: '703', name: '采购单列表', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/purchase-list' }, { id: '705', name: '赎回列表', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/redeem-list' }, { id: '706', name: '赎回待审核', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/tobeRedeem-list' } ], functionList: null, children: [ { id: '702', name: '采购待审核', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/purchase-uncheck-list' }, { id: '703', name: '采购单列表', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/purchase-list' }, { id: '705', name: '赎回列表', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/redeem-list' }, { id: '706', name: '赎回待审核', type: 1, parentId: '7', level: 2, menuList: null, functionList: null, path: '/purchase/tobeRedeem-list' } ], icon: 'iconfont iconcaigou', path: '/purchase' }, { id: '9', name: '仓储中心', type: 1, parentId: null, level: 1, menuList: [ { id: '901', name: '仓库管理', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/wms-list' }, { id: '902', name: '门店库存', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/branch-iventory-list' }, { id: '903', name: '全公司库存', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/company-iventory-list' }, { id: '906', name: '入库单', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/receipt-list' }, { id: '907', name: '出库单', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/out-list' } ], functionList: null, children: [ { id: '901', name: '仓库管理', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/wms-list' }, { id: '902', name: '门店库存', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/branch-iventory-list' }, { id: '903', name: '全公司库存', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/company-iventory-list' }, { id: '906', name: '入库单', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/receipt-list' }, { id: '907', name: '出库单', type: 1, parentId: '9', level: 2, menuList: null, functionList: null, path: '/warehouse/out-list' } ], icon: 'iconfont iconcangku', path: '/warehouse' }, { id: '10', name: '财务中心', type: 1, parentId: null, level: 1, menuList: [ { id: '1001', name: '收款单列表', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/collection/receipt-list' }, { id: '1002', name: '付款单列表', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/finacial/payment-list' }, { id: '1005', name: '待付款', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/finacial/unpaid-list' }, { id: '1006', name: '待收款', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/collection/unreceive-list' }, { id: '1007', name: '发票管理', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/invoice/invoice-list' }, { id: '1008', name: '采购单凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/purchase-voucher-list' }, { id: '1009', name: '发票凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/invoice-voucher-list' }, { id: '1010', name: '赎回凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/redemption-voucher-list' } ], functionList: null, children: [ { id: '1001', name: '收款单列表', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/collection/receipt-list' }, { id: '1002', name: '付款单列表', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/finacial/payment-list' }, { id: '1005', name: '待付款', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/finacial/unpaid-list' }, { id: '1006', name: '待收款', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/collection/unreceive-list' }, { id: '1007', name: '发票管理', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/invoice/invoice-list' }, { id: '1008', name: '采购单凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/purchase-voucher-list' }, { id: '1009', name: '发票凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/invoice-voucher-list' }, { id: '1010', name: '赎回凭证', type: 1, parentId: '10', level: 2, menuList: null, functionList: null, path: '/voucher/redemption-voucher-list' } ], icon: 'iconfont iconfinance_book', path: '/finacial' }, { id: '14', name: '商机中心', type: 1, parentId: null, level: 1, menuList: [ { id: '1401', name: '商机列表', type: 1, parentId: '14', level: 2, menuList: null, functionList: null, path: '/opportunity/opportunity-list' } ], functionList: null, children: [ { id: '1401', name: '商机列表', type: 1, parentId: '14', level: 2, menuList: null, functionList: null, path: '/opportunity/opportunity-list' } ], icon: 'iconfont iconweb-icon-', path: '/opportunity' } ]; const userInfo = { user: { id: 'ZhangFeng', name: '张峰', locked: null, phone: '18120150534', deptId: [8], deptList: null, position: '', roleList: [], avatar: null }, token: '<KEY>', menuList: [], menuInfo: { data: [], pathMap: [] } }; const bindGlobalDataFn = () => { window.menuList = menuList; window.userInfo = userInfo; }; export default bindGlobalDataFn;
264b25c5ce245d6c9adcf58ddf000d167dfcdf7c
[ "Markdown", "Java", "TypeScript" ]
38
TypeScript
KeithZhang/fullstack-boilerplate
758cb92ee53d9a55181b282832e85d99b7add63c
4263c33aa84d86aaf93523938aa93817508aa61a
refs/heads/master
<repo_name>whitejamesthe2nd/onward<file_sep>/routes/api/project.js const express = require("express"); const asyncHandler = require("express-async-handler"); const {Project} = require('../../db/models'); const router = express.Router(); // To get your tasks router.get('/', asyncHandler( async(req,res)=>{ const {userId} = req.body; const projects = await Project.findAll({were:{userId:userId}}); res.json(projects); })); // To create your task router.post('/', asyncHandler(async (req,res)=>{ const {userId,name, description} = req.body; let newProject = await Project.create({userId:userId, name:name, description:description}); res.json(newProject); })) // To delete your project // ToDo set up propper id handling router.delete('/', asyncHandler( async (req,res)=>{ const {projectId} = req.body; await Project.destroy({where:{id:projectId}}); res.json({message:'success'}) })) module.exports = router; <file_sep>/documentation/State-Sample.md ```javascript { tasks:[ "Let's go to the mall", "Do Home Work", "Leet Code", "Look for that job", ], User:{ id: 1, firstName: James, email:<EMAIL> Organizations:[ { name: AppAcademy }, { name: Mind_Over_motivation }, ] }, ui:{ loading:Boolean }, errors:[] } <file_sep>/db/models/organization.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Organization = sequelize.define('Organization', { userId: DataTypes.INTEGER, name: DataTypes.STRING, description: DataTypes.TEXT }, {}); Organization.associate = function(models) { // associations can be defined here // Organization.hasMany(models.User,{foreignKey:'userId'}); }; return Organization; }; <file_sep>/client/src/components/ProjectTasks.js import React from 'react'; import NewTaskForm from '../components/NewtaskForm'; import {getTasks } from '../store/onward'; import { useDispatch, useSelector } from "react-redux"; import Task from './Task'; import { useEffect } from 'react'; export default function ProjectTasks (){ const data = useSelector(state=>state.reducer); const dispatch = useDispatch(); useEffect(()=>{ dispatch(getTasks()); },[dispatch]); // console.log(data); if(!data.projects){ dispatch(getTasks); } return ( <> <div> <h2 class='center-me header'>Tasks</h2> {data.tasks.map(task => <Task id={task.id}description={task.description}/>)} {<NewTaskForm />} </div> </> ); } <file_sep>/db/seeders/20201002163855-Tasks.js 'use strict'; function r(o) { o.createdAt = new Date(); o.updatedAt = new Date(); return o; } module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: */ return queryInterface.bulkInsert('Tasks', [ r({ userId: 1, projectId: 1,description: 'Make database schema'}), r({ userId: 1, projectId: 1, description: 'Make Restful endpoints for routes'}), r({ userId: 1, projectId: 1, description: 'Finish Auth'}), r({ userId: 1, projectId: 1, description: 'Apply CSS'}), ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ } }; <file_sep>/db/seeders/20201002165101-Orginzation.js function r(o) { o.createdAt = new Date(); o.updatedAt = new Date(); return o; } module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: */ return queryInterface.bulkInsert('Organizations', [ r({ userId: 1, name: 'App Academey', description: ' A bootcamp driven to produce the future software engineers' }) ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ } }; <file_sep>/client/src/store/onward.js // import { removeUser } from './authentication'; const LOAD_PROJECTS = "api/task/LOAD_PROJECTS"; const LOAD_TASKS = "api/task/LOAD_TASKS"; const LOAD_ORG = "api/task/LOAD_ORG"; const loadTasks = (tasks) => { return { type: LOAD_TASKS, tasks }; }; const loadProjects = (projects) => { return { type: LOAD_PROJECTS, projects }; }; const loadOrg = (orgs) => { return { type: LOAD_ORG, orgs }; }; // const setCurrent = (pokemon) => { // return { // type: SET_CURRENT, // pokemon // }; // }; // const setTypes = (types) => { // return { // type: LOAD_TYPES, // types // }; // }; // const formErrors = (errors) => { // return { // type: FORM_ERRORS, // errors // }; // }; // export const getOnePokemon = (id) => async (dispatch) => { // const res = await fetch(`/api/pokemon/${id}`); // if (res.ok) { // const data = await res.json(); // dispatch(setCurrent(data)); // return data; // } else if (res.status === 401) { // return dispatch(removeUser()); // } // throw res; // }; export const getTasks = (userId) => async dispatch => { // const obj = {userId:userId} const res = await fetch(`/api/task/${userId}`); console.log(res); if (res.ok) { const data = await res.json(); const {tasks, projects, organization} = data; // console.log(data); // console.log(load(data)); dispatch(loadTasks(tasks)); dispatch(loadProjects(projects)); dispatch(loadOrg(organization)); // return data; } throw res; }; export const createTask = (obj) => async dispatch => { const {userId} = obj; const res = await fetch('/api/task/', { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj), }); if (res.ok) { dispatch(getTasks(userId)); return res; } throw res; }; export const createProject = (obj) => async dispatch => { const {userId} = obj; const res = await fetch('/api/project/', { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj), }); if (res.ok) { dispatch(getTasks(userId)); return res; } throw res; }; export const deleteTask = (recieve)=> async dispatch => { const {target, userId} = recieve; let obj = {taskId:target}; const res = await fetch('/api/task/', { method: "delete", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj), }); if (res.ok) { dispatch(getTasks(userId)); return res; } } export const deleteProject = (recieve)=> async dispatch => { const {target, userId} = recieve; console.log('Helllooooo'); let obj = {projectId:target}; const res = await fetch('/api/project/', { method: "delete", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj), }); if (res.ok) { dispatch(getTasks(userId)); return res; } } const initialState = { tasks: [], projects:[], orgs:[] } export default function reducer(state=initialState, action) { switch (action.type) { case LOAD_TASKS: return { ...state, tasks: action.tasks }; case LOAD_PROJECTS: return { ...state, projects: action.projects }; case LOAD_ORG: return { ...state, orgs: action.orgs }; default: return state; } } <file_sep>/documentation/DataBase-Schema.md ## `users` | Column Name | Data Type | Details | |:-----------------|:-----------:|:----------------------| | `id` | integer | not null, primary key | | `username` | string | not null, indexed, unique | | `email` | string | not null, indexed, unique | | `hashedPassword` | string | not null | | `token_id` | string | not null, indexed, unique | | `created_at` | datetime | not null | | `updated_at` | datetime | not null | * index on `username, unique: true` * index on `email, unique: true` * index on `session_token, unique: true` ## `Tasks` | Column Name | Data Type | Details | |:-----------------|:-----------:|:-----------------------| | `id` | integer | not null, primary key | | `user_id` | integer | not null, foriegn key,unique| | `project_id` | integer | not null, foriegn key,unique| | `description` | string | not null, | | `created_at` | datetime | not null | | `updated_at` | datetime | not null | * `user_id` references `users` * `project_id` references `projects` ## `Projects` | Column Name | Data Type | Details | |:-----------------|:-----------:|:---------------------------| | `id` | integer | not null, primary key | | `user_id` | integer | not null, indexed, unique, foreign key| | `name` | string | not null | | `description` | text | | | `created_at` | datetime | not null | | `updated_at` | datetime | not null | * `user_id` references `users` ## `Organizations` | Column Name | Data Type | Details | |:-----------------|:-----------:|:-----------------------------------| | `id` | integer | not null, primary key | | `users_id` | integer | not null, unique, foreign key | | `description` | string | not null | | `created_at` | datetime | not null | | `updated_at` | datetime | not null | * `users` references `users` <file_sep>/documentation/Frontend-Routes-and-Components.md Routes * `Root` * `App` * `NavBar` * Main Component * `Footer` Routes defined in App * `/` * Landing Page * `/login` * Form * `/signup` * Form * `/Home` * Tasks * Projects * Organizations * `/Project:id/Task` * tasks * create task button <file_sep>/client/src/components/NewtaskForm.js // import React, { Component } from 'react'; import React, { useState } from 'react' import { useDispatch, useSelector } from 'react-redux'; import {createTask} from '../store/onward'; function NewTaskForm (){ const [description, setDescription] = useState(); const data = useSelector(state=>state); const dispatch = useDispatch(); const handleSubmit = (e) =>{ e.preventDefault(); const obj = {userId:data.auth.id, description:description}; dispatch(createTask(obj)); } return( <form onSubmit={handleSubmit}> <button type='submit'>+</button> <input type='text' onChange={(e) => setDescription(e.target.value)}/> </form> ) } export default NewTaskForm; <file_sep>/client/src/components/Organization.js // import React, { Component } from 'react'; import React, { useState } from 'react' import { useDispatch, useSelector } from 'react-redux'; function NewOrganizationForm (props){ const [description, setDescription] = useState(); const [name, setName] = useState(); const dispatch = useDispatch(); const handleSubmit = (e) =>{ e.preventDefault(); // dispatch(createTask(description)); } return( <> <h1>{props.name}</h1> <p>{props.description}</p> </> // <form onSubmit={handleSubmit}> // <input type='text' placeholder='Organization Name' onChange={(e) => setName(e.target.value)}/> // <input type='text' placeholder='Description'onChange={(e) => setDescription(e.target.value)}/> // <button type='submit'>Create Organization</button> // </form> ) } export default NewOrganizationForm; <file_sep>/client/src/App.js import React from 'react'; import { BrowserRouter, Switch, Route, NavLink } from 'react-router-dom'; import LoginPage from './components/LoginPage'; import Home from './components/Home'; import NewOrgainzationForm from './components/Organization'; import ProjectTasks from './components/ProjectTasks'; import { useDispatch, useSelector } from "react-redux"; function App() { const data = useSelector(state=>state.reducer); return ( <> <BrowserRouter> <div class='navBar'> <nav class='horizontal'> <div><NavLink to="/" className='color' activeClass="active">Home</NavLink></div> <div><NavLink to="/newOrganization" className='color' activeClass="active">Organizations</NavLink></div> <div><NavLink to="/login" className='color' activeClass="active">Login</NavLink></div> </nav> </div> <Switch> <Route path='/projectTasks'> <ProjectTasks /> </Route> <Route path="/login"> <LoginPage /> </Route> <Route path="/newOrganization"> {data.orgs.map(org => <NewOrgainzationForm name={org.name} description={org.description}/>)} </Route> <Route path="/"> <Home /> </Route> </Switch> </BrowserRouter> <div class='center-me color'><a href='https://github.com/whitejamesthe2nd'>Check out my github</a></div> </> ); } export default App; <file_sep>/documentation/Home.md # Brewer Design Documents Welcome to the Onward to Completion wiki! <!-- <future link to herokuapp> --> * <a href="https://github.com/whitejamesthe2nd/OnwardToCompletetion/wiki/MVP-List">MVP List</a> * <a href="https://github.com/whitejamesthe2nd/OnwardToCompletetion/wiki/Database-Schema">Database Schema</a> * <a href="https://github.com/whitejamesthe2nd/OnwardToCompletetion/wiki/State-Shape">Sample State</a> * <a href="https://github.com/whitejamesthe2nd/OnwardToCompletetion/wiki/Frontend-Routes-and-Components">Frontend Routes and Components</a> * <a href="https://github.com/whitejamesthe2nd/OnwardToCompletetion/wiki/Backend-Routes">Backend Routes</a> <file_sep>/client/src/components/Project.js import React from 'react'; import { BrowserRouter, Switch, Route, NavLink } from 'react-router-dom'; import ProjectTasks from './ProjectTasks'; import { useDispatch, useSelector } from "react-redux"; const {deleteProject, default: reducer} = require('../store/onward'); function Project(props) { const dispatch = useDispatch(); const auth = useSelector(state=>state.auth); // const reducer = useSelector(state=>state.reducer); const handleClick = (e)=>{ console.log(auth.id); const obj = {target: e.target.value, userId:auth.id} dispatch(deleteProject(obj)); } return ( <div class='rows'> <BrowserRouter> <> <button class="ui secondary button inline" value={props.id} onClick={handleClick}>Complete</button> <div class='inline'><a href='/projectTasks' value={props.id} >{props.name}</a></div> <div class='inline'>: {props.description}</div> </> <Switch> {/* <Route path='/projectTasks'> <ProjectTasks /> </Route> */} </Switch> </BrowserRouter> </div> ); } export default Project; <file_sep>/client/src/components/NewProjectForm.js // import React, { Component } from 'react'; import React, { useState } from 'react' import { useDispatch, useSelector } from 'react-redux'; import {createProject} from '../store/onward'; function NewProjectForm (){ const [description, setDescription] = useState(); const [name, setName] = useState(); const dispatch = useDispatch(); const auth = useSelector(state => state.auth); const handleSubmit = (e) =>{ e.preventDefault(); dispatch(createProject({name:name, description:description, userId:auth.id})); // dispatch(createProject(description)); } return( <form onSubmit={handleSubmit}> <input type='text' placeholder='Project Name' onChange={(e) => setName(e.target.value)}/> <input type='text' placeholder='Description'onChange={(e) => setDescription(e.target.value)}/> <button type='submit'>Create Project</button> </form> ) } export default NewProjectForm; <file_sep>/documentation/Backend-Routes.md ## HTML * `GET /` `StaticPagesController#root` ## API Endpoints ### `users` * `GET /api/users/:id` - returns user Home page stuff * `POST /api/users` - sign up ### `session` * `POST /api/session` - log in * `DELETE /api/session` - log out ### `tasks` * `GET /api/users:id/tasks` - get tasks associated with the user. ### `projects` * `GET /api/user:id/projects` - returns list of projects associated with the user ### `Organizations` * `GET /api/user:id/organizations` - returns list of projects organizations with the user <file_sep>/documentation/MVP-list.md OnwardToCompletion is gonna be an asana clone if I have enough time I am gonna add in positive reinforcement features,like inspirational messages as you create and fininsh tasks, to the base to add a nice twist. ### 1. Hosting on Heroku ### 2. Account Sign-up, Login, Logout and Guest User * Users Can login/Log out * Users can basically only use the site when logged in with features such as task management and project tracking. * A demo user for users to take the site fro a test drive. ### 3. Landing Page * Explaining esentially the purpouse and nature of a task manager with static information kinda like a sales pitch * Links to sign Up and Sign in pages ### 4.NavBar * access to log in/ log out * access to tasks and projects ### 5. Home Page * Current Projects list * Current Organizations ### 6. My Tasks Page * Can Create New tasks * Shows List of Current tasks ### Bonus * Calendar * Comment on tasks(maybe a single task page) * Priority Sorting for Tasks * Loading Pages with inspirational messages * Helpful or positive reinforcement messages for createing and completeing tasks. * A list of completed tasks
376d9872735155cbe7c841da828ccb4ba5f0f084
[ "JavaScript", "Markdown" ]
17
JavaScript
whitejamesthe2nd/onward
2dc243a858b7ff0d56a1f7e5b473678deeecc4e9
8d674c7c3ebba0ec8fa41244dc03da4f5c350a60
refs/heads/master
<repo_name>provpup/node_web_scraper<file_sep>/index.js var request = require('request'); var url = require('url'); var path = require('path'); var $ = require('cheerio'); var fs = require('fs'); var stringify = require('csv-stringify'); function writeCsvFile(csvFile, data) { stringify(data, function(err, output) { fs.writeFile(csvFile, output, function(err) { if (err) { return console.err(err); } console.log('wrote ' + csvFile); }); }); } function htmlDownload(err, response, html) { if (err) { return console.error(err); } var imageFileData = []; var $table = $.load(html)('table'); var $tableRows = $table.find('tr'); $tableRows.each(function(index, element) { var permissions = $(this).find('code').eq(0).text(); var $linkNode = $(this).find('a').eq(0); var imageUrl = domain + $linkNode.attr('href'); var fileType = path.extname(imageUrl); imageFileData.push([permissions, imageUrl, fileType]); }); writeCsvFile(__dirname + '/images.csv', imageFileData); } var urlToVisit = 'http://substack.net/images/'; var parsedUrl = url.parse(urlToVisit); var domain = parsedUrl.protocol + '//' + parsedUrl.host; request(urlToVisit, htmlDownload);
bb570abcc37df257add320139cbb53bba66310c5
[ "JavaScript" ]
1
JavaScript
provpup/node_web_scraper
565b3a7e76972efbfa65227c7c32e1bf72e9a585
d99cffb3522a61caedbdd7bfc9ee988bc40b86f2